One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.0-beta.6
Toby Kalkmand0832c3307be
diff --git a/VERSION b/VERSIONindex 76daa65..2002824 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.5.0-beta.5+1.5.0-beta.6diff --git a/WIRE.md b/WIRE.mdindex 29404a6..92d1cd5 100644--- a/WIRE.md+++ b/WIRE.md@@ -135,10 +135,10 @@ Rules:it is not dialled, the responder never computes or matches its key id, and Overview asks theuser to pair that machine again: "*name* was paired on Beamer 1.4. Pair the two again to linkthem on 1.5.0." A new pairing with that machine replaces it (section 6).-- **Removing a peer** deletes its entry, token included, closes its links at once, and ends its- ownership if it holds it (section 4). The peer is told nothing; its next link's key id is- unknown here, so it is closed with nothing sent, and the peer says this machine closed the- connection (section 2).+- **Removing a peer** resets a local Match design with selection to None, then deletes its entry+ and token, closes its links, and ends its ownership if it holds it (section 4). Its next link's+ key id is unknown here, so it is closed with nothing sent, and the peer says this machine closed+ the connection (section 2).- **Turning `allow_drive` off** ends that peer's ownership at once. Turning `send` off lets go ofthat peer if this machine's input is on it, and closes the link this machine opened to it.- **Writes are atomic**: a new file beside the old, then a rename over it.@@ -467,7 +467,8 @@ Capabilities say what a machine does with a message it receives:| `gestures` | it acts on `gesture` || `media_keys` | it acts on the media key names (section 7) || `text` | it types `text` |-| `settings` | it keeps Same on all machines (`settings`) |+| `settings` | it receives Same on all machines (`settings`) |+| `design_sync` | with `settings`, it sends and receives direct Design states (`settings.data.design_sync`) and can be followed |A sender does not send a message its peer's capabilities do not cover. A receiver that gets oneanyway drops it, and still acknowledges it when it carries a `seq`.@@ -1058,7 +1059,9 @@ A key travels as `key`, a name, in `keydown` and `keyup`:point, with Shift applied: `"A"` with Shift down, `"a"` without. While Command, Control or Alt(not Shift) is held, it sends the key's own unshifted character from its layout instead, soOption-V on a Mac is `"v"` and not `"√"`, and a German keyboard's Command-Z is `"z"`. Numpad- keys send their character (`"1"`, `"+"`).+ keys send their character (`"1"`, `"+"`). When Windows cannot compose a dead key and the next+ character into one code point, it sends the visible sequence through `text` instead; a held base+ key repeats its character as `text` and its physical key-up remains swallowed.- **`us`** is sent beside a character: the unshifted, lower-case character the same key positiontypes on a US layout, for a receiver whose layout cannot type `key`. A key with no UScharacter (on a JIS keyboard, say) sends none.@@ -1090,23 +1093,24 @@ The machines fall in two families: the Mac (`macos`, `ios`), and the PC (`window`android`, and any unknown platform). Between two machines of the same family every key goes outas itself. Between the two families, the sender applies its user's saved style:-| Physical key on the sender | Same family | Across, Semantic (the default) | Across, Positional |-|---|---|---|---|-| Mac Control | `ctrl` | `cmd` | `ctrl` |-| Mac right Control | `ctrl_r` | `cmd` | `ctrl` |-| Mac Command | `cmd` | `ctrl` | `cmd` |-| Mac right Command | `cmd_r` | `ctrl` | `cmd` |-| Mac Option | `alt` | `alt` | `alt` |-| Mac right Option | `alt_r` | `alt` | `alt` |-| PC Control | `ctrl` | `cmd` | `ctrl` |-| PC right Control | `ctrl_r` | `cmd_r` | `ctrl_r` |-| PC Windows or Super | `cmd` | `ctrl` | `cmd` |-| PC right Windows or Super | `cmd_r` | `ctrl_r` | `cmd_r` |-| PC Alt | `alt` | `alt` | `alt` |-| PC right Alt or AltGr | `alt_r` | `alt_r` | `alt_r` |+| Physical key on the sender | Same family | Across, Semantic (the default) | Across, Positional | Across, Mac keyboard layout (PC sender only) |+|---|---|---|---|---|---|+| Mac Control | `ctrl` | `cmd` | `ctrl` | — |+| Mac right Control | `ctrl_r` | `cmd` | `ctrl` | — |+| Mac Command | `cmd` | `ctrl` | `cmd` | — |+| Mac right Command | `cmd_r` | `ctrl` | `cmd` | — |+| Mac Option | `alt` | `alt` | `alt` | — |+| Mac right Option | `alt_r` | `alt` | `alt` | — |+| PC Control | `ctrl` | `cmd` | `ctrl` | `ctrl` |+| PC right Control | `ctrl_r` | `cmd_r` | `ctrl_r` | `ctrl_r` |+| PC Windows or Super | `cmd` | `ctrl` | `cmd` | `alt` |+| PC right Windows or Super | `cmd_r` | `ctrl_r` | `cmd_r` | `alt_r` |+| PC Alt | `alt` | `alt` | `alt` | `cmd` |+| PC right Alt or AltGr | `alt_r` | `alt_r` | `alt_r` | `cmd_r` |- Semantic makes the everyday shortcuts line up: Command-C on a Mac arrives as Control-C on a PC,- and Control-C on a PC as Command-C on a Mac. Positional keeps each key in its place.+ and Control-C on a PC as Command-C on a Mac. Positional keeps each key in its place. Mac keyboard+ layout maps a PC keyboard's modifiers to the corresponding Mac keys by their positions.- The Mac's rows across families are 1.4.x's `DEFAULT_KEY_MAP` and `LEGACY_POSITIONAL_KEY_MAP`as they stand, sides folded. The PC's are Windows' capture names and 1.4.x's `POSITIONAL_SWAP`.Same family is new: the Mac as itself with its sides kept (the first design named the folded@@ -1115,6 +1119,9 @@ as itself. Between the two families, the sender applies its user's saved style:- The saved style is the Mac's `key_map` (a style name, or a map a user wrote by hand, whichapplies across families only) and Windows' `modifier_style`. Both survive the migration. ALinux app keeps `modifier_style` as Windows does.+- The PC keeps `modifier_style` locally; it is not sent to peers or shared by Same on all machines.+ Key messages contain only the resulting key names, which older peers already understand. A+ settings file without this field defaults to Semantic.- A Linux sender reads keys by evdev code: `KEY_LEFTCTRL` and `KEY_RIGHTCTRL` are PC Control,`KEY_LEFTMETA` and `KEY_RIGHTMETA` Windows or Super, `KEY_LEFTALT` Alt and `KEY_RIGHTALT` rightAlt or AltGr. A Linux receiver presses the same codes for the same names.@@ -1271,7 +1278,9 @@ every peer.made the change, or `""`. A sender always sends all three. A receiver reads a missing `by` as`""`, and also reads a `by` spelt in standard base64 with padding, as the desktops do; amessage missing `on` or `set_at`, or with any of the three of the wrong type or not an id, is- malformed and ignored whole. `crossing` and `design` are objects, present only when `on` is+ malformed and ignored whole. The receiver validates this envelope before reading `design_sync`,+ so a malformed outer field drops the optional Design state with the rest of the message.+ `crossing` and `design` are objects, present only when `on` istrue; one that is absent or is not an object brings no values, and the message stands.- **Each value stands alone.** Unlike every other message, a value in `crossing` or `design`outside the table below, or one this receiver cannot hold (an effect it does not have), is@@ -1306,6 +1315,40 @@ every peer.- A change made here is stamped with the current time, and never lower than the stamp held plusone, so a change on a machine whose clock is behind still wins.+**Follow a machine's design.** Each machine's Design page has **Match design with**: None, or one+paired machine advertising both `settings` and `design_sync`. The selection is local; there is no+group object and the selection is never sent. A machine that does not advertise `design_sync` is+shown unavailable with “Needs beta.6 or later”.++The optional `design_sync` member is independent of `on`. A capable machine sends its own current+Design state to each directly linked capable peer after link-up and whenever its Design changes,+even while Same on all machines is off. The state is:++```json+{"type":"settings","data":{"on":false,"set_at":1790000000,"by":"<b64>",+ "design_sync":{"set_at":1790000001,"by":"<b64>","values":{+ "glow_style":"glow","glow_colour":"signal","effect_length":"normal",+ "effect_size":"medium","shortcut_arrival":true,"shortcut_arrival_style":"match"}}}}+```++`design_sync` is a complete independently stamped Design state. Its `set_at` and `by` use the+newer-wins ordering and clock bounds above. Values are validated individually; unsupported keys or+values are ignored. Missing `effect_size` means `"medium"`; its wire type is string and allowed+values are `"small"`, `"medium"` and `"large"`. Same on all machines has precedence: the follow+selection stays set but does not apply while Same is on. A newer state from the selected machine+applies to this machine's Design only when its stamp is newer than this machine's own Design stamp.+The follower keeps the leader's `set_at` and `by`, so an announcement carries the same stamp through+a chain (C follows B, B follows A) and both sides of a mutual follow converge on the newest state+when their initial announcements cross in flight. If applying a state leaves every Design value+identical, it is not a change and nothing is announced; the newer stamp is still kept locally, so an+older state cannot replace it.++Editing any Design control on a follower turns following off and the page says so. Turning off+Same on all machines resumes following from the selected machine's latest received state. Removing+or unpairing the selected machine resets the selection to None. An offline followed machine leaves+the last look in place; the next link-up sends its current state and catches the follower up.+Older peers ignore the optional field. A peer that does not send it cannot be followed.+## Versions- **Wire version 6** is in Beamer 1.5.0 and later. It refuses versions 5 and below, and they refuse@@ -1342,6 +1385,8 @@ one against the code and against the primitives written out by hand.- `ack` carries `held_us`, and the responder acknowledges a lone event at once.- Each initiator counts `seq` from 1 on every link; version 5's Mac carried it across reconnects.- New messages: `accept`, `accepts`, `refuse`, `paired`, `text`.+- `settings` gains the optional `design_sync` member for per-machine Design matches; older betas+ ignore it, while 1.5 keeps it separate from the existing `on` switch.## Changes from the first design@@ -1363,10 +1408,13 @@ one against the code and against the primitives written out by hand.the keys. Version 6 puts a per-pair key id there instead, with the ids sealed in `hello` and`welcome`, and adds forward secrecy (decided 1 and 2).- **Pairing by QR** carries a second secret (decided 7).+- **Design matching** is a local choice to follow one machine directly. Applying a newer state+ republishes the local result so chains carry on; identical values publish nothing, so mutual+ follows converge without forwarding received state (decided 8).## Decided-Decided on 30-09-2026, and 6 amended on 01-10-2026. The text above already follows these.+Decided on 30-09-2026, 6 on 01-10-2026, and 8 on 02-10-2026. The text above already follows these.1. **A per-pair key id in the preamble, not the machine id.** The first 16 bytes of`HKDF-SHA-256(token, salt "beamer-link-v6", info "beamer-key-id")`; the machine ids travel in@@ -1381,6 +1429,10 @@ Decided on 30-09-2026, and 6 amended on 01-10-2026. The text above already follo(sections 1 and 2).7. **The QR's extra secret.** 16 random bytes per code in the QR as `k`; `qr: 1` in`pair_start` makes the password the code followed by those bytes (section 6).+8. **Follow a machine's Design directly.** A local selection names at most one paired machine and+ never goes on the wire. Machines send their own stamped Design to direct capable peers; a+ follower that changes applies and announces its own resulting state. Identical values announce+ nothing, so a mutual follow converges. Same on all machines takes precedence (section 10).## Open questionsdiff --git a/core/effects.py b/core/effects.pyindex e5bc1fc..7f6624f 100644--- a/core/effects.py+++ b/core/effects.py@@ -357,14 +357,15 @@ 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):+def state(screen_w, screen_h, os_name, method, palette, *, reduced=False, dark=True, notch=None,+ effect_size="medium", **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={},+ effect_size=effect_size, hash=hash_n, memo={},)if notch is not None:s.notch = SimpleNamespace(**notch)@@ -404,12 +405,19 @@ class Effect:self.arrive_seconds = min(0.8, float(arrive_seconds))+def _light_aperture(pen, state, departing):+ from .fx_light import _aperture+ _aperture(pen, state, departing)++# 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_folio", "Folio", ("crease", "pleat", "concertina"), ("vellum", "carbon_copy", "marbled")),+ ("fx_selvedge", "Selvedge", ("thread", "weave", "jacquard"), ("flax", "madder", "tide")),("fx_ink", "Ink", ("capillary", "viscous_drop", "sumi_bloom"), ("indigo_ink", "matcha", "terracotta")),("fx_warp", "Warp", ("light_slit", "hyperdrive", "wormhole"), ("neon", "vaporwave", "cyber")),)@@ -422,11 +430,13 @@ STAND_INS = {"capillary": "glow", "viscous_drop": "glow", "sumi_bloom": "glow","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)+EFFECT_IDS = ("aperture",) + 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)+LIGHT_AS_GIVEN = ("aperture", "crease", "pleat", "concertina", "thread", "weave", "jacquard") + 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@@ -439,6 +449,7 @@ def _load():if _loaded is None:import importlibeffects, packs = {}, {}+ effects["aperture"] = CLASSIC["aperture"]for module_name, _name, effect_ids, pack_ids in ALL_DIRECTIONS:module = importlib.import_module(f"{__package__}.{module_name}")by_id = {effect.id: effect for effect in module.EFFECTS}@@ -514,7 +525,6 @@ LOCATOR = Effect("locator", "Ring", "quiet", "A ring in the chosen colours close# 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.0CLASSIC_ARM = 200.0CLASSIC_FLASH_S = 0.35CLASSIC_FINISH_S = 0.6@@ -573,12 +583,13 @@ def _classic_depart(beam):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))+ w, h = s.screen.w, s.screen.h+ full_depth = edge_depth(w, h, getattr(s, "effect_size", "medium"))+ depth = full_depth if beam else full_depth * (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.hpen.globalCompositeOperation = "lighter" if s.dark else "source-over"if r.kind == "corner":vertical, horizontal = getattr(r, "corner", "top_right").split("_")@@ -610,10 +621,16 @@ def _classic_depart(beam):CLASSIC = {- "glow": Effect("glow", "Glow", "classic", "A band of light that deepens the harder you push.",+ "glow": Effect("glow", "Glow", "quiet", "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.",+ "beam": Effect("beam", "Beam", "medium", "A thin line with a comet of light running along it.",_classic_depart(True), lambda pen, s: None, CLASSIC_FINISH_S, 0.0),+ "aperture": Effect(+ "aperture", "Aperture", "showpiece",+ "A fine lens of light opens under pressure and closes softly behind the arriving pointer.",+ lambda pen, state: _light_aperture(pen, state, True),+ lambda pen, state: _light_aperture(pen, state, False), 0.62, 0.62,+ ),}@@ -640,11 +657,13 @@ def switch_style_groups():cannot load; the overlay has already said why."""groups = [(None, (("match", "Same as crossing"), ("locator", "Ring")))]try:+ _load()+ light = (("Light", (("aperture", CLASSIC["aperture"].name),)),)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+ return groups + list(light) + founddef switch_effect(choice, crossing_style):@@ -700,7 +719,7 @@ def preview_size(method):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):+def preview_scene(fx, t, method, palette, reduced=False, dark=True, pace=1.0, effect_size="medium"):"""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`@@ -748,18 +767,19 @@ def preview_scene(fx, t, method, palette, reduced=False, dark=True, pace=1.0):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)+ pressure=pressure, tick=tick, since=None, effect_size=effect_size, **common)pen = draw(fx, "depart", s, mac_origin)if pen is not None:scene["pens"].append(pen)return scenesince = (t - _P_CROSS) / paces = 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)+ along=0.5, pressure=0.0, tick=None, since=since, effect_size=effect_size, **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)+ s = state(w, h, "windows", method, palette, point=point(*land), edge=land_edge, since=since,+ effect_size=effect_size, **common)pen = draw(fx, "arrive", s, pc_origin)if pen is not None:scene["pens"].append(pen)@@ -778,7 +798,7 @@ 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):+def preview_switch_scene(fx, t, palette, os_name="mac", reduced=False, dark=True, pace=1.0, effect_size="medium"):"""The Design pages' loop for what a switch plays, in preview_scene's shape: one screen, thepointer still near its middle, and `fx`'s switch arrival round it every SWITCH_LOOP_S."""t = t % SWITCH_LOOP_S@@ -787,7 +807,8 @@ def preview_switch_scene(fx, t, palette, os_name="mac", reduced=False, dark=Truescene = {"screens": [(0.0, 0.0, w, h, os_name)], "notch": None, "pointer": (at[0], at[1], os_name), "pens": []}since = (t - _S_START) / paceif since >= 0.0:- s = state(w, h, os_name, "switch", legible(palette, dark, fx), reduced=reduced, dark=dark, point=point(*at),+ s = state(w, h, os_name, "switch", legible(palette, dark, fx), reduced=reduced, dark=dark,+ effect_size=effect_size, point=point(*at),edge=nearest_edge(at[0], at[1], w, h), since=since)pen = draw(fx, "arrive", s)if pen is not None:@@ -798,7 +819,23 @@ def preview_switch_scene(fx, t, palette, os_name="mac", reduced=False, dark=True# 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}+SIZES = (("small", "Small"), ("medium", "Medium"), ("large", "Large"))+PACES = {"short": 0.5, "normal": 1.0, "long": 2.0}+_SIZE_FRACTIONS = {"small": 0.03, "medium": 0.045, "large": 0.06}+_MIN_EDGE_DEPTH = 24.0+_MAX_EDGE_DEPTH = 144.0+_EFFECT_REFERENCE_DEPTH = 36.0+++def edge_depth(screen_w, screen_h, size="medium"):+ """The edge band's depth in screen units, scaled to the shorter side of its display."""+ fraction = _SIZE_FRACTIONS.get(size, _SIZE_FRACTIONS["medium"])+ return max(_MIN_EDGE_DEPTH, min(_MAX_EDGE_DEPTH, min(float(screen_w), float(screen_h)) * fraction))+++def effect_depth_scale(s):+ """Scale material depths from their 1200 by 800 reference canvas to this screen and Size."""+ return edge_depth(s.screen.w, s.screen.h, getattr(s, "effect_size", "medium")) / _EFFECT_REFERENCE_DEPTHdef pace(length):@@ -824,6 +861,7 @@ class Player:self.crossed_at = None# How long everything after the push takes, as a multiple of each effect's own timing.self.pace = pace+ self.effect_size = "medium"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.@@ -892,7 +930,7 @@ class Player: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,+ notch=local_notch, effect_size=self.effect_size, 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:@@ -909,7 +947,7 @@ class Player:# 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,+ dark=dark, notch=None if a["switch"] else local_notch, effect_size=self.effect_size,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:diff --git a/core/fx_folio.py b/core/fx_folio.pynew file mode 100644index 0000000..0020e06--- /dev/null+++ b/core/fx_folio.py@@ -0,0 +1,104 @@+"""Folio: a scored edge lifts into paper folds and lays itself flat on arrival."""++import math++from .effects import Effect, clamp, ease_out, effect_depth_scale, lerp+from .fx_material import stroke, surface+++def _sheet(pen, s, level, departing):+ duration = (0.48, 0.62, 0.78)[level]+ t = s.since+ if t is not None and t >= duration:+ return+ pushing = departing and t is None+ p = clamp(s.pressure) if pushing else 1.0+ u = 0.0 if pushing else clamp(t / duration)+ size = effect_depth_scale(s)+ alpha = clamp(p * 5) if pushing else 1 - clamp((u - 0.58) / 0.42)+ motion = 0.65 if s.reduced else p+ at = surface(pen, s, departing)+ span = (48, 90, 144)[level]+ count = (2, 6, 12)[level]+ depth = (12, 28, 46)[level] * size+ base = 3 * size+ wall = 2 * size+ gap = 0.0+ if not pushing and not s.reduced:+ if departing:+ gap = span * ease_out(clamp(u / 0.8))+ motion = 1 - ease_out(u)+ else:+ gap = span * (1 - ease_out(clamp(u / 0.55))) * 0.5+ motion = (1 - ease_out(u)) + 0.22 * math.sin(math.pi * u)+ if s.reduced and not pushing:+ alpha = 1 - u+ step = 2 * span / count+ palette = s.palette+ facets = []+ for i in range(count):+ a, b = -span + i * step, -span + (i + 1) * step+ side = -1 if (a + b) < 0 else 1+ a, b = a + side * gap, b + side * gap+ def ridge(j):+ envelope = math.sin(math.pi * j / count) ** 0.7+ return base + depth * motion * envelope * (1 if j % 2 else 0.64)+ ra, rb = ridge(i), ridge(i + 1)+ facets.append((i, a, b, ra, rb))+ # Batch by pigment: the native replayers otherwise rebuild dozens of identical brushes.+ for pigment, colour in enumerate(palette):+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ if i % len(palette) == pigment:+ pen.moveTo(*at(a, wall))+ pen.lineTo(*at(a, ra))+ pen.lineTo(*at(b, rb))+ pen.lineTo(*at(b, wall))+ pen.closePath()+ pen.fillStyle, pen.globalAlpha = colour, alpha * 0.9+ pen.fill()+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ if i % 2:+ pen.moveTo(*at(a, wall))+ pen.lineTo(*at(a, ra))+ pen.lineTo(*at(b, rb))+ pen.lineTo(*at(b, wall))+ pen.closePath()+ pen.fillStyle, pen.globalAlpha = "#000000", alpha * 0.18+ pen.fill()+ for pigment, colour in enumerate(palette):+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ if (i + 1) % len(palette) == pigment:+ pen.moveTo(*at(a, wall))+ pen.lineTo(*at(a, ra))+ pen.lineTo(*at(b, rb))+ stroke(pen, colour, 1.0, alpha * 0.9, s.dark)+ if level == 2:+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ for k in (0.34, 0.67):+ pen.moveTo(*at(a, lerp(wall, ra, k)))+ pen.lineTo(*at(b, lerp(wall, rb, k)))+ stroke(pen, palette[-1], 0.65, alpha * 0.45, s.dark)+++def _make(id_, name, level, blurb):+ return Effect(id_, name, ("quiet", "medium", "showpiece")[level], blurb,+ lambda pen, s: _sheet(pen, s, level, True),+ lambda pen, s: _sheet(pen, s, level, False),+ (0.48, 0.62, 0.78)[level], (0.48, 0.62, 0.78)[level])+++EFFECTS = [+ _make("crease", "Crease", 0, "A small paper crease lifts under pressure, parts, then settles flat where you arrive."),+ _make("pleat", "Pleat", 1, "Six alternating folds gather at the edge, slide apart and unfold on the other screen."),+ _make("concertina", "Concertina", 2, "A scored paper fan rises along the boundary, opens a passage and folds itself away behind you."),+]++PACKS = {+ "vellum": ("Vellum", ["#c69a60", "#f0ddac", "#88674c"]),+ "carbon_copy": ("Carbon copy", ["#6688ae", "#bbcad9", "#344d72"]),+ "marbled": ("Marbled", ["#bd6858", "#6c9691", "#e1bb78"]),+}diff --git a/core/fx_light.py b/core/fx_light.pynew file mode 100644index 0000000..da54adb--- /dev/null+++ b/core/fx_light.py@@ -0,0 +1,41 @@+"""The third Light effect: a narrow lens opens at the crossing, then closes behind it."""++import math++from .effects import clamp, ease_out, effect_depth_scale, parse_colour+from .fx_material import stroke, surface+++def _aperture(pen, s, departing):+ t = s.since+ if t is not None and t >= 0.62:+ return+ pushing = departing and t is None+ p = clamp(s.pressure) if pushing else 1.0+ size = effect_depth_scale(s)+ u = 0.0 if pushing else clamp(t / 0.62)+ alpha = clamp(p * 4) if pushing else 1 - u+ opening = 0.65 if s.reduced else p+ if not pushing and not s.reduced:+ opening = (1 - ease_out(u)) if not departing else 1 + math.sin(math.pi * u) * 0.8+ at = surface(pen, s, departing)+ span = 38 + 52 * opening+ depth = (3 + 13 * opening) * size+ pen.beginPath()+ # A fixed path budget also carries the lens cleanly round corners and the notch.+ for half in (0, 1):+ for j in range(17):+ x = (-span + 2 * span * j / 16) * (1 if half == 0 else -1)+ envelope = max(0, 1 - (x / span) ** 2)+ y = 3 * size + envelope * depth * (1 if half == 0 else 0.18)+ (pen.moveTo if half == 0 and j == 0 else pen.lineTo)(*at(x, y))+ pen.closePath()+ a, b = at(-span, 0), at(span, 0)+ gradient = pen.createLinearGradient(*a, *b)+ palette = s.palette+ for i, colour in enumerate(palette):+ r, g, blue, _ = parse_colour(colour)+ gradient.addColorStop(i / max(1, len(palette) - 1), (r, g, blue, 0.24))+ pen.fillStyle, pen.globalAlpha = gradient, alpha+ pen.fill()+ stroke(pen, palette[len(palette) // 2], 1.4, alpha, s.dark)diff --git a/core/fx_material.py b/core/fx_material.pynew file mode 100644index 0000000..0f4241f--- /dev/null+++ b/core/fx_material.py@@ -0,0 +1,30 @@+"""Boundary coordinates shared by the folded, woven and aperture effects."""++from .fx_instrument import frame+++def surface(pen, s, departing):+ """Map along/inward coordinates round corners and outside the hardware notch."""+ if not departing and s.method == "switch":+ pen.translate(s.point.x, max(2, min(s.screen.h - 60, s.point.y - 18)))+ return lambda u, v: (u, v)+ k = frame(pen, s, departing)+ if k.kind == "corner":+ return lambda u, v: (u + v, v) if u >= 0 else (v, -u + v)+ if k.kind == "notch":+ def mapped(u, v):+ p = k.track.at(k.tp + u)+ return p.x + p.nx * v, p.y + p.ny * v+ return mapped+ return lambda u, v: (u, v)+++def stroke(pen, colour, width, alpha, dark):+ """A narrow contrasting keyline preserves the material against busy wallpaper."""+ pen.lineJoin, pen.lineCap = "round", "round"+ pen.strokeStyle = "#000000"+ pen.lineWidth, pen.globalAlpha = width + 1.6, alpha * (0.4 if dark else 0.62)+ pen.stroke()+ pen.strokeStyle = colour+ pen.lineWidth, pen.globalAlpha = width, alpha+ pen.stroke()diff --git a/core/fx_selvedge.py b/core/fx_selvedge.pynew file mode 100644index 0000000..f9db669--- /dev/null+++ b/core/fx_selvedge.py@@ -0,0 +1,94 @@+"""Selvedge: tension opens a woven seam; the threads stay continuous and mend behind you."""++import math++from .effects import Effect, clamp, ease_out, effect_depth_scale+from .fx_material import stroke, surface+++def _cloth(pen, s, level, departing):+ duration = (0.48, 0.64, 0.78)[level]+ t = s.since+ if t is not None and t >= duration:+ return+ pushing = departing and t is None+ p = clamp(s.pressure) if pushing else 1.0+ u = 0.0 if pushing else clamp(t / duration)+ size = effect_depth_scale(s)+ alpha = clamp(p * 5) if pushing else 1 - clamp((u - 0.55) / 0.45)+ tension = 0.55 if s.reduced else p+ opening = 0.0+ if not pushing:+ if s.reduced:+ alpha = 1 - u+ elif departing:+ opening = math.sin(math.pi * ease_out(u)) * 29 * size+ tension = 1 - ease_out(u)+ else:+ opening = 24 * size * (1 - ease_out(clamp(u / 0.65)))+ tension = 0.65 * (1 - ease_out(u))+ at = surface(pen, s, departing)+ span = (48, 88, 132)[level]+ rows = (2, 4, 6)[level]+ samples = (8, 10, 12)[level]+ palette = s.palette+ # The warp stays anchored at the wall while the weft tightens across it.+ if level:+ pen.beginPath()+ for i in range(-8 if level == 2 else -5, 9 if level == 2 else 6):+ x = i * 14+ envelope = max(0, 1 - abs(x) / span)+ y = (5 + (rows - 1) * 4 + 13 * tension * envelope) * size+ pen.moveTo(*at(x, 2 * size))+ pen.lineTo(*at(x + math.copysign(opening * envelope, x or 1), y))+ stroke(pen, palette[1 % len(palette)], 1.0, alpha * 0.62, s.dark)+ for pigment, colour in enumerate(palette):+ pen.beginPath()+ for row in range(rows):+ if row % len(palette) != pigment:+ continue+ def yarn(x):+ envelope = max(0, 1 - (x / span) ** 2)+ lift = (10 + level * 5) * tension * envelope * size+ split = opening * envelope * (1 if row % 2 else -0.12)+ return max(2 * size, 7 * size + row * 4 * size + lift + split)+ pen.moveTo(*at(-span, yarn(-span)))+ step = 2 * span / samples+ for j in range(samples):+ a, b = -span + j * step, -span + (j + 1) * step+ # One cubic per half weave replaces a polyline's dense sampled geometry.+ weave = (3 if level < 2 else 7) * (1 - 0.65 * tension) * size * (-1 if (j + row) % 2 else 1)+ c1, c2 = a + step / 3, b - step / 3+ pen.bezierCurveTo(*at(c1, max(2, yarn(c1) + weave)),+ *at(c2, max(2, yarn(c2) + weave)), *at(b, yarn(b)))+ stroke(pen, colour, 1.8 if level == 0 else 1.6, alpha, s.dark)+ if level:+ # Short overpasses hide the warp at alternating crossings, making an actual weave.+ pen.beginPath()+ for i in range(-4, 5):+ x = i * 14+ envelope = max(0, 1 - (x / span) ** 2)+ y = (9 + (10 + level * 5) * tension * envelope) * size + opening * envelope+ pen.moveTo(*at(x - 2, y - size))+ pen.lineTo(*at(x + 2, y + size))+ stroke(pen, palette[-1], 2.1, alpha * 0.85, s.dark)+++def _make(id_, name, level, blurb):+ return Effect(id_, name, ("quiet", "medium", "showpiece")[level], blurb,+ lambda pen, s: _cloth(pen, s, level, True),+ lambda pen, s: _cloth(pen, s, level, False),+ (0.48, 0.64, 0.78)[level], (0.48, 0.64, 0.78)[level])+++EFFECTS = [+ _make("thread", "Thread", 0, "Two fine yarns tighten, part for the pointer and stitch the seam closed behind it."),+ _make("weave", "Weave", 1, "A woven border gathers tension, opens between its strands and gently mends on arrival."),+ _make("jacquard", "Jacquard", 2, "A diamond-patterned textile tightens across the edge, opens its weave and settles behind you."),+]++PACKS = {+ "flax": ("Flax", ["#cfb885", "#8a9c84", "#efdfb8"]),+ "madder": ("Madder", ["#c45b68", "#873d57", "#e5b09b"]),+ "tide": ("Tide", ["#58a9a3", "#547498", "#b1d1c1"]),+}diff --git a/core/keytable.py b/core/keytable.pyindex 732408e..1b3b93e 100644--- a/core/keytable.py+++ b/core/keytable.py@@ -8,7 +8,7 @@ from typing import Mapping, Optional, UnionMAC_PLATFORMS = frozenset({"macos", "ios"})-STYLES = ("semantic", "positional")+STYLES = ("semantic", "positional", "mac_layout")# Across families, Semantic: the everyday shortcuts line up (Command-C arrives as Control-C).# 1.4.x's DEFAULT_KEY_MAP on the Mac and the Windows capture names on Windows.@@ -16,12 +16,19 @@ _MAC_SEMANTIC = {"ctrl": "cmd", "ctrl_r": "cmd", "cmd": "ctrl", "cmd_r": "ctrl",_MAC_POSITIONAL = {"ctrl": "ctrl", "ctrl_r": "ctrl", "cmd": "cmd", "cmd_r": "cmd", "alt": "alt", "alt_r": "alt"}_PC_SEMANTIC = {"ctrl": "cmd", "ctrl_r": "cmd_r", "cmd": "ctrl", "cmd_r": "ctrl_r"}_PC_POSITIONAL: dict = {}+_PC_MAC_LAYOUT = {+ "ctrl": "ctrl", "ctrl_r": "ctrl_r",+ "cmd": "alt", "cmd_r": "alt_r",+ "alt": "cmd", "alt_r": "cmd_r",+}_ACROSS = {(True, "semantic"): _MAC_SEMANTIC,(True, "positional"): _MAC_POSITIONAL,+ (True, "mac_layout"): _MAC_SEMANTIC,(False, "semantic"): _PC_SEMANTIC,(False, "positional"): _PC_POSITIONAL,+ (False, "mac_layout"): _PC_MAC_LAYOUT,}diff --git a/core/owner.py b/core/owner.pyindex 94157b1..affb952 100644--- a/core/owner.py+++ b/core/owner.py@@ -320,6 +320,10 @@ class Owner:pressed[ident] = _release(message)elif kind in _UPS:pressed.pop(ident, None)+ if kind == "text" and message.pop("_bracket_modifiers", False):+ message = dict(message, _pressed_keys=[+ dict(release["data"]) for (key_kind, _key), release in pressed.items() if key_kind == "key"+ ])return [Send(self.on, message)]def _replay_held(self):diff --git a/core/receiver.py b/core/receiver.pyindex 3ce4742..0636ff2 100644--- a/core/receiver.py+++ b/core/receiver.py@@ -1044,7 +1044,8 @@ class LinkResponder:return Trueoffset = corner_offset(model.corner, model.edge) if isinstance(model, crossing.CornerPush) else outcome.offsetself._disarm_locked()- LOGGER.info("The pointer pushed through a zone here; asking %s to move its input on", link.name)+ LOGGER.info("The pointer pushed through the zone at this machine's %s edge; asking %s to move its input on",+ model.edge, link.name)link.post(protocol.switch_v6(link.route, peer, outcome.edge, offset))after.append(lambda: self._callback("pressure", model.edge, 1.0, True, part))return True@@ -1344,6 +1345,7 @@ class LinkResponder:if focus["edge"] is not None:x, y = crossing.arrival_position(desktop.monitors(), focus["edge"], focus["offset"])desktop.set_cursor_position(x, y)+ LOGGER.info("%s's pointer arrived at this machine's %s edge", link.name, focus["edge"])self._callback("arrival", focus["edge"], x, y)else:x, y = desktop.cursor_position()diff --git a/core/settings_sync.py b/core/settings_sync.pyindex 9fbe175..1e50da9 100644--- a/core/settings_sync.py+++ b/core/settings_sync.py@@ -38,7 +38,7 @@ LENGTHS = tuple(value for value, _name in effects.LENGTHS)NOT_TRIGGERS = ("browser_back", "browser_forward", "backspace", "tab", "enter", "esc", "space", "print_screen")CROSSING_KEYS = ("resistance_px", "block_while_dragging", "shortcut", "trigger_key", "trigger_style", "double_tap_ms")-DESIGN_KEYS = ("glow_style", "glow_colour", "effect_length", "shortcut_arrival", "shortcut_arrival_style")+DESIGN_KEYS = ("glow_style", "glow_colour", "effect_length", "effect_size", "shortcut_arrival", "shortcut_arrival_style")MAX_STAMP = 2 ** 53 - 2DAY = 24 * 60 * 60@@ -49,6 +49,7 @@ PC_FIELDS = {"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",+ "effect_size": "effect_size","shortcut_arrival": "shortcut_arrival", "shortcut_arrival_style": "shortcut_arrival_style",}# The Mac keeps the shortcut's key at the top of its settings and the rest in `crossing`.@@ -76,30 +77,99 @@ def _valid(key, value, trigger_keys):return value in GLOW_COLOURSif key == "effect_length":return value in LENGTHS+ if key == "effect_size":+ return value in tuple(size for size, _name in effects.SIZES)if key == "shortcut_arrival_style":return value in effects.SWITCH_STYLESreturn False-def message_data(on, set_at, values=None, by=""):+def message_data(on, set_at, values=None, by="", design_state=None):"""What a `settings` message carries: whether it is on, when that or a shared value lastchanged and by which machine (`by`, its id as base64), and while on, the values."""data = {"on": bool(on), "set_at": int(set_at), "by": by}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}+ if design_state is not None:+ data["design_sync"] = design_statereturn data-def read(data, trigger_keys):+def read_design_state(data, trigger_keys, now=None):+ """A directly advertised local Design state from a settings message, or None if absent or+ invalid. Each supported value stands alone, as for Same on all machines. The outer settings+ envelope is validated first, so a valid optional member cannot rescue a malformed message."""+ if not _valid_envelope(data, now):+ return None+ state = data.get("design_sync")+ if not isinstance(state, dict) or type(state.get("set_at")) is not int:+ return None+ by = state.get("by", "")+ if _id(by) is None:+ return None+ set_at = state["set_at"]+ if set_at < 0 or set_at > MAX_STAMP or set_at > (time.time() if now is None else now) + DAY:+ return None+ values = state.get("values")+ if not isinstance(values, dict):+ return None+ accepted = {key: values[key] for key in DESIGN_KEYS+ if key in values and _valid(key, values[key], trigger_keys)}+ if "effect_size" not in values:+ accepted["effect_size"] = "medium"+ return {"set_at": set_at, "by": by, "values": accepted}+++def design_arrived(state, set_at_here, by_here=""):+ """Whether a validated Design state is newer than the one this machine currently holds."""+ if not isinstance(state, dict):+ return False+ by = _id(state.get("by", ""))+ if by is None:+ return False+ held_by = _id(by_here) or b""+ set_at = state.get("set_at")+ return type(set_at) is int and (set_at > int(set_at_here or 0) or+ (set_at == int(set_at_here or 0) and by > held_by))+++def followed_design(current, state, source, follower, same_on, set_at_here, by_here):+ """A newer direct state to apply locally, or None. Its stamp remains the leader's so every+ follower in a chain carries the same newest state; identical values need no announcement."""+ if (state is None or source != follower or same_on+ or not design_arrived(state, set_at_here, by_here)):+ return None+ values = dict(current)+ for key in DESIGN_KEYS:+ if key in state["values"]:+ values[key] = state["values"][key]+ changed = any(current.get(key) != values.get(key) for key in DESIGN_KEYS)+ if not changed:+ return {"changed": False, "values": values, "set_at": state["set_at"], "by": state["by"]}+ return {"changed": True, "values": values, "set_at": state["set_at"], "by": state["by"]}+++def design_change_stamp(current, incoming, set_at_here, source_state, own_id, now=None):+ """A Same-on Design change announced as this machine's direct state, or None if unchanged."""+ if not isinstance(current, dict) or not isinstance(incoming, dict):+ return None+ if not any(current.get(key) != incoming.get(key) for key in DESIGN_KEYS):+ return None+ held = int(set_at_here or 0)+ if isinstance(source_state, dict) and type(source_state.get("set_at")) is int:+ held = max(held, source_state["set_at"])+ stamp = next_stamp(held, time.time() if now is None else now)+ return {"set_at": stamp, "by": own_id}+++def read(data, trigger_keys, now=None):"""(on, set_at, values) from a `settings` message's data, or None when it is not one. A valuethis end cannot hold -- a key it does not have, an effect it does not know, a zone -- is leftout 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 type(set_at) is not int:+ if not _valid_envelope(data, now):return None+ set_at = data["set_at"]values = {}for group, keys in (("crossing", CROSSING_KEYS), ("design", DESIGN_KEYS)):section = data.get(group)@@ -130,6 +200,16 @@ def _id(text):return ident if len(ident) == MACHINE_ID_SIZE else None+def _valid_envelope(data, now=None):+ if not isinstance(data, dict) or not isinstance(data.get("on"), bool):+ return False+ set_at = data.get("set_at")+ if type(set_at) is not int or _id(data.get("by", "")) is None:+ return False+ return (0 <= set_at <= MAX_STAMP+ and set_at <= (time.time() if now is None else now) + DAY)++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@@ -145,7 +225,7 @@ def arrived(data, set_at_here, trigger_keys, by_here="", now=None):Newer is a higher stamp, or the same stamp and the larger `by` as bytes; `by_here` is the idthat made the change this end holds. Equal in both is the copy that arrives over a secondlink, and changes nothing, so a state sent on never comes back round."""- read_back = read(data, trigger_keys)+ read_back = read(data, trigger_keys, now)by = _id(data.get("by", "")) if read_back is not None else Noneif read_back is None or by is None:return None@@ -181,6 +261,7 @@ def mac_values(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 if key != "shortcut"}+ values["effect_size"] = crossing.get("effect_size", "medium")values["shortcut"] = "shortcut" in crossing.get("methods", [])return _in_order(values)@@ -204,6 +285,7 @@ def apply_mac(raw, values):def pc_values(config):"""The shared values in the PC's Config."""values = {key: getattr(config, field) for key, field in PC_FIELDS.items()}+ values["effect_size"] = getattr(config, "effect_size", "medium")values["shortcut"] = "shortcut" in config.crossing_methodsreturn _in_order(values)diff --git a/core/tests/render_effect_sets.py b/core/tests/render_effect_sets.pynew file mode 100644index 0000000..19763ad--- /dev/null+++ b/core/tests/render_effect_sets.py@@ -0,0 +1,254 @@+"""Offscreen judging sequences and native frame timings; never constructs an app window.++Run with the Mac venv and --output PATH for renders, or either platform's venv and --benchmark.+"""++import argparse+import json+import statistics+import sys+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / ("mac_app" if sys.platform == "darwin" else "win_app")))++from core import effects++NEW_IDS = ("aperture", "crease", "pleat", "concertina", "thread", "weave", "jacquard")+++class Bitmap:+ def __init__(self, width, height, scale=1):+ self.width, self.height = width, height+ if sys.platform == "darwin":+ import Quartz as cg+ from effects_overlay import replay+ self.cg, self.replay = cg, replay+ self.data = bytearray(width * height * 4)+ self.ctx = cg.CGBitmapContextCreate(self.data, width, height, 8, width * 4,+ cg.CGColorSpaceCreateWithName(cg.kCGColorSpaceSRGB),+ cg.kCGImageAlphaPremultipliedLast | cg.kCGBitmapByteOrder32Big)+ cg.CGContextTranslateCTM(self.ctx, 0, height)+ cg.CGContextScaleCTM(self.ctx, scale, -scale)+ else:+ from PySide6.QtGui import QImage, QPainter+ from effect_overlay import replay+ self.replay = replay+ self.image = QImage(width, height, QImage.Format.Format_RGBA8888_Premultiplied)+ self.painter = QPainter(self.image)+ self.painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ self.painter.scale(scale, scale)++ def clear(self, dark):+ rgb = (0.065, 0.075, 0.09) if dark else (0.93, 0.92, 0.89)+ if sys.platform == "darwin":+ self.cg.CGContextSetRGBFillColor(self.ctx, *rgb, 1)+ self.cg.CGContextFillRect(self.ctx, ((-4000, -4000), (8000, 8000)))+ else:+ from PySide6.QtGui import QColor+ self.painter.fillRect(-4000, -4000, 8000, 8000, QColor.fromRgbF(*rgb))++ def draw(self, pens):+ if sys.platform == "darwin":+ self.replay(self.cg, self.ctx, pens)+ else:+ self.replay(self.painter, pens)++ def pil(self):+ from PIL import Image+ if sys.platform == "darwin":+ return Image.frombytes("RGBA", (self.width, self.height), bytes(self.data)).convert("RGB")+ return Image.frombytes("RGBA", (self.width, self.height), bytes(self.image.bits())).convert("RGB")++ def close(self):+ if sys.platform != "darwin":+ self.painter.end()+++def catalogue():+ from tokens import PALETTES+ yield "light", tuple(effects.CLASSIC), ("signal", "Signal", PALETTES["signal"])+ for _module, name, ids, packs in effects.DIRECTIONS:+ pack_name, palette = effects.pack(packs[0])+ yield name.lower(), ids, (packs[0], pack_name, palette)+++def preview(fx, t, palette, dark, method="edge"):+ scene = (effects.preview_switch_scene(fx, max(0, t - 1.85), palette, dark=dark) if method == "switch"+ else effects.preview_scene(fx, t, method, palette, dark=dark))+ width, height = effects.preview_size(method)+ bitmap = Bitmap(round(width * 0.6), round(height * 0.6), 0.6)+ bitmap.clear(dark)+ if method != "switch":+ # Display boundaries belong to the judging scene, never to the effect itself.+ pen = effects.Pen()+ pen.fillStyle = "#030406" if dark else "#d0cec8"+ if method == "notch":+ pen.fillRect(0, 450, 800, 40)+ else:+ pen.fillRect(800, 0, 40, 450)+ bitmap.draw([pen])+ for pen in scene["pens"]:+ def overlap(screen):+ x, y, w, h, _os = screen+ a, b, c, d = pen.bounds+ return max(0, min(c, x + w) - max(a, x)) * max(0, min(d, y + h) - max(b, y))+ x, y, w, h, _os = max(scene["screens"], key=overlap)+ pen.clip = (x, y, x + w, y + h)+ bitmap.draw(scene["pens"])+ if scene["notch"]:+ pen = effects.Pen()+ pen.fillStyle = "#000000"+ effects.round_rect(pen, *scene["notch"])+ pen.fill()+ bitmap.draw([pen])+ pointer = scene["pointer"]+ if pointer:+ x, y, _os = pointer+ pen = effects.Pen()+ pen.fillStyle = "#f7f5ef" if dark else "#24262c"+ pen.beginPath()+ pen.moveTo(x, y)+ pen.lineTo(x + 5, y + 16)+ pen.lineTo(x + 8, y + 10)+ pen.lineTo(x + 15, y + 8)+ pen.closePath()+ pen.fill()+ bitmap.draw([pen])+ result = bitmap.pil()+ bitmap.close()+ return result+++def render(output):+ from PIL import Image, ImageDraw, ImageFont+ output.mkdir(parents=True, exist_ok=True)+ font = ImageFont.truetype(str(ROOT / "win_app/assets/HankenGrotesk-Variable.ttf"), 17)+ times = (0.92, 1.35, 1.78, 2.18, 2.27, 2.44, 2.7)+ stages = ("Push · 10%", "Push · 45%", "Push · 85%", "Threshold", "Give", "Arrival", "Settle")+ total = 0+ for direction, ids, (_pack_id, pack_name, palette) in catalogue():+ for effect_id in ids:+ fx = effects.preview_effect(effect_id)+ for dark, method in ((dark, method) for dark in (True, False)+ for method in (("edge", "corner", "notch", "switch")+ if effect_id in NEW_IDS else ("edge",))):+ mode = "dark" if dark else "light"+ suffix = "" if method == "edge" else f"-{method}"+ stem = f"{direction}-{effect_id}-{mode}{suffix}"+ background, foreground = ("#101318", "#e5e8ef") if dark else ("#eeebe3", "#26272c")+ frames = []+ for i in range(56):+ t = 0.7 + i * 0.05+ picture = preview(fx, t, palette, dark, method)+ frame = Image.new("RGB", (picture.width, picture.height + 42), background)+ frame.paste(picture, (0, 42))+ label = f"{direction.title()} / {fx.name} · {method.title()} · {pack_name}"+ ImageDraw.Draw(frame).text((16, 10), label, font=font, fill=foreground)+ frames.append(frame)+ frames[0].save(output / f"{stem}.gif", save_all=True, append_images=frames[1:],+ duration=50, loop=0, disposal=2)+ strip = Image.new("RGB", (336 * len(times), 256), background)+ draw = ImageDraw.Draw(strip)+ for i, (t, stage) in enumerate(zip(times, stages)):+ # A crop around the crossing keeps quiet effects readable at their true scale.+ box = {"edge": (324, 24, 660, 240), "corner": (324, 0, 660, 216),+ "notch": (72, 180, 408, 396), "switch": (72, 0, 408, 216)}[method]+ crop = preview(fx, t, palette, dark, method).crop(box)+ strip.paste(crop, (336 * i, 40))+ label = stage if method != "switch" else ("Waiting" if t < 2.2 else stage)+ draw.text((336 * i + 12, 10), label, font=font, fill=foreground)+ strip.save(output / f"{stem}-strip.png")+ total += 2+ print(f"Rendered {total} files to {output}")+ judging_index(output)+++def judging_index(output):+ from html import escape+ parts = ['''<!doctype html><html lang="en-GB"><meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Beamer crossing effects</title><style>+body{margin:0 auto;padding:36px 24px;max-width:1500px;background:#17191c;color:#ede9df;+font:16px/1.5 system-ui,sans-serif}h1{font-size:32px}h2{margin:48px 0 8px}h3{margin:28px 0 4px}+p{max-width:75ch;color:#c0bbae}a{color:#d0c299}figure{margin:0}img{width:100%;display:block}+.pair{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}figcaption{padding:8px 0}+details{margin:12px 0}summary{cursor:pointer}.packs{display:flex;gap:24px;flex-wrap:wrap}+.swatch{display:inline-block;width:22px;height:22px;vertical-align:middle;margin-right:3px}+@media(max-width:700px){.pair{grid-template-columns:1fr}}+</style><h1>Beamer crossing effects</h1>+<p>Offscreen native renders. Light, Folio and Selvedge come first; the existing directions follow+for comparison. Each loop shows pressure building, breakthrough and arrival.</p>''']+ entries = list(catalogue())+ entries.sort(key=lambda row: (row[0] not in ("light", "folio", "selvedge"),+ {"light": 0, "folio": 1, "selvedge": 2}.get(row[0], 3)))+ for direction, ids, (_pack, _name, _palette) in entries:+ parts.append(f"<h2>{escape(direction.title())}</h2>")+ packs = next((row[3] for row in effects.DIRECTIONS if row[1].lower() == direction), ())+ parts.append('<div class="packs">')+ for pack_id in packs:+ name, colours = effects.pack(pack_id)+ swatches = ''.join(f'<span class="swatch" style="background:{c}"></span>' for c in colours)+ parts.append(f'<span>{swatches} {escape(name)}</span>')+ parts.append('</div>')+ for effect_id in ids:+ fx = effects.preview_effect(effect_id)+ parts.append(f'<h3>{escape(fx.name)} · {escape(fx.intensity.title())}</h3><p>{escape(fx.blurb)}</p>')+ methods = ("edge", "corner", "notch", "switch") if effect_id in NEW_IDS else ("edge",)+ for method in methods:+ if method != "edge":+ parts.append(f'<details><summary>{method.title()}</summary>')+ parts.append('<div class="pair">')+ for mode in ("dark", "light"):+ suffix = '' if method == 'edge' else f'-{method}'+ stem = f'{direction}-{effect_id}-{mode}{suffix}'+ parts.append(f'<figure><img loading="lazy" src="{stem}.gif" alt="{escape(fx.name)} on {mode} wallpaper">'+ f'<figcaption>{mode.title()} · <a href="{stem}-strip.png">Frame strip</a></figcaption></figure>')+ parts.append('</div>')+ if method != "edge":+ parts.append('</details>')+ parts.append('</html>')+ (output / 'index.html').write_text('\n'.join(parts), encoding='utf-8')+++def benchmark():+ results = []+ for effect_id in NEW_IDS:+ fx = effects.preview_effect(effect_id)+ palette = effects.pack("marbled" if effect_id in ("crease", "pleat", "concertina") else "tide")[1]+ generation, native = [], []+ bitmap = Bitmap(3280, 900, 2)+ for i in range(180):+ dark = bool(i % 2)+ t = 1.1 + (i % 90) * 0.025+ start = time.perf_counter()+ scene = effects.preview_scene(fx, t, "edge", palette, dark=dark)+ recorded = time.perf_counter()+ bitmap.clear(dark)+ bitmap.draw(scene["pens"])+ ended = time.perf_counter()+ if i >= 20:+ generation.append((recorded - start) * 1000)+ native.append((ended - start) * 1000)+ bitmap.close()+ def p95(values):+ return round(sorted(values)[int(len(values) * 0.95)], 3)+ results.append(dict(effect=effect_id, record_p95_ms=p95(generation),+ total_p95_ms=p95(native), total_median_ms=round(statistics.median(native), 3)))+ print(json.dumps(dict(platform=sys.platform, scale=2, budget_record_ms=2, budget_total_ms=8,+ frames_per_effect=160, results=results), indent=2))+ if any(row["record_p95_ms"] >= 2 or row["total_p95_ms"] >= 8 for row in results):+ raise SystemExit("Frame budget exceeded")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path)+ parser.add_argument("--benchmark", action="store_true")+ args = parser.parse_args()+ if args.output:+ render(args.output)+ if args.benchmark:+ benchmark()diff --git a/core/tests/run_effect_checks.py b/core/tests/run_effect_checks.pynew file mode 100644index 0000000..861bd67--- /dev/null+++ b/core/tests/run_effect_checks.py@@ -0,0 +1,53 @@+"""Run the effects checks with synthetic settings confined to this checkout.++Mac: touched modules only. Windows: the complete Windows suite and the new core contracts.+"""++import argparse+import os+from pathlib import Path+import sys+import tempfile+import unittest++ROOT = Path(__file__).resolve().parents[2]+parser = argparse.ArgumentParser(description=__doc__)+parser.add_argument("--touched", action="store_true", help="Rerun affected Windows modules after the full suite")+args = parser.parse_args()+scratch = ROOT / ".test-tmp"+scratch.mkdir(exist_ok=True)+tempfile.tempdir = str(scratch)+os.environ["QT_QPA_PLATFORM"] = "offscreen"+if sys.platform == "win32":+ os.environ["LOCALAPPDATA"] = str(scratch / "local")+++def synthetic_settings_only(event, args):+ if event != "open" or not isinstance(args[0], (str, bytes, os.PathLike)):+ return+ path = Path(os.fsdecode(args[0])).resolve()+ if path.name.lower() in ("settings.json", "config.json") and not path.is_relative_to(ROOT):+ raise PermissionError("Tests may only open synthetic settings within their worktree")+++sys.addaudithook(synthetic_settings_only)+sys.path.insert(0, str(ROOT))+app = ROOT / ("mac_app" if sys.platform == "darwin" else "win_app")+sys.path.insert(0, str(app))+sys.path.insert(0, str(app / "tests"))+loader = unittest.TestLoader()+suite = unittest.TestSuite()+suite.addTests(loader.loadTestsFromNames(["core.tests.test_effect_sets", "core.tests.test_settings_sync"]))+if sys.platform == "darwin":+ suite.addTests(loader.loadTestsFromNames([+ "test_pages", "test_settings_store", "test_effect_layouts", "test_previews", "test_effects_overlay",+ ]))+elif args.touched:+ suite.addTests(loader.loadTestsFromNames([+ "test_pages_win", "test_app_config", "test_settings_migration", "test_same_on_both",+ "test_effect_layouts", "test_effect_overlay", "test_effect_fires",+ ]))+else:+ suite.addTests(loader.discover(str(app / "tests")))+result = unittest.TextTestRunner(verbosity=1).run(suite)+raise SystemExit(not result.wasSuccessful())diff --git a/core/tests/test_effect_sets.py b/core/tests/test_effect_sets.pynew file mode 100644index 0000000..1ead1db--- /dev/null+++ b/core/tests/test_effect_sets.py@@ -0,0 +1,321 @@+"""Pure-core contracts for the Light, Folio and Selvedge effect sets."""++import colorsys+import math+import statistics+import time+import unittest+from types import SimpleNamespace++from core import effects+++IDS = ("aperture", "crease", "pleat", "concertina", "thread", "weave", "jacquard")+PALETTES = {+ "crease": "vellum",+ "pleat": "carbon_copy",+ "concertina": "marbled",+ "thread": "flax",+ "weave": "madder",+ "jacquard": "tide",+}+W, H = 1200.0, 800.0+NOTCH = {"x": 500.0, "y": 0.0, "w": 200.0, "h": 32.0, "r": 10.0}+++def palette_for(effect_id, dark):+ pack_id = PALETTES.get(effect_id)+ raw = effects.pack(pack_id) if pack_id else None+ if raw is None: # Aperture uses the caller's shared spectrum palette.+ raw = ("Spectrum", ["#58c8f0", "#a673ec", "#f05e8a"])+ return effects.legible(raw[1], dark, effects.effect(effect_id))+++def edge_departure(edge, along, pressure, *, reduced=False, dark=True, tick=None, since=None, effect_size="medium"):+ if edge in ("left", "right"):+ x, y = (0.0 if edge == "left" else W - 1.0), H * along+ region = {"kind": "edge", "edge": edge, "x": x, "y": 0.0, "w": 1.0, "h": H}+ else:+ x, y = W * along, (0.0 if edge == "top" else H - 1.0)+ region = {"kind": "edge", "edge": edge, "x": 0.0, "y": y, "w": W, "h": 1.0}+ return effects.state(W, H, "mac", "edge", [], reduced=reduced, dark=dark, effect_size=effect_size,+ region=SimpleNamespace(**region), point=effects.point(x, y), along=along,+ pressure=pressure, tick=tick, since=since)+++def corner_departure(corner, pressure, *, reduced=False, dark=True, tick=None, since=None):+ vertical, horizontal = corner.split("_")+ x, y = (0.0 if horizontal == "left" else W - 1.0), (0.0 if vertical == "top" else H - 1.0)+ region = {"kind": "corner", "edge": horizontal, "corner": corner, "x": x, "y": y, "w": 8.0, "h": 8.0}+ return effects.state(W, H, "mac", "corner", [], reduced=reduced, dark=dark,+ region=SimpleNamespace(**region), point=effects.point(x, y), along=0.5,+ pressure=pressure, tick=tick, since=since)+++def notch_departure(pressure=0.8, *, reduced=False, dark=True):+ region = {"kind": "notch", "edge": "top", "x": NOTCH["x"], "y": 0.0,+ "w": NOTCH["w"], "h": 1.0}+ return effects.state(W, H, "mac", "notch", [], notch=NOTCH, reduced=reduced, dark=dark,+ region=SimpleNamespace(**region),+ point=effects.point(NOTCH["x"] + NOTCH["w"] / 2.0, 0.0), along=0.5,+ pressure=pressure, tick=None, since=None)+++def arrival(edge, x, y, *, notch=True, reduced=False, dark=True, since=0.18, method="edge"):+ return effects.state(W, H, "mac", method, [], reduced=reduced, dark=dark,+ notch=NOTCH if notch else None, point=effects.point(x, y), edge=edge, since=since)+++def coords_and_segment_count(pen):+ count = 0+ for op in pen.ops:+ if op[0] not in ("fill", "stroke"):+ raise AssertionError(f"unsupported drawing operation: {op[0]!r}")+ if isinstance(op[2], effects.Gradient):+ if not all(math.isfinite(value) for value in op[2].geometry):+ raise AssertionError(f"non-finite gradient geometry: {op[2].geometry!r}")+ for segment in op[1]:+ count += 1+ if segment[0] not in ("M", "L", "Q", "C", "Z"):+ raise AssertionError(f"unsupported path command: {segment[0]!r}")+ for value in segment[1:]:+ if not math.isfinite(value):+ raise AssertionError(f"non-finite path coordinate: {segment!r}")+ return count+++def assert_bounded_frame(test, pen):+ test.assertLessEqual(len(pen.ops), 100)+ test.assertLessEqual(coords_and_segment_count(pen), 3000)+ if pen.bounds:+ test.assertTrue(all(math.isfinite(value) for value in pen.bounds))+ test.assertLess(pen.bounds[0], pen.bounds[2])+ test.assertLess(pen.bounds[1], pen.bounds[3])+++def benchmark_frame_generation(samples=300):+ """Return median and p95 milliseconds for a representative Folio frame; opt-in diagnostic."""+ fx = effects.effect("concertina")+ s = corner_departure("top_right", 0.8)+ palette = palette_for(fx.id, True)+ timings = []+ for _ in range(samples):+ s.palette = palette+ start = time.perf_counter_ns()+ effects.draw(fx, "depart", s)+ timings.append((time.perf_counter_ns() - start) / 1_000_000)+ ordered = sorted(timings)+ return {"median_ms": statistics.median(timings), "p95_ms": ordered[int(0.95 * (len(ordered) - 1))]}+++class EffectSetRegistryTests(unittest.TestCase):+ def test_new_effects_are_recognised_and_hidden_ids_stay_hidden(self):+ self.assertTrue(set(IDS) <= set(effects.EFFECT_IDS))+ for effect_id in IDS:+ with self.subTest(effect=effect_id):+ self.assertIsNotNone(effects.effect(effect_id))+ hidden_ids = {effect_id for module, _name, ids, _packs in effects.ALL_DIRECTIONS+ if module in effects.HIDDEN for effect_id in ids}+ hidden_packs = {pack_id for module, _name, _ids, packs in effects.ALL_DIRECTIONS+ if module in effects.HIDDEN for pack_id in packs}+ self.assertTrue(hidden_ids.isdisjoint(effects.EFFECT_IDS))+ self.assertTrue(hidden_packs.isdisjoint(effects.PACK_IDS))++ def test_each_new_pack_is_offered_and_legible_for_both_wallpaper_modes(self):+ for pack_id in effects.PACK_IDS:+ with self.subTest(pack=pack_id):+ self.assertIsNotNone(effects.pack(pack_id))+ for effect_id, pack_id in PALETTES.items():+ with self.subTest(effect=effect_id, pack=pack_id):+ packed = effects.pack(pack_id)+ self.assertIsNotNone(packed)+ self.assertEqual(len(packed[1]), 3)+ for dark in (False, True):+ colours = effects.legible(packed[1], dark, effects.effect(effect_id))+ self.assertEqual(len(colours), len(packed[1]))+ self.assertTrue(all(len(effects.parse_colour(c)) == 4 for c in colours))+ for colour in colours:+ lightness = colorsys.rgb_to_hls(*effects.parse_colour(colour)[:3])[1]+ if dark:+ self.assertGreaterEqual(lightness, effects.DARK_FLOOR - 1 / 255)+ else:+ self.assertLessEqual(lightness, effects.LIGHT_CEILING + 1 / 255)+++class EffectFrameContracts(unittest.TestCase):+ def draw_departure(self, effect_id, s):+ s.palette = palette_for(effect_id, s.dark)+ return effects.draw(effects.effect(effect_id), "depart", s)++ def draw_arrival(self, effect_id, s):+ s.palette = palette_for(effect_id, s.dark)+ return effects.draw(effects.effect(effect_id), "arrive", s)++ def test_full_phase_grid_in_both_wallpapers_and_motion_modes(self):+ for effect_id in IDS:+ for dark in (False, True):+ for reduced in (False, True):+ cases = [edge_departure(edge, along, 0.5, dark=dark, reduced=reduced)+ for edge in ("left", "right", "top", "bottom") for along in (0, 0.5, 1)]+ cases.extend(corner_departure(corner, 0.5, dark=dark, reduced=reduced)+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"))+ cases.append(notch_departure(dark=dark, reduced=reduced))+ for s in cases:+ for pressure in (0, 0.01, 0.25, 0.5, 0.75, 1):+ s.pressure = pressure+ pen = self.draw_departure(effect_id, s)+ if pressure:+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)+ else:+ self.assertIsNone(pen)+ for since in (0, 0.08, 0.25, 0.55, 0.79):+ s.since = since+ pen = self.draw_departure(effect_id, s)+ if since < effects.effect(effect_id).depart_seconds:+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)+ incoming = arrival(s.region.edge, s.point.x, s.point.y,+ notch=s.region.kind == "notch", reduced=reduced,+ dark=dark, since=since, method=s.method)+ pen = self.draw_arrival(effect_id, incoming)+ if since < effects.effect(effect_id).arrive_seconds:+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)++ def test_selected_size_scales_every_new_crossing_effect(self):+ for effect_id in IDS:+ bounds = []+ for size in ("small", "large"):+ pen = self.draw_departure(effect_id, edge_departure("right", 0.5, 1.0, effect_size=size))+ self.assertIsNotNone(pen)+ bounds.append(pen.bounds)+ with self.subTest(effect=effect_id):+ self.assertLess(bounds[1][0], bounds[0][0])++ def test_switch_preview_uses_the_selected_size_for_every_new_effect(self):+ for effect_id in IDS:+ bounds = []+ for size in ("small", "large"):+ scene = effects.preview_switch_scene(effects.effect(effect_id), 0.55, palette_for(effect_id, True),+ effect_size=size)+ self.assertEqual(len(scene["pens"]), 1)+ bounds.append(scene["pens"][0].bounds)+ with self.subTest(effect=effect_id):+ self.assertGreater(bounds[1][3] - bounds[1][1], bounds[0][3] - bounds[0][1])++ def test_crossing_preview_arrival_uses_the_selected_size_for_every_new_effect(self):+ for effect_id in IDS:+ bounds = []+ for size in ("small", "large"):+ scene = effects.preview_scene(effects.effect(effect_id), 2.3, "edge", palette_for(effect_id, True),+ effect_size=size)+ self.assertEqual(len(scene["pens"]), 2)+ bounds.append(scene["pens"][-1].bounds)+ with self.subTest(effect=effect_id):+ self.assertGreater(bounds[1][2] - bounds[1][0], bounds[0][2] - bounds[0][0])++ def test_pressure_grid_draws_bounded_frames_on_each_edge_and_along_position(self):+ for effect_id in IDS:+ for edge in ("left", "right", "top", "bottom"):+ for along in (0.0, 0.5, 1.0):+ for pressure in (0.0, 0.01, 0.25, 0.5, 0.75, 1.0):+ with self.subTest(effect=effect_id, edge=edge, along=along, pressure=pressure):+ pen = self.draw_departure(effect_id, edge_departure(edge, along, pressure))+ if pressure == 0.0:+ self.assertIsNone(pen)+ elif pen is not None:+ assert_bounded_frame(self, pen)++ def test_tick_departures_and_all_corners_draw_bounded_frames(self):+ tick = SimpleNamespace(index=2, age=0.04)+ for effect_id in IDS:+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):+ for active_tick in (None, tick):+ with self.subTest(effect=effect_id, corner=corner, tick=active_tick is not None):+ pen = self.draw_departure(effect_id, corner_departure(corner, 0.75, tick=active_tick))+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)++ def test_notch_departure_and_arrival_with_or_without_hardware_notch(self):+ for effect_id in IDS:+ with self.subTest(effect=effect_id, kind="notch-depart"):+ pen = self.draw_departure(effect_id, notch_departure())+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)+ for present in (False, True):+ with self.subTest(effect=effect_id, kind="notch-arrive", present=present):+ s = arrival("top", 600.0, 2.0, notch=present)+ pen = self.draw_arrival(effect_id, s)+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)++ def test_reduced_motion_departures_draw_across_edges_corners_and_the_notch(self):+ for effect_id in IDS:+ cases = [edge_departure(edge, 0.5, 0.75, reduced=True)+ for edge in ("left", "right", "top", "bottom")]+ cases.extend(corner_departure(corner, 0.75, reduced=True)+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"))+ cases.append(notch_departure(reduced=True))+ for index, s in enumerate(cases):+ with self.subTest(effect=effect_id, case=index):+ pen = self.draw_departure(effect_id, s)+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)++ def test_edge_and_switch_arrivals_draw_in_light_and_dark_modes(self):+ cases = (("left", 2.0, 400.0), ("right", W - 2.0, 400.0),+ ("top", 300.0, 2.0), ("bottom", 300.0, H - 2.0))+ for effect_id in IDS:+ for dark in (False, True):+ for edge, x, y in cases:+ for reduced in (False, True):+ with self.subTest(effect=effect_id, dark=dark, edge=edge, reduced=reduced):+ pen = self.draw_arrival(effect_id, arrival(edge, x, y, dark=dark, reduced=reduced))+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)+ with self.subTest(effect=effect_id, dark=dark, method="switch"):+ pen = self.draw_arrival(effect_id, arrival("left", 600.0, 400.0, notch=False,+ dark=dark, method="switch"))+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)++ def test_switch_arrivals_near_each_corner_are_finite(self):+ for effect_id in IDS:+ for x, y in ((2.0, 2.0), (W - 2.0, 2.0), (2.0, H - 2.0), (W - 2.0, H - 2.0)):+ with self.subTest(effect=effect_id, point=(x, y)):+ s = arrival("left", x, y, notch=False, method="switch")+ pen = self.draw_arrival(effect_id, s)+ self.assertIsNotNone(pen)+ assert_bounded_frame(self, pen)++ def test_zero_pressure_and_expired_frames_are_silent(self):+ for effect_id in IDS:+ fx = effects.effect(effect_id)+ with self.subTest(effect=effect_id, phase="zero-pressure"):+ self.assertIsNone(self.draw_departure(effect_id, edge_departure("left", 0.5, 0.0)))+ for kind, duration, s in (+ ("depart", fx.depart_seconds, edge_departure("right", 0.5, 1.0, since=fx.depart_seconds + 0.1)),+ ("arrive", fx.arrive_seconds, arrival("top", 250.0, 2.0, since=fx.arrive_seconds + 0.1)),+ ):+ with self.subTest(effect=effect_id, phase=kind, duration=duration):+ s.palette = palette_for(effect_id, s.dark)+ self.assertIsNone(effects.draw(fx, kind, s))++ def test_reduced_motion_keeps_arrival_geometry_fixed_while_opacity_changes(self):+ for effect_id in IDS:+ for method, edge, x, y in (("edge", "left", 2.0, 400.0),+ ("switch", "left", 600.0, 400.0)):+ frames = []+ for since in (0.12, 0.32):+ s = arrival(edge, x, y, notch=False, reduced=True, since=since, method=method)+ pen = self.draw_arrival(effect_id, s)+ self.assertIsNotNone(pen)+ frames.append(pen)+ with self.subTest(effect=effect_id, method=method):+ self.assertEqual([op[1] for op in frames[0].ops], [op[1] for op in frames[1].ops])+ self.assertNotEqual([op[3] for op in frames[0].ops], [op[3] for op in frames[1].ops])+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_effect_size.py b/core/tests/test_effect_size.pynew file mode 100644index 0000000..20a558e--- /dev/null+++ b/core/tests/test_effect_size.py@@ -0,0 +1,53 @@+import unittest+from unittest import mock+from types import SimpleNamespace++from core import effects+++class EdgeDepthTests(unittest.TestCase):+ def test_each_size_scales_from_the_shorter_screen_side(self):+ expected = {+ "small": (29.46, 64.8),+ "medium": (44.19, 97.2),+ "large": (58.92, 129.6),+ }+ for size, (laptop, television) in expected.items():+ with self.subTest(size=size):+ self.assertAlmostEqual(effects.edge_depth(1512, 982, size), laptop)+ self.assertAlmostEqual(effects.edge_depth(3840, 2160, size), television)++ def test_small_displays_keep_a_usable_floor_and_large_displays_a_ceiling(self):+ self.assertEqual(effects.edge_depth(320, 240, "small"), 24.0)+ self.assertEqual(effects.edge_depth(16000, 9000, "large"), 144.0)++ def test_glow_and_beam_draw_the_selected_depth(self):+ expected = {"small": 29.46, "medium": 44.19, "large": 58.92}+ for size, depth in expected.items():+ with self.subTest(size=size):+ region = SimpleNamespace(kind="edge", edge="right", x=1511.0, y=0.0, w=1.0, h=982.0)+ for style in ("glow", "beam"):+ state = effects.state(1512, 982, "mac", "edge", ["#ffffff"], effect_size=size,+ region=region, point=effects.point(1511, 491), along=0.5,+ pressure=1.0, tick=None, since=None)+ pen = effects.draw(effects.CLASSIC[style], "depart", state)+ furthest_layer = max(abs(op[1][1][1] - op[1][0][1]) for op in pen.ops)+ self.assertAlmostEqual(furthest_layer, depth * (0.45 if style == "beam" else 1.0), places=5)++ def test_length_uses_the_new_paces(self):+ self.assertEqual([effects.pace(value) for value in ("short", "normal", "long")], [0.5, 1.0, 2.0])++ def test_live_player_passes_the_selected_size_to_edge_and_arrival_effects(self):+ player = effects.Player()+ player.effect_size = "large"+ player.push(0.0, "edge", {"kind": "edge", "edge": "right", "x": 1511.0, "y": 0.0,+ "w": 1.0, "h": 982.0}, (1511.0, 491.0), 0.8)+ player.arrive(0.0, "edge", (0.0, 491.0), "left")+ with mock.patch.object(effects, "state", wraps=effects.state) as make_state:+ player.frames(0.2, effects.effect("rupture"), (1512.0, 982.0, "windows"),+ ["#ffffff"], False, True)+ self.assertEqual([call.kwargs["effect_size"] for call in make_state.call_args_list], ["large", "large"])+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_keytable.py b/core/tests/test_keytable.pyindex aa8eda0..aab34df 100644--- a/core/tests/test_keytable.py+++ b/core/tests/test_keytable.py@@ -25,6 +25,11 @@ PC_ROWS = [("alt", "alt", "alt", "alt"),("alt_r", "alt_r", "alt_r", "alt_r"),]+PC_MAC_LAYOUT_ROWS = [+ ("ctrl", "ctrl"), ("ctrl_r", "ctrl_r"),+ ("cmd", "alt"), ("cmd_r", "alt_r"),+ ("alt", "cmd"), ("alt_r", "cmd_r"),+]# 1.4.x as it stands: the Mac's two key_map styles, and Windows' capture names (Ctrl is "cmd", the# Windows key is "ctrl") with POSITIONAL_SWAP on top.@@ -55,6 +60,14 @@ class TableTests(unittest.TestCase):self.assertEqual(keytable.wire_name(physical, own, peer, "semantic"), semantic, (own, peer, physical))self.assertEqual(keytable.wire_name(physical, own, peer, "positional"), positional, (own, peer, physical))+ def test_mac_layout_maps_each_pc_modifier_side_to_its_mac_key(self):+ for physical, expected in PC_MAC_LAYOUT_ROWS:+ self.assertEqual(keytable.wire_name(physical, "windows", "macos", "mac_layout"), expected)++ def test_mac_layout_leaves_non_modifier_keys_unchanged(self):+ for name in ("shift", "shift_r", "caps_lock", "a", "enter", "f13"):+ self.assertEqual(keytable.wire_name(name, "windows", "macos", "mac_layout"), name)+def test_an_unknown_platform_is_a_pc_on_both_sides(self):self.assertEqual(keytable.wire_name("cmd", "haiku", "macos", "semantic"), "ctrl")self.assertEqual(keytable.wire_name("cmd", "macos", "haiku", "semantic"), "ctrl")diff --git a/core/tests/test_responder_ported.py b/core/tests/test_responder_ported.pyindex 82747e9..f74e602 100644--- a/core/tests/test_responder_ported.py+++ b/core/tests/test_responder_ported.py@@ -420,6 +420,18 @@ class Pressure(Case):self.assertEqual(self.machine.pressures[1], ("left", 1.0, True, None))self.assertNotIn(("move", -60, 0), self.machine.injected())+ def test_the_log_names_the_edge_a_pointer_landed_on_and_the_edge_it_pushed_through(self):+ # 02-10 20:40: input bounced between two machines every half second, and neither log+ # said which edges, so a bad arrangement could not be told from a hand wiggling at one.+ with self.assertLogs(receiver.LOGGER, level="INFO") as said:+ link = self.owner(resistance_px=0, reach=[], edge="right", offset=0.5)+ self.assertTrue(wait_for(lambda: self.machine.arrivals), self.machine.arrivals)+ self.machine.desktop.cursor = (0, 540)+ link.move(-60, 0)+ link.expect(SWITCH)+ self.assertTrue(any("arrived at this machine's right edge" in line for line in said.output), said.output)+ self.assertTrue(any("pushed through the zone at this machine's left edge" in line for line in said.output), said.output)+class RearmNeverRevives(Case):"""H: a settings change re-arms only zones that are live; and a replayed frame ends the link."""diff --git a/core/tests/test_settings_sync.py b/core/tests/test_settings_sync.pyindex 77fd0d1..a9e4bc9 100644--- a/core/tests/test_settings_sync.py+++ b/core/tests/test_settings_sync.py@@ -18,7 +18,8 @@ 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,+ "glow_style": "glow", "glow_colour": "signal", "effect_length": "normal", "effect_size": "medium",+ "shortcut_arrival": True,"shortcut_arrival_style": "match", "notch_style": "beam", "notch_after_ms": 1200, "haptics": True,"hold_full_screen": False,}@@ -31,7 +32,7 @@ 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",+ double_tap_ms=300, glow_style="glow", glow_colour="signal", effect_length="normal", effect_size="medium",shortcut_arrival=True, shortcut_arrival_style="match", mac_return_edge="left", edge_glow=True,appearance="light",)@@ -40,6 +41,175 @@ def pc_config(**fields):class MessageTests(unittest.TestCase):+ def test_pc_modifier_style_is_local_and_not_part_of_same_on_all_machines(self):+ self.assertNotIn("modifier_style", settings_sync.CROSSING_KEYS + settings_sync.DESIGN_KEYS)++ def test_new_design_choices_survive_the_settings_message_round_trip(self):+ from core import effects++ styles = ("aperture", "crease", "pleat", "concertina", "thread", "weave", "jacquard")+ colours = ("vellum", "carbon_copy", "marbled", "flax", "madder", "tide")+ for style in styles:+ for colour in colours:+ with self.subTest(style=style, colour=colour):+ values = settings_sync.mac_values(mac_raw(+ glow_style=style, glow_colour=colour, shortcut_arrival_style=style,+ ))+ data = settings_sync.message_data(True, 7, values)+ _on, _stamp, received = settings_sync.read(data, KEYS)+ self.assertEqual(received["glow_style"], style)+ self.assertEqual(received["glow_colour"], colour)+ self.assertEqual(received["shortcut_arrival_style"], style)+ self.assertTrue(set(styles) <= set(effects.EFFECT_IDS))+ self.assertTrue(set(colours) <= set(effects.PACK_IDS))+ def test_an_optional_design_state_keeps_its_own_stamp_and_effect_size(self):+ values = {**settings_sync.mac_values(mac_raw()), "effect_size": "large"}+ design_state = {"set_at": 63, "by": b64(b"\x03" * 16), "values": values}+ data = settings_sync.message_data(False, 50, design_state=design_state)++ self.assertFalse(data["on"])+ self.assertEqual(data["design_sync"], design_state)++ def test_a_settings_message_without_a_design_state_remains_readable(self):+ data = settings_sync.message_data(False, 50)++ self.assertIsNone(settings_sync.read_design_state(data, KEYS))++ def test_a_design_state_is_validated_independently_of_same_on_all_machines(self):+ values = {"glow_style": "beam", "unknown": "ignored"}+ state = {"set_at": NOW, "by": b64(b"\x03" * 16), "values": values}++ self.assertEqual(settings_sync.read_design_state(+ {"on": False, "set_at": NOW, "by": b64(bytes(16)), "design_sync": state}, KEYS),+ {"set_at": NOW, "by": state["by"],+ "values": {"effect_size": "medium", "glow_style": "beam"}})++ def test_an_invalid_effect_size_is_ignored_but_a_missing_one_defaults_to_medium(self):+ state = {"set_at": NOW, "by": b64(bytes(16)),+ "values": {"effect_size": "giant", "glow_style": "beam"}}++ self.assertEqual(settings_sync.read_design_state(+ {"on": False, "set_at": NOW, "by": b64(bytes(16)), "design_sync": state}, KEYS),+ {"set_at": NOW, "by": state["by"], "values": {"glow_style": "beam"}})++ def test_a_design_state_in_a_malformed_settings_envelope_is_ignored(self):+ for outer in ({"on": "no"}, {"set_at": True}, {"by": "not an id"}):+ data = {"on": False, "set_at": NOW, "by": b64(bytes(16)), **outer,+ "design_sync": {"set_at": NOW + 1, "by": b64(bytes([1]) * 16),+ "values": {"glow_style": "beam"}}}+ self.assertIsNone(settings_sync.read_design_state(data, KEYS), outer)++ def test_same_on_design_change_gets_a_new_local_design_stamp(self):+ changed = settings_sync.design_change_stamp(+ {"effect_length": "normal"}, {"effect_length": "long"}, 50,+ {"set_at": 90}, b64(b"\x02" * 16), now=100,+ )++ self.assertEqual(changed, {"set_at": 100, "by": b64(b"\x02" * 16)})+ self.assertIsNone(settings_sync.design_change_stamp(+ {"effect_length": "long"}, {"effect_length": "long"}, 50,+ {"set_at": 90}, b64(b"\x02" * 16), now=100,+ ))++ def test_design_states_use_the_same_stamp_order_as_same_on_all_machines(self):+ larger = {"set_at": 100, "by": b64(b"\x02" * 16), "values": {"glow_style": "beam"}}+ self.assertTrue(settings_sync.design_arrived(larger, 100, b64(b"\x01" * 16)))+ self.assertFalse(settings_sync.design_arrived(larger, 100, larger["by"]))+ self.assertFalse(settings_sync.design_arrived(larger, 101, ""))++ def test_design_follow_chain_keeps_the_leaders_stamp(self):+ a_id, b_id = (b64(bytes([byte]) * 16) for byte in (1, 2))+ a_state = {"set_at": 100, "by": a_id, "values": {"glow_style": "beam"}}++ b = settings_sync.followed_design({"glow_style": "glow"}, a_state, a_id, a_id, False,+ 50, b64(bytes(16)))+ c = settings_sync.followed_design({"glow_style": "glow"},+ {"set_at": b["set_at"], "by": b["by"], "values": b["values"]},+ b_id, b_id, False, 20, b64(bytes(16)))++ self.assertTrue(b["changed"] and c["changed"])+ self.assertEqual(c["values"]["glow_style"], "beam")+ self.assertEqual((b["set_at"], b["by"], c["set_at"], c["by"]),+ (100, a_id, 100, a_id))++ def test_follower_accepts_the_leaders_next_stamp_after_reannouncing_it(self):+ a_id, b_id = b64(b"\x01" * 16), b64(b"\x02" * 16)+ current = {"glow_style": "glow"}+ first = {"set_at": 100, "by": a_id, "values": {"glow_style": "beam"}}+ applied = settings_sync.followed_design(current, first, a_id, a_id, False,+ 50, "")+ next_from_a = {"set_at": 101, "by": a_id, "values": {"glow_style": "flint"}}++ updated = settings_sync.followed_design(+ applied["values"], next_from_a, a_id, a_id, False,+ applied["set_at"], applied["by"],+ )++ self.assertTrue(updated["changed"])+ self.assertEqual(updated["values"]["glow_style"], "flint")+ self.assertEqual((updated["set_at"], updated["by"]), (101, a_id))++ def test_mutual_design_follow_converges_without_a_second_announcement(self):+ a_id, b_id = b64(b"\x01" * 16), b64(b"\x02" * 16)+ b_after_a = settings_sync.followed_design(+ {"glow_style": "glow"}, {"set_at": 100, "by": a_id, "values": {"glow_style": "beam"}},+ a_id, a_id, False, 90, b64(bytes(16)),+ )+ a_after_b = settings_sync.followed_design(+ {"glow_style": "beam"},+ {"set_at": b_after_a["set_at"], "by": b_after_a["by"], "values": b_after_a["values"]},+ b_id, b_id, False, 100, a_id,+ )++ self.assertTrue(b_after_a["changed"])+ self.assertIsNone(a_after_b)++ def test_mutual_design_announcements_crossing_in_flight_converge_on_the_newer_stamp(self):+ a_id, b_id = b64(bytes([1]) * 16), b64(bytes([2]) * 16)+ ids = {"A": a_id, "B": b_id}+ held = {+ "A": {"values": {"glow_style": "beam"}, "set_at": 200, "by": a_id},+ "B": {"values": {"glow_style": "glow"}, "set_at": 100, "by": b_id},+ }+ # Both link-up announcements are already in flight before either side reacts.+ queue = [("A", "B", dict(held["A"])), ("B", "A", dict(held["B"]))]+ sent = 0+ while queue:+ source, follower, incoming = queue.pop(0)+ sent += 1+ self.assertLess(sent, 10, "mutual follows kept re-announcing")+ current = held[follower]+ applied = settings_sync.followed_design(+ current["values"], incoming,+ source, source, False, current["set_at"], current["by"],+ )+ if applied is not None and applied["changed"]:+ held[follower] = {"values": applied["values"], "set_at": applied["set_at"], "by": applied["by"]}+ queue.append((follower, source, dict(held[follower])))++ self.assertEqual(held["A"]["values"]["glow_style"], "beam")+ self.assertEqual(held["B"]["values"]["glow_style"], "beam")+ self.assertEqual((held["A"]["set_at"], held["A"]["by"]), (200, a_id))+ self.assertEqual((held["B"]["set_at"], held["B"]["by"]), (200, a_id))++ def test_design_follow_ignores_other_peers_and_waits_while_same_is_on(self):+ state = {"set_at": 100, "by": b64(b"\x02" * 16), "values": {"glow_style": "beam"}}+ peer = state["by"]+ current = {"glow_style": "glow"}++ self.assertIsNone(settings_sync.followed_design(current, state, peer, "", False, 0, ""))+ self.assertIsNone(settings_sync.followed_design(current, state, peer, peer, True, 0, ""))++ def test_a_newer_identical_design_keeps_its_stamp_without_an_announcement(self):+ peer = b64(bytes([2]) * 16)+ applied = settings_sync.followed_design(+ {"glow_style": "beam"}, {"set_at": 100, "by": peer, "values": {"glow_style": "beam"}},+ peer, peer, False, 50, "",+ )++ self.assertEqual(applied, {"changed": False, "values": {"glow_style": "beam"},+ "set_at": 100, "by": peer})+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, "by": ""})@@ -48,6 +218,7 @@ class MessageTests(unittest.TestCase):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["design"]["effect_size"], "medium")self.assertIs(data["crossing"]["shortcut"], True)flat = {**data["crossing"], **data["design"]}for own in ("notch_style", "notch_after_ms", "haptics", "glow", "appearance", "edge", "hold_full_screen",@@ -148,6 +319,22 @@ class MessageTests(unittest.TestCase):class AdapterTests(unittest.TestCase):+ def test_size_is_read_applied_and_transmitted_on_both_machines(self):+ mac = mac_raw(effect_size="large")+ values = settings_sync.mac_values(mac)+ self.assertEqual(values["effect_size"], "large")+ self.assertEqual(settings_sync.apply_mac(mac_raw(), values)["crossing"]["effect_size"], "large")+ message = settings_sync.message_data(True, 1, values)+ self.assertEqual(message["design"]["effect_size"], "large")+ self.assertEqual(settings_sync.read(message, KEYS)[2]["effect_size"], "large")++ pc = pc_config(effect_size="small")+ values = settings_sync.pc_values(pc)+ self.assertEqual(values["effect_size"], "small")+ target = pc_config()+ settings_sync.apply_pc(target, values)+ self.assertEqual(target.effect_size, "small")+def test_the_mac_keeps_its_notch_its_zones_and_its_own_rows(self):raw = mac_raw()values = settings_sync.mac_values(mac_raw(glow_style="beam", resistance_px=40))diff --git a/core/tests/test_v6_vectors.py b/core/tests/test_v6_vectors.pyindex 8dc072c..84ec861 100644--- a/core/tests/test_v6_vectors.py+++ b/core/tests/test_v6_vectors.py@@ -468,7 +468,7 @@ def _wire_md_rows():rows = {}for line in section.splitlines():cells = [cell.strip().strip("`") for cell in line.strip().strip("|").split("|")]- if len(cells) == 4 and cells[0] not in ("Physical key on the sender", "---"):+ if len(cells) == 5 and cells[0] not in ("Physical key on the sender", "---"):rows[cells[0]] = tuple(cells[1:])return rows@@ -482,6 +482,8 @@ class KeyTableTests(unittest.TestCase):self.assertEqual(keytable.wire_name(row["physical"], own, own, "semantic"), row["same_family"])self.assertEqual(keytable.wire_name(row["physical"], own, peer, "semantic"), row["across_semantic"])self.assertEqual(keytable.wire_name(row["physical"], own, peer, "positional"), row["across_positional"])+ if row["sender"] == "pc":+ self.assertEqual(keytable.wire_name(row["physical"], own, peer, "mac_layout"), row["across_mac_layout"])def test_the_rows_are_section_7s_table(self):table = _wire_md_rows()@@ -489,7 +491,10 @@ class KeyTableTests(unittest.TestCase):self.assertEqual({row["key"] for row in V6["key_table"]["rows"]}, set(table))for row in V6["key_table"]["rows"]:with self.subTest(key=row["key"]):- self.assertEqual((row["same_family"], row["across_semantic"], row["across_positional"]), table[row["key"]])+ self.assertEqual(+ (row["same_family"], row["across_semantic"], row["across_positional"], row["across_mac_layout"]),+ table[row["key"]],+ )def test_the_families_names_and_evdev_codes(self):data = V6["key_table"]diff --git a/core/tests/v6_vectors.json b/core/tests/v6_vectors.jsonindex 67a50a2..9aa48c1 100644--- a/core/tests/v6_vectors.json+++ b/core/tests/v6_vectors.json@@ -1307,7 +1307,7 @@]},"key_table": {- "$comment": "WIRE.md section 7's table. `sender` is the family of the machine whose key was pressed (mac: macos and ios; pc: every other platform, an unknown one included); `physical` is the key on that machine's own keyboard; the three columns are the name it travels as to a peer of the same family, and across families under each saved style. `evdev` maps a Linux sender's key codes to physical names; a code not in it is a character key.",+ "$comment": "WIRE.md section 7's table. `sender` is the family of the machine whose key was pressed (mac: macos and ios; pc: every other platform, an unknown one included); `physical` is the key on that machine's own keyboard; the columns are the name it travels as to a peer of the same family and across families under each saved style. `evdev` maps a Linux sender's key codes to physical names; a code not in it is a character key.","mac_platforms": ["ios","macos"@@ -1320,7 +1320,8 @@"physical": "ctrl","same_family": "ctrl","across_semantic": "cmd",- "across_positional": "ctrl"+ "across_positional": "ctrl",+ "across_mac_layout": "\u2014"},{"key": "Mac right Control",@@ -1328,7 +1329,8 @@"physical": "ctrl_r","same_family": "ctrl_r","across_semantic": "cmd",- "across_positional": "ctrl"+ "across_positional": "ctrl",+ "across_mac_layout": "\u2014"},{"key": "Mac Command",@@ -1336,7 +1338,8 @@"physical": "cmd","same_family": "cmd","across_semantic": "ctrl",- "across_positional": "cmd"+ "across_positional": "cmd",+ "across_mac_layout": "\u2014"},{"key": "Mac right Command",@@ -1344,7 +1347,8 @@"physical": "cmd_r","same_family": "cmd_r","across_semantic": "ctrl",- "across_positional": "cmd"+ "across_positional": "cmd",+ "across_mac_layout": "\u2014"},{"key": "Mac Option",@@ -1352,7 +1356,8 @@"physical": "alt","same_family": "alt","across_semantic": "alt",- "across_positional": "alt"+ "across_positional": "alt",+ "across_mac_layout": "\u2014"},{"key": "Mac right Option",@@ -1360,7 +1365,8 @@"physical": "alt_r","same_family": "alt_r","across_semantic": "alt",- "across_positional": "alt"+ "across_positional": "alt",+ "across_mac_layout": "\u2014"},{"key": "PC Control",@@ -1368,7 +1374,8 @@"physical": "ctrl","same_family": "ctrl","across_semantic": "cmd",- "across_positional": "ctrl"+ "across_positional": "ctrl",+ "across_mac_layout": "ctrl"},{"key": "PC right Control",@@ -1376,7 +1383,8 @@"physical": "ctrl_r","same_family": "ctrl_r","across_semantic": "cmd_r",- "across_positional": "ctrl_r"+ "across_positional": "ctrl_r",+ "across_mac_layout": "ctrl_r"},{"key": "PC Windows or Super",@@ -1384,7 +1392,8 @@"physical": "cmd","same_family": "cmd","across_semantic": "ctrl",- "across_positional": "cmd"+ "across_positional": "cmd",+ "across_mac_layout": "alt"},{"key": "PC right Windows or Super",@@ -1392,7 +1401,8 @@"physical": "cmd_r","same_family": "cmd_r","across_semantic": "ctrl_r",- "across_positional": "cmd_r"+ "across_positional": "cmd_r",+ "across_mac_layout": "alt_r"},{"key": "PC Alt",@@ -1400,7 +1410,8 @@"physical": "alt","same_family": "alt","across_semantic": "alt",- "across_positional": "alt"+ "across_positional": "alt",+ "across_mac_layout": "cmd"},{"key": "PC right Alt or AltGr",@@ -1408,7 +1419,8 @@"physical": "alt_r","same_family": "alt_r","across_semantic": "alt_r",- "across_positional": "alt_r"+ "across_positional": "alt_r",+ "across_mac_layout": "cmd_r"}],"names": [diff --git a/mac_app/bridge.py b/mac_app/bridge.pyindex c54dd92..c5565fb 100644--- a/mac_app/bridge.py+++ b/mac_app/bridge.py@@ -65,7 +65,7 @@ ROUND_TRIP_MAX_AGE_SECONDS = 5.0# the ownership by force after one second), then goes ahead.LET_GO_WAIT_SECONDS = 1.3OWN_PLATFORM = "macos"-CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings")+CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync")MEDIA_KEY_NAMES = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"})# Why input came home, in words, for the alert. A why that is not here comes home quietly.@@ -808,7 +808,7 @@ class KVMController:def full_screen_app(self):"""The full-screen app holding the edges, or None: also None while this Mac's own settinghas 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):+ if self.cfg.crossing.get("hold_full_screen", False):return self._full_screen_appreturn None@@ -2225,10 +2225,11 @@ class KVMController:def _on_moved(self, moved):self.logger.info(- "move applied: to %s from %s why %s (thread %s)",+ "move applied: to %s from %s why %s%s (thread %s)",self._name_of(moved.to) if moved.to is not None else "home",self._name_of(moved.left) if moved.left is not None else "home",moved.why,+ f" at the {moved.edge} edge" if isinstance(moved.edge, str) else "",threading.current_thread().name,)if moved.to is not None:diff --git a/mac_app/config.py b/mac_app/config.pyindex f8744fc..8376695 100644--- a/mac_app/config.py+++ b/mac_app/config.py@@ -84,6 +84,9 @@ class Config:# Who made the change the stamp above is for, as a machine id: the tie-break between two ends# that changed it in the same second (WIRE.md section 10).same_by: str = ""+ design_set_at: int = 0+ design_by: str = ""+ design_follow_peer: str = ""# How the PC's pointer and scroll feel on this Mac; see receiver.InputScale.pointer_speed: float = 1.0scroll_speed: float = 1.0@@ -176,6 +179,9 @@ def parse_config(raw: dict) -> Config:same_on_both=raw.get("same_on_both", False) is True,same_set_at=_stamp(raw.get("same_set_at", 0)),same_by=str(raw.get("same_by", "") or ""),+ design_set_at=_stamp(raw.get("design_set_at", 0)),+ design_by=str(raw.get("design_by", "") or ""),+ design_follow_peer=str(raw.get("design_follow_peer", "") or ""),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.pyindex 27c4a5a..c27fd2c 100644--- a/mac_app/crossing.py+++ b/mac_app/crossing.py@@ -41,7 +41,7 @@ DEFAULT_CROSSING = {"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,+ "hold_full_screen": False,# "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.@@ -50,6 +50,7 @@ DEFAULT_CROSSING = {"shortcut_arrival_style": "match",# How long an effect takes to play through once the pointer crosses: see effects.LENGTHS."effect_length": "normal",+ "effect_size": "medium",# Unix seconds at the moment this Mac last changed the arrangement -- which# edge leads to the PC. Either machine may change it, so when two ends meet# holding different answers the newer stamp wins. Never read by the engine;diff --git a/mac_app/effects_overlay.py b/mac_app/effects_overlay.pyindex b3bc4d1..946faf4 100644--- a/mac_app/effects_overlay.py+++ b/mac_app/effects_overlay.py@@ -429,6 +429,7 @@ class EffectsOverlay:raise ValueError(f"no crossing effect called {feel['glow_style']!r}")self.palette = palette(feel["glow_colour"])self.player.pace = effects.pace(feel.get("effect_length"))+ self.player.effect_size = feel.get("effect_size", "medium")self.reduced = reduce_motion()self.dark = dark_appearance()self.box = tuple(self.controller._current_desktop_bounds())diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pyindex 6ab2dac..8a5c1c4 100644--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@ -387,8 +387,11 @@ def full_screen_app():app = AppKit.NSWorkspace.sharedWorkspace().frontmostApplication()if app is None:return None+ pid = app.processIdentifier()+ if pid == os.getpid():+ return Nonename = app.localizedName() or "An app"- if _ax_full_screen(app.processIdentifier()):+ if _ax_full_screen(pid):return nameerror, displays, count = Quartz.CGGetActiveDisplayList(16, None, None)if error != 0:@@ -398,7 +401,7 @@ def full_screen_app():rect = Quartz.CGDisplayBounds(display)display_frames.append((rect.origin.x, rect.origin.y, rect.size.width, rect.size.height))windows = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)- if _covers_a_display(windows or (), app.processIdentifier(), display_frames):+ if _covers_a_display(windows or (), pid, display_frames):return namereturn None@@ -499,7 +502,6 @@ class EdgeGlow:dark_appearance = staticmethod(notch_beam.dark_appearance)- BAND_MAX = 18.0FLASH_SECONDS = 0.18PREVIEW_SECONDS = 0.6# How far a corner's light reaches along each of its two walls.@@ -640,16 +642,19 @@ class EdgeGlow:returnself._ensure_panel()strength = max(level, flash, lingering)- band = 3.0 + 3.0 * strength if beam else 2.0 + self.BAND_MAX * strength+ box = self.controller._current_desktop_bounds()+ display = effects_overlay.display_at((self.region[0] + self.region[2] / 2.0,+ self.region[1] + self.region[3] / 2.0), box)+ full_depth = effects.edge_depth(display[2] - display[0], display[3] - display[1],+ feel.get("effect_size", "medium"))+ band = full_depth if beam else full_depth * (0.35 + 0.65 * max(level, flash))if self._corner() is not None:- self._draw_corner(feel, beam, band, level, flash, strength)+ self._draw_corner(feel, beam, band, full_depth, level, flash, strength)returnif self.side is not None:self.side.setHidden_(True)if self.mac_edge == "top":- x, y, width, height = self.region- band = self._top_band(band, beam, effects_overlay.display_at(- (x + width / 2.0, y + height / 2.0), self.controller._current_desktop_bounds()))+ band = self._top_band(band, beam, display, full_depth)self.panel.setFrame_display_(self._band_frame(band), False)# Colour runs along the edge: top to bottom on a side, left to right along the top or bottom.start, end = ((0.5, 1.0), (0.5, 0.0)) if self.mac_edge in ("left", "right") else ((0.0, 0.5), (1.0, 0.5))@@ -715,18 +720,19 @@ class EdgeGlow:display = effects_overlay.display_at((x + width / 2.0, y + height / 2.0), box)return effects_overlay.corner_name(self.region, display), display- def _top_band(self, band, beam, display):+ def _top_band(self, band, beam, display, full_depth):"""How deep the glow reaches down from the top of `display`. Over a menu bar it is scaledto fill the bar at full strength: the bar is about twice the band, so at the band's owndepth it lit only the bar's top half, under the status items and the clock, and a corner'stop arm read as a faint stripe beside the full side arm. The beam is a line and stays one."""bar = menu_bar_height(display)- full = 2.0 + self.BAND_MAX- if beam or bar <= full:+ if beam or bar <= 0:return band- return band * bar / full+ if bar >= full_depth:+ return min(full_depth, band)+ return min(bar, band * bar / full_depth)- def _draw_corner(self, feel, beam, band, level, flash, strength):+ def _draw_corner(self, feel, beam, band, full_depth, level, flash, strength):"""The band along both of the corner's walls, brightest where they meet and fading out alongeach, so it reads as the corner rather than two edges; the beam's comet runs in along the topor bottom wall and out along the side. One gradient layer per wall, each masked by its fade."""@@ -747,7 +753,7 @@ class EdgeGlow:fade = lambda u: max(0.0, 1.0 - u) ** 1.4# AppKit's layer space runs up from the bottom; u runs from the corner outward.at_top = vertical == "top"- across = self._top_band(band, beam, (left, top, right, bottom)) if at_top else band+ across = self._top_band(band, beam, (left, top, right, bottom), full_depth) if at_top else bandwalls = ((self.fill, self.masks[0], ((0.0, arm - across) if at_top else (0.0, 0.0), (arm, across)),((1.0, 0.5), (0.0, 0.5)) if horizontal == "right" else ((0.0, 0.5), (1.0, 0.5)),@@ -931,6 +937,43 @@ class FlippedView(AppKit.NSView):return True+def window_fill_frame(window):+ screen = window.screen() or AppKit.NSScreen.mainScreen()+ return screen.visibleFrame()+++def titlebar_action(setting):+ value = (setting or "").strip().casefold()+ if value in {"fill", "zoom"}:+ return "fill"+ if value in {"minimise", "minimize"}:+ return "minimise"+ return None+++def perform_titlebar_double_click(window, setting=None):+ if setting is None:+ domain = AppKit.NSUserDefaults.standardUserDefaults().persistentDomainForName_("NSGlobalDomain") or {}+ setting = domain.get("AppleActionOnDoubleClick")+ action = titlebar_action(setting)+ if action == "fill":+ window.zoom_(None)+ elif action == "minimise":+ window.miniaturize_(None)+++def perform_titlebar_drag(window, event):+ window.performWindowDragWithEvent_(event)+++class TitlebarStrip(AppKit.NSView):+ def mouseDown_(self, event):+ if event.clickCount() >= 2:+ perform_titlebar_double_click(self.window())+ else:+ perform_titlebar_drag(self.window(), event)++class ControlWindow(AppKit.NSObject):def initWithController_settingsStore_logger_(self, controller, settings_store, logger):self = objc.super(ControlWindow, self).init()@@ -965,6 +1008,7 @@ class ControlWindow(AppKit.NSObject):self.previews = Noneself._apply_serial = 0self._save_pending = False+ self._design_states = {}# The machine the Crossing page shows and writes the ways of: an id ("" is the entry# migrated from 1.4.x), None while nothing is paired.self.chosen_peer = None@@ -997,7 +1041,12 @@ class ControlWindow(AppKit.NSObject):theme.tint(content.layer(), background="ground")self.appearance_watch = theme.AppearanceWatch.alloc().initWithCallback_(lambda: self._apply_appearance())- top = widgets.hairline()+ top = TitlebarStrip.alloc().initWithFrame_(((0, 0), (900, 18)))+ top.setTranslatesAutoresizingMaskIntoConstraints_(False)+ top.setWantsLayer_(True)+ theme.tint(top.layer(), background="ground")+ top_rule = widgets.box("rule")+ top.addSubview_(top_rule)self.sidebar = widgets.Sidebar(pages.PAGES,self._select_page,@@ -1016,6 +1065,11 @@ class ControlWindow(AppKit.NSObject):top.topAnchor().constraintEqualToAnchor_(content.topAnchor()),top.leadingAnchor().constraintEqualToAnchor_(content.leadingAnchor()),top.trailingAnchor().constraintEqualToAnchor_(content.trailingAnchor()),+ top.heightAnchor().constraintEqualToConstant_(18),+ top_rule.leadingAnchor().constraintEqualToAnchor_(top.leadingAnchor()),+ top_rule.trailingAnchor().constraintEqualToAnchor_(top.trailingAnchor()),+ top_rule.bottomAnchor().constraintEqualToAnchor_(top.bottomAnchor()),+ top_rule.heightAnchor().constraintEqualToConstant_(1),self.sidebar_width,self.sidebar.view.topAnchor().constraintEqualToAnchor_(top.bottomAnchor()),self.sidebar.view.bottomAnchor().constraintEqualToAnchor_(content.bottomAnchor()),@@ -1077,6 +1131,9 @@ class ControlWindow(AppKit.NSObject):self.sidebar_width.setConstant_(sidebar)self._apply_width(width - sidebar - 1)+ def windowWillUseStandardFrame_defaultFrame_(self, window, _default_frame):+ return window_fill_frame(window)+@objc.python_methoddef _apply_width(self, width):"""Two layouts, not a continuous reflow. Wide, Pairing puts the machine list beside the code;@@ -1175,6 +1232,7 @@ class ControlWindow(AppKit.NSObject):self.tick_steps_select.value = crossing_raw["haptic_steps"]self.hold_box.value = crossing_raw["hold_full_screen"]self._load_shared(raw)+ self._refresh_design_follow()@objc.python_methoddef _load_shared(self, raw):@@ -1193,6 +1251,7 @@ class ControlWindow(AppKit.NSObject):self.dragging_box.value = crossing_raw["block_while_dragging"]self.glow_style_select.value = crossing_raw["glow_style"]self.length_select.value = crossing_raw.get("effect_length", "normal")+ self.size_select.value = crossing_raw.get("effect_size", "medium")self.glow_colour_select.value = crossing_raw["glow_colour"]self._reflect()@@ -1270,8 +1329,8 @@ class ControlWindow(AppKit.NSObject):if fx is not None:self.effect_blurb.set(fx.blurb)# Drawing every still is tens of milliseconds, so only what they show redraws them: the- # colour, the place, the length, the palette, and for Same as crossing the crossing style.- stills = (colour, style, place, self.length_select.value, theme.is_dark())+ # colour, the place, the length, the size, the palette, and for Same as crossing the crossing style.+ stills = (colour, style, place, self.length_select.value, self.size_select.value, theme.is_dark())if stills != self._stills:self._stills = stillsfor still in self.effect_stills:@@ -1573,6 +1632,11 @@ class ControlWindow(AppKit.NSObject):except SettingsError as exc:self.logger.warning("settings not read after the peers changed: %s", exc)return+ peer_ids = {entry.get("id") for entry in self.settings_store.current()["peers"]}+ if cfg.design_follow_peer and cfg.design_follow_peer not in peer_ids:+ raw = config_to_raw(cfg)+ raw["design_follow_peer"] = ""+ cfg = self.settings_store.save(raw)self.controller.peers_changed()self.controller.apply_settings(cfg)if self.windows_input is not None:@@ -1685,10 +1749,16 @@ class ControlWindow(AppKit.NSObject):top, leading, bottom, trailing = theme.PAGE_PADDINGpadding = [body.topAnchor().constraintEqualToAnchor_constant_(page.topAnchor(), top),- body.leadingAnchor().constraintEqualToAnchor_constant_(page.leadingAnchor(), leading),+ body.leadingAnchor().constraintGreaterThanOrEqualToAnchor_constant_(page.leadingAnchor(), leading),page.bottomAnchor().constraintGreaterThanOrEqualToAnchor_constant_(body.bottomAnchor(), bottom),- page.trailingAnchor().constraintEqualToAnchor_constant_(body.trailingAnchor(), trailing),+ page.trailingAnchor().constraintGreaterThanOrEqualToAnchor_constant_(body.trailingAnchor(), trailing),+ body.centerXAnchor().constraintEqualToAnchor_(page.centerXAnchor()),+ body.widthAnchor().constraintLessThanOrEqualToConstant_(theme.PAGE_CONTENT_WIDTH),]+ available_width = body.widthAnchor().constraintEqualToAnchor_constant_(page.widthAnchor(), -(leading + trailing))+ # Below WindowSizeStayPut (500): above it, the column's 960 pt cap became the window's.+ available_width.setPriority_(AppKit.NSLayoutPriorityDragThatCannotResizeWindow)+ padding.append(available_width)# 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.@@ -1796,6 +1866,7 @@ class ControlWindow(AppKit.NSObject):for note in self.own_notes:if note.view.isHidden() == on:motion.set_hidden(note.view, not on)+ self._refresh_design_follow()@objc.python_methoddef _set_same(self, on):@@ -1812,6 +1883,8 @@ class ControlWindow(AppKit.NSObject):returnself.controller.apply_settings(cfg)self._send_same()+ if not on:+ self._apply_followed_design()self._show_same()@objc.python_method@@ -1819,8 +1892,54 @@ class ControlWindow(AppKit.NSObject):"""This Mac's settings message, for a change here and for announcing on a new link. Calledfrom the links' threads as well, so it reads the settings once."""cfg = self.controller.cfg+ values = settings_sync.mac_values(config_to_raw(cfg))+ design_state = {+ "set_at": cfg.design_set_at,+ "by": cfg.design_by or self.own_id(),+ "values": {key: values[key] for key in settings_sync.DESIGN_KEYS},+ }return settings_sync.message_data(cfg.same_on_both, cfg.same_set_at,- settings_sync.mac_values(config_to_raw(cfg)), by=cfg.same_by or self.own_id())+ values, by=cfg.same_by or self.own_id(), design_state=design_state)++ @objc.python_method+ def _apply_followed_design(self):+ cfg = self.controller.cfg+ peer = cfg.design_follow_peer+ state = self._design_states.get(peer)+ if not peer or state is None or cfg.same_on_both:+ return+ current = settings_sync.mac_values(config_to_raw(cfg))+ taken = settings_sync.followed_design(current, state, peer, peer, cfg.same_on_both,+ cfg.design_set_at, cfg.design_by)+ if taken is None:+ return+ raw = settings_sync.apply_mac(config_to_raw(cfg), taken["values"])+ raw["design_set_at"] = taken["set_at"]+ raw["design_by"] = taken["by"]+ try:+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError):+ self.logger.exception("could not save followed Design from %s", peer)+ return+ self.controller.apply_settings(cfg)+ self._load_shared(config_to_raw(cfg))+ if taken["changed"]:+ self._send_same()++ @objc.python_method+ def _receive_design(self, data, peer):+ if peer is None:+ return+ peer_id = protocol.id_text(peer) if isinstance(peer, bytes) else peer+ state = settings_sync.read_design_state(data, KEY_NAME_TO_CODE)+ if state is None:+ return+ held = self._design_states.get(peer_id)+ if held is None or settings_sync.design_arrived(state, held["set_at"], held["by"]):+ self._design_states[peer_id] = state+ self._refresh_design_follow()+ if peer_id == self.controller.cfg.design_follow_peer:+ self._apply_followed_design()@objc.python_methoddef own_id(self):@@ -1842,28 +1961,44 @@ class ControlWindow(AppKit.NSObject):when it is newer than this Mac's; then its values replace the shared ones here, and it issent on, unchanged, to every other machine that keeps it."""cfg = self.controller.cfg+ was_on = cfg.same_on_bothtaken = settings_sync.arrived(data, cfg.same_set_at, KEY_NAME_TO_CODE, by_here=cfg.same_by)- 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- raw["same_by"] = data.get("by", "")- 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 %s sent", peer)- return- self.controller.apply_settings(cfg)- self._send_same(data, source=peer)- if self.previews is not None:- self.previews.repaint()- self.logger.info("settings from %s applied (same on all machines %s)", peer, "on" if on else "off")- self._load_shared(config_to_raw(cfg))- self.refresh()+ if taken is not None:+ on, set_at, values = taken+ raw = config_to_raw(cfg)+ design_stamp = None+ if on:+ design_stamp = settings_sync.design_change_stamp(+ settings_sync.mac_values(raw), values, cfg.design_set_at,+ settings_sync.read_design_state(data, KEY_NAME_TO_CODE), self.own_id(),+ )+ raw["same_on_both"] = on+ raw["same_set_at"] = set_at+ raw["same_by"] = data.get("by", "")+ if on:+ raw = settings_sync.apply_mac(raw, values)+ if design_stamp is not None:+ raw["design_set_at"] = design_stamp["set_at"]+ raw["design_by"] = design_stamp["by"]+ try:+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError):+ self.logger.exception("could not save the settings %s sent", peer)+ return+ self.controller.apply_settings(cfg)+ # Keep global settings' existing forwarding, but replace the optional direct state+ # with this machine's own state instead of relaying the sender's state.+ forwarded = dict(data)+ forwarded["design_sync"] = self.same_state()["design_sync"]+ self._send_same(forwarded, source=peer)+ if self.previews is not None:+ self.previews.repaint()+ self.logger.info("settings from %s applied (same on all machines %s)", peer, "on" if on else "off")+ self._load_shared(config_to_raw(cfg))+ self.refresh()+ self._receive_design(data, peer)+ if taken is not None and was_on and not on:+ self._apply_followed_design()@objc.python_methoddef _login_module(self):@@ -1968,6 +2103,69 @@ class ControlWindow(AppKit.NSObject):for module in (self._on_screen_module(), self.style_module, self.colour_module,self._trackpad_module(), self._appearance_module()):widgets.add(body, module.view)+ self.follow_module = widgets.Module(spacing=10)+ self.follow_module.add(widgets.eyebrow("Match design with"))+ self.follow_host = widgets.stack(spacing=0)+ self.follow_module.add(self.follow_host)+ self.follow_note = widgets.note()+ self.follow_module.add(self.follow_note.view)+ widgets.add(body, self.follow_module.view)+ self._refresh_design_follow()++ @objc.python_method+ def _refresh_design_follow(self):+ if not hasattr(self, "follow_host"):+ return+ for view in self.follow_host.arrangedSubviews():+ self.follow_host.removeArrangedSubview_(view)+ view.removeFromSuperview()+ peers = self.settings_store.current()["peers"]+ labels = peerlist.labels(peers)+ choices = [("", "None")]+ unsupported = set()+ for entry in peers:+ peer = entry.get("id", "")+ if not peer:+ continue+ title = labels.get(entry.get("token", ""), entry.get("name") or "Machine")+ if peer not in self._design_states:+ title += " — Needs beta.6 or later"+ unsupported.add(peer)+ choices.append((peer, title))+ self.follow_select = widgets.Segmented(choices, columns=min(2, len(choices)),+ on_change=self._set_design_follow)+ self.follow_select.value = self.controller.cfg.design_follow_peer+ for value, cell, _words in self.follow_select.cells:+ if value in unsupported:+ cell.enabled = False+ cell.setAlphaValue_(0.45)+ cell.setToolTip_("Needs beta.6 or later")+ widgets.add(self.follow_host, self.follow_select.view)+ peer = self.controller.cfg.design_follow_peer+ if peer:+ entry = next((item for item in peers if item.get("id") == peer), {})+ name = labels.get(entry.get("token", ""), entry.get("name") or "that machine")+ if self.controller.cfg.same_on_both:+ self.follow_note.set(f"Following {name}, paused while Same on all machines is on.")+ else:+ self.follow_note.set(f"Following {name}. Change a Design setting to stop following.")+ elif unsupported:+ self.follow_note.set("A paired machine is unavailable until it has beta.6 or later.")+ else:+ self.follow_note.set("None: this machine keeps its own Design.")++ @objc.python_method+ def _set_design_follow(self, peer):+ raw = config_to_raw(self.controller.cfg)+ raw["design_follow_peer"] = peer or ""+ try:+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError):+ self.logger.exception("could not save Match design with")+ return+ self.controller.apply_settings(cfg)+ self._refresh_design_follow()+ self._apply_followed_design()@objc.python_methoddef _appearance_module(self):@@ -2097,7 +2295,7 @@ 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)+ self.hold_box = widgets.Switch("Hold this Mac's edges while an app on it is full screen", on_change=self._hold_changed)module.add(self.hold_box.view)module.add(self._own_note())module.add(widgets.note(@@ -2464,12 +2662,14 @@ class ControlWindow(AppKit.NSObject):colour = lambda: self.glow_colour_select.value or "signal"place = lambda: self.placepace = lambda: effects.pace(self.length_select.value)+ effect_size = lambda: self.size_select.value or "medium"# The two sets of tiles, one per mode; only the chosen mode's shows.self.crossing_styles_box = widgets.stack(spacing=0)rows = []for group, choices in pages.style_groups(self.effects_ready):# Glow and Beam as stills of the same scene as the effects, so every tile reads alike.- tiles = [(value, title, detail, previews.effect_still(value, colour, self.logger, place=place, pace=pace))+ tiles = [(value, title, detail, previews.effect_still(value, colour, self.logger, place=place,+ pace=pace, effect_size=effect_size))for value, title, detail in choices]self.effect_stills.extend(tile[3] for tile in tiles)if group == pages.TODAY:@@ -2493,7 +2693,8 @@ class ControlWindow(AppKit.NSObject):tiles = []for value, title, detail in choices:fx = lambda value=value: effects.switch_effect(value, self.glow_style_select.value or "glow")- tiles.append((value, title, detail, previews.switch_still(fx, colour, self.logger, pace=pace)))+ tiles.append((value, title, detail, previews.switch_still(+ fx, colour, self.logger, pace=pace, effect_size=effect_size)))self.effect_stills.extend(tile[3] for tile in tiles)rows.append(self._style_group(self.switch_styles_box, group, tiles))widgets.add(self.switch_styles_box, widgets.note(@@ -2512,9 +2713,15 @@ class ControlWindow(AppKit.NSObject):module.body.setCustomSpacing_afterView_(18, self.chosen_box)# Every style and every switch plays at this length, so it follows the tiles either way.self.length_select = widgets.Segmented(effects.LENGTHS, on_change=self._changed)- module.add(widgets.field_row("Length", self.length_select.view)[0])+ self.size_select = widgets.Segmented(effects.SIZES, on_change=self._changed)+ length_size = widgets.stack(vertical=False, spacing=14)+ length_size.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ length_size.addArrangedSubview_(widgets.field_row("Length", self.length_select.view)[0])+ length_size.addArrangedSubview_(widgets.field_row("Size", self.size_select.view)[0])+ widgets.add(module.body, length_size)module.add(widgets.note(- "How long each animation takes to play through once the pointer crosses, and to land."+ "Length sets how long each animation takes to play through once the pointer crosses, and to land. "+ "Size sets the depth of the edge band.").view)return module@@ -2641,7 +2848,7 @@ class ControlWindow(AppKit.NSObject):module.add(self.wake_hint.view)module.add(widgets.hairline())line = widgets.stack(vertical=False, spacing=12)- line.addArrangedSubview_(widgets.note("A new address or port takes effect when you connect.").view)+ line.addArrangedSubview_(widgets.note("A new address or port takes effect when you connect.", reading=False).view)line.addArrangedSubview_(widgets.Button("Connect", self, "connect:", style="primary").view)module.add(line)return module@@ -2719,6 +2926,9 @@ class ControlWindow(AppKit.NSObject):self.message_label = widgets.note(pages.footer(None))line = widgets.stack(vertical=False, spacing=16)line.addArrangedSubview_(self.message_label.view)+ # Without a slack view the line is as wide as the note (at most 560 pt), the bar and the+ # pane follow it, and the window can never be wider than the sidebar plus that: 773 pt.+ line.addArrangedSubview_(widgets.hug(widgets.box(), AppKit.NSLayoutPriorityDefaultLow))bar.addSubview_(line)widgets.pin(line, bar, (12, 16, 12, 16))return bar@@ -2826,14 +3036,23 @@ class ControlWindow(AppKit.NSObject):"glow_style": self.glow_style_select.value,"glow_colour": self.glow_colour_select.value,"effect_length": self.length_select.value or "normal",+ "effect_size": self.size_select.value or "medium","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))+ before = settings_sync.mac_values(config_to_raw(self.controller.cfg))+ after = settings_sync.mac_values(raw)+ shared = self.controller.cfg.same_on_both and settings_sync.changed(before, after)+ design_changed = any(before.get(key) != after.get(key) for key in settings_sync.DESIGN_KEYS)+ if design_changed:+ raw["design_follow_peer"] = ""+ raw["design_set_at"] = settings_sync.next_stamp(+ max(self.controller.cfg.design_set_at, self.controller.cfg.same_set_at), time.time())+ raw["design_by"] = self.own_id()if shared:- raw["same_set_at"] = settings_sync.next_stamp(self.controller.cfg.same_set_at, time.time())+ raw["same_set_at"] = settings_sync.next_stamp(+ max(self.controller.cfg.same_set_at, raw.get("design_set_at", 0)), time.time())raw["same_by"] = self.own_id()cfg = self.settings_store.save(raw)except (SettingsError, TypeError, ValueError) as exc:@@ -2845,6 +3064,9 @@ class ControlWindow(AppKit.NSObject):self.previews.repaint()if shared:self._send_same()+ elif design_changed:+ self._send_same()+ self._refresh_design_follow()if self._write_ways():self._say("Saved. Changes apply as you make them.", "ink_2")diff --git a/mac_app/link_state.py b/mac_app/link_state.pyindex f33f614..4de1098 100644--- a/mac_app/link_state.py+++ b/mac_app/link_state.py@@ -73,7 +73,7 @@ def describe(controller) -> LinkState:if armed and controller.full_screen_app is not None:return LinkState("full_screen", INK, "Held", "Held",- f"{controller.full_screen_app} is full screen, so edges are off while it has focus.", SIGNAL,+ "Held: an app is full screen.", SIGNAL,)via = " through the macOS 27 tunnel" if tunnel else ""return LinkState("mac", INK, "On Mac", linked, f"Connected to {peer}{via}.", SIGNAL)diff --git a/mac_app/machines_panel.py b/mac_app/machines_panel.pyindex 7e3d03c..272e6c0 100644--- a/mac_app/machines_panel.py+++ b/mac_app/machines_panel.py@@ -74,7 +74,7 @@ class MachinesPanel:self.empty = widgets.note("No machines paired yet.")module.add(self.empty.view)line = widgets.stack(vertical=False, spacing=10)- self.list_note = widgets.note("Beamer connects to each machine on its own whenever both are running.")+ self.list_note = widgets.note("Beamer connects to each machine on its own whenever both are running.", reading=False)line.addArrangedSubview_(self.list_note.view)self.pair_button = widgets.action_button("Pair a machine", self._toggle_sheet, scale="small")line.addArrangedSubview_(self.pair_button.view)@@ -342,7 +342,7 @@ class MachinesPanel:if self.removing != row.token:return self._chip("Remove", lambda t=row.token: self._ask_to_remove(t), f"Remove {label}", (row.token, "remove"))line = widgets.stack(vertical=False, spacing=8)- words = widgets.note(f"Remove {label}? It stays paired on that machine until you remove this one there too.", ink="ink")+ words = widgets.note(f"Remove {label}? It stays paired on that machine until you remove this one there too.", ink="ink", reading=False)line.addArrangedSubview_(words.view)line.addArrangedSubview_(self._chip("Remove", lambda t=row.token: self._remove(t), f"Confirm removing {label}", (row.token, "confirm")))line.addArrangedSubview_(self._chip("Keep", self._keep, f"Keep {label}", (row.token, "keep")))diff --git a/mac_app/pages.py b/mac_app/pages.pyindex efd844a..1b4d790 100644--- a/mac_app/pages.py+++ b/mac_app/pages.py@@ -79,10 +79,11 @@ def step(current, direction):# The Design page's styles and colours. The classic Glow and Beam come first and stay the default;# the crossing effects follow in effects.DIRECTIONS order, each direction a row of quiet, medium# and showpiece, and its three colour packs a row of swatches.-TODAY = "Classic"+TODAY = "Light"TODAY_STYLES = (("glow", "Glow", "A band of light that deepens the harder you push."),("beam", "Beam", "A thin line with a comet of light running along it."),+ ("aperture", "Aperture", "A fine lens of light opens under pressure and closes softly behind the arriving pointer."),)INTENSITIES = {"quiet": "Quiet", "medium": "Medium", "showpiece": "Showpiece", "classic": "Classic"}@@ -99,9 +100,12 @@ def effects_load_error():def style_groups(with_effects=True):"""[(group, [(style id, name, detail)])] for the style tiles."""+ with_effects = with_effects and effects_load_error() is None# Glow and Beam's detail is their kind, as an effect's is its intensity; what they do is said# under the preview.- groups = [(TODAY, [(value, name, INTENSITIES["classic"]) for value, name, _blurb in TODAY_STYLES])]+ classic_styles = TODAY_STYLES if with_effects else TODAY_STYLES[:2]+ groups = [(TODAY, [(value, name, effects.CLASSIC[value].intensity.capitalize())+ for value, name, _blurb in classic_styles])]for _module, direction, effect_ids, _packs in effects.DIRECTIONS if with_effects else ():row = []for effect_id in effect_ids:@@ -118,7 +122,10 @@ def switch_style_groups(with_effects=True):"""[(group, [(value, name, detail)])] for the style tiles in Switch mode: what a switch plays,effects.SWITCH_STYLES, with the effects grouped as the crossing's are."""simple = [("match", "Same as crossing", "Plays the crossing style"), ("locator", "Ring", "Closes onto the pointer")]- return [(SIMPLE, simple)] + style_groups(with_effects)[1:]+ with_effects = with_effects and effects_load_error() is None+ aperture = [(TODAY, [("aperture", effects.CLASSIC["aperture"].name,+ effects.CLASSIC["aperture"].intensity.capitalize())])] if with_effects else []+ return [(SIMPLE, simple)] + aperture + style_groups(with_effects)[1:]def colour_groups(today_colours, with_effects=True):@@ -382,10 +389,7 @@ def crossing_state_sentence(paired, sending, connected, armed, paused, full_screif paused:return "Paused. Edges, corners and the notch do nothing until you resume; the shortcut still works."if full_screen_app is not None:- return (- f"Off while {full_screen_app} is full screen, so the pointer stays put at "- "the edges; the shortcut still works."- )+ return "Held: an app is full screen."return "On. Pause it to lean on an edge without switching."diff --git a/mac_app/previews.py b/mac_app/previews.pyindex 013cb06..a160b5f 100644--- a/mac_app/previews.py+++ b/mac_app/previews.py@@ -551,9 +551,9 @@ def _played(view, still_at):return still_at if since is None else still_at + max(0.0, time.monotonic() - since)-def effect_still(effect_id, colour, logger, height=84, place=lambda: "edge", pace=lambda: 1.0):- """A tile's still frame of `effect_id`, in whatever colour `colour()` names, at the place- `place()` names and the length `pace()` gives, when it draws."""+def effect_still(effect_id, colour, logger, height=84, place=lambda: "edge", pace=lambda: 1.0,+ effect_size=lambda: "medium"):+ """A tile's still frame of `effect_id`, in the selected colour, place, length and size."""view = effects_overlay.EffectsCanvas.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 1, 1))view.setTranslatesAutoresizingMaskIntoConstraints_(False)view.heightAnchor().constraintEqualToConstant_(height).setActive_(True)@@ -570,7 +570,7 @@ def effect_still(effect_id, colour, logger, height=84, place=lambda: "edge", pacdark = theme.is_dark()where = place()scene = effects.preview_scene(fx, _played(view, STILL_AT_S), where, effects_overlay.palette(colour()), dark=dark,- pace=pace())+ pace=pace(), effect_size=effect_size())# A small pointer, so the effect rather than the arrow is what a tile shows.effects_overlay.draw_scene(Quartz, ctx, scene, width, height, where, dark, crop=STILL_CROPS[where], pointer=11.0)@@ -578,7 +578,7 @@ def effect_still(effect_id, colour, logger, height=84, place=lambda: "edge", pacreturn view-def switch_still(fx, colour, logger, height=84, pace=lambda: 1.0):+def switch_still(fx, colour, logger, height=84, pace=lambda: 1.0, effect_size=lambda: "medium"):"""A tile's still frame of what a switch plays: `fx()` is the Effect, asked when it draws, sinceSame as crossing follows the crossing style."""view = effect_still(None, colour, logger, height)@@ -586,7 +586,7 @@ def switch_still(fx, colour, logger, height=84, pace=lambda: 1.0):def paint(ctx, width, height):dark = theme.is_dark()scene = effects.preview_switch_scene(fx(), _played(view, SWITCH_STILL_AT_S), effects_overlay.palette(colour()),- dark=dark, pace=pace())+ dark=dark, pace=pace(), effect_size=effect_size())effects_overlay.draw_scene(Quartz, ctx, scene, width, height, "switch", dark, crop=SWITCH_STILL_CROP, pointer=11.0)view.painter = paintdiff --git a/mac_app/settings_store.py b/mac_app/settings_store.pyindex 8ee8e3a..33c88a4 100644--- a/mac_app/settings_store.py+++ b/mac_app/settings_store.py@@ -106,6 +106,9 @@ def editable_default_config():same_on_both=False,same_set_at=0,same_by="",+ design_set_at=0,+ design_by="",+ design_follow_peer="",pointer_speed=1.0,scroll_speed=1.0,reverse_scroll=False,@@ -138,6 +141,9 @@ def config_to_raw(cfg):"same_on_both": cfg.same_on_both,"same_set_at": cfg.same_set_at,"same_by": cfg.same_by,+ "design_set_at": cfg.design_set_at,+ "design_by": cfg.design_by,+ "design_follow_peer": cfg.design_follow_peer,"pointer_speed": cfg.pointer_speed,"scroll_speed": cfg.scroll_speed,"reverse_scroll": cfg.reverse_scroll,@@ -730,6 +736,7 @@ class SettingsStore:("glow_colour", GLOW_COLOURS + effects.PACK_IDS),("shortcut_arrival_style", effects.SWITCH_STYLES),("effect_length", tuple(value for value, _name in effects.LENGTHS)),+ ("effect_size", tuple(value for value, _name in effects.SIZES)),)for name, allowed in choices:if crossing[name] not in allowed:diff --git a/mac_app/setup.py b/mac_app/setup.pyindex 6443cdb..b3650cb 100644--- a/mac_app/setup.py+++ b/mac_app/setup.py@@ -81,6 +81,7 @@ setup("core.peerlist", "core.protocol", "core.receiver", "core.return_edge", "core.settings_sync","core.updates", "core.wol","core.fx_ink", "core.fx_instrument", "core.fx_membrane", "core.fx_sparks", "core.fx_warp",+ "core.fx_light", "core.fx_material", "core.fx_folio", "core.fx_selvedge",],"iconfile": "../Beamer.icns","plist": {diff --git a/mac_app/tests/test_appearance.py b/mac_app/tests/test_appearance.pyindex 39da359..2153b4e 100644--- a/mac_app/tests/test_appearance.py+++ b/mac_app/tests/test_appearance.py@@ -6,7 +6,6 @@ import jsonimport loggingimport sysimport tempfile-import timeimport unittestfrom pathlib import Pathfrom unittest import mock@@ -14,7 +13,6 @@ from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[2]))import AppKit # noqa: E402-import objc # noqa: E402import Quartz # noqa: E402AppKit.NSApplication.sharedApplication()@@ -119,7 +117,7 @@ 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):+ def test_turning_animations_off_hides_the_style_modules_without_a_visible_window(self):window = self.windowwindow._select_page("design")scroll = window.pages["design"]@@ -129,30 +127,12 @@ class WindowAppearanceTests(unittest.TestCase):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):+ with mock.patch.object(motion, "live", return_value=False):window.glow_box.value = Falsewindow._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 = Truewindow._reflect()diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.pyindex 6038c2c..05887fc 100644--- a/mac_app/tests/test_bridge.py+++ b/mac_app/tests/test_bridge.py@@ -1482,6 +1482,8 @@ class CrossingWiringTests(unittest.TestCase):self.assertTrue(self.controller.redirecting, "resuming re-arms the edge with no other change")def test_a_full_screen_app_inhibits_the_pointer_methods_but_not_the_shortcut(self):+ # The hold is off by default since 02-10-2026.+ self.controller.cfg.crossing["hold_full_screen"] = Trueself.controller.full_screen_app = "Steam"event, returned = self._push(10)self.assertIs(returned, event)diff --git a/mac_app/tests/test_crossing_matrix.py b/mac_app/tests/test_crossing_matrix.pyindex 2768348..1fbf89c 100644--- a/mac_app/tests/test_crossing_matrix.py+++ b/mac_app/tests/test_crossing_matrix.py@@ -508,7 +508,8 @@ class MacDrivenTests(unittest.TestCase):# no longer passes a held edge. Lifted, the same push leads home.for held in ("crossing_paused", "full_screen_app"):with self.subTest(held=held):- duo = self.duo(crossing={"edge": "right"})+ # The full-screen hold is off by default since 02-10-2026.+ duo = self.duo(crossing={"edge": "right", "hold_full_screen": True})self.drive(duo, "right")setattr(duo.mac, held, True if held == "crossing_paused" else "Steam")duo.pc_leans(MAC_EDGE_POINT["right"], 30, times=4)@@ -518,6 +519,19 @@ class MacDrivenTests(unittest.TestCase):self.assertIsNotNone(duo.pc_switch(), "the edge did not lead home once released")duo.close()+ def test_this_macs_full_screen_setting_alone_decides_its_edges_while_the_pc_drives_it(self):+ for enabled in (False, True):+ with self.subTest(hold_full_screen=enabled):+ duo = self.duo(crossing={"edge": "right", "hold_full_screen": enabled})+ self.drive(duo, "right")+ duo.mac.full_screen_app = "Steam"+ duo.pc_leans(MAC_EDGE_POINT["right"], 30, times=4)+ if enabled:+ self.assertIsNone(duo.pc_switch(0.2), "the Mac's enabled hold let the PC cross its edge")+ else:+ self.assertIsNotNone(duo.pc_switch(), "the Mac's disabled hold held its edge")+ duo.close()+def test_this_macs_own_pointer_can_take_input_back_only_with_its_own_link_to_the_pc_up(self):# Pinned known gap (G7 in the report): the push back needs the Mac's own link.duo = self.duo(crossing={"edge": "right"})diff --git a/mac_app/tests/test_effect_fires.py b/mac_app/tests/test_effect_fires.pyindex eab3981..ea92730 100644--- a/mac_app/tests/test_effect_fires.py+++ b/mac_app/tests/test_effect_fires.py@@ -23,6 +23,7 @@ from PyObjCTools import AppHelperimport crossingimport desktop_macfrom kvm_bridge_app import TrayApp+from core import effectsdef _feel(**overrides):@@ -333,7 +334,7 @@ class MenuBarArmTest(unittest.TestCase):def test_a_top_corners_arm_fills_the_menu_bar_as_the_side_arm_fills_its_band(self):glow = self._glow("glow", (1720.0, 0.0, 8.0, 8.0), "right")self._draw(glow, 37.0)- side = 2.0 + glow.BAND_MAX+ side = effects.edge_depth(1728, 1117, "medium")self.assertAlmostEqual(glow.fill.frame().size.height, 37.0)self.assertAlmostEqual(glow.side.frame().size.width, side)# Still hung from the top of the screen.diff --git a/mac_app/tests/test_effect_layouts.py b/mac_app/tests/test_effect_layouts.pyindex b6c3bd3..835df18 100644--- a/mac_app/tests/test_effect_layouts.py+++ b/mac_app/tests/test_effect_layouts.py@@ -288,6 +288,12 @@ class ClassicPreviewTests(unittest.TestCase):self.assertGreater(pen.bounds[3], effects.CLASSIC_ARM - 10)self.assertLessEqual(pen.bounds[2], w + 4)+ def test_aperture_is_a_light_effect_and_has_a_preview(self):+ fx = effects.preview_effect("aperture")+ self.assertEqual((fx.id, fx.intensity), ("aperture", "showpiece"))+ self.assertEqual(effects.switch_effect("aperture", "glow").id, "aperture")+ self.assertTrue(effects.preview_scene(fx, 1.8, "edge", PALETTE)["pens"])+def test_only_the_styles_have_a_preview(self):self.assertIsNone(effects.preview_effect("nonsense"))self.assertEqual(effects.preview_effect("flint").id, "flint")@@ -309,7 +315,7 @@ class LengthTests(unittest.TestCase):lasted[length] = tself.assertLess(lasted["short"], lasted["normal"])self.assertLess(lasted["normal"], lasted["long"])- self.assertAlmostEqual(lasted["long"] / lasted["normal"], 1.5, delta=0.1)+ self.assertAlmostEqual(lasted["long"] / lasted["normal"], 2.0, delta=0.1)def test_the_push_follows_the_hand_whatever_the_length(self):fx = effects.effect("flint")diff --git a/mac_app/tests/test_effect_size_settings.py b/mac_app/tests/test_effect_size_settings.pynew file mode 100644index 0000000..f591396--- /dev/null+++ b/mac_app/tests/test_effect_size_settings.py@@ -0,0 +1,28 @@+import unittest+from unittest import mock++import config as config_module+import kvm_bridge_app+import settings_store+++class EffectSizeSettingsTests(unittest.TestCase):+ def test_top_edge_band_never_exceeds_the_selected_depth(self):+ with mock.patch.object(kvm_bridge_app, "menu_bar_height", return_value=36):+ band = kvm_bridge_app.EdgeGlow._top_band(None, 40, False, (0, 0, 1512, 982), 24)+ self.assertEqual(band, 24)++ def test_missing_size_defaults_to_medium_and_round_trips(self):+ raw = settings_store.config_to_raw(settings_store.editable_default_config())+ raw["crossing"].pop("effect_size", None)+ self.assertEqual(config_module.parse_config(raw).crossing["effect_size"], "medium")++ raw["crossing"]["effect_size"] = "large"+ loaded = config_module.parse_config(raw)+ settings_store.SettingsStore("/unused")._validate(loaded)+ saved = settings_store.config_to_raw(loaded)+ self.assertEqual(saved["crossing"]["effect_size"], "large")+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_effects_overlay.py b/mac_app/tests/test_effects_overlay.pyindex 52744af..6072522 100644--- a/mac_app/tests/test_effects_overlay.py+++ b/mac_app/tests/test_effects_overlay.py@@ -603,7 +603,7 @@ class RealEffectIntegrationTest(unittest.TestCase):drew_something = Falsechecked_any = Falsefor effect_id in effects.EFFECT_IDS:- module_name = _MODULE_FOR_EFFECT[effect_id]+ module_name = "fx_light" if effect_id == "aperture" else _MODULE_FOR_EFFECT[effect_id]with self.subTest(effect=effect_id, module=module_name):try:importlib.import_module(f"core.{module_name}")diff --git a/mac_app/tests/test_full_screen.py b/mac_app/tests/test_full_screen.pyindex 2691a5e..0a0b50c 100644--- a/mac_app/tests/test_full_screen.py+++ b/mac_app/tests/test_full_screen.py@@ -1,6 +1,9 @@+import osimport sysimport unittestfrom pathlib import Path+from types import SimpleNamespace+from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -19,6 +22,18 @@ def window(pid, layer, x, y, width, height):class CoversADisplayTest(unittest.TestCase):+ def test_beamer_is_not_a_full_screen_app_to_itself(self):+ app = mock.Mock()+ workspace = mock.Mock()+ workspace.frontmostApplication.return_value = app+ app.localizedName.return_value = "Beamer"+ app.processIdentifier.return_value = os.getpid()+ appkit = SimpleNamespace(NSWorkspace=SimpleNamespace(sharedWorkspace=lambda: workspace))+ with mock.patch.object(kvm_bridge_app, "AppKit", appkit), \+ mock.patch.object(kvm_bridge_app, "_ax_full_screen", return_value=True) as ax:+ self.assertIsNone(kvm_bridge_app.full_screen_app())+ ax.assert_not_called()+def test_a_zoomed_window_under_the_menu_bar_is_not_full_screen(self):self.assertFalse(kvm_bridge_app._covers_a_display([window(9, 0, 0, 33, 1728, 1084)], 9, DISPLAYS)diff --git a/mac_app/tests/test_jump_key_recorder_layout.py b/mac_app/tests/test_jump_key_recorder_layout.pynew file mode 100644index 0000000..854549f--- /dev/null+++ b/mac_app/tests/test_jump_key_recorder_layout.py@@ -0,0 +1,28 @@+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import AppKit++AppKit.NSApplication.sharedApplication()++import theme+import widgets+++class JumpKeyRecorderLayoutTests(unittest.TestCase):+ def test_empty_key_uses_body_type_and_the_hint_sits_below(self):+ recorder = widgets.JumpKeyRecorder()+ font = recorder.key.view.attributedStringValue().attribute_atIndex_effectiveRange_(+ AppKit.NSFontAttributeName, 0, None+ )[0]++ self.assertEqual(font.pointSize(), theme.TYPE["body"])+ self.assertNotIn("Mono", font.fontName())+ self.assertEqual(recorder.line.orientation(), AppKit.NSUserInterfaceLayoutOrientationVertical)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_link_state.py b/mac_app/tests/test_link_state.pyindex 5074280..57610c6 100644--- a/mac_app/tests/test_link_state.py+++ b/mac_app/tests/test_link_state.py@@ -79,7 +79,9 @@ class LinkStateTest(unittest.TestCase):self.assertState("windows", "signal", redirecting=True)self.assertState("unlocking", "amber", status="Unlocking STUDIO-PC…", windows_locked=True, redirecting=True)self.assertState("paused", "ink", crossing_paused=True)- self.assertState("full_screen", "ink", full_screen_app="Final Cut Pro")+ state = link_state.describe(controller(full_screen_app="Final Cut Pro"))+ self.assertEqual((state.key, state.word, state.detail),+ ("full_screen", "Held", "Held: an app is full screen."))self.assertState("waking", "amber", waking=True, connected=False)def test_tunnel_is_tagged(self):diff --git a/mac_app/tests/test_mac_links.py b/mac_app/tests/test_mac_links.pyindex db7265d..897ee6f 100644--- a/mac_app/tests/test_mac_links.py+++ b/mac_app/tests/test_mac_links.py@@ -458,6 +458,12 @@ class ComingHomeTests(Base):self.assertEqual(let_go["target"], self.own)self.assertEqual(self.alerts, [])+ def test_the_log_names_the_edge_input_comes_home_at(self):+ with self.assertLogs(self.controller.logger, level="INFO") as said:+ self.arrives(protocol.switch_v6(1, protocol.read_id(self.own), "right", 0.25))+ moves = [line for line in said.output if "move applied:" in line]+ self.assertTrue(moves and "at the right edge" in moves[-1], said.output)+def test_a_send_home_without_a_position_still_returns_input_and_shows_the_arrival(self):self.arrives(protocol.switch_v6(1, protocol.read_id(self.own)))self.assertFalse(self.controller.redirecting)diff --git a/mac_app/tests/test_machines_panel.py b/mac_app/tests/test_machines_panel.pyindex 310f9dc..5a7f30f 100644--- a/mac_app/tests/test_machines_panel.py+++ b/mac_app/tests/test_machines_panel.py@@ -579,9 +579,23 @@ class CodeBoxCentringTests(Base):window.setContentSize_((773, window.frame().size.height))boxes = self.panel.code_boxesboxes.focus(window)+ boxes.fields[0].selectText_(None)+ self.assertIsInstance(window.firstResponder(), AppKit.NSTextView)for digit in "408819":window.firstResponder().insertText_(digit)self.assertEqual(boxes.value, "408819")+ editor = boxes.fields[-1].currentEditor()+ self.assertIsNotNone(editor, "the last code box must still be in field-editor mode")+ self.assertEqual(editor.alignment(), AppKit.NSTextAlignmentCenter)+ self.assertEqual(+ editor.typingAttributes()[AppKit.NSParagraphStyleAttributeName].alignment(),+ AppKit.NSTextAlignmentCenter,+ )+ layout = editor.layoutManager()+ glyph_range = layout.glyphRangeForCharacterRange_actualCharacterRange_((0, 1), None)[0]+ glyph = layout.boundingRectForGlyphRange_inTextContainer_(glyph_range, editor.textContainer())+ offset = glyph.origin.x + glyph.size.width / 2 - editor.bounds().size.width / 2+ self.assertLessEqual(abs(offset), 0.3, f"the active field editor draws the digit off-centre: {offset}")window.contentView().layoutSubtreeIfNeeded()view = boxes.viewbounds = view.bounds()diff --git a/mac_app/tests/test_pages.py b/mac_app/tests/test_pages.pyindex 05de160..9b57e0f 100644--- a/mac_app/tests/test_pages.py+++ b/mac_app/tests/test_pages.py@@ -82,12 +82,13 @@ class DesignChoicesTest(unittest.TestCase):from core import effectsgroups = pages.style_groups()- self.assertEqual([group for group, _ in groups], ["Classic", "Membrane", "Sparks", "Instrument"])- self.assertEqual([value for value, _title, _detail in groups[0][1]], ["glow", "beam"])+ self.assertEqual([group for group, _ in groups], ["Light", "Membrane", "Sparks", "Instrument", "Folio", "Selvedge"])+ self.assertEqual([value for value, _title, _detail in groups[0][1]], ["glow", "beam", "aperture"])+ self.assertEqual([detail for _value, _title, detail in groups[0][1]], ["Quiet", "Medium", "Showpiece"])for group, choices in groups[1:]:with self.subTest(group=group):self.assertEqual([detail for _value, _title, detail in choices], ["Quiet", "Medium", "Showpiece"])- values = [value for _group, choices in groups[1:] for value, _title, _detail in choices]+ values = [value for _group, choices in groups for value, _title, _detail in choices if value not in ("glow", "beam")]self.assertEqual(tuple(values), effects.EFFECT_IDS)self.assertEqual(groups[1][1][0][:2], ("skin", "Skin"))@@ -96,8 +97,8 @@ class DesignChoicesTest(unittest.TestCase):from core import effectsgroups = pages.colour_groups(crossing.GLOW_COLOURS)- self.assertEqual(groups[0], ("Classic", [(name, name.capitalize()) for name in crossing.GLOW_COLOURS]))- self.assertEqual([group for group, _ in groups[1:]], ["Membrane", "Sparks", "Instrument"])+ self.assertEqual(groups[0], ("Light", [(name, name.capitalize()) for name in crossing.GLOW_COLOURS]))+ self.assertEqual([group for group, _ in groups[1:]], ["Membrane", "Sparks", "Instrument", "Folio", "Selvedge"])self.assertEqual(tuple(value for _group, choices in groups[1:] for value, _title in choices), effects.PACK_IDS)self.assertIn(("sodium", "Sodium"), groups[3][1])@@ -105,8 +106,8 @@ class DesignChoicesTest(unittest.TestCase):import crossingself.assertIsNone(pages.effects_load_error())- self.assertEqual([group for group, _ in pages.style_groups(False)], ["Classic"])- self.assertEqual([group for group, _ in pages.colour_groups(crossing.GLOW_COLOURS, False)], ["Classic"])+ self.assertEqual([group for group, _ in pages.style_groups(False)], ["Light"])+ self.assertEqual([group for group, _ in pages.colour_groups(crossing.GLOW_COLOURS, False)], ["Light"])from unittest import mockfrom core import effects@@ -129,7 +130,7 @@ class DesignChoicesTest(unittest.TestCase):def test_glow_and_beam_tiles_read_as_the_effects_do(self):today = pages.style_groups()[0][1]- self.assertEqual([detail for _value, _name, detail in today], ["Classic", "Classic"])+ self.assertEqual([detail for _value, _name, detail in today], ["Quiet", "Medium", "Showpiece"])def test_the_notch_style_only_matters_under_glow_and_beam(self):self.assertTrue(pages.notch_style_applies("glow"))@@ -189,7 +190,7 @@ class CrossingPageRulesTests(unittest.TestCase):self.assertTrue(line(True, True, False, True, False, None).startswith("Not connected to any machine"))self.assertEqual(line(True, True, True, False, False, None), "Only the shortcut is switched on; there is nothing to pause.")self.assertTrue(line(True, True, True, True, True, None).startswith("Paused."))- self.assertTrue(line(True, True, True, True, False, "Keynote").startswith("Off while Keynote is full screen"))+ self.assertEqual(line(True, True, True, True, False, "Keynote"), "Held: an app is full screen.")self.assertEqual(line(True, True, True, True, False, None), "On. Pause it to lean on an edge without switching.")def test_a_reason_shows_even_when_only_the_shortcut_is_on(self):diff --git a/mac_app/tests/test_same_on_both.py b/mac_app/tests/test_same_on_both.pyindex 58ae974..11ed0c3 100644--- a/mac_app/tests/test_same_on_both.py+++ b/mac_app/tests/test_same_on_both.py@@ -45,6 +45,7 @@ class SameOnBothTests(unittest.TestCase):path = Path(self.directory.name) / "config.json"raw = settings_store.config_to_raw(settings_store.editable_default_config())raw.update(host="192.0.2.20", auth_token=PAIRED_TOKEN)+ raw["crossing"]["hold_full_screen"] = Trueraw["crossing"]["methods"] = ["shortcut", "edge", "notch"]path.write_text(json.dumps(raw))self.store = settings_store.SettingsStore(path)@@ -65,6 +66,167 @@ class SameOnBothTests(unittest.TestCase):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_full_screen_hold_switch_names_this_macs_edges(self):+ self.assertEqual(self.window.hold_box.words.text, "Hold this Mac's edges while an app on it is full screen")+ def test_this_machines_design_state_is_sent_even_when_same_is_off(self):+ data = self.window.same_state()++ self.assertFalse(data["on"])+ self.assertEqual(set(data["design_sync"]["values"]), set(settings_sync.DESIGN_KEYS))+ self.assertEqual(data["design_sync"]["values"]["effect_size"], "medium")++ def test_a_followed_machine_changes_this_design_and_this_mac_announces_its_own_state(self):+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))+ received = settings_sync.message_data(+ False, 50, by=PEER,+ design_state={"set_at": 100, "by": PEER,+ "values": {"effect_length": "long", "effect_size": "large"}},+ )++ self.window.apply_same(received, peer=PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "long")+ self.assertEqual(self.window.size_select.value, "large")+ self.assertEqual((self.window.controller.cfg.design_set_at, self.window.controller.cfg.design_by),+ (100, PEER))+ self.assertTrue(self.sent)+ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "long")+ self.assertEqual((self.sent[-1]["design_sync"]["set_at"], self.sent[-1]["design_sync"]["by"]),+ (100, PEER))++ def test_a_design_state_in_a_malformed_settings_envelope_is_dropped_whole(self):+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))+ state = {"set_at": 100, "by": PEER, "values": {"effect_length": "long"}}++ for outer in ({"on": "no"}, {"set_at": True}, {"by": "not an id"}):+ data = settings_sync.message_data(False, 50, by=PEER, design_state=state)+ data.update(outer)+ self.window.apply_same(data, peer=PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "normal")+ self.assertNotIn(PEER, self.window._design_states)+ self.assertEqual(self.sent, [])++ def test_follow_accepts_the_leaders_next_change_after_this_mac_reannounces(self):+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ raw["design_set_at"] = 50+ raw["design_by"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))++ self.window._receive_design(settings_sync.message_data(+ False, 50, by=PEER,+ design_state={"set_at": 100, "by": PEER, "values": {"effect_length": "long"}},+ ), PEER)+ self.window._receive_design(settings_sync.message_data(+ False, 51, by=PEER,+ design_state={"set_at": 101, "by": PEER, "values": {"effect_length": "short"}},+ ), PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "short")+ self.assertEqual((self.window.controller.cfg.design_set_at, self.window.controller.cfg.design_by),+ (101, PEER))+ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "short")+ self.assertEqual((self.sent[-1]["design_sync"]["set_at"], self.sent[-1]["design_sync"]["by"]),+ (101, PEER))++ def test_same_on_design_change_is_announced_with_a_new_local_design_stamp(self):+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["same_on_both"] = True+ raw["same_set_at"] = 10+ raw["same_by"] = PEER+ raw["design_set_at"] = 20+ raw["design_by"] = self.window.own_id()+ raw["crossing"]["effect_length"] = "short"+ self.window.controller.apply_settings(self.store.save(raw))+ incoming = settings_sync.message_data(+ True, 11, values={"effect_length": "long"}, by=HIGH,+ design_state={"set_at": 100, "by": HIGH, "values": {"effect_length": "long"}},+ )++ self.window.apply_same(incoming, peer=HIGH)++ cfg = self.window.controller.cfg+ self.assertEqual(cfg.crossing["effect_length"], "long")+ self.assertGreater(cfg.design_set_at, 100)+ self.assertEqual(cfg.design_by, self.window.own_id())+ self.assertEqual(self.sent[-1]["design_sync"]["set_at"], cfg.design_set_at)+ self.assertNotEqual(self.sent[-1]["design_sync"]["by"], HIGH)++ def test_same_off_from_another_machine_resumes_the_cached_followed_design(self):+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["same_on_both"] = True+ raw["same_set_at"] = 10+ raw["same_by"] = HIGH+ raw["design_follow_peer"] = PEER+ raw["crossing"]["effect_length"] = "short"+ self.window.controller.apply_settings(self.store.save(raw))+ self.window._design_states[PEER] = {+ "set_at": 100, "by": PEER, "values": {"effect_length": "long"},+ }+ incoming = settings_sync.message_data(False, 11, by=HIGH)++ self.window.apply_same(incoming, peer=HIGH)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "long")+ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "long")+ self.assertEqual((self.sent[-1]["design_sync"]["set_at"], self.sent[-1]["design_sync"]["by"]),+ (100, PEER))++ def test_same_on_all_machines_takes_precedence_without_clearing_following(self):+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw.update(design_follow_peer=PEER, same_on_both=True, same_set_at=100)+ self.window.controller.apply_settings(self.store.save(raw))+ received = settings_sync.message_data(+ True, 101, settings_sync.mac_values(raw), by=PEER,+ design_state={"set_at": 202, "by": PEER, "values": {"effect_length": "long"}},+ )++ self.window.apply_same(received, peer=PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "normal")+ self.assertEqual(self.window.controller.cfg.design_follow_peer, PEER)++ def test_editing_a_design_control_turns_following_off_and_announces_the_edit(self):+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))+ self.sent.clear()+ self.window.length_select.value = "short"++ self.window._apply_settings()++ self.assertEqual(self.window.controller.cfg.design_follow_peer, "")+ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "short")++ def test_removing_the_followed_machine_resets_the_local_selection(self):+ entry = {**settings_store.PEER_DEFAULTS, "id": PEER, "token": "peer-token", "name": "Peer",+ "platform": "windows", "port": protocol.DEFAULT_PORT}+ self.store.add_peer(entry)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))++ self.store.remove_peer("peer-token")+ self.window.peers_changed()++ self.assertEqual(self.window.controller.cfg.design_follow_peer, "")++ def test_a_peer_that_has_not_sent_a_design_state_is_disabled(self):+ entry = {**settings_store.PEER_DEFAULTS, "id": PEER, "token": "peer-token", "name": "Old PC",+ "platform": "windows", "port": protocol.DEFAULT_PORT}+ self.store.add_peer(entry)++ self.window._refresh_design_follow()++ cell = next(cell for value, cell, _words in self.window.follow_select.cells if value == PEER)+ self.assertFalse(cell.enabled)+ self.assertIn("Needs beta.6 or later", next(title for value, title in self.window.follow_select.choices if value == PEER))+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@@ -87,6 +249,7 @@ class SameOnBothTests(unittest.TestCase):self.assertEqual(self.window.panel.pair_status.text, "That code was not accepted.")def test_the_hold_switch_reaches_the_controller_before_the_debounce(self):+ self.window.hold_box.value = Trueself.window.controller.full_screen_app = "Game"self.window.hold_box._toggle()self.assertIs(self.window.controller.cfg.crossing["hold_full_screen"], False)@@ -95,6 +258,7 @@ class SameOnBothTests(unittest.TestCase):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.value = Trueself.window.hold_box._toggle()self.window.apply_same(pc_message(True, 100))self.assertFalse(self.window.hold_box.value)@@ -123,10 +287,25 @@ class SameOnBothTests(unittest.TestCase):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):+ def test_a_design_change_while_off_announces_its_local_design_state(self):self.window.length_select.value = "short"self.window._apply_settings()- self.assertEqual(self.sent, [])+ self.assertEqual(len(self.sent), 1)+ self.assertFalse(self.sent[0]["on"])+ self.assertEqual(self.sent[0]["design_sync"]["values"]["effect_length"], "short")++ def test_changing_size_redraws_the_design_tiles(self):+ from unittest import mock++ stills = [mock.Mock() for _ in self.window.effect_stills]+ self.window.effect_stills = stills+ with mock.patch.object(self.window.previews, "repaint") as repaint:+ self.window.size_select.value = "small"+ self.window._reflect()+ self.assertTrue(stills)+ for still in stills:+ still.setNeedsDisplay_.assert_called_once_with(True)+ repaint.assert_called_once_with()def test_an_old_pc_turns_the_switch_off_and_says_why(self):self.window._set_same(True)@@ -136,10 +315,12 @@ class SameOnBothTests(unittest.TestCase):self.assertFalse(self.window.same_switch.value)self.assertIn("too old", self.window.same_note.text)- def test_a_peers_state_is_sent_on_unchanged_to_the_others_but_not_back_to_it(self):+ def test_a_peers_same_state_is_forwarded_with_this_macs_own_design_state(self):data = pc_message(True, 100, by=PEER)self.window.apply_same(data, peer=PEER)- self.assertEqual(self.sent, [data])+ self.assertEqual(len(self.sent), 1)+ self.assertEqual({key: value for key, value in self.sent[0].items() if key != "design_sync"}, data)+ self.assertNotEqual(self.sent[0]["design_sync"]["by"], PEER)self.assertEqual(self.sources, [PEER])def test_who_made_the_change_is_kept_with_it(self):diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.pyindex ac830b1..b0afd6d 100644--- a/mac_app/tests/test_settings_store.py+++ b/mac_app/tests/test_settings_store.py@@ -92,15 +92,16 @@ class SettingsStoreTests(unittest.TestCase):store.set_jump_key(peer["id"], "", "alt_r")self.assertEqual(store.current()["peers"][0]["jump_key"], "")- def test_the_full_screen_hold_defaults_on_and_round_trips(self):+ def test_the_full_screen_hold_defaults_off_and_preserves_each_saved_choice(self):with tempfile.TemporaryDirectory() as directory:store = SettingsStore(Path(directory) / "settings.json")loaded = store.save(self.valid_raw())- self.assertTrue(loaded.crossing["hold_full_screen"])+ self.assertFalse(loaded.crossing["hold_full_screen"])+ for choice in (False, True):+ raw = config_to_raw(loaded)+ raw["crossing"]["hold_full_screen"] = choice+ self.assertEqual(store.save(raw).crossing["hold_full_screen"], choice)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)@@ -269,7 +270,7 @@ class SettingsStoreTests(unittest.TestCase):from core import effectspairs = [(style, "signal") for style in effects.EFFECT_IDS]- pairs += [(style, colour) for style in ("glow", "beam") for colour in effects.PACK_IDS]+ pairs += [(style, colour) for style in ("glow", "beam", "aperture") for colour in effects.PACK_IDS]pairs += list(zip(effects.EFFECT_IDS, effects.PACK_IDS))with tempfile.TemporaryDirectory() as directory:store = SettingsStore(Path(directory) / "settings.json")diff --git a/mac_app/tests/test_widgets.py b/mac_app/tests/test_widgets.pynew file mode 100644index 0000000..b753297--- /dev/null+++ b/mac_app/tests/test_widgets.py@@ -0,0 +1,37 @@+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import AppKit++AppKit.NSApplication.sharedApplication()++import theme+import widgets+++class WidthTests(unittest.TestCase):+ def test_reading_note_stays_capped_inside_a_wider_stack(self):+ parent = widgets.stack()+ note = widgets.note("A note that can wrap.")++ widgets.add(parent, note.view)++ constraints = list(note.view.constraints())+ cap = next(c for c in constraints if c.firstAttribute() == AppKit.NSLayoutAttributeWidth+ and c.relation() == AppKit.NSLayoutRelationLessThanOrEqual)+ reach = next(c for c in parent.constraints() if c.firstItem() == note.view+ and c.secondItem() == parent and c.firstAttribute() == AppKit.NSLayoutAttributeWidth)+ fill_to_cap = next(c for c in note.view.constraints() if c.firstItem() == note.view+ and c.secondItem() is None and c.firstAttribute() == AppKit.NSLayoutAttributeWidth+ and c.relation() == AppKit.NSLayoutRelationEqual)+ self.assertEqual(cap.constant(), theme.READING_WIDTH)+ self.assertEqual(reach.relation(), AppKit.NSLayoutRelationLessThanOrEqual)+ self.assertEqual(fill_to_cap.priority(), 255)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_window_geometry.py b/mac_app/tests/test_window_geometry.pynew file mode 100644index 0000000..e66ffb7--- /dev/null+++ b/mac_app/tests/test_window_geometry.py@@ -0,0 +1,138 @@+import sys+import unittest+import logging+import threading+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import kvm_bridge_app+import settings_store+++def offscreen_control_window():+ AppKit = kvm_bridge_app.AppKit+ AppKit.NSApplication.sharedApplication()+ token = "synthetic-render-only"+ cfg = settings_store.editable_default_config()+ cfg.host = "192.0.2.20"+ cfg.port = 24820+ cfg.auth_token = token+ cfg.pc_name = "Windows PC"+ store = object.__new__(settings_store.SettingsStore)+ store.lock = threading.RLock()+ store._handed_token = token+ store._cache = store._complete({**store._fresh(), "peers": []})+ logger = logging.getLogger("test-window-geometry")+ from wake import WakingController++ controller = WakingController(cfg, logger=logger)+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), mock.patch.object(+ kvm_bridge_app, "input_monitoring_granted", return_value=True+ ):+ return kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(+ controller, store, logger+ )+++class WindowGeometryTests(unittest.TestCase):+ def test_resizable_window_keeps_a_requested_full_screen_width(self):+ AppKit = kvm_bridge_app.AppKit+ window = offscreen_control_window()+ # The window takes its largest size from every constraint above WindowSizeStayPut (500),+ # so one page's rigid row or reading-width note used to cap it at 773 to 837 pt.+ screen_width = AppKit.NSScreen.mainScreen().visibleFrame().size.width++ window.window.setFrame_display_(((100000, 100000), (screen_width, 900)), False)+ from Foundation import NSDate, NSRunLoop++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ self.assertEqual(window.window.frame().size.width, screen_width)++ def test_a_full_screen_page_keeps_its_content_column_centred(self):+ window = offscreen_control_window()+ window.window.setFrame_display_(((100000, 100000), (1728, 900)), False)+ from Foundation import NSDate, NSRunLoop++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ # Every page: one row of a reading-width note and a button, with nothing to take the spare+ # width, held Overview's column at 706 pt and Connection's at 684.+ for key, page in window.pages.items():+ page = page.documentView()+ body = page.subviews()[0]+ with self.subTest(page=key):+ self.assertEqual(body.frame().size.width, kvm_bridge_app.theme.PAGE_CONTENT_WIDTH)+ left = body.frame().origin.x+ right = page.frame().size.width - left - body.frame().size.width+ self.assertAlmostEqual(left, right, delta=1)++ def test_a_full_screen_remove_question_keeps_its_buttons_their_own_width(self):+ from types import SimpleNamespace+ from Foundation import NSDate, NSRunLoop++ window = offscreen_control_window()+ state = SimpleNamespace(word="Connected", led="signal", blink=False, tone="signal", detail="")+ row = SimpleNamespace(label="Windows PC", state=state, token="t1", platform="Windows", address="192.0.2.20",+ in_use=True, drives=True, driven=True)+ window.panel.removing = "t1"+ window.panel._build_rows([row])+ window.window.setFrame_display_(((100000, 100000), (1728, 900)), False)+ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ def walk(view):+ yield view+ for sub in view.subviews():+ yield from walk(sub)++ chips = {view.accessibilityLabel(): view for view in walk(window.panel.list)+ if view.accessibilityLabel() in ("Confirm removing Windows PC", "Keep Windows PC")}+ self.assertEqual(len(chips), 2)+ # The question's note stopped at the reading width and the spare width went to Keep.+ for name, chip in chips.items():+ with self.subTest(chip=name):+ self.assertAlmostEqual(chip.frame().size.width, chip.fittingSize().width, delta=1)++ def test_zoom_uses_the_visible_screen_frame(self):+ frame = ((40.0, 24.0), (1440.0, 940.0))+ screen = mock.Mock()+ screen.visibleFrame.return_value = frame+ window = mock.Mock()+ window.screen.return_value = screen+ fill_frame = getattr(kvm_bridge_app, "window_fill_frame", lambda _window: None)++ self.assertEqual(fill_frame(window), frame)++ def test_the_global_titlebar_setting_selects_fill_or_minimise(self):+ action = getattr(kvm_bridge_app, "titlebar_action", lambda _setting: None)++ self.assertEqual(action("Fill"), "fill")+ self.assertEqual(action("Zoom"), "fill")+ self.assertEqual(action("Minimise"), "minimise")++ def test_double_click_applies_the_selected_titlebar_action(self):+ perform = getattr(kvm_bridge_app, "perform_titlebar_double_click", lambda *_args: None)+ window = mock.Mock()++ perform(window, "Fill")+ window.zoom_.assert_called_once_with(None)++ window.reset_mock()+ perform(window, "Minimise")+ window.miniaturize_.assert_called_once_with(None)++ def test_single_click_on_the_top_strip_starts_a_window_drag(self):+ strip = kvm_bridge_app.TitlebarStrip.alloc().initWithFrame_(((0, 0), (1, 1)))+ event = mock.Mock()+ event.clickCount.return_value = 1++ with mock.patch.object(kvm_bridge_app, "perform_titlebar_drag") as drag:+ strip.mouseDown_(event)++ drag.assert_called_once_with(strip.window(), event)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/widgets.py b/mac_app/widgets.pyindex 70358f0..a1d46f5 100644--- a/mac_app/widgets.py+++ b/mac_app/widgets.py@@ -38,12 +38,38 @@ def stack(vertical: bool = True, spacing: float = 10.0):return view+def _width_cap(view):+ for c in view.constraints():+ if (+ c.firstItem() == view+ and c.secondItem() is None+ and c.firstAttribute() == AppKit.NSLayoutAttributeWidth+ and c.relation() == AppKit.NSLayoutRelationLessThanOrEqual+ ):+ return c.constant()+ return None++def add(parent, view, full_width: bool = True):"""Adds an arranged subview, stretched to the stack's width. NSStackView aligns its children- but does not stretch them, and a control that stops short of the module edge is the giveaway."""+ but does not stretch them, and a control that stops short of the module edge is the giveaway.+ A child with its own maximum width (a note at the reading width) is as wide as the stack up to+ that maximum. Tied to the stack outright, it fixed its whole column at that width, and through+ the column the window: on 1.5.0 the window could not be made wider than 773 to 837 pt."""parent.addArrangedSubview_(view)- if full_width:+ if not full_width:+ return view+ cap = _width_cap(view)+ if cap is None:view.widthAnchor().constraintEqualToAnchor_(parent.widthAnchor()).setActive_(True)+ return view+ view.widthAnchor().constraintLessThanOrEqualToAnchor_(parent.widthAnchor()).setActive_(True)+ # Towards the cap rather than the stack, so the pull never grows with the column. Above the+ # label's own hugging (251), so it fills to the cap; below NSStackView's equal sizing (260),+ # so it cannot unbalance Pairing's two halves.+ reach = view.widthAnchor().constraintEqualToConstant_(cap)+ reach.setPriority_(255)+ reach.setActive_(True)return view@@ -130,9 +156,9 @@ class Label:squeeze(self.view)self._render()- def set(self, text=None, ink=None, size=None, weight=None):+ def set(self, text=None, ink=None, size=None, weight=None, mono=None):changed = False- for name, value in (("text", text), ("ink", ink), ("size", size), ("weight", weight)):+ for name, value in (("text", text), ("ink", ink), ("size", size), ("weight", weight), ("mono", mono)):if value is not None and value != getattr(self, name):setattr(self, name, value)changed = True@@ -153,9 +179,12 @@ def eyebrow(text, ink="ink_3"):return Label(text, theme.TYPE["eyebrow"], 700, ink, tracking=theme.TRACKING["eyebrow"], upper=True).view-def note(text="", ink="ink_2", align=None):+def note(text="", ink="ink_2", align=None, reading=True):+ """`reading=False` for a note beside a control in a row: capped there, nothing could take the+ row's spare width, and the row, its module and the page column stopped at note plus control."""label = Label(text, theme.TYPE["note"], ink=ink, wrap=True, align=align)- label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)+ if reading:+ label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)return label@@ -1150,15 +1179,24 @@ class JumpKeyRecorder:face = box("ground", radius=theme.RADIUS["keycap"] - 1)self.view.addSubview_(face)pin(face, self.view, (1, 1, 3, 1))- self.key = Label(self._title(), theme.TYPE["keycap"], mono=True, tracking=-0.02)+ self.key = Label(self._title(), theme.TYPE["body"], ink="ink_3")squeeze(self.key.view)- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight)- line = stack(vertical=False, spacing=10)- line.addArrangedSubview_(self.key.view)- line.addArrangedSubview_(self.hint.view)- hug(self.key.view, AppKit.NSLayoutPriorityDefaultLow)+ self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentLeft)+ self.line = stack(spacing=5)+ self.line.addArrangedSubview_(self.key.view)+ self.line.addArrangedSubview_(self.hint.view)+ line = self.lineface.addSubview_(line)- pin(line, face, (9, 12, 8, 12))+ pin(line, face, (7, 12, 7, 12))++ def _show_title(self, ink=None):+ has_value = bool(self.value)+ self.key.set(+ self._title(),+ size=theme.TYPE["keycap"] if has_value else theme.TYPE["body"],+ ink=ink or ("ink" if has_value else "ink_3"),+ mono=has_value,+ )def _title(self):if not self.value:@@ -1168,14 +1206,14 @@ class JumpKeyRecorder:def set_value(self, value):self.value = value or ""- self.key.set(self._title())+ self._show_title()self.view.setAccessibilityLabel_("Jump straight here key, " + self._title())def _clicked(self):if self.monitor is not None:self._stop()return- self.key.set("Press a key combination…", ink="signal")+ self.key.set("Press a key combination…", size=theme.TYPE["body"], ink="signal", mono=False)self.hint.set("Click again to cancel")paint(self.view, "signal")self.monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(@@ -1213,7 +1251,7 @@ class JumpKeyRecorder:self.monitor = Noneif self.on_arm is not None:self.on_arm(False)- self.key.set(self._title(), ink="ink")+ self._show_title()self.hint.set(self.HINT)paint(self.view, "edge")diff --git a/theme.py b/theme.pyindex ce55215..4136a27 100644--- a/theme.py+++ b/theme.py@@ -24,6 +24,7 @@ RADIUS = tokens.RADIUSTRACKING = tokens.TRACKINGMODULE_PADDING = tokens.MODULE_PADDINGRACK_GAP = tokens.RACK_GAP+PAGE_CONTENT_WIDTH = tokens.PAGE_CONTENT_WIDTHMIN_WINDOW = tokens.MIN_WINDOW["mac"]# Derived here rather than added to the shared tokens: the mock's negative tracking on the large@@ -245,7 +246,7 @@ def appearance_named(dark: bool):return AppKit.NSAppearance.appearanceNamed_(AppKit.NSAppearanceNameDarkAqua if dark else AppKit.NSAppearanceNameAqua)# The longest a line of running text may get before it wraps, whatever the window width.-READING_WIDTH = 560.0+READING_WIDTH = tokens.READING_WIDTHclass AppearanceWatch(AppKit.NSObject):diff --git a/tokens.py b/tokens.pyindex dbb5b81..e10a308 100644--- a/tokens.py+++ b/tokens.py@@ -115,6 +115,8 @@ RADIUS = {MODULE_PADDING = (14.0, 16.0)RACK_GAP = 1.0MIN_WINDOW = {"mac": (640, 540), "windows": (640, 600)}+READING_WIDTH = 560.0+PAGE_CONTENT_WIDTH = 960.0# Mass-spring parameters (mass 1) for everything that moves. The notch island integrates two of# these, width and depth; a trackpad tick adds `tick_velocity` points per second to the width.diff --git a/win_app/app_config.py b/win_app/app_config.pyindex 90dedc1..b508490 100644--- a/win_app/app_config.py+++ b/win_app/app_config.py@@ -52,7 +52,7 @@ TRIGGER_VKS = {}TRIGGER_KEYS = {name: capture_win.VK_TITLES[vk] for name, vk in TRIGGER_VKS.items()}UNRECORDABLE_TRIGGER_VKS = capture_win.UNRECORDABLE_TRIGGER_VKS-MODIFIER_STYLES = ("semantic", "positional")+MODIFIER_STYLES = ("semantic", "positional", "mac_layout")def palette_colours(colour: str) -> tuple:@@ -95,6 +95,7 @@ class Config:shortcut_arrival_style: str = "match"# How long an effect takes to play through once the pointer crosses: see effects.LENGTHS.effect_length: str = "normal"+ effect_size: str = "medium"# The Mac's name from the last pairing, for the window to say who this PC is paired with.paired_with: str = ""# Whether each machine may take the other's input. Two plain switches: the@@ -110,6 +111,9 @@ class Config:same_set_at: int = 0# The machine that made that last change, its id as base64: the larger id wins a tie.same_by: str = ""+ design_set_at: int = 0+ design_by: str = ""+ design_follow_peer: str = ""# How the Mac's pointer and scroll feel on this PC; see receiver.InputScale.pointer_speed: float = 1.0scroll_speed: float = 1.0@@ -132,7 +136,7 @@ class Config:# 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+ hold_full_screen: bool = False# The Mac's address is learned, never typed: it is the peer address the# Mac's own link arrives from.mac_host: str = ""@@ -272,6 +276,9 @@ def validate_config(config: Config) -> None:lengths = tuple(value for value, _name in effects.LENGTHS)if config.effect_length not in lengths:raise ConfigError(f"effect_length must be one of: {', '.join(lengths)}")+ sizes = tuple(value for value, _name in effects.SIZES)+ if config.effect_size not in sizes:+ raise ConfigError(f"effect_size must be one of: {', '.join(sizes)}")if not isinstance(config.paired_with, str):raise ConfigError("paired_with must be text")if not isinstance(config.send_to_mac, bool):@@ -313,6 +320,7 @@ def config_from_dict(raw: dict) -> Config:shortcut_arrival=raw.get("shortcut_arrival", True),shortcut_arrival_style=switch_style,effect_length=raw.get("effect_length", "normal"),+ effect_size=raw.get("effect_size", "medium"),paired_with=raw.get("paired_with", "") or "",allow_mac_to_drive=raw.get("allow_mac_to_drive", True),check_updates=raw.get("check_updates", True),@@ -320,6 +328,9 @@ def config_from_dict(raw: dict) -> Config:same_on_both=raw.get("same_on_both", False),same_set_at=_stamp(raw.get("same_set_at", 0)),same_by=raw.get("same_by", "") or "",+ design_set_at=_stamp(raw.get("design_set_at", 0)),+ design_by=raw.get("design_by", "") or "",+ design_follow_peer=raw.get("design_follow_peer", "") or "",pointer_speed=raw.get("pointer_speed", 1.0),scroll_speed=raw.get("scroll_speed", 1.0),reverse_scroll=raw.get("reverse_scroll", False),@@ -333,7 +344,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),+ hold_full_screen=raw.get("hold_full_screen", False),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 "",@@ -378,6 +389,7 @@ def config_to_dict(config: Config) -> dict:"shortcut_arrival": config.shortcut_arrival,"shortcut_arrival_style": config.shortcut_arrival_style,"effect_length": config.effect_length,+ "effect_size": config.effect_size,"paired_with": config.paired_with,"allow_mac_to_drive": config.allow_mac_to_drive,"check_updates": config.check_updates,@@ -385,6 +397,9 @@ def config_to_dict(config: Config) -> dict:"same_on_both": config.same_on_both,"same_set_at": int(config.same_set_at),"same_by": config.same_by,+ "design_set_at": int(config.design_set_at),+ "design_by": config.design_by,+ "design_follow_peer": config.design_follow_peer,"pointer_speed": config.pointer_speed,"scroll_speed": config.scroll_speed,"reverse_scroll": config.reverse_scroll,diff --git a/win_app/capture_win.py b/win_app/capture_win.pyindex f889041..87a543d 100644--- a/win_app/capture_win.py+++ b/win_app/capture_win.py@@ -44,7 +44,8 @@ import loggingimport sysimport threadingimport time-from typing import Callable, Dict, List, Optional, Set, Tuple+import unicodedata+from typing import Callable, Dict, List, Optional, Set, Tuple, Unionfrom input_injector import INJECTED_MARK, SCAN_TO_US@@ -274,28 +275,70 @@ class KeyboardState:"""The keyboard bytes ToUnicodeEx is asked to translate against: shift andcaps lock as they really are, every other modifier cleared. Held as aplain dict of virtual key to byte so the translation is testable without- Windows."""+ Windows. Dead accents stay here in software, never in Windows' keyboard state."""def __init__(self) -> None:self.shift_down = Falseself.caps_lock = False+ self.pending_dead_key: Optional[str] = Nonedef bytes_for(self) -> Dict[int, int]:state = {VK_SHIFT: 0x80 if self.shift_down else 0x00, VK_CAPITAL: 0x01 if self.caps_lock else 0x00}return state-def key_name(vk: int, scan: int, state: KeyboardState, translate: Callable[[int, int, Dict[int, int]], Optional[str]]) -> Optional[str]:+class DeadKey:+ def __init__(self, character: str) -> None:+ self.character = character+++class TextInput:+ def __init__(self, text: str) -> None:+ self.text = text+++def _compose_dead_key(dead_key: str, character: str) -> Union[str, TextInput]:+ name = unicodedata.name(dead_key, "")+ if name.startswith("MODIFIER LETTER "):+ name = name[len("MODIFIER LETTER "):]+ try:+ combining = unicodedata.lookup("COMBINING " + name)+ except KeyError:+ return TextInput(dead_key + character)+ composed = unicodedata.normalize("NFC", character + combining)+ return composed if len(composed) == 1 else TextInput(dead_key + character)+++def key_name(+ vk: int,+ scan: int,+ state: KeyboardState,+ translate: Callable[[int, int, Dict[int, int]], Optional[Union[str, DeadKey]]],+ down: bool = True,+) -> Optional[Union[str, DeadKey, TextInput]]:"""The wire name for one key press: a named key where there is one, else- the character it types with only shift and caps lock applied, else None- when the layout produces nothing usable (a dead key, or a key with no- character at all)."""+ the character it types with only shift and caps lock applied. A dead key+ waits for the next printable character; a key with no usable character is+ ignored."""named = VK_TO_NAME.get(vk)if named is not None:+ if state.pending_dead_key and named == "space":+ character, state.pending_dead_key = state.pending_dead_key, None+ return character+ if state.pending_dead_key and named not in MODIFIER_NAMES:+ state.pending_dead_key = Nonereturn namedcharacter = translate(vk, scan, state.bytes_for())+ if isinstance(character, DeadKey):+ if down:+ state.pending_dead_key = character.character+ return DeadKey(character.character)if not character or not character.isprintable():+ state.pending_dead_key = Nonereturn None+ if down and state.pending_dead_key:+ character = _compose_dead_key(state.pending_dead_key, character)+ state.pending_dead_key = Nonereturn character@@ -409,6 +452,8 @@ class Hooks:self._thread_id: Optional[int] = Noneself._ready = threading.Event()self._state = KeyboardState()+ self._dead_keys_swallowed: Set[int] = set()+ self._text_keyups_swallowed: Set[int] = set()self._failure: Optional[BaseException] = Noneself._handles: List[int] = []# Kept alive for as long as the hooks are installed: a callback that@@ -444,6 +489,10 @@ class Hooks:thread.join(timeout=2.0)if thread.is_alive():LOGGER.error("The hook thread did not stop within two seconds")+ else:+ self._text_keyups_swallowed.clear()+ else:+ self._text_keyups_swallowed.clear()self._thread = Noneself._thread_id = None@@ -496,6 +545,7 @@ class Hooks:# a freed callback on its first WM_INPUT._unregister_window_class(module)self._callbacks = []+ self._text_keyups_swallowed.clear()def _window_proc(self, hwnd, message, wparam, lparam):if message == WM_INPUT:@@ -521,7 +571,30 @@ class Hooks:self._state.shift_down = downelif data.vkCode == VK_CAPITAL and down:self._state.caps_lock = not self._state.caps_lock- name = key_name(data.vkCode, data.scanCode, self._state, _to_unicode)+ if data.vkCode in self._text_keyups_swallowed:+ if not down:+ self._text_keyups_swallowed.discard(data.vkCode)+ else:+ repeated = key_name(data.vkCode, data.scanCode, self._state, _to_unicode, True)+ if isinstance(repeated, str) and len(repeated) == 1:+ self._on_key(TextInput(repeated), True, data.vkCode, None)+ return 1+ name = key_name(data.vkCode, data.scanCode, self._state, _to_unicode, down)+ if isinstance(name, TextInput):+ if down and self._on_key(name, down, data.vkCode, None):+ self._text_keyups_swallowed.add(data.vkCode)+ return 1+ return user32.CallNextHookEx(None, code, wparam, lparam)+ if isinstance(name, DeadKey):+ if not down and data.vkCode in self._dead_keys_swallowed:+ self._dead_keys_swallowed.discard(data.vkCode)+ return 1+ if down and self._on_key(name, down, data.vkCode, None):+ self._dead_keys_swallowed.add(data.vkCode)+ return 1+ if down:+ self._state.pending_dead_key = None+ return user32.CallNextHookEx(None, code, wparam, lparam)if name is None:return user32.CallNextHookEx(None, code, wparam, lparam)us = None if data.flags & LLKHF_EXTENDED else SCAN_TO_US.get(data.scanCode)@@ -773,13 +846,12 @@ def hand_motion(flags: int, last_x: int, last_y: int, extra_information: int) ->return last_x, last_y-def _to_unicode(vk: int, scan: int, state: Dict[int, int]) -> Optional[str]:+def _to_unicode(vk: int, scan: int, state: Dict[int, int]) -> Optional[Union[str, DeadKey]]:"""The character `vk` types under `state`, or None. Called with thenon-shift modifiers already cleared, so a chord yields its plain key.ToUnicodeEx is asked not to change the keyboard state (the 1<<2 flag):- without it, translating a dead key here would eat the accent the user is- actually typing on this PC.+ the dead accent is tracked in KeyboardState instead."""if user32 is None:raise RuntimeError("ToUnicodeEx is only available on Windows")@@ -789,6 +861,8 @@ def _to_unicode(vk: int, scan: int, state: Dict[int, int]) -> Optional[str]:buffer = ctypes.create_unicode_buffer(8)layout = user32.GetKeyboardLayout(0)count = user32.ToUnicodeEx(vk, scan, key_state, buffer, len(buffer), 1 << 2, layout)- if count <= 0:+ if count < 0:+ return DeadKey(buffer.value[:abs(count)]) if buffer.value else None+ if count == 0:return Nonereturn buffer.value[:count]diff --git a/win_app/desktop_win.py b/win_app/desktop_win.pyindex 8130653..36b2cc7 100644--- a/win_app/desktop_win.py+++ b/win_app/desktop_win.py@@ -6,6 +6,7 @@ others unconverted."""import ctypesimport logging+import osimport sysfrom typing import List, Tuple@@ -121,6 +122,9 @@ def full_screen_app():"""The name of the foreground app while it is full screen, else None. GUI thread, once asecond, as the Mac checks."""_require()+ pid = _foreground_process_id()+ if pid is None or pid == os.getpid():+ return Nonestate = ctypes.c_int(0)if ctypes.windll.shell32.SHQueryUserNotificationState(ctypes.byref(state)) != 0:return None@@ -129,6 +133,15 @@ def full_screen_app():return None+def _foreground_process_id():+ hwnd = user32.GetForegroundWindow()+ if not hwnd:+ return None+ pid = ctypes.c_ulong(0)+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))+ return pid.value++class MONITORINFO(ctypes.Structure):_fields_ = [("cbSize", ctypes.c_ulong), ("rcMonitor", RECT), ("rcWork", RECT), ("dwFlags", ctypes.c_ulong)]diff --git a/win_app/diagram.py b/win_app/diagram.pyindex 165cf0b..892521a 100644--- a/win_app/diagram.py+++ b/win_app/diagram.py@@ -101,8 +101,17 @@ class ArrangementDiagram(QWidget):def _drawing(self, width: float):keys = [key for key, place in self._places.items() if place[3] > 0.001]placed = [tuple(self._places[key][:3]) for key in keys]- pc, rects, height = pages_win.layout_rects(max(1.0, width - 2 * PAD), PAD, placed, SCREEN, GAP,- centre_pc=len(self._machines) > 1)+ available = max(1.0, width - 2 * PAD)+ centre_pc = len(self._machines) > 1+ pc, rects, _height = pages_win.layout_rects(available, PAD, placed, SCREEN, GAP,+ centre_pc=centre_pc)+ bounds_left = min([pc[0], *(rect[0] for rect in rects)])+ bounds_right = max([pc[0] + pc[2], *(rect[0] + rect[2] for rect in rects)])+ scale = max(1.0, available * 0.68 / max(1.0, bounds_right - bounds_left))+ screen = (SCREEN[0] * scale, SCREEN[1] * scale)+ gap = GAP * scale+ pc, rects, height = pages_win.layout_rects(available, PAD, placed, screen, gap,+ centre_pc=centre_pc)return (pc[0] + PAD, pc[1], pc[2], pc[3]), {key: (rect[0] + PAD, *rect[1:]) for key, rect in zip(keys, rects)}, heightdef _height(self) -> int:diff --git a/win_app/edge_glow.py b/win_app/edge_glow.pyindex dc742b6..1aaa39c 100644--- a/win_app/edge_glow.py+++ b/win_app/edge_glow.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport copyimport ctypes+import mathimport sysimport time@@ -287,6 +288,8 @@ class EdgeGlow(QWidget):self._part = Noneself._style = "glow"self._colour = "signal"+ self._size = "medium"+ self._band = float(BAND_PX)self._state = GlowState()self._dark = Trueself._updated_at = 0.0@@ -295,9 +298,10 @@ class EdgeGlow(QWidget):self._timer.setInterval(16)self._timer.timeout.connect(self._tick)- def configure(self, style: str, colour: str, length: str = "normal") -> None:+ def configure(self, style: str, colour: str, length: str = "normal", size: str = "medium") -> None:self._style = styleself._colour = colour+ self._size = sizeself._state.pace = effects.pace(length)def set_pressure(self, edge: str, pressure: float, crossed: bool, part=None) -> None:@@ -329,19 +333,21 @@ class EdgeGlow(QWidget):cursor = QCursor.pos()owner = next((r for r in rects if r.x <= cursor.x() < r.x + r.width and r.y <= cursor.y() < r.y + r.height),None) or crossing.owning_monitor(rects, self._edge)+ self._band = effects.edge_depth(owner.width, owner.height, self._size)if self._part in crossing.CORNERS:box = corner_of_monitor(owner, self._part, min(CORNER_ARM_PX, owner.width, owner.height))self.setGeometry(QRect(box.x, box.y, box.width, box.height))returnowner = part_of_monitor(owner, self._edge, self._part)+ band = math.ceil(self._band)if self._edge == "left":- self.setGeometry(QRect(owner.x, owner.y, BAND_PX, owner.height))+ self.setGeometry(QRect(owner.x, owner.y, band, owner.height))elif self._edge == "right":- self.setGeometry(QRect(owner.right - BAND_PX + 1, owner.y, BAND_PX, owner.height))+ self.setGeometry(QRect(owner.right - band + 1, owner.y, band, owner.height))elif self._edge == "top":- self.setGeometry(QRect(owner.x, owner.y, owner.width, BAND_PX))+ self.setGeometry(QRect(owner.x, owner.y, owner.width, band))else:- self.setGeometry(QRect(owner.x, owner.bottom - BAND_PX + 1, owner.width, BAND_PX))+ self.setGeometry(QRect(owner.x, owner.bottom - band + 1, owner.width, band))def _tick(self) -> None:now = time.monotonic()@@ -359,9 +365,11 @@ class EdgeGlow(QWidget):def paintEvent(self, _event) -> None:painter = QPainter(self)if self._part in crossing.CORNERS:- paint_corner(painter, self.rect(), self._part, self._style, self._colour, self._state, dark=self._dark)+ paint_corner(painter, self.rect(), self._part, self._style, self._colour, self._state,+ band=self._band, dark=self._dark)else:- paint(painter, self.rect(), self._edge, self._style, self._colour, self._state, dark=self._dark,+ paint(painter, self.rect(), self._edge, self._style, self._colour, self._state,+ band=self._band, dark=self._dark,taper=self._part in crossing.PARTS)painter.end()diff --git a/win_app/effect_overlay.py b/win_app/effect_overlay.pyindex 84d4511..903b816 100644--- a/win_app/effect_overlay.py+++ b/win_app/effect_overlay.py@@ -277,7 +277,7 @@ class EffectOverlay(QWidget):self._timer.setInterval(FRAME_MS)self._timer.timeout.connect(self._tick)- def configure(self, style: str, colour: str, length: str = "normal") -> None:+ def configure(self, style: str, colour: str, length: str = "normal", size: str = "medium") -> None:if style != self._style:self._style = styleself.player = effects.Player()@@ -293,6 +293,7 @@ class EffectOverlay(QWidget):# Read each time, like the colours; a Player already playing keeps the pace it started with.if not self.player.busy:self.player.pace = effects.pace(length)+ self.player.effect_size = sizetry:self._palette = app_config.palette_colours(colour)except Exception:diff --git a/win_app/effect_previews.py b/win_app/effect_previews.pyindex 98fd5e5..2944aa0 100644--- a/win_app/effect_previews.py+++ b/win_app/effect_previews.py@@ -159,6 +159,7 @@ class EffectStill(QWidget):self.palette = tuple(palette)self.place = "edge"self.pace = 1.0+ self.effect_size = "medium"self._image = Noneself.playing_since = Noneself.setFixedHeight(STILL_HEIGHT)@@ -183,6 +184,12 @@ class EffectStill(QWidget):self._image = Noneself.update()+ def set_effect_size(self, size: str) -> None:+ if size != self.effect_size:+ self.effect_size = size+ self._image = None+ self.update()+def refresh_colours(self) -> None:# A cached image, not a live paint: without this an appearance switch leaves it showing# the old palette until something else invalidates the cache.@@ -217,7 +224,7 @@ class EffectStill(QWidget):def _paint_still(self, painter: QPainter, t: float) -> None:scene = effects.preview_scene(effects.preview_effect(self.effect_id), t, self.place, self.palette,- system_reduced_motion(), theme.is_dark(), self.pace)+ system_reduced_motion(), theme.is_dark(), self.pace, self.effect_size)width = STILL_VIEW_Wview_h = min(effects.PREVIEW_SCREEN[1], width * self.height() / max(1, self.width()))centre = STILL_CENTRE[self.place]@@ -244,7 +251,7 @@ class SwitchStill(EffectStill):def _paint_still(self, painter: QPainter, t: float) -> None:fx = effects.switch_effect(self.effect_id, self.crossing_style)scene = effects.preview_switch_scene(fx, t, self.palette, "windows", system_reduced_motion(), theme.is_dark(),- self.pace)+ self.pace, self.effect_size)paint_scene(painter, QRectF(self.rect()), SWITCH_STILL_VIEW, scene, 10.0, labels=False)diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex ad6a946..c7157b8 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -13,10 +13,11 @@ import timefrom typing import Optionalfrom PySide6.QtCore import QEvent, QObject, QRectF, QSize, QTimer, Qt, QUrl, Signal-from PySide6.QtGui import QAction, QColor, QDesktopServices, QIcon, QKeySequence, QPainter, QPixmap, QShortcut+from PySide6.QtGui import QAction, QColor, QDesktopServices, QIcon, QKeySequence, QPainter, QPixmap, QShortcut, QStandardItem, QStandardItemModelfrom PySide6.QtWidgets import (QApplication,QCheckBox,+ QComboBox,QFrame,QGridLayout,QHBoxLayout,@@ -120,12 +121,17 @@ CORNER_CHOICES = (("bottom_right", "Bottom-right"),)TRIGGER_STYLE_CHOICES = (("double_tap", "Double-tap"), ("hold", "Hold"))-MODIFIER_STYLE_CHOICES = (("semantic", "Same shortcuts"), ("positional", "Same positions"))+MODIFIER_STYLE_CHOICES = (+ ("semantic", "Same shortcuts"),+ ("positional", "Same positions"),+ ("mac_layout", "Mac keyboard layout"),+)MODIFIER_NOTES = {"semantic": "On a Mac, Ctrl arrives as Command and the Windows key as Control, so Ctrl+C ""copies there too. Between two PCs every key arrives as itself.","positional": "On a Mac, each key arrives as the Mac key in the same place: Ctrl as Control, the ""Windows key as Command. Between two PCs every key arrives as itself.",+ "mac_layout": "To a Mac: Alt becomes Command and Win becomes Option; Ctrl stays Control.",}FULL_SCREEN_CHECK_MS = 1000# How long a dragged slider waits, still, before the value it settled on is written to disk.@@ -354,6 +360,7 @@ class WindowsApplication(QWidget):self.scope_labels: dict = {}self.own_notes: list = []self._same_seen = None+ self._design_states = {}# Pause crossing and the full-screen hold are about this screen: a peer's pointer does# not go home through a held edge either.self.server.edges_held = lambda: self.sender.edges_held@@ -384,6 +391,7 @@ class WindowsApplication(QWidget):# With nothing paired the window still has this PC's own settings to show and keep.self._config = load_config(config_path, unpaired_ok=True)self._same_seen = self._same_fields()+ self._design_seen = self._design_fields()self._apply_input_scale(self._config)self._host = self._config.hostself._paired = bool(self.book.peers())@@ -499,7 +507,19 @@ class WindowsApplication(QWidget):scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)page = QWidget()page.setProperty("vernier", "plain")- layout = QVBoxLayout(page)+ page_layout = QVBoxLayout(page)+ page_layout.setContentsMargins(0, 0, 0, 0)+ page_layout.setSpacing(0)+ centred = QHBoxLayout()+ centred.setContentsMargins(0, 0, 0, 0)+ centred.addStretch(1)+ content = QWidget()+ content.setProperty("vernier", "plain")+ content.setMaximumWidth(tokens.PAGE_CONTENT_WIDTH)+ centred.addWidget(content)+ centred.addStretch(1)+ page_layout.addLayout(centred)+ layout = QVBoxLayout(content)layout.setContentsMargins(28, 24, 28, 24)layout.setSpacing(16)heading = widgets.label(title.upper(), "heading")@@ -650,9 +670,9 @@ 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 = widgets.Switch("Hold this PC's edges while an app on it 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.setChecked(self._config.hold_full_screen if self._config else False)self.hold_switch.toggled.connect(self._set_hold_full_screen)module.body.addWidget(self.hold_switch)own_note = self._own_note()@@ -703,7 +723,7 @@ class WindowsApplication(QWidget):return pages_win.crossing_state_sentence(*self._crossing_state_args())def _check_full_screen(self) -> None:- """The Mac's rule: a full-screen app in front holds the edges, the shortcut still works.+ """This PC's rule: a full-screen app in front holds its edges, the shortcut still works.A failure stops the check for the run rather than logging once a second."""try:self.sender.full_screen_app = desktop_win.full_screen_app()@@ -759,15 +779,95 @@ class WindowsApplication(QWidget):for note in self.own_notes:if motion.target_shown(note) != on:motion.set_shown(note, on)+ self._refresh_design_follow()def _same_fields(self) -> tuple:return tuple(settings_sync.pc_values(self._config).values())+ def _design_fields(self) -> tuple:+ values = settings_sync.pc_values(self._config)+ return tuple(values.get(key) for key in settings_sync.DESIGN_KEYS)+def _same_state(self) -> dict:config = self._config+ values = settings_sync.pc_values(config)+ design_state = {+ "set_at": config.design_set_at,+ "by": config.design_by or config.machine_id,+ "values": {key: values[key] for key in settings_sync.DESIGN_KEYS},+ }return settings_sync.message_data(- config.same_on_both, config.same_set_at, settings_sync.pc_values(config), by=config.same_by+ config.same_on_both, config.same_set_at, values, by=config.same_by, design_state=design_state+ )++ def _refresh_design_follow(self) -> None:+ if not hasattr(self, "design_follow_choice") or self._config is None:+ return+ choice = self.design_follow_choice+ choice.blockSignals(True)+ model = QStandardItemModel(choice)+ none = QStandardItem("None")+ none.setData("", Qt.ItemDataRole.UserRole)+ model.appendRow(none)+ unavailable = []+ for entry in self._peer_entries:+ peer_text = entry.get("id", "")+ peer = protocol.read_id(peer_text)+ if peer is None:+ continue+ name = self._shown(entry.get("name") or entry.get("platform") or "Paired machine")+ supported = peer_text in self._design_states+ item = QStandardItem(name if supported else f"{name} — Needs beta.6 or later")+ item.setData(peer_text, Qt.ItemDataRole.UserRole)+ if not supported:+ item.setEnabled(False)+ unavailable.append(name)+ model.appendRow(item)+ choice.setModel(model)+ selected = choice.findData(self._config.design_follow_peer, Qt.ItemDataRole.UserRole)+ choice.setCurrentIndex(max(0, selected))+ choice.blockSignals(False)+ peer = next((item for item in self._peer_entries if item.get("id") == self._config.design_follow_peer), None)+ if peer:+ name = self._shown(peer.get('name') or 'that machine')+ if self._config.same_on_both:+ self.design_follow_note.setText(f"Following {name}, paused while Same on all machines is on.")+ else:+ self.design_follow_note.setText(f"Following {name}. Change a Design setting to stop following.")+ elif unavailable:+ self.design_follow_note.setText("A paired machine is unavailable until it has beta.6 or later.")+ else:+ self.design_follow_note.setText("None: this PC keeps its own Design.")++ def _design_follow_chosen(self, _index: int) -> None:+ if self._config is None:+ return+ self._config.design_follow_peer = self.design_follow_choice.currentData(Qt.ItemDataRole.UserRole) or ""+ self._persist()+ self._refresh_design_follow()+ self._apply_followed_design()++ def _apply_followed_design(self) -> None:+ config = self._config+ peer = config.design_follow_peer+ state = self._design_states.get(peer)+ if not peer or state is None or config.same_on_both:+ return+ current = settings_sync.pc_values(config)+ taken = settings_sync.followed_design(+ current, state, peer, peer, config.same_on_both, config.design_set_at,+ config.design_by,)+ if taken is None:+ return+ settings_sync.apply_pc(config, taken["values"])+ config.design_set_at = taken["set_at"]+ config.design_by = taken["by"]+ self._design_seen = tuple(getattr(config, key) for key in settings_sync.DESIGN_KEYS)+ self._reflect_config(config)+ if self._persist() and taken["changed"]:+ self._send_same()+ self._refresh_design_follow()def _send_same(self, source: Optional[bytes] = None, data: Optional[dict] = None) -> None:"""This PC's state, or `data` unchanged when a newer one arrived and goes on (section 10), to@@ -840,7 +940,7 @@ class WindowsApplication(QWidget):"platform": OWN_PLATFORM,"app": VERSION[:32] if VERSION.isascii() and VERSION.isprintable() else "dev",# A swipe has no shortcut every Linux desktop shares, so Linux does not offer gestures.- "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings")+ "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync")if not (cap == "gestures" and OWN_PLATFORM == "linux")],"port": self._settings_port,}@@ -861,6 +961,8 @@ class WindowsApplication(QWidget):self._config.same_by = self._config.machine_idself._persist()self._send_same()+ if not on:+ self._apply_followed_design()self._show_same()def _on_settings(self, peer: str, data) -> None:@@ -869,34 +971,55 @@ class WindowsApplication(QWidget):that takes it, which stops the first time it meets a copy it already holds."""if self._config is None:return+ was_on = self._config.same_on_both+ state = settings_sync.read_design_state(data, TRIGGER_KEYS)+ if state is not None:+ held = self._design_states.get(peer)+ if held is None or settings_sync.design_arrived(state, held["set_at"], held["by"]):+ self._design_states[peer] = state+ source = protocol.read_id(peer)taken = settings_sync.arrived(data, self._config.same_set_at, TRIGGER_KEYS, by_here=self._config.same_by)- 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- config.same_by = data.get("by", "") if isinstance(data.get("by"), str) else ""- if on:- settings_sync.apply_pc(config, values)- try:- app_config.validate_config(config)- except ConfigError:- LOGGER.exception("Settings from a peer could not be applied")- return- self._config = config- self._same_seen = self._same_fields()- if not self._persist():- return- LOGGER.info("Settings from a peer applied (same on all machines %s)", "on" if on else "off")- self.sender.update_config(config)- self._configure_trigger(config)- self._reflect_config(config)- self._show_same()- self._send_same(source=protocol.read_id(peer), data=data)+ if taken is not None:+ 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+ config.same_by = data.get("by", "") if isinstance(data.get("by"), str) else ""+ if on:+ design_stamp = settings_sync.design_change_stamp(+ settings_sync.pc_values(config), values, config.design_set_at,+ state, config.machine_id,+ )+ settings_sync.apply_pc(config, values)+ if design_stamp is not None:+ config.design_set_at = design_stamp["set_at"]+ config.design_by = design_stamp["by"]+ try:+ app_config.validate_config(config)+ except ConfigError:+ LOGGER.exception("Settings from a peer could not be applied")+ return+ self._config = config+ self._same_seen = self._same_fields()+ self._design_seen = self._design_fields()+ if not self._persist():+ return+ LOGGER.info("Settings from a peer applied (same on all machines %s)", "on" if on else "off")+ self.sender.update_config(config)+ self._configure_trigger(config)+ self._reflect_config(config)+ self._show_same()+ forwarded = dict(data)+ forwarded["design_sync"] = self._same_state()["design_sync"]+ self._send_same(source=source, data=forwarded)+ if state is not None:+ self._apply_followed_design()+ self._refresh_design_follow()+ if taken is not None and was_on and not on:+ self._apply_followed_design()def _sign_in_module(self) -> QWidget:module = widgets.Module("At sign-in")@@ -1536,7 +1659,7 @@ class WindowsApplication(QWidget):def _modifier_module(self, current: Config) -> QWidget:module = widgets.Module("Modifier keys")self.modifier_choice = widgets.Choice(- MODIFIER_STYLE_CHOICES, columns=2, current=current.modifier_style, on_change=self._set_modifier_style+ MODIFIER_STYLE_CHOICES, columns=3, current=current.modifier_style, on_change=self._set_modifier_style)self.modifier_choice.set_names("Modifier keys")module.body.addWidget(self.modifier_choice.view)@@ -1731,6 +1854,14 @@ class WindowsApplication(QWidget):layout.addWidget(self._on_screen_module(current))self.look_module = self._edge_look_module(current)layout.addWidget(self.look_module)+ follow = widgets.Module("Match design with")+ self.design_follow_choice = QComboBox()+ self.design_follow_choice.currentIndexChanged.connect(self._design_follow_chosen)+ follow.body.addWidget(self.design_follow_choice)+ self.design_follow_note = widgets.label("None: this PC keeps its own Design.", "note", wrap=True)+ follow.body.addWidget(self.design_follow_note)+ layout.addWidget(follow)+ self._refresh_design_follow()layout.addWidget(self._appearance_module(current))self._reflect_look()@@ -1844,11 +1975,19 @@ class WindowsApplication(QWidget):# Every style and every switch plays at this length, so it follows the tiles either way.self.length_choice = widgets.Choice(effects.LENGTHS, 3, current.effect_length, on_change=self._apply_look)self.length_choice.set_names("Length")- module.body.addWidget(self._row(- widgets.label("Length", "key"), self.length_choice.view,- widgets.label("How long each animation takes to play through once the pointer crosses, and to land.",- "small", wrap=True),- ))+ self.size_choice = widgets.Choice(effects.SIZES, 3, current.effect_size, on_change=self._apply_look)+ self.size_choice.set_names("Size")+ controls = QHBoxLayout()+ controls.setSpacing(12)+ for title, choice in (("Length", self.length_choice), ("Size", self.size_choice)):+ field = QVBoxLayout()+ field.setSpacing(5)+ field.addWidget(widgets.label(title, "key"))+ field.addWidget(choice.view)+ controls.addLayout(field, 1)+ module.body.addLayout(controls)+ module.body.addWidget(widgets.label(+ "Length sets how long each animation plays. Size sets the edge band's depth.", "small", wrap=True))module.body.addSpacing(10)colour_head = QHBoxLayout()colour_head.setSpacing(8)@@ -1886,6 +2025,7 @@ class WindowsApplication(QWidget):self._config.glow_style = self.glow_style_choice.valueself._config.glow_colour = self.glow_colour_choice.valueself._config.effect_length = self.length_choice.value or "normal"+ self._config.effect_size = self.size_choice.value or "medium"self._persist()self._hide_crossing()@@ -1911,12 +2051,15 @@ class WindowsApplication(QWidget):method = self.effect_method_choice.value or "edge"switch_style = (self.switch_style_choice.value or "match") if switching else Nonelength = self.length_choice.value or "normal"- look = (style, colour, switching, switch_style, method, edge, length)+ size = self.size_choice.value or "medium"+ look = (style, colour, switching, switch_style, method, edge, length, size)previous, self._look = self._look, look# Each still redrawn by this change cross-fades: every one with the colour or the length, the# crossing's with the place, the Shortcut and menu stills with the crossing style beside them.stills = []- if previous is not None and (previous[1], previous[6]) != (colour, length):+ if previous is not None and (previous[1], previous[6], previous[7]) != (colour, length, size):+ stills = [*self.effect_stills.values(), *self.switch_stills.values()]+ elif previous is not None and previous[7] != size:stills = [*self.effect_stills.values(), *self.switch_stills.values()]elif previous is not None and previous[4] != method:stills = list(self.effect_stills.values())@@ -1963,6 +2106,7 @@ class WindowsApplication(QWidget):pace = effects.pace(length)for still in (*self.effect_stills.values(), *self.switch_stills.values()):still.set_pace(pace)+ still.set_effect_size(size)for still in self.effect_stills.values():still.set_place(method)for still, shot in still_shots.items():@@ -1995,8 +2139,17 @@ class WindowsApplication(QWidget):fields = self._same_fields()shared = self._same_seen is not None and fields != self._same_seen and self._config.same_on_bothself._same_seen = fields+ design_fields = self._design_fields()+ design_changed = self._design_seen is not None and design_fields != self._design_seen+ self._design_seen = design_fields+ if design_changed:+ self._config.design_follow_peer = ""+ self._config.design_set_at = settings_sync.next_stamp(+ max(self._config.design_set_at, self._config.same_set_at), time.time())+ self._config.design_by = self._config.machine_idif shared:- self._config.same_set_at = settings_sync.next_stamp(self._config.same_set_at, time.time())+ self._config.same_set_at = settings_sync.next_stamp(+ max(self._config.same_set_at, self._config.design_set_at), time.time())self._config.same_by = self._config.machine_idtry:with app_config.SETTINGS_LOCK:@@ -2013,8 +2166,9 @@ class WindowsApplication(QWidget):# next crossing: its way on is built from these settings when it arrives.self.server.peers_changed()self.sender.refresh()- if shared:+ if shared or design_changed:self._send_same()+ self._refresh_design_follow()return Trueexcept (ConfigError, OSError):LOGGER.exception("Setting could not be saved")@@ -2096,6 +2250,11 @@ class WindowsApplication(QWidget):LOGGER.exception("The peers could not be read")peers, zones = [], []self._peer_entries, self._zone_entries = peers, zones+ if self._config is not None and self._config.design_follow_peer not in {p.get("id") for p in peers}:+ if self._config.design_follow_peer:+ self._config.design_follow_peer = ""+ self._persist()+ self._refresh_design_follow()self.machines.set_peers(self._peer_items(peers))if hasattr(self, "arrangement_diagram"):self._reflect_other_name()@@ -2258,6 +2417,8 @@ class WindowsApplication(QWidget):removed = peerlist.remove_peer(settings, token)if removed is None:return+ if settings.get("design_follow_peer") == removed.get("id"):+ settings["design_follow_peer"] = ""after = ways.way_back_state(settings)app_config.write_settings(self.config_path, settings)remaining = bool(settings["peers"])@@ -2280,6 +2441,7 @@ class WindowsApplication(QWidget):except (ConfigError, OSError):self._config = Noneself._same_seen = self._same_fields() if self._config is not None else None+ self._design_seen = self._design_fields() if self._config is not None else Noneself.sender.update_config(self._config)if self._config is not None:self._reflect_config(self._config)@@ -2516,6 +2678,7 @@ class WindowsApplication(QWidget):self._config = configself._settings_port = config.portself._same_seen = self._same_fields()+ self._design_seen = self._design_fields()self._apply_input_scale(config)if not config.edge_glow:self._hide_crossing()@@ -2767,6 +2930,7 @@ class WindowsApplication(QWidget):self.glow_style_choice.set_value(config.glow_style)self.glow_colour_choice.set_value(config.glow_colour)self.length_choice.set_value(config.effect_length)+ self.size_choice.set_value(config.effect_size)self._reflect_look()self.appearance_choice.set_value(config.appearance)self._apply_appearance(config.appearance)@@ -2881,6 +3045,10 @@ class WindowsApplication(QWidget):"""Every key, on the hook thread. The trigger is swallowed as itswitches; everything else goes to the Mac only while the Mac hasinput, and a key on the ignored list not even then."""+ if isinstance(name, capture_win.TextInput):+ return self.sender.on_text(name.text, vk)+ if isinstance(name, capture_win.DeadKey):+ return self.sender.on_dead_key(vk)if self.sender.handle_jump_key(name, down, vk):return Trueaction = self._trigger.feed(name, down, time.monotonic())@@ -3041,7 +3209,7 @@ class WindowsApplication(QWidget):self.effects = EffectOverlay(on_failure=self._on_effects_failed)if self.effects.failed:return None- self.effects.configure(config.glow_style, config.glow_colour, config.effect_length)+ self.effects.configure(config.glow_style, config.glow_colour, config.effect_length, config.effect_size)if self.effects.failed or self.effects._fx is None:return Nonereturn self.effects@@ -3058,7 +3226,7 @@ class WindowsApplication(QWidget):self.glow = EdgeGlow()# An effect that failed earlier in the run falls back to the plain glow, in its colour.self.glow.configure(style if style in ("glow", "beam") else "glow", self._config.glow_colour,- self._config.effect_length)+ self._config.effect_length, self._config.effect_size)self.glow.set_pressure(edge, pressure, crossed, part)def _on_arrival(self, method: str, edge: str, x: float, y: float) -> None:@@ -3087,7 +3255,7 @@ class WindowsApplication(QWidget):self.effects = EffectOverlay(on_failure=self._on_effects_failed)if self.effects.failed:return None- self.effects.configure(config.glow_style, config.glow_colour, config.effect_length)+ self.effects.configure(config.glow_style, config.glow_colour, config.effect_length, config.effect_size)if self.effects.failed or self.effects._fx is None:return Nonereturn self.effectsdiff --git a/win_app/machines_win.py b/win_app/machines_win.pyindex 0790edf..0c38686 100644--- a/win_app/machines_win.py+++ b/win_app/machines_win.py@@ -258,6 +258,7 @@ class PairingSheet(widgets.Module):row.setSpacing(18)self.code_label = widgets.label("", "code")self.code_label.setFont(theme.mono_font(theme.PAIRING_CODE))+ self.code_label.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)self.code_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByKeyboard| Qt.TextInteractionFlag.TextSelectableByMouse)self.code_label.setFocusPolicy(Qt.FocusPolicy.StrongFocus)diff --git a/win_app/pages_win.py b/win_app/pages_win.pyindex 3b1e7be..3c26724 100644--- a/win_app/pages_win.py+++ b/win_app/pages_win.py@@ -63,20 +63,21 @@ def dots(config_error: bool, firewall_tone: str | None) -> dict:return {}-# The Design page's styles and colours: Classic first, then each crossing effects direction in-# effects.DIRECTIONS order. Classic's Glow and Beam light this PC's edge or corner as the pointer+# The Design page's styles and colours: Light first, then each crossing effects direction in+# effects.DIRECTIONS order. Light's Glow, Beam and Aperture draw this PC's edge or corner as the pointer# leaves; the effects draw the departure and the arrival, at an edge, a corner or the Mac's notch.-CLASSIC = "Classic"+CLASSIC = "Light"TODAY_STYLES = (("glow", "Glow", "A band of light that deepens the harder you push."),("beam", "Beam", "A thin line with a comet of light running along it."),+ ("aperture", "Aperture", "A fine lens of light opens under pressure and closes softly behind the arriving pointer."),)TODAY_COLOURS = (("signal", "Signal"), ("colourful", "Colourful"), ("ocean", "Ocean"), ("sunset", "Sunset"), ("mono", "Mono"))def effects_load_error():"""None when every crossing effect loads, else the exception: the Design page then offers only- Classic's styles and colours rather than failing to build, and Beamer still starts."""+ Light's styles and colours rather than failing to build, and Beamer still starts."""try:effects._load()except Exception as exc:@@ -89,9 +90,11 @@ def style_groups() -> tuple:its intensity: quiet, medium or showpiece."""# Glow and Beam's detail is their kind, as an effect's is its intensity; what they do is said# under the preview.- groups = [(CLASSIC, tuple((value, name, CLASSIC) for value, name, _blurb in TODAY_STYLES))]if effects_load_error() is not None:- return tuple(groups)+ return ((CLASSIC, tuple((value, name, effects.CLASSIC[value].intensity.capitalize())+ for value, name, _blurb in TODAY_STYLES[:2])),)+ groups = [(CLASSIC, tuple((value, name, effects.CLASSIC[value].intensity.capitalize())+ for value, name, _blurb in TODAY_STYLES))]for _module, title, effect_ids, _packs in effects.DIRECTIONS:found = [effects.effect(effect_id) for effect_id in effect_ids]groups.append((title, tuple((fx.id, fx.name, fx.intensity.capitalize()) for fx in found)))@@ -217,10 +220,7 @@ def crossing_state_sentence(paired, heard, sending, connected, armed, paused, fuif paused:return "Paused. The edge, part of the edge and corner do nothing until you resume; the shortcut still works."if full_screen_app is not None:- return (- f"Off while {full_screen_app} is full screen, so the pointer stays put at "- "the edges; the shortcut still works."- )+ return "Held: an app is full screen."return "On. Pause it to lean on an edge without switching."@@ -258,7 +258,11 @@ SWITCH_SIMPLE = (def switch_groups() -> tuple:"""style_groups() for a switch: SWITCH_SIMPLE in place of Classic, then the same directions."""- return ((SIMPLE, SWITCH_SIMPLE),) + style_groups()[1:]+ if effects_load_error() is not None:+ return ((SIMPLE, SWITCH_SIMPLE),)+ aperture = ((CLASSIC, (("aperture", effects.CLASSIC["aperture"].name,+ effects.CLASSIC["aperture"].intensity.capitalize()),)),)+ return ((SIMPLE, SWITCH_SIMPLE),) + aperture + style_groups()[1:]# The Crossing page's "Where your Mac is": the value is the edge of this PC that leads to the Mac.diff --git a/win_app/sender.py b/win_app/sender.pyindex 0918b32..e2b37b1 100644--- a/win_app/sender.py+++ b/win_app/sender.py@@ -57,6 +57,7 @@ PHYSICAL = {"cmd": "ctrl", "cmd_r": "ctrl_r", "ctrl": "cmd", "ctrl_r": "cmd_r"}MEDIA_KEYS = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"})+MODIFIER_KEYS = frozenset({"shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r"})# What this machine tells its peers it is (WIRE.md section 2); Linux and Windows read keys alike.OWN_PLATFORM = "linux" if sys.platform.startswith("linux") else "windows"INPUT_TYPES = protocol.INPUT_TYPES@@ -72,6 +73,10 @@ HOME_REASONS = {}+def _at_edge(edge) -> str:+ return f", at its {edge} edge" if isinstance(edge, str) else ""++def is_this_machine(host: str, local_addresses=None, address_towards=None) -> bool:"""Whether `host` is this PC rather than a peer. Worth a guard of its own: a peer's address islearned from the peer address of its own link, and when the Mac connects through the macOS 27@@ -285,7 +290,7 @@ class LinkSender:def full_screen_app(self):"""The full-screen app holding the edges, or None: also None while this PC's own settinghas 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):+ if self._setting("hold_full_screen", False):return self._full_screen_appreturn None@@ -415,6 +420,18 @@ class LinkSender:self.go(target)return True+ def on_dead_key(self, vk: Optional[int] = None) -> bool:+ """Swallow a dead key only while its live peer owns this PC's input."""+ owner = self._owner+ if owner is None or not owner.away:+ return False+ if not self._live():+ self._lost()+ return False+ if vk is not None and self._ignore_gate.keeps(ignored.key(vk), True):+ return False+ return True+def on_key(self, name: str, down: bool, vk: Optional[int] = None, us: Optional[str] = None) -> bool:"""One key, from the hook thread: True when it is not for this PC. Held keys are known bytheir virtual key where there is one: the name is the character with Shift applied, so@@ -435,6 +452,29 @@ class LinkSender:return Falsereturn self._input({"type": protocol.MSG_KEYDOWN if down else protocol.MSG_KEYUP, "data": dict(data)})+ def on_text(self, text: str, vk: Optional[int] = None) -> bool:+ """Sends a composed key sequence as text when this PC's input is away."""+ owner = self._owner+ if owner is None:+ return False+ if owner.away:+ if not self._live():+ self._lost()+ return False+ elif vk is not None and self._ignore_gate.keeps(ignored.key(vk), True):+ return False+ actions = []+ with self._lock:+ owner = self._owner+ if owner is None:+ return False+ message = protocol.text_msg(text)+ message["_bracket_modifiers"] = True+ actions = owner.input(message)+ self._queue(actions)+ self._report(actions)+ return not any(action is owner_module.LOCAL for action in actions)+@staticmethoddef _key_data(name: str, us: Optional[str]) -> dict:"""A key message's data, with the physical key's name. `us` is the key's place on a US@@ -751,6 +791,27 @@ class LinkSender:"""Hands what the owner answered to the outbound worker, in order. Called with the lock stillheld, in the same step as the decision, so two threads' decisions cannot reach the worker theother way round (a release behind the press it releases would leave the key down)."""+ queued_actions = []+ for action in actions:+ if isinstance(action, owner_module.Send) and action.message.get("type") == protocol.MSG_TEXT:+ modifiers = [+ data for data in action.message.pop("_pressed_keys", [])+ if data.get("key") in MODIFIER_KEYS+ ]+ queued_actions.extend(+ owner_module.Send(action.peer, {"type": protocol.MSG_KEYUP, "data": modifier,+ "_preserve_key_name": True})+ for modifier in modifiers+ )+ queued_actions.append(action)+ queued_actions.extend(+ owner_module.Send(action.peer, {"type": protocol.MSG_KEYDOWN, "data": modifier})+ for modifier in modifiers+ )+ continue+ queued_actions.append(action)++ actions = queued_actionsfor index, action in enumerate(actions):if isinstance(action, (owner_module.Send, owner_module.SendClipboard, owner_module.SetClipboard, owner_module.Drop)):try:@@ -894,7 +955,8 @@ class LinkSender:data.get("resistance_px"), data.get("reach"), bool(data.get("stay")),)elif kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):- message = self._key_message(peer, message)+ preserve = message.pop("_preserve_key_name", False)+ message = self._key_message(peer, message, preserve=preserve)if message is None:returnif kind in INPUT_TYPES:@@ -904,7 +966,7 @@ class LinkSender:else:self.links.post(peer, message)- def _key_message(self, peer: bytes, message: dict) -> Optional[dict]:+ def _key_message(self, peer: bytes, message: dict, preserve: bool = False) -> Optional[dict]:"""The key as `peer` is sent it: named by the key table for the peer's platform and theuser's style, and dropped when the peer does not take media keys."""data = message["data"]@@ -913,7 +975,9 @@ class LinkSender:if physical in MEDIA_KEYS and "media_keys" not in self.links.caps(peer):return Noneheld = (peer, physical)- if message["type"] == protocol.MSG_KEYUP and held in self._sent_names:+ if message["type"] == protocol.MSG_KEYUP and held in self._sent_names and preserve:+ name = self._sent_names[held]+ elif message["type"] == protocol.MSG_KEYUP and held in self._sent_names:# The release leaves under the name its press went under, whatever the style says now.name = self._sent_names.pop(held)elif message["type"] == protocol.MSG_KEYDOWN and held in self._sent_names:@@ -986,7 +1050,7 @@ class LinkSender:self._last_on = protocol.id_text(moved.to)if self._pin_point is None:self._pin_point = self._desktop_module().cursor_position()- LOGGER.info("input is on %s", self._name(moved.to))+ LOGGER.info("input is on %s%s", self._name(moved.to), _at_edge(moved.edge))self._report_redirecting(True)returnself._pin_point = None@@ -995,7 +1059,7 @@ class LinkSender:# of deltas still in flight cannot cross twice, and nothing else re-arms it.with self._lock:self._arm_locked()- LOGGER.info("input returned to this PC (%s)", moved.why)+ LOGGER.info("input returned to this PC (%s)%s", moved.why, _at_edge(moved.edge))self._report_redirecting(False)if moved.edge in return_edge.EDGES and isinstance(moved.offset, (int, float)):self._land(moved.edge, moved.offset)diff --git a/win_app/tests/test_app_config.py b/win_app/tests/test_app_config.pyindex c36bd29..61bfd98 100644--- a/win_app/tests/test_app_config.py+++ b/win_app/tests/test_app_config.py@@ -73,6 +73,8 @@ class EdgeGlowConfigTests(unittest.TestCase):self.assertEqual((config.glow_style, config.glow_colour), ("glow", "ember"))config = config_from_dict({**BASE, "glow_style": "discharge", "glow_colour": "sunset"})self.assertEqual((config.glow_style, config.glow_colour), ("discharge", "sunset"))+ config = config_from_dict({**BASE, "glow_style": "aperture", "glow_colour": "marbled"})+ self.assertEqual((config.glow_style, config.glow_colour), ("aperture", "marbled"))def test_a_colour_resolves_to_todays_palette_else_its_pack(self):from core import effects@@ -89,6 +91,13 @@ class EdgeGlowConfigTests(unittest.TestCase):with self.assertRaises(ConfigError):config_from_dict({**BASE, "effect_length": "forever"})+ def test_effect_size_defaults_to_medium_and_round_trips(self):+ self.assertEqual(config_from_dict(dict(BASE)).effect_size, "medium")+ config = config_from_dict({**BASE, "effect_size": "large"})+ self.assertEqual(config_to_dict(config)["effect_size"], "large")+ with self.assertRaises(ConfigError):+ config_from_dict({**BASE, "effect_size": "huge"})+def test_a_saved_warp_choice_reads_as_its_stand_in(self):# Warp is offered nowhere for now; a PC that chose it keeps working.config = config_from_dict({**BASE, "glow_style": "light_slit", "glow_colour": "neon",diff --git a/win_app/tests/test_capture_win.py b/win_app/tests/test_capture_win.pyindex b6133a4..a38fd0e 100644--- a/win_app/tests/test_capture_win.py+++ b/win_app/tests/test_capture_win.py@@ -3,8 +3,10 @@ real keyboard layout through ToUnicodeEx, which reads a keyboard state handedto it rather than the live one, so nothing here touches what is actually beingtyped."""+import ctypesimport sysimport unittest+from unittest.mock import Mock, patchimport capture_winfrom capture_win import REDIRECT, RETURN, TOGGLE, KeyboardState, Trigger, key_name, wheel_notches@@ -40,6 +42,145 @@ class NameTests(unittest.TestCase):state = KeyboardState()self.assertIsNone(key_name(0xFF, 0, state, names_only))+ def test_a_dead_key_is_composed_without_leaving_state_for_the_next_translation(self):+ class FrenchLayout:+ def __init__(self):+ self.pending = False+ self.flags = []++ def GetKeyboardLayout(self, _thread):+ return 1++ def ToUnicodeEx(self, vk, scan, key_state, buffer, size, flags, layout):+ self.flags.append(flags)+ if vk == 0xDD:+ if not flags & 0x4:+ self.pending = True+ buffer[0] = "^"+ return -1+ self.assert_no_pending = not self.pending+ self.pending = False+ buffer[0] = "ê" if self.pending else "e"+ return 1++ layout = FrenchLayout()+ state = KeyboardState()+ with patch.object(capture_win, "user32", layout):+ dead_key = key_name(0xDD, 0, state, capture_win._to_unicode)+ self.assertEqual(getattr(dead_key, "character", None), "^")+ self.assertEqual(key_name(0x45, 0, state, capture_win._to_unicode), "ê")+ self.assertEqual(layout.flags, [0x4, 0x4])+ self.assertTrue(layout.assert_no_pending)++ def test_a_dead_key_followed_by_space_types_its_spacing_character(self):+ state = KeyboardState()++ def translate(vk, scan, key_state):+ return capture_win.DeadKey("^") if vk == 0xDD else "space"++ self.assertEqual(getattr(key_name(0xDD, 0, state, translate), "character", None), "^")+ self.assertEqual(key_name(0x20, 0, state, translate), "^")++ def test_a_dead_key_without_a_unicode_composition_becomes_text(self):+ state = KeyboardState()++ def translate(vk, scan, key_state):+ return capture_win.DeadKey("§") if vk == 0xDD else "a"++ key_name(0xDD, 0, state, translate)+ text = key_name(0x41, 0, state, translate)+ self.assertEqual(type(text).__name__, "TextInput")+ self.assertEqual(text.text, "§a")++ def test_circumflex_followed_by_x_becomes_text_and_by_e_composes(self):+ state = KeyboardState()++ def translate(vk, scan, key_state):+ return capture_win.DeadKey("^") if vk == 0xDD else {0x58: "x", 0x45: "e"}.get(vk)++ key_name(0xDD, 0, state, translate)+ text = key_name(0x58, 0, state, translate)+ self.assertIsInstance(text, capture_win.TextInput)+ self.assertEqual(text.text, "^x")++ key_name(0xDD, 0, state, translate)+ self.assertEqual(key_name(0x45, 0, state, translate), "ê")++ def test_consumed_text_input_swallows_the_physical_key_release(self):+ class HookData(ctypes.Structure):+ _fields_ = [+ ("vkCode", ctypes.c_ulong),+ ("scanCode", ctypes.c_ulong),+ ("flags", ctypes.c_ulong),+ ("time", ctypes.c_ulong),+ ("dwExtraInfo", ctypes.c_size_t),+ ]++ on_key = Mock(return_value=True)+ hooks = capture_win.Hooks(on_key, Mock(), Mock())+ data = HookData(0x41, 0x1E, 0, 0, 0)+ user32 = Mock()+ user32.CallNextHookEx.return_value = 99++ with patch.object(capture_win, "KBDLLHOOKSTRUCT", HookData, create=True), \+ patch.object(capture_win, "user32", user32), \+ patch.object(capture_win, "key_name", return_value=capture_win.TextInput("§a")):+ key_down = hooks._keyboard_proc(capture_win.HC_ACTION, capture_win.WM_KEYDOWN, ctypes.byref(data))+ key_up = hooks._keyboard_proc(capture_win.HC_ACTION, capture_win.WM_KEYUP, ctypes.byref(data))++ self.assertEqual((key_down, key_up), (1, 1))+ on_key.assert_called_once()+ self.assertIsInstance(on_key.call_args.args[0], capture_win.TextInput)+ self.assertEqual(on_key.call_args.args[1:], (True, 0x41, None))+ self.assertEqual(hooks._text_keyups_swallowed, set())++ def test_stopping_hooks_clears_pending_text_key_releases(self):+ hooks = capture_win.Hooks(Mock(), Mock(), Mock())+ hooks._text_keyups_swallowed.add(0x41)++ hooks.stop()++ self.assertEqual(hooks._text_keyups_swallowed, set())++ def test_a_repeated_base_key_after_text_fallback_repeats_as_text(self):+ class HookData(ctypes.Structure):+ _fields_ = [+ ("vkCode", ctypes.c_ulong),+ ("scanCode", ctypes.c_ulong),+ ("flags", ctypes.c_ulong),+ ("time", ctypes.c_ulong),+ ("dwExtraInfo", ctypes.c_size_t),+ ]++ on_key = Mock(return_value=True)+ hooks = capture_win.Hooks(on_key, Mock(), Mock())+ hooks._text_keyups_swallowed.add(0x41)+ data = HookData(0x41, 0x1E, 0, 0, 0)+ user32 = Mock()++ with patch.object(capture_win, "KBDLLHOOKSTRUCT", HookData, create=True), \+ patch.object(capture_win, "user32", user32), \+ patch.object(capture_win, "key_name", return_value="a"):+ repeated_down = hooks._keyboard_proc(capture_win.HC_ACTION, capture_win.WM_KEYDOWN, ctypes.byref(data))+ key_up = hooks._keyboard_proc(capture_win.HC_ACTION, capture_win.WM_KEYUP, ctypes.byref(data))++ self.assertEqual((repeated_down, key_up), (1, 1))+ on_key.assert_called_once()+ self.assertEqual(on_key.call_args.args[0].text, "a")+ self.assertIsInstance(on_key.call_args.args[0], capture_win.TextInput)++ def test_a_key_release_does_not_consume_a_pending_dead_key(self):+ state = KeyboardState()++ def translate(vk, scan, key_state):+ return {0x41: "a", 0x45: "e"}.get(vk)++ self.assertEqual(key_name(0x41, 0, state, translate, down=True), "a")+ self.assertEqual(getattr(key_name(0xDD, 0, state, lambda *_: capture_win.DeadKey("^")), "character", None), "^")+ self.assertEqual(key_name(0x41, 0, state, translate, down=False), "a")+ self.assertEqual(state.pending_dead_key, "^")+ self.assertEqual(key_name(0x45, 0, state, translate, down=True), "ê")+@unittest.skipUnless(sys.platform == "win32", "ToUnicodeEx needs Windows")class LayoutTests(unittest.TestCase):diff --git a/win_app/tests/test_edge_glow.py b/win_app/tests/test_edge_glow.pyindex 4ed516c..7fa82c8 100644--- a/win_app/tests/test_edge_glow.py+++ b/win_app/tests/test_edge_glow.py@@ -1,7 +1,17 @@import unittest+import os+import sys+from types import SimpleNamespace+from unittest import mock++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))try:+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ from PySide6.QtCore import QPoint, QRect+ from PySide6.QtWidgets import QApplicationimport edge_glow+ from core import effectsexcept ImportError: # PySide6 is only in the Windows build venvedge_glow = None@@ -21,6 +31,21 @@ class BeamMathsTests(unittest.TestCase):self.assertEqual(edge_glow.comet_alpha(0.0, 0.5, 1.0), 1.0)[email protected](edge_glow is None, "PySide6 is not installed")+class SelectedSizeTests(unittest.TestCase):+ def test_glow_window_geometry_uses_the_selected_display_scaled_size(self):+ _app = QApplication.instance() or QApplication([])+ screen = SimpleNamespace(geometry=lambda: QRect(0, 0, 1920, 1080))+ glow = edge_glow.EdgeGlow()+ self.addCleanup(glow.deleteLater)+ glow.configure("glow", "signal", size="large")+ glow._edge, glow._part = "left", None+ with mock.patch.object(edge_glow.QApplication, "screens", return_value=[screen]), \+ mock.patch.object(edge_glow.QCursor, "pos", return_value=QPoint(0, 500)):+ glow._place()+ self.assertEqual(glow.geometry().width(), round(effects.edge_depth(1920, 1080, "large")))++@unittest.skipIf(edge_glow is None, "PySide6 is not installed")class GlowStateTests(unittest.TestCase):def test_a_breakthrough_flashes_then_fades_out(self):diff --git a/win_app/tests/test_effect_fires.py b/win_app/tests/test_effect_fires.pyindex ea56bd2..8328421 100644--- a/win_app/tests/test_effect_fires.py+++ b/win_app/tests/test_effect_fires.py@@ -20,10 +20,13 @@ counts as "an effect" is config plumbing already covered by test_effect_overlay.file's concern."""import os+import sysimport unittestfrom types import SimpleNamespacefrom unittest import mock+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+try:from PySide6.QtWidgets import QApplication@@ -34,10 +37,11 @@ except ImportError: # PySide6 is only in the Windows venvdef _owner(edge_glow=True, glow_style="glow", glow_colour="signal", shortcut_arrival=True,- shortcut_arrival_style="match", effects=None, glow=None):+ shortcut_arrival_style="match", effect_size="medium", effects=None, glow=None):config = SimpleNamespace(edge_glow=edge_glow, glow_style=glow_style, glow_colour=glow_colour,shortcut_arrival=shortcut_arrival, shortcut_arrival_style=shortcut_arrival_style, effect_length="normal",+ effect_size=effect_size,)return SimpleNamespace(_closing=False, _config=config, effects=effects, glow=glow)@@ -60,14 +64,20 @@ class PressureRoutingTest(unittest.TestCase):owner = _owner(glow_style="glow", glow_colour="ocean", glow=mock.Mock())owner._effect_overlay = mock.Mock(return_value=None)kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)- owner.glow.configure.assert_called_once_with("glow", "ocean", "normal")+ owner.glow.configure.assert_called_once_with("glow", "ocean", "normal", "medium")owner.glow.set_pressure.assert_called_once_with("left", 0.4, False, None)def test_a_beam_style_push_configures_the_glow_as_beam(self):owner = _owner(glow_style="beam", glow=mock.Mock())owner._effect_overlay = mock.Mock(return_value=None)kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)- owner.glow.configure.assert_called_once_with("beam", "signal", "normal")+ owner.glow.configure.assert_called_once_with("beam", "signal", "normal", "medium")++ def test_the_selected_size_reaches_the_glow_renderer(self):+ owner = _owner(glow_style="glow", glow=mock.Mock(), effect_size="large")+ owner._effect_overlay = mock.Mock(return_value=None)+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)+ owner.glow.configure.assert_called_once_with("glow", "signal", "normal", "large")def test_an_effect_that_failed_earlier_falls_back_to_plain_glow(self):"""_on_pressure's own comment: an effect that failed earlier in the run falls back to@@ -76,7 +86,7 @@ class PressureRoutingTest(unittest.TestCase):owner = _owner(glow_style="wormhole", glow_colour="mono", glow=mock.Mock())owner._effect_overlay = mock.Mock(return_value=None)kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)- owner.glow.configure.assert_called_once_with("glow", "mono", "normal")+ owner.glow.configure.assert_called_once_with("glow", "mono", "normal", "medium")def test_a_part_of_the_edge_push_passes_the_part_through_to_the_overlay(self):owner = _owner(glow_style="rupture")diff --git a/win_app/tests/test_effect_layouts.py b/win_app/tests/test_effect_layouts.pyindex aa2b68e..f07c174 100644--- a/win_app/tests/test_effect_layouts.py+++ b/win_app/tests/test_effect_layouts.py@@ -309,7 +309,7 @@ class LengthTests(unittest.TestCase):lasted[length] = tself.assertLess(lasted["short"], lasted["normal"])self.assertLess(lasted["normal"], lasted["long"])- self.assertAlmostEqual(lasted["long"] / lasted["normal"], 1.5, delta=0.1)+ self.assertAlmostEqual(lasted["long"] / lasted["normal"], 2.0, delta=0.1)def test_the_push_follows_the_hand_whatever_the_length(self):fx = effects.effect("flint")diff --git a/win_app/tests/test_full_screen_win.py b/win_app/tests/test_full_screen_win.pynew file mode 100644index 0000000..98f0430--- /dev/null+++ b/win_app/tests/test_full_screen_win.py@@ -0,0 +1,40 @@+import ctypes+import os+import sys+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++import desktop_win+++class FullScreenAppTest(unittest.TestCase):+ def test_beamer_is_not_a_full_screen_app_to_itself(self):+ state = ctypes.c_int(3)++ def query_user_notification_state(value):+ value._obj.value = state.value+ return 0++ process = ctypes.c_ulong(os.getpid())+ foreground = SimpleNamespace(+ GetForegroundWindow=lambda: 42,+ GetWindowThreadProcessId=lambda _hwnd, value: setattr(value._obj, "value", process.value),+ )+ shell = SimpleNamespace(SHQueryUserNotificationState=query_user_notification_state)+ with mock.patch.object(desktop_win, "_require"), \+ mock.patch.object(desktop_win, "user32", foreground), \+ mock.patch.object(desktop_win.ctypes, "windll", SimpleNamespace(shell32=shell), create=True), \+ mock.patch.object(desktop_win, "_foreground_covers_its_monitor") as covers, \+ mock.patch.object(desktop_win, "_foreground_app_name") as name:+ self.assertIsNone(desktop_win.full_screen_app())+ covers.assert_not_called()+ name.assert_not_called()+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.pyindex 7f3e0ec..7552aad 100644--- a/win_app/tests/test_links.py+++ b/win_app/tests/test_links.py@@ -21,6 +21,22 @@ def target_of(message):return protocol.read_id(message["data"]["target"])+class DeadKeyRoutingTests(unittest.TestCase):+ def setUp(self):+ self.rig = Rig()+ self.sender = self.rig.sender++ def test_a_dead_key_is_swallowed_only_while_its_peer_is_live(self):+ self.sender.set_redirecting(True)+ sent = list(self.rig.sent(B))+ self.assertTrue(self.sender.on_dead_key())+ self.assertEqual(self.rig.sent(B), sent)++ self.rig.links.up_set.discard(B)+ self.assertFalse(self.sender.on_dead_key())+ self.assertFalse(self.sender.redirecting)++class EdgeTests(unittest.TestCase):"""The outward crossing: the zone's model, the gate and the pin, which is everything the hookthread does per mouse move."""@@ -155,6 +171,38 @@ class TakingTests(unittest.TestCase):self.assertEqual(kinds, ["focus", "clipboard", "keydown"])self.assertEqual(self.rig.sent(B, "clipboard")[0]["data"]["text"], "here")+ def test_noncomposable_dead_key_sequence_is_sent_as_text(self):+ self.sender.set_redirecting(True)+ self.assertTrue(self.sender.on_text("§a", 0x41))+ self.assertEqual(self.rig.sent(B, protocol.MSG_TEXT)[0]["data"]["text"], "§a")++ def test_noncomposable_dead_key_text_releases_and_restores_remote_modifiers(self):+ self.sender.set_redirecting(True)+ self.rig.flush()+ self.rig.links.sent.clear()+ self.assertTrue(self.sender.on_key("shift", True, 0x10))++ self.assertTrue(self.sender.on_text("§A", 0x41))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(B)],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN],+ )++ def test_temporary_text_release_keeps_the_held_modifier_wire_name_if_style_changes(self):+ self.sender.set_redirecting(True)+ self.rig.accept_take()+ self.sender.on_key("cmd", True, 0xA2)+ self.rig.flush()+ original = self.rig.sent(B, protocol.MSG_KEYDOWN)[0]["data"]["key"]+ physical = self.sender._keys_down[0xA2]++ released = self.sender._key_message(B, {"type": protocol.MSG_KEYUP, "data": dict(physical)}, preserve=True)+ self.sender.update_config(make_config(modifier_style="positional"))+ restored = self.sender._key_message(B, {"type": protocol.MSG_KEYDOWN, "data": dict(physical)})++ self.assertEqual((released["data"]["key"], restored["data"]["key"]), (original, original))+def test_an_image_too_large_to_decode_is_not_sent_but_the_text_is(self):for image, sent in ((pngs.png(), True), (pngs.png(16384, 16384), False)):with self.subTest(sent=sent):@@ -321,12 +369,59 @@ class OnwardTests(unittest.TestCase):self.rig.inbound(C, protocol.accept_msg(self.sender._owner.route))self.assertEqual([m["data"]["key"] for m in self.rig.sent(C, "keydown")], ["a"])+ def test_text_during_chained_handover_brackets_a_modifier_waiting_to_be_replayed(self):+ self.switch(C)+ self.assertTrue(self.sender.on_key("shift", True, 0x10))+ self.assertTrue(self.sender.on_text("A", 0x41))++ self.rig.inbound(C, protocol.accept_msg(self.sender._owner.route))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(C) if message["type"] in protocol.INPUT_TYPES],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN],+ )++ def test_text_replayed_after_a_refused_handover_brackets_the_current_machines_modifier(self):+ self.sender.on_key("shift", True, 0x10)+ self.rig.flush()+ self.switch(C)+ self.assertTrue(self.sender.on_text("^x", 0x58))++ self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned"))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(B) if message["type"] in protocol.INPUT_TYPES],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN],+ )++ def test_text_replay_keeps_a_modifier_bracket_when_the_key_repeats_during_handover(self):+ self.sender.on_key("shift", True, 0x10)+ self.rig.flush()+ self.switch(C)+ self.assertTrue(self.sender.on_text("^x", 0x58))+ self.sender.on_key("shift", True, 0x10)++ self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned"))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(B) if message["type"] in protocol.INPUT_TYPES],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN, protocol.MSG_KEYDOWN],+ )+def test_a_switch_home_lands_the_pointer_and_reports_the_arrival(self):self.switch(HERE, edge="left", offset=0.5)self.assertFalse(self.sender.redirecting)self.assertEqual(self.rig.desktop.placed, [(0, 540)])self.assertEqual(self.rig.arrivals, [("left", 0, 540)])+ def test_the_log_names_the_edge_input_lands_at_both_ways(self):+ with self.assertLogs(sender.LOGGER, "INFO") as said:+ self.switch(C, edge="right", offset=0.25)+ self.rig.inbound(C, protocol.accept_msg(self.sender._owner.route))+ self.rig.inbound(C, protocol.switch_v6(self.sender._owner.route, HERE, edge="left", offset=0.5))+ self.assertTrue(any("input is on Other, at its right edge" in line for line in said.output), said.output)+ self.assertTrue(any("input returned to this PC (switch), at its left edge" in line for line in said.output), said.output)+def test_a_switch_home_with_no_position_reports_where_the_pointer_is(self):self.switch(HERE)self.assertEqual(self.rig.arrivals, [(None, 0, 500)])@@ -406,6 +501,18 @@ class KeyTests(unittest.TestCase):self.sender.on_key("ctrl", True, 0x5B)self.assertEqual(self.keys(), [("keydown", "ctrl"), ("keydown", "cmd")])+ def test_mac_layout_sends_both_sides_of_each_modifier_to_the_mac_key(self):+ self.sender.update_config(make_config(modifier_style="mac_layout"))+ for name, vk in (("cmd", 0xA2), ("cmd_r", 0xA3), ("ctrl", 0x5B), ("ctrl_r", 0x5C),+ ("alt", 0xA4), ("alt_r", 0xA5)):+ self.sender.on_key(name, True, vk)+ self.sender.on_key(name, False, vk)+ self.assertEqual(+ self.keys(),+ [(kind, key) for key in ("ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r")+ for kind in ("keydown", "keyup")],+ )+def test_to_another_pc_every_key_goes_as_itself(self):rig = Rig(entries=[harness.entry(B, "Other PC", platform="windows", side="left")])rig.sender.set_redirecting(True)diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.pyindex 6987b98..343b103 100644--- a/win_app/tests/test_pages_win.py+++ b/win_app/tests/test_pages_win.py@@ -73,14 +73,14 @@ class DesignGroupsTest(unittest.TestCase):def test_glow_and_beam_tiles_read_as_the_effects_do(self):today = pages_win.style_groups()[0][1]- self.assertEqual([detail for _value, _name, detail in today], ["Classic", "Classic"])+ self.assertEqual([detail for _value, _name, detail in today], ["Quiet", "Medium", "Showpiece"])def test_styles_are_classic_then_each_direction_in_order(self):groups = pages_win.style_groups()self.assertEqual([title for title, _items in groups],- ["Classic", "Membrane", "Sparks", "Instrument"])- self.assertEqual([style for style, _n, _d in groups[0][1]], ["glow", "beam"])- effect_ids = tuple(style for _title, items in groups[1:] for style, _n, _d in items)+ ["Light", "Membrane", "Sparks", "Instrument", "Folio", "Selvedge"])+ self.assertEqual([style for style, _n, _d in groups[0][1]], ["glow", "beam", "aperture"])+ effect_ids = tuple(style for _title, items in groups for style, _n, _d in items if style not in ("glow", "beam"))self.assertEqual(effect_ids, effects.EFFECT_IDS)def test_every_effect_tile_names_its_intensity(self):@@ -105,8 +105,8 @@ class DesignGroupsTest(unittest.TestCase):styles, colours = pages_win.style_groups(), pages_win.colour_groups()finally:effects._load = real- self.assertEqual([title for title, _items in styles], ["Classic"])- self.assertEqual([title for title, _items in colours], ["Classic"])+ self.assertEqual([title for title, _items in styles], ["Light"])+ self.assertEqual([title for title, _items in colours], ["Light"])def test_only_the_new_effects_count_as_effects(self):self.assertFalse(pages_win.is_effect("glow"))@@ -221,11 +221,12 @@ class SwitchGroupsTest(unittest.TestCase):self.assertEqual(sorted(values), sorted(effects.SWITCH_STYLES))self.assertEqual(len(values), len(set(values)))- def test_simple_comes_first_then_the_crossing_directions(self):+ def test_simple_and_aperture_come_first_then_the_crossing_directions(self):groups = pages_win.switch_groups()self.assertEqual(groups[0], ("Simple", (("match", "Same as crossing", "Plays the crossing style"),("locator", "Ring", "Closes onto the pointer"))))- self.assertEqual(groups[1:], pages_win.style_groups()[1:])+ self.assertEqual(groups[1], ("Light", (("aperture", "Aperture", "Showpiece"),)))+ self.assertEqual(groups[2:], pages_win.style_groups()[1:])@unittest.skipIf(widgets is None, "needs PySide6")@@ -244,7 +245,7 @@ class DesignControlsTest(unittest.TestCase):tiles = widgets.TileGroups(groups, "glow", on_change=chosen.append)tiles.groups["Sparks"]._chosen("discharge")self.assertEqual((tiles.value, chosen), ("discharge", ["discharge"]))- self.assertEqual(tiles.groups["Classic"].value, "discharge")+ self.assertEqual(tiles.groups["Light"].value, "discharge")tiles.set_value("skin")self.assertEqual(chosen, ["discharge"], "set_value must not report a change")self.assertTrue(all(group.value == "skin" for group in tiles.groups.values()))@@ -346,6 +347,34 @@ class CrossingPageTest(unittest.TestCase):rows |= {"shortcut"} if motion.target_shown(page.shortcut_module) else set()return rows+ def test_the_native_titlebar_can_maximise_and_has_no_width_cap(self):+ from PySide6.QtCore import Qt++ self.assertTrue(self.page.windowFlags() & Qt.WindowType.WindowMaximizeButtonHint)+ self.assertEqual(self.page.maximumWidth(), 16777215)++ def test_crossing_controls_and_diagram_stay_in_a_capped_column(self):+ from PySide6.QtWidgets import QApplication++ self.page.resize(2560, 1440)+ self.page.show()+ self.page._select_page("crossing")+ QApplication.processEvents()++ self.assertLessEqual(self.page.arrangement_diagram.width(), 960)+ self.assertLessEqual(max(button.width() for button in self.page.edge_choice._buttons.values()), 240)++ def test_jump_placeholder_uses_body_text_with_the_hint_below(self):+ from PySide6.QtWidgets import QApplication++ self.page.resize(820, 700)+ self.page.show()+ self.page._select_page("crossing")+ QApplication.processEvents()++ self.assertEqual(self.page.jump_recorder.key.property("vernier"), "body")+ self.assertLess(self.page.jump_recorder.key.y(), self.page.jump_recorder.hint.y())+def test_rows_hide_and_come_back_with_the_ways(self):self.ways()self.assertEqual(self.shown(), {"edge", "shortcut"})@@ -388,7 +417,8 @@ class CrossingPageTest(unittest.TestCase):self.assertTrue(line(True, True, True, False, True, False, None).startswith("Not connected to the other machine"))self.assertTrue(line(True, True, True, True, False, False, None).startswith("Only the shortcut"))self.assertTrue(line(True, True, True, True, True, True, None).startswith("Paused."))- self.assertTrue(line(True, True, True, True, True, False, "Keynote").startswith("Off while Keynote"))+ self.assertEqual(line(True, True, True, True, True, False, "Keynote"),+ "Held: an app is full screen.")self.assertEqual(line(True, True, True, True, True, False, None), "On. Pause it to lean on an edge without switching.")def test_the_crossing_line_names_the_machine_it_is_given(self):diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.pyindex ebe6f6c..00c4fa8 100644--- a/win_app/tests/test_pairing_window.py+++ b/win_app/tests/test_pairing_window.py@@ -16,6 +16,7 @@ from core import pairing, peerlist, protocolfrom core.tests import responder_harness as harnesstry:+ from PySide6.QtCore import Qtfrom PySide6.QtWidgets import QApplicationimport app_config@@ -402,6 +403,11 @@ class PairingSheetWindowTest(unittest.TestCase):self.assertTrue(self.window.sheet.code_showing)self.assertTrue(self.window.sheet.count_label.text().startswith("Expires in "))+ def test_pairing_code_text_is_centred_in_its_stretched_label(self):+ self.show_code()+ alignment = self.window.sheet.code_label.alignment()+ self.assertTrue(alignment & Qt.AlignmentFlag.AlignHCenter)+def test_cancelling_the_code_puts_the_button_back_and_says_nothing(self):self.show_code()self.window._cancel_code()diff --git a/win_app/tests/test_parity.py b/win_app/tests/test_parity.pyindex 8922239..a956fbf 100644--- a/win_app/tests/test_parity.py+++ b/win_app/tests/test_parity.py@@ -13,7 +13,10 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(import app_configimport capture_winfrom app_config import ConfigError, config_from_dict, config_to_dict, default_config+from core import protocol+from core.return_edge import Rectfrom core.tests import responder_harness as harness+from core.tests.responder_harness import Initiator, Machinefrom links_rig import B, Rig, make_config@@ -96,12 +99,17 @@ 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_the_full_screen_hold_defaults_off_and_preserves_each_saved_choice(self):+ self.assertFalse(config_from_dict(raw()).hold_full_screen)+ for choice in (False, True):+ saved = config_to_dict(replace(default_config(), auth_token="t", hold_full_screen=choice))+ self.assertEqual(config_from_dict(saved).hold_full_screen, choice)++ def test_mac_layout_round_trips_and_an_older_file_defaults_to_semantic(self):+ old = config_from_dict(raw())+ self.assertEqual(old.modifier_style, "semantic")+ saved = config_to_dict(replace(old, modifier_style="mac_layout"))+ self.assertEqual(config_from_dict(saved).modifier_style, "mac_layout")def test_an_unknown_modifier_style_is_refused(self):with self.assertRaises(ConfigError):@@ -126,6 +134,8 @@ class HeldEdgeTests(unittest.TestCase):self.assertTrue(self.sender.redirecting)def test_a_full_screen_app_holds_the_edge(self):+ # The hold is off by default since 02-10-2026.+ self.sender.update_config(make_config(hold_full_screen=True))self.sender.full_screen_app = "Game"self.push()self.assertFalse(self.sender.redirecting)@@ -138,6 +148,33 @@ class HeldEdgeTests(unittest.TestCase):self.push()self.assertTrue(self.sender.redirecting)+ def test_this_pcs_full_screen_setting_decides_its_edges_while_the_mac_drives_it(self):+ for enabled in (False, True):+ with self.subTest(hold_full_screen=enabled):+ rig = Rig(cursor=(0, 500), hold_full_screen=enabled)+ rig.sender.full_screen_app = "Game"+ desktop = harness.FakeDesktop([Rect(0, 0, 1920, 1080)], cursor=(0, 500))+ machine = Machine(+ [harness.entry(B, "Mac", side="left")],+ [{"peer": protocol.id_text(B), "kind": "edge"}],+ desktop=desktop,+ ).start()+ self.addCleanup(machine.stop)+ # This is the WindowsApplication receiver wiring, using this PC's own setting.+ machine.responder.edges_held = lambda: rig.sender.edges_held+ link = Initiator(machine, B)+ self.addCleanup(link.close)+ link.handshake()+ route = link.take()+ self.assertEqual(link.answer(route)[0], protocol.MSG_ACCEPT)+ seq = link.move(-200, 0)+ self.assertIsNotNone(link.acked(seq))+ crossed = link.expect(protocol.MSG_SWITCH, timeout=0.2)+ if enabled:+ self.assertIsNone(crossed, "the PC's enabled hold let the Mac cross its edge")+ else:+ self.assertEqual(crossed["next"], protocol.id_text(B))+def test_a_drag_against_the_edge_does_not_cross(self):self.sender.on_button("left", True)self.push()diff --git a/win_app/tests/test_same_on_both.py b/win_app/tests/test_same_on_both.pyindex ecd2b39..f70acd1 100644--- a/win_app/tests/test_same_on_both.py+++ b/win_app/tests/test_same_on_both.py@@ -7,6 +7,7 @@ import osimport tempfileimport unittestfrom pathlib import Path+from unittest import mocktry:from PySide6.QtWidgets import QApplication@@ -55,10 +56,182 @@ class SameOnBothTest(unittest.TestCase):self.window.server.stop()self.window.deleteLater()+ def pair_peer(self, peer: str) -> None:+ settings = app_config.load_settings(self.path)+ settings["peers"][0]["id"] = peer+ app_config.write_settings(self.path, settings)+ self.window._refresh_peers()+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_full_screen_hold_switch_names_this_pcs_edges(self):+ self.assertEqual(self.window.hold_switch.text(), "Hold this PC's edges while an app on it is full screen")+ def test_this_pcs_design_state_is_announced_when_same_is_off(self):+ data = self.window._same_state()++ self.assertFalse(data["on"])+ self.assertEqual(data["design_sync"]["values"]["effect_size"], "medium")+ self.assertEqual(set(data["design_sync"]["values"]), set(settings_sync.DESIGN_KEYS))++ def test_a_followed_design_is_applied_and_renamed_as_this_pcs_state(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ received = settings_sync.message_data(+ False, 100, by=peer,+ design_state={"set_at": 200, "by": peer,+ "values": {"effect_length": "long"}},+ )++ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "long")+ self.assertEqual((self.window._config.design_set_at, self.window._config.design_by), (200, peer))+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "long")++ def test_a_design_state_in_a_malformed_settings_envelope_is_dropped_whole(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ state = {"set_at": 200, "by": peer, "values": {"effect_length": "long"}}++ for outer in ({"on": "no"}, {"set_at": True}, {"by": "not an id"}):+ received = settings_sync.message_data(False, 100, by=peer, design_state=state)+ received.update(outer)+ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "normal")+ self.assertNotIn(peer, self.window._design_states)+ self.assertEqual(self.sent, [])++ def test_follow_accepts_the_leaders_next_change_after_this_pc_reannounces(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ config = self.window._config+ config.design_follow_peer = peer+ config.design_set_at = 50+ config.design_by = peer++ for stamp, length in ((100, "long"), (101, "short")):+ received = settings_sync.message_data(+ False, stamp - 50, by=peer,+ design_state={"set_at": stamp, "by": peer, "values": {"effect_length": length}},+ )+ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "short")+ self.assertEqual((self.window._config.design_set_at, self.window._config.design_by), (101, peer))+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "short")+ self.assertEqual((self.sent[-1][1]["design_sync"]["set_at"], self.sent[-1][1]["design_sync"]["by"]),+ (101, peer))++ def test_followed_size_updates_the_control_without_saving_a_local_edit(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ received = settings_sync.message_data(+ False, 100, by=peer,+ design_state={"set_at": 200, "by": peer, "values": {"effect_size": "large"}},+ )++ self.window._on_settings(peer, received)++ self.assertEqual(self.window.size_choice.value, "large")+ self.assertEqual(self.window._config.effect_size, "large")+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_size"], "large")++ def test_same_on_design_change_is_announced_with_a_new_local_design_stamp(self):+ source = protocol.id_text(harness.C)+ config = self.window._config+ config.same_on_both = True+ config.same_set_at = 10+ config.same_by = source+ config.design_set_at = 20+ config.design_by = config.machine_id+ config.effect_length = "short"+ received = mac_message(True, 11, by=source, effect_length="long")+ received["design_sync"] = {+ "set_at": 100, "by": source, "values": {"effect_length": "long"},+ }++ self.window._on_settings(source, received)++ self.assertEqual(self.window._config.effect_length, "long")+ self.assertGreater(self.window._config.design_set_at, 100)+ self.assertEqual(self.window._config.design_by, self.window._config.machine_id)+ self.assertEqual(self.sent[-1][1]["design_sync"]["set_at"], self.window._config.design_set_at)+ self.assertNotEqual(self.sent[-1][1]["design_sync"]["by"], source)++ def test_same_off_from_another_machine_resumes_the_cached_followed_design(self):+ leader = protocol.id_text(harness.B)+ other = protocol.id_text(harness.C)+ self.pair_peer(leader)+ config = self.window._config+ config.same_on_both = True+ config.same_set_at = 10+ config.same_by = other+ config.design_follow_peer = leader+ config.effect_length = "short"+ self.window._design_states[leader] = {+ "set_at": 100, "by": leader, "values": {"effect_length": "long"},+ }+ apply_followed = mock.Mock(wraps=self.window._apply_followed_design)+ self.window._apply_followed_design = apply_followed++ self.window._on_settings(other, settings_sync.message_data(False, 11, by=other))++ apply_followed.assert_called_once()+ self.assertEqual(self.window._config.effect_length, "long")+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "long")+ self.assertEqual((self.sent[-1][1]["design_sync"]["set_at"], self.sent[-1][1]["design_sync"]["by"]),+ (100, protocol.id_text(harness.B)))++ def test_editing_a_design_control_stops_following(self):+ self.window._config.design_follow_peer = protocol.id_text(harness.B)+ self.window._design_seen = self.window._design_fields()+ self.window.length_choice.set_value("short")+ self.window._apply_look()++ self.assertEqual(self.window._config.design_follow_peer, "")+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "short")++ def test_unpairing_the_followed_machine_resets_the_selection(self):+ peer = protocol.id_text(harness.B)+ self.window._config.design_follow_peer = peer+ with mock.patch.object(self.window.book, "peers", return_value=[]), \+ mock.patch.object(self.window.book, "zones", return_value=[]):+ self.window._refresh_peers()++ self.assertEqual(self.window._config.design_follow_peer, "")++ def test_same_on_all_machines_keeps_precedence_over_a_followed_design(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ self.window._config.same_on_both = True+ self.window._config.same_set_at = 100+ received = settings_sync.message_data(+ True, 101, settings_sync.pc_values(self.window._config), by=peer,+ design_state={"set_at": 202, "by": peer,+ "values": {"effect_length": "long"}},+ )++ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "normal")+ self.assertEqual(self.window._config.design_follow_peer, protocol.id_text(harness.B))++ def test_an_older_peer_is_disabled_in_match_design_with(self):+ self.window._peer_entries = [{"id": protocol.id_text(harness.B), "name": "Old PC"}]+ self.peers = {harness.B: {"settings"}}++ self.window._refresh_design_follow()++ self.assertFalse(self.window.design_follow_choice.model().item(1).isEnabled())+ self.assertIn("Needs beta.6 or later", self.window.design_follow_choice.itemText(1))+def test_the_macs_settings_arrive_on_this_pcs_fields_and_controls(self):self.window._on_settings(protocol.id_text(harness.B), mac_message(True, 100))config = self.window._config@@ -127,16 +300,23 @@ class SameOnBothTest(unittest.TestCase):self.assertEqual([peer["token"] for peer in saved["peers"]], [harness.TOKENS[harness.B]])self.assertEqual(self.window._config.auth_token, harness.TOKENS[harness.B])- def test_a_state_that_goes_on_is_sent_as_it_arrived(self):+ def test_a_state_that_goes_on_is_forwarded_with_this_pcs_direct_design_state(self):self.peers = {harness.B: {"settings"}, harness.C: {"settings"}}message = mac_message(True, 100)self.window._on_settings(protocol.id_text(harness.B), message)- self.assertEqual(self.sent, [(harness.C, message)])+ self.assertEqual(len(self.sent), 1)+ self.assertEqual(self.sent[0][0], harness.C)+ forwarded = self.sent[0][1]+ self.assertEqual({key: value for key, value in forwarded.items() if key != "design_sync"},+ {key: value for key, value in message.items() if key != "design_sync"})+ self.assertEqual(forwarded["design_sync"]["by"], self.window._config.machine_id)- def test_a_change_here_while_off_goes_nowhere(self):+ def test_a_design_change_here_while_off_announces_its_local_state(self):self.window._config.effect_length = "short"self.window._persist()- self.assertEqual(self.sent, [])+ self.assertEqual(len(self.sent), 2)+ self.assertTrue(all(message["design_sync"]["values"]["effect_length"] == "short"+ for _peer, message in self.sent))def test_announcing_carries_a_chosen_arrangement_the_peers_it_may_send_to_and_the_settings(self):settings = app_config.load_settings(self.path)diff --git a/win_app/tests/test_wide_layout.py b/win_app/tests/test_wide_layout.pynew file mode 100644index 0000000..b0d3ee2--- /dev/null+++ b/win_app/tests/test_wide_layout.py@@ -0,0 +1,42 @@+import os+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++from PySide6.QtWidgets import QApplication++import diagram+import theme+import widgets+++class WideLayoutTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.app = QApplication.instance() or QApplication([])+ theme.init_fonts()++ def test_wrapped_paragraphs_keep_a_readable_measure(self):+ paragraph = widgets.label("A long settings explanation.", "note", wrap=True)++ self.assertEqual(paragraph.maximumWidth(), 560)++ def test_the_arrangement_diagram_uses_more_width_on_a_wide_page(self):+ drawing = diagram.ArrangementDiagram()+ drawing.set_machines(+ [{"key": "desk", "label": "Desk", "side": "right", "methods": ["edge"],+ "parts": [], "chosen": True}],+ "Right Ctrl", "hold", True,+ )++ narrow = drawing._drawing(640.0)[0][2]+ wide = drawing._drawing(1440.0)[0][2]+ self.assertGreater(wide, narrow)++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tokens.py b/win_app/tokens.pyindex dbb5b81..e10a308 100644--- a/win_app/tokens.py+++ b/win_app/tokens.py@@ -115,6 +115,8 @@ RADIUS = {MODULE_PADDING = (14.0, 16.0)RACK_GAP = 1.0MIN_WINDOW = {"mac": (640, 540), "windows": (640, 600)}+READING_WIDTH = 560.0+PAGE_CONTENT_WIDTH = 960.0# Mass-spring parameters (mass 1) for everything that moves. The notch island integrates two of# these, width and depth; a trackpad tick adds `tick_velocity` points per second to the width.diff --git a/win_app/widgets.py b/win_app/widgets.pyindex cd108a1..9c9f3b5 100644--- a/win_app/widgets.py+++ b/win_app/widgets.py@@ -35,6 +35,8 @@ def label(text: str, role: str, wrap: bool = False) -> QLabel:item = QLabel(text)item.setProperty("vernier", role)item.setWordWrap(wrap)+ if wrap and role in {"note", "note-quiet", "note-amber"}:+ item.setMaximumWidth(tokens.READING_WIDTH)return item@@ -576,16 +578,16 @@ class JumpKeyRecorder(QPushButton):self.armed = Falseself.setProperty("vernier", "keycap")self.setCursor(Qt.CursorShape.PointingHandCursor)- self.setFixedHeight(42)- row = QHBoxLayout(self)- row.setContentsMargins(12, 0, 12, 0)- row.setSpacing(10)- self.key = label("Choose a key combination", "keycap")+ self.setMinimumHeight(52)+ row = QVBoxLayout(self)+ row.setContentsMargins(12, 5, 12, 5)+ row.setSpacing(2)+ self.key = label("Choose a key combination", "body")self.hint = label("Click, then press a key combination", "small")self.key.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)self.hint.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)- row.addWidget(self.key, 1)- row.addWidget(self.hint, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)+ row.addWidget(self.key)+ row.addWidget(self.hint)self.clicked.connect(self._toggle)self._names = {"ctrl": "Win", "cmd": "Ctrl", "alt": "Alt", "shift": "Shift"}@@ -596,6 +598,7 @@ class JumpKeyRecorder(QPushButton):self.setAccessibleName(f"Jump straight here key, {shown}")if not self.armed:self.key.setText(shown)+ set_role(self.key, "keycap" if self.value else "body")def cancel(self) -> None:if not self.armed:@@ -605,7 +608,7 @@ class JumpKeyRecorder(QPushButton):if self.on_arm is not None:self.on_arm(False)self.set_value(self.value)- set_role(self.key, "keycap")+ set_role(self.key, "keycap" if self.value else "body")self.hint.setText("Click, then press a key combination")set_role(self, "keycap")