Skip to content

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

Beamer 1.5.5

Toby Kalkman18fcc5dfc37e
diff --git a/README.md b/README.md
index 3fe84b8..14564ea 100644
--- a/README.md
+++ b/README.md
@@ -109,6 +109,8 @@ In your own appearance: light if your GitHub is light, dark if it is dark.
- **Or press a key.** Double-tap or hold a trigger key to switch without moving the pointer. Right
Option on the Mac and Right Ctrl on the PC to start with; on either machine it can be any key
that types nothing, recorded by pressing it.
+- **Shake to come home.** While you drive another machine, a quick shake of this machine's mouse or
+ trackpad brings input straight back. Shake sensitivity sets how much movement it takes.
- **Either way round.** The Mac drives the PC and the PC drives the Mac. Each machine has a switch
per direction, so you can turn one way off and keep the other. Macs can drive Macs, and Windows
PCs can drive Windows PCs, too.
@@ -152,6 +154,10 @@ In your own appearance: light if your GitHub is light, dark if it is dark.
- **Keep settings in step.** Same on all machines shares resistance, drag protection, Shortcut,
effect style, colour, length, size and landing animation with compatible paired machines. Zones,
jump keys, full-screen hold, whether effects animate, and window appearance stay local.
+- **One desk, several profiles.** Same ways on every machine shares the crossing ways between
+ 1.5.5 machines, so you can set up any machine from the one in front of you and keep up to eight
+ named profiles. Machine tiles on the Crossing map resize, so different screen sizes line up.
+- **In Italian too.** Language on the Connection page picks Automatic, English or Italiano.
- **Match design.** Follow one paired machine's style, colour, length, size and landing animation.
Changing one of those here stops following. Animation enable and window appearance stay local.
- **A more responsive settings window.** Mac resizing and scrolling stay smooth, the Design grid
diff --git a/VERSION b/VERSION
index 94fe62c..9075be4 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.5.4
+1.5.5
diff --git a/WIRE.md b/WIRE.md
index 374fd00..d2307b1 100644
--- a/WIRE.md
+++ b/WIRE.md
@@ -1113,6 +1113,7 @@ A key travels as `key`, a name, in `keydown` and `keyup`:
| Group | Names |
|---|---|
| Modifiers | `shift`, `shift_r`, `ctrl`, `ctrl_r`, `alt`, `alt_r`, `cmd`, `cmd_r`, `caps_lock` |
+ | Input method | `hangul`, `hanja` |
| Editing and movement | `backspace`, `tab`, `enter`, `esc`, `space`, `delete`, `insert`, `home`, `end`, `page_up`, `page_down`, `left`, `right`, `up`, `down` |
| Function | `f1` to `f24` |
| Windows keys | `menu`, `print_screen`, `pause`, `num_lock`, `scroll_lock`, `browser_back`, `browser_forward`, `browser_refresh`, `browser_stop`, `browser_search`, `browser_favourites`, `browser_home`, `mail`, `media_select`, `launch_app1`, `launch_app2` |
@@ -1120,13 +1121,18 @@ A key travels as `key`, a name, in `keydown` and `keyup`:
| System actions | `search`, `spotlight`, `dictation` |
The numpad's Enter is `enter`.
+ `hangul` and `hanja` are HID Lang1 and Lang2. On a JIS Mac they share the Kana (`0x68`) and Eisu
+ (`0x66`) keycodes; on Windows they share VK_KANA and VK_KANJI. A Japanese keyboard's Kana key
+ therefore travels as `hangul`, which is accepted because it lands on the same Windows VK.
- **`keyup`** carries the same `key` and `us` as the `keydown` it releases, even if Shift changed
in between. Auto-repeat is more `keydown`s with no `keyup` between them. `caps_lock` is sent as a
- `keydown` and a `keyup` together on each press.
+ `keydown` and a `keyup` together on each press. `hangul` and `hanja` use the same tap rule: each
+ physical press sends both messages, and the physical release sends nothing.
- **On the receiver**, `ctrl` is Control, `alt` is Option or Alt, and `cmd` is Command on a Mac,
the Windows key on Windows and Super on Linux. It types a character as given, pressing or
releasing Shift around it as its own layout needs, and falls back to `us` when its layout has no
- key for the character. A name it cannot press is dropped.
+ key for the character. A name it cannot press is dropped; a receiver without `hangul` or `hanja`
+ drops them in the same way as any unknown name.
- **A phone** has no physical keys to map. It shows a modifier row named for the platform it is
driving and sends names directly: Command-C to a Mac is `keydown cmd`, `keydown "c"` with `us`
`"c"`, `keyup "c"`, `keyup cmd`.
diff --git a/core/crossing_state.py b/core/crossing_state.py
index 70df322..a37624f 100644
--- a/core/crossing_state.py
+++ b/core/crossing_state.py
@@ -5,11 +5,13 @@ Callers save the Outcome and carry out its messages before re-arming their respo
"""
import copy
+import functools
import math
+import os
import time
from typing import TypedDict
-from core import protocol, return_edge, settings_sync, ways
+from core import profiles, protocol, return_edge, settings_sync, ways
class Outcome(TypedDict):
@@ -21,16 +23,24 @@ class Outcome(TypedDict):
tell: list
send_picture: bool
forward_picture: bool
+ send_desk: list
+ forward: dict
+ answer: dict
+ reason: str
def _outcome(before, saved=None, result=None, *, accepted=True, tell=(),
- send_picture=False, forward_picture=False):
- saved = copy.deepcopy(before if saved is None else saved)
+ send_picture=False, forward_picture=False, send_desk=(), forward=None,
+ answer=None, reason="", owned=False):
+ """`owned`: `saved` is a copy this event made and nothing else holds, so it is kept, not copied."""
+ saved = saved if owned and saved is not None else copy.deepcopy(before if saved is None else saved)
return Outcome(settings=saved, changed=saved != before, accepted=accepted,
snap=copy.deepcopy((result or {}).get("snap", {})),
tiles=copy.deepcopy((result or {}).get("tiles", {})),
tell=list(dict.fromkeys(tell)), send_picture=send_picture,
- forward_picture=forward_picture)
+ forward_picture=forward_picture, send_desk=list(dict.fromkeys(send_desk)),
+ forward=copy.deepcopy(forward or {}), answer=copy.deepcopy(answer or {}),
+ reason=reason)
def _initial(settings, capable=(), fill=True):
@@ -196,8 +206,11 @@ def receive_picture(settings, state, *, source, platform, capable, live, gone, o
own = saved.get("machine_id")
saved.update(layout=layout, layout_set_at=state["set_at"], layout_by=state["by"])
corrected = ways.refresh_displays(saved, own_displays, now=now)
- if (own_displays and not corrected
- and state["tiles"].get(own, {}).get("displays") != saved["layout"][own].get("displays")):
+ # A picture that has no tile for this machine is one relayed from a machine that does not know
+ # it (A-B-C with A and C unpaired). Restamping against it would make each end answer the
+ # other's picture for ever; link_up and paired already tell a new peer about this machine.
+ if (own_displays and not corrected and own in state["tiles"]
+ and state["tiles"][own].get("displays") != saved["layout"][own].get("displays")):
_stamp(saved, now)
corrected = True
result = _compile(saved, platform, capable=capable, live=live, gone=gone, now=now)
@@ -326,3 +339,425 @@ def migrate(settings, platform, *, capable=()):
saved = _initial(settings, capable)
result = _compile(saved, platform, capable=capable)
return _outcome(settings, result["settings"], result)
+
+
+def _platform(settings, supplied=None):
+ if supplied in ("mac", "pc", "windows", "linux"):
+ return supplied
+ own = settings.get("machine_id", "")
+ state = settings.get("crossing_desk", {}).get("status", {}).get(own, {})
+ value = state.get("value", {}) if isinstance(state, dict) else {}
+ platform = value.get("platform") if isinstance(value, dict) else None
+ return platform if platform in ("mac", "pc", "windows", "linux") else "windows"
+
+
+def _profile_event(function):
+ """Reconcile profile-aware events at their shared boundary, including no-op events."""
+ @functools.wraps(function)
+ def wrapped(settings, *args, **kwargs):
+ if (not isinstance(settings, dict) or "crossing_own" not in settings
+ or settings.get("_crossing_profiles_upgrade_pending") is True):
+ return function(settings, *args, **kwargs)
+ supplied_platform = kwargs.get("platform")
+ if supplied_platform is None and function.__name__ == "migrate" and args:
+ supplied_platform = args[0]
+ platform = _platform(settings, supplied_platform)
+ capable = kwargs.get("capable", ())
+ live, gone, now = kwargs.get("live"), kwargs.get("gone"), kwargs.get("now")
+ app = settings.get("crossing_desk", {}).get("status", {}).get(
+ settings.get("machine_id"), {}).get("value", {}).get("app", profiles.APP_VERSION)
+ original = settings
+ # Settings reconcile would leave as they are go to the event uncopied: no event writes to its
+ # argument (each copies first, as the unreconciled path above already relies on), so the
+ # caller's settings stay untouched either way.
+ if profiles.reconciled(settings, platform=platform, app=app):
+ prepared, before_paths = settings, []
+ else:
+ prepared, before_paths = profiles.reconcile(settings, platform=platform,
+ capable=capable, live=live,
+ gone=gone, now=now, app=app)
+ out = function(prepared, *args, **kwargs)
+ if not out.get("accepted", True):
+ out["settings"] = copy.deepcopy(original)
+ out["changed"] = False
+ out["send_desk"] = []
+ out["tell"] = []
+ out["send_picture"] = False
+ out["forward_picture"] = False
+ out["forward"] = {}
+ out["answer"] = {}
+ return out
+ saved, after_paths = out["settings"], []
+ # Forwarded duplicates and stale-register replies leave the prepared settings
+ # untouched. Projecting them again multiplies the work of every mesh relay.
+ if saved != prepared and not profiles.reconciled(saved, platform=platform, app=app):
+ saved, after_paths = profiles.reconcile(saved, platform=platform,
+ capable=capable, live=live,
+ gone=gone, now=now, app=app)
+ if profiles.desk_size(saved) > profiles.MAX_DESK_BYTES:
+ out["settings"] = copy.deepcopy(original)
+ out["changed"] = False
+ out["accepted"] = False
+ out["reason"] = "desk_full"
+ out["send_desk"] = []
+ out["tell"] = []
+ out["send_picture"] = False
+ out["forward_picture"] = False
+ out["forward"] = {}
+ out["answer"] = {}
+ return out
+ paths = [*before_paths, *out.get("send_desk", []), *after_paths]
+ out["settings"] = saved
+ out["changed"] = saved != original
+ out["send_desk"] = list(dict.fromkeys(paths))
+ if out["changed"]:
+ out["tell"] = list(dict.fromkeys([*out.get("tell", []), *_tells(original, saved)]))
+ return out
+ return wrapped
+
+
+def _register_value(register, default=None):
+ return register.get("value", default) if isinstance(register, dict) else default
+
+
+def _desk(settings):
+ return settings["crossing_desk"]
+
+
+def _own(settings):
+ return settings["crossing_own"]
+
+
+def _active(settings):
+ return _register_value(_desk(settings).get("active"), profiles.DESK_ID)
+
+
+def _profile_stamp(settings, held=None, now=None, floor=0):
+ own = settings.get("machine_id", "")
+ current = int(held.get("set_at", 0)) if isinstance(held, dict) else 0
+ return max(int(time.time() if now is None else now), current + 1, floor), own
+
+
+def _desk_size(settings):
+ return profiles.desk_size(settings)
+
+
+def set_same_ways(settings, enabled, *, platform=None, now=None, capable=(), live=None, gone=None):
+ saved = copy.deepcopy(settings)
+ desk = _desk(saved)
+ held = desk.get("on", {})
+ if _register_value(held) is bool(enabled):
+ return _outcome(settings)
+ before = copy.deepcopy(desk)
+ desk["on"] = profiles.register(bool(enabled), now, saved.get("machine_id", ""), held=held)
+ paths = list(profiles.apply_transitions(saved, before, now))
+ return _outcome(settings, saved, send_desk=[("on",), *paths])
+
+
+def set_own_ways(settings, use_own, *, platform=None, now=None, capable=(), live=None, gone=None):
+ saved = copy.deepcopy(settings)
+ _own(saved)["use_own"] = bool(use_own)
+ return _outcome(settings, saved)
+
+
+def share_mine(settings, *, platform=None, now=None):
+ if not profiles.same_ways_on(settings):
+ return _outcome(settings, accepted=False, reason="sync_off")
+ saved = copy.deepcopy(settings)
+ pid, own = _active(saved), saved.get("machine_id", "")
+ path = profiles.put_row(saved, pid, own, _own(saved).get("row", {}), now,
+ why="replaced_by", by=own)
+ return _outcome(settings, saved, send_desk=[path])
+
+
+def _edit_choice_row(row, peer, *, edge=None, thirds=None, edges=None, corners=None,
+ corner=None, corner_at=None, notch=None, notch_return=None,
+ platform="mac"):
+ row = profiles.canonical_row(row)
+ ways_row = row.setdefault(peer, {"ways": ways._read_intent({"peers": []}, peer),
+ "notch_return": False})
+ intent = ways_row["ways"]
+ for key, value in (("edge", edge), ("corner", corner), ("notch", notch)):
+ if value is not None and (key != "notch" or platform == "mac"):
+ intent[key] = bool(value)
+ if notch_return is not None and platform == "mac":
+ ways_row["notch_return"] = bool(notch_return)
+ if notch and platform == "mac":
+ for other, entry in row.items():
+ if other != peer:
+ entry["ways"]["notch"] = False
+ if thirds is not None:
+ picked = [part for part in ways.PARTS if part in thirds]
+ if picked:
+ intent["thirds"] = picked
+ if edges is not None:
+ intent["edges"] = [side for side in ways.EDGES if isinstance(edges, list) and side in edges]
+ holders = {corner for ident, entry in row.items() if ident != peer
+ for corner in entry["ways"].get("corners", [])}
+ if corners is not None:
+ picked = [value for value in ways.CORNERS if isinstance(corners, list) and value in corners
+ and value not in holders]
+ intent["corners"] = picked
+ intent["corner"] = bool(picked)
+ if picked:
+ intent["corner_at"] = picked[0]
+ elif corner is not None or corner_at in ways.CORNERS:
+ wanted = corner_at if corner_at in ways.CORNERS else intent["corner_at"]
+ enabled = intent["corner"] if corner is None else bool(corner)
+ if enabled and wanted in holders:
+ return row, False
+ intent.update(corner_at=wanted, corners=[wanted] if enabled else [], corner=enabled)
+ return profiles.canonical_row(row), True
+
+
+def edit_other(settings, machine, peer, *, platform=None, now=None, edge=None, thirds=None,
+ edges=None, corners=None, corner=None, corner_at=None, notch=None,
+ notch_return=None):
+ saved = copy.deepcopy(settings)
+ own = saved.get("machine_id", "")
+ if machine == own:
+ raise ValueError("edit_other requires another machine")
+ if not profiles.same_ways_on(saved):
+ return _outcome(settings, accepted=False, reason="sync_off")
+ if protocol.read_id(machine) is None or protocol.read_id(peer) is None:
+ return _outcome(settings, accepted=False, reason="invalid_machine")
+ pid = _active(saved)
+ target = _desk(saved).get("profiles", {}).get(pid)
+ if not isinstance(target, dict):
+ return _outcome(settings, accepted=False, reason="profile_missing")
+ current = target.get("rows", {}).get(machine, {"value": {}})
+ current_row = profiles.canonical_row(current.get("value", {}))
+ if peer not in current_row and len(current_row) >= 32:
+ return _outcome(settings, accepted=False, reason="row_full")
+ # Its own status says, else what pairing recorded, so a Mac's notch can be set before it reports.
+ target_platform = "mac" if profiles.view_platform(saved, machine) == "mac" else "windows"
+ updated, accepted = _edit_choice_row(
+ current_row, peer, edge=edge, thirds=thirds, edges=edges,
+ corners=corners, corner=corner, corner_at=corner_at, notch=notch,
+ notch_return=notch_return, platform=target_platform)
+ if not accepted:
+ return _outcome(settings, accepted=False)
+ path = profiles.put_row(saved, pid, machine, updated, now, why="edited", by=own)
+ if _desk_size(saved) > profiles.MAX_DESK_BYTES:
+ return _outcome(settings, accepted=False, reason="desk_full")
+ return _outcome(settings, saved, send_desk=[path])
+
+
+def new_profile(settings, name, *, platform=None, now=None):
+ trimmed = name.strip() if isinstance(name, str) else ""
+ if not 1 <= len(trimmed) <= 32:
+ return _outcome(settings, accepted=False, reason="invalid_name")
+ saved = copy.deepcopy(settings)
+ desk, own, pid = _desk(saved), saved.get("machine_id", ""), _active(saved)
+ profiles_map = desk.setdefault("profiles", {})
+ profiles.prune_removed(saved, profiles.MAX_HELD - 1)
+ live_profiles = [p for p in profiles_map if not profiles.removed(desk, p)]
+ if len(live_profiles) >= profiles.MAX_PROFILES or len(profiles_map) >= profiles.MAX_HELD:
+ return _outcome(settings, accepted=False, reason="desk_full")
+ new_id = protocol.id_text(os.urandom(16))
+ source = profiles_map[pid]
+ stamp = max(int(time.time() if now is None else now),
+ int(desk.get("on", {}).get("set_at", 0)) + 1)
+ rows = {machine: {"set_at": stamp, "by": own,
+ "value": profiles.canonical_row(register.get("value", {}))}
+ for machine, register in source.get("rows", {}).items()}
+ source_home = source.get("home", {})
+ source_shake = source_home.get("shake", {})
+ shake = profiles.register(source_shake.get("value", True), now, own, held=source_shake,
+ floor=int(desk.get("on", {}).get("set_at", 0)) + 1)
+ source_sensitivity = source_home.get("sensitivity", {})
+ sensitivity = profiles.register(source_sensitivity.get("value", 100), now, own,
+ held=source_sensitivity,
+ floor=int(desk.get("on", {}).get("set_at", 0)) + 1)
+ profile = {"name": profiles.register(trimmed, now, own), "removed": None,
+ "home": {"shake": shake, "sensitivity": sensitivity}, "rows": rows}
+ profiles_map[new_id] = profile
+ if _desk_size(saved) > profiles.MAX_DESK_BYTES:
+ return _outcome(settings, accepted=False, reason="desk_full")
+ paths = [("name", new_id), ("home", new_id, "shake"),
+ ("home", new_id, "sensitivity"),
+ *(('row', new_id, machine) for machine in rows)]
+ return _outcome(settings, saved, send_desk=paths)
+
+
+def rename_profile(settings, profile_id, name, *, platform=None, now=None):
+ trimmed = name.strip() if isinstance(name, str) else ""
+ if not 1 <= len(trimmed) <= 32:
+ return _outcome(settings, accepted=False, reason="invalid_name")
+ saved = copy.deepcopy(settings)
+ profile = _desk(saved).get("profiles", {}).get(profile_id)
+ if not isinstance(profile, dict) or profiles.removed(_desk(saved), profile_id):
+ return _outcome(settings, accepted=False, reason="profile_missing")
+ profile["name"] = profiles.register(trimmed, now, saved.get("machine_id", ""),
+ held=profile.get("name"))
+ if _desk_size(saved) > profiles.MAX_DESK_BYTES:
+ return _outcome(settings, accepted=False, reason="desk_full")
+ return _outcome(settings, saved, send_desk=[("name", profile_id)])
+
+
+def remove_profile(settings, profile_id, *, platform=None, now=None):
+ saved = copy.deepcopy(settings)
+ desk = _desk(saved)
+ profile = desk.get("profiles", {}).get(profile_id)
+ count = sum(not profiles.removed(desk, pid) for pid in desk.get("profiles", {}))
+ if (not isinstance(profile, dict) or profiles.removed(desk, profile_id)
+ or profile_id == _active(saved) or count <= 1):
+ return _outcome(settings, accepted=False, reason="active_or_last_profile")
+ stamp, own = _profile_stamp(saved, profile.get("removed"), now)
+ profile["removed"] = {"set_at": stamp, "by": own}
+ return _outcome(settings, saved, send_desk=[("removed", profile_id)])
+
+
+def switch_profile(settings, profile_id, *, platform=None, capable=(), live=None, gone=None, now=None):
+ saved = copy.deepcopy(settings)
+ desk = _desk(saved)
+ profiles_map = desk.get("profiles", {})
+ target = profiles_map.get(profile_id)
+ if not isinstance(target, dict) or profiles.removed(desk, profile_id):
+ return _outcome(settings, accepted=False, reason="profile_missing")
+ old_id = _active(saved)
+ if old_id == profile_id:
+ return _outcome(settings)
+ old = profiles_map[old_id]
+ own = saved.get("machine_id", "")
+ clock = int(time.time() if now is None else now)
+ old_picture = old.get("picture") if isinstance(old.get("picture"), dict) else {}
+ old_tiles = {}
+ for peer, tile_value in saved.get("layout", {}).items():
+ if not isinstance(tile_value, dict):
+ continue
+ tile = {key: copy.deepcopy(tile_value[key]) for key in ("x", "y", "w", "h", "display_offsets")
+ if key in tile_value}
+ displays = tile_value.get("displays")
+ if isinstance(displays, dict):
+ tile["display_offsets"] = {key: value for key, value in tile.get("display_offsets", {}).items()
+ if key in displays}
+ if not tile["display_offsets"]:
+ tile.pop("display_offsets", None)
+ else:
+ tile.pop("display_offsets", None)
+ old_tiles[peer] = tile
+ old["picture"] = {"set_at": max(clock, int(old_picture.get("set_at", 0)) + 1),
+ "by": own, "tiles": old_tiles}
+ target_picture = target.get("picture")
+ picture_tiles = target_picture.get("tiles", {}) if isinstance(target_picture, dict) else None
+ if not isinstance(picture_tiles, dict):
+ picture_tiles = {peer: tile for peer, tile in old_tiles.items()}
+ layout = {}
+ for peer, tile_value in picture_tiles.items():
+ if not isinstance(tile_value, dict):
+ continue
+ tile = copy.deepcopy(tile_value)
+ held = saved.get("layout", {}).get(peer, {})
+ if isinstance(held, dict) and isinstance(held.get("displays"), dict):
+ tile["displays"] = copy.deepcopy(held["displays"])
+ offsets = tile.get("display_offsets")
+ if isinstance(offsets, dict):
+ tile["display_offsets"] = {key: value for key, value in offsets.items()
+ if key in held["displays"]}
+ if not tile["display_offsets"]:
+ tile.pop("display_offsets", None)
+ else:
+ tile.pop("display_offsets", None)
+ layout[peer] = tile
+ layout = ways.retain_held_peer_tiles(saved, layout, saved.get("layout", {}), layout)
+ saved["layout"] = layout
+ saved["layout_set_at"] = max(clock, int(saved.get("layout_set_at", 0)) + 1)
+ saved["layout_by"] = own
+ # The target keeps its picture register: dropping it here alone would leave this machine's desk
+ # different from every other's. While active it is simply not read.
+ active = desk.get("active", {})
+ desk["active"] = profiles.register(profile_id, now, own, held=active)
+ paths = list(profiles.apply_transitions(saved, copy.deepcopy(settings["crossing_desk"]), now))
+ compile_result = _compile(saved, _platform(saved, platform), capable=capable,
+ live=live, gone=gone, now=now)
+ if not compile_result["accepted"]:
+ return _outcome(settings, accepted=False, reason="invalid_picture")
+ saved = compile_result["settings"]
+ return _outcome(settings, saved, compile_result, send_picture=True,
+ send_desk=[("picture", old_id), ("picture", profile_id), ("active",), *paths])
+
+
+def set_shake(settings, enabled, *, platform=None, now=None):
+ saved = copy.deepcopy(settings)
+ desk, own = _desk(saved), _own(saved)
+ if profiles.same_ways_on(saved):
+ pid = _active(saved)
+ profile = desk["profiles"][pid]
+ held = profile.setdefault("home", {}).get("shake")
+ profile["home"]["shake"] = profiles.register(bool(enabled), now,
+ saved.get("machine_id", ""), held=held,
+ floor=int(desk.get("on", {}).get("set_at", 0)) + 1)
+ paths = [("home", pid, "shake")]
+ else:
+ own["shake"] = bool(enabled)
+ paths = []
+ return _outcome(settings, saved, send_desk=paths)
+
+
+def set_shake_sensitivity(settings, sensitivity, *, platform=None, now=None):
+ if type(sensitivity) is not int or not 50 <= sensitivity <= 200:
+ return _outcome(settings, accepted=False, reason="invalid_sensitivity")
+ saved = copy.deepcopy(settings)
+ desk, own = _desk(saved), _own(saved)
+ if profiles.same_ways_on(saved):
+ pid = _active(saved)
+ profile = desk["profiles"][pid]
+ held = profile.setdefault("home", {}).get("sensitivity")
+ profile["home"]["sensitivity"] = profiles.register(
+ sensitivity, now, saved.get("machine_id", ""), held=held,
+ floor=int(desk.get("on", {}).get("set_at", 0)) + 1)
+ paths = [("home", pid, "sensitivity")]
+ else:
+ own["shake_sensitivity"] = sensitivity
+ paths = []
+ return _outcome(settings, saved, send_desk=paths)
+
+
+def restore_saved(settings, saved_id, *, platform=None, capable=(), live=None, gone=None, now=None):
+ saved = copy.deepcopy(settings)
+ archive = _own(saved).get("saved", [])
+ item = next((entry for entry in archive if entry.get("id") == saved_id), None)
+ if item is None or not isinstance(item.get("row"), dict):
+ return _outcome(settings, accepted=False, reason="saved_missing")
+ profiles.archive(saved, profiles.in_force(saved)[0], "restored", now)
+ profiles.archive(saved, _own(saved).get("row", {}), "restored", now)
+ _own(saved)["row"] = profiles.canonical_row(item["row"])
+ _own(saved)["use_own"] = True
+ _own(saved).setdefault("editing", {}).pop("own", None)
+ result = _compile(saved, _platform(saved, platform), capable=capable,
+ live=live, gone=gone, now=now)
+ return _outcome(settings, result["settings"], result)
+
+
+def delete_saved(settings, saved_id, *, platform=None, now=None):
+ saved = copy.deepcopy(settings)
+ archive = _own(saved).setdefault("saved", [])
+ kept = [entry for entry in archive if entry.get("id") != saved_id]
+ if len(kept) == len(archive):
+ return _outcome(settings, accepted=False, reason="saved_missing")
+ _own(saved)["saved"] = kept
+ return _outcome(settings, saved)
+
+
+def desk_arrived(settings, state, *, source, platform=None, capable=(), linked=True,
+ live=None, gone=None, now=None):
+ source = source if isinstance(source, str) else protocol.id_text(source)
+ entry = ways._entry(settings, source)
+ if (entry is None or entry.get("allow_drive") is not True or not linked
+ or ways.peerlist.dormant_reason(entry) is not None):
+ return _outcome(settings, accepted=False, reason="untrusted")
+ saved, paths, forward, answer, accepted, reason = profiles.merge_desk(
+ settings, state, source=source, now=now, borrow=True)
+ if not accepted:
+ return _outcome(settings, accepted=False, reason=reason)
+ # A merge that took something made its own copy; one that took nothing lent `settings` back.
+ return _outcome(settings, None if saved is settings else saved, accepted=True, send_desk=paths,
+ forward=forward, answer=answer, reason=reason, owned=True)
+
+
+for _event in (drop, edit_ways, receive_picture, receive_arrangement, link_up, leave_out,
+ put_back, displays_changed, paired, migrate, set_same_ways, set_own_ways,
+ share_mine, edit_other, new_profile, rename_profile, remove_profile,
+ switch_profile, set_shake, set_shake_sensitivity, restore_saved, delete_saved, desk_arrived):
+ globals()[_event.__name__] = _profile_event(_event)
diff --git a/core/effects.py b/core/effects.py
index 0431729..e99a802 100644
--- a/core/effects.py
+++ b/core/effects.py
@@ -19,6 +19,8 @@ import math
import re
from types import SimpleNamespace
+from core.i18n import N_
+
TAU = math.pi * 2.0
IDENTITY = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
@@ -417,13 +419,13 @@ def _light_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 colour packs. Ids are settings values, so never rename one.
ALL_DIRECTIONS = (
- ("fx_membrane", "Membrane", ("skin", "film", "rupture"), ("oil_slick", "soap_bubble", "pearl", "opal", "sea_glass")),
- ("fx_sparks", "Sparks", ("flint", "filings", "discharge"), ("ember", "forge", "sparkler_gold", "arc", "magnesium")),
- ("fx_instrument", "Instrument", ("rule", "gauge", "rangefinder"), ("phosphor", "sodium", "contrast", "ruby", "cobalt")),
- ("fx_folio", "Folio", ("crease", "pleat", "concertina"), ("vellum", "carbon_copy", "marbled", "moss", "plum")),
- ("fx_selvedge", "Selvedge", ("thread", "weave", "jacquard"), ("flax", "madder", "tide", "woad", "saffron")),
- ("fx_ink", "Ink", ("capillary", "viscous_drop", "sumi_bloom"), ("indigo_ink", "matcha", "terracotta")),
- ("fx_warp", "Warp", ("light_slit", "hyperdrive", "wormhole"), ("neon", "vaporwave", "cyber")),
+ ("fx_membrane", N_("Membrane"), ("skin", "film", "rupture"), ("oil_slick", "soap_bubble", "pearl", "opal", "sea_glass")),
+ ("fx_sparks", N_("Sparks"), ("flint", "filings", "discharge"), ("ember", "forge", "sparkler_gold", "arc", "magnesium")),
+ ("fx_instrument", N_("Instrument"), ("rule", "gauge", "rangefinder"), ("phosphor", "sodium", "contrast", "ruby", "cobalt")),
+ ("fx_folio", N_("Folio"), ("crease", "pleat", "concertina"), ("vellum", "carbon_copy", "marbled", "moss", "plum")),
+ ("fx_selvedge", N_("Selvedge"), ("thread", "weave", "jacquard"), ("flax", "madder", "tide", "woad", "saffron")),
+ ("fx_ink", N_("Ink"), ("capillary", "viscous_drop", "sumi_bloom"), ("indigo_ink", "matcha", "terracotta")),
+ ("fx_warp", N_("Warp"), ("light_slit", "hyperdrive", "wormhole"), ("neon", "vaporwave", "cyber")),
)
# Directions kept in the code but offered nowhere: not on the Design pages, not as a setting. A
# setting that chose one of their effects or packs becomes its stand-in when it is read, and a
@@ -442,18 +444,26 @@ LIGHT_AS_GIVEN = ("aperture", "crease", "pleat", "concertina", "thread", "weave"
for effect in effects
)
MONO_PACKS = {
- 'mono': ('White', ['#ebebeb', '#969696', '#ebebeb']),
- 'mono_silver': ('Silver', ['#c9ced2', '#a8afb6', '#e1e5e8']),
- 'mono_graphite': ('Graphite', ['#65696f', '#4a4f55', '#868c94']),
- 'mono_ink': ('Ink', ['#25282c', '#101215', '#41464d']),
- 'mono_warm': ('Warm grey', ['#b7ada0', '#8a8074', '#d8cfc2']),
+ 'mono': (N_("White"), ['#ebebeb', '#969696', '#ebebeb']),
+ 'mono_silver': (N_("Silver"), ['#c9ced2', '#a8afb6', '#e1e5e8']),
+ 'mono_graphite': (N_("Graphite"), ['#65696f', '#4a4f55', '#868c94']),
+ 'mono_ink': (N_("Ink"), ['#25282c', '#101215', '#41464d']),
+ 'mono_warm': (N_("Warm grey"), ['#b7ada0', '#8a8074', '#d8cfc2']),
}
+GROUP_LIGHT = N_("Light")
+GROUP_MONO = N_("Mono")
+GROUP_BRIGHT = N_("Bright")
+INTENSITY_NAMES = {"quiet": N_("Quiet"), "medium": N_("Medium"), "showpiece": N_("Showpiece")}
+
+
+def intensity_name(value):
+ return INTENSITY_NAMES[value]
BRIGHT_PACKS = {
- 'citron': ('Citron', ['#d5ff00', '#c1f000', '#e3ff38']),
- 'laser': ('Laser', ['#1affbe', '#00efa9', '#42ffd0']),
- 'electric': ('Electric', ['#1aa7ff', '#0098f0', '#36b8ff']),
- 'fuchsia': ('Fuchsia', ['#ff66b3', '#ff4da6', '#ff80bf']),
- 'ultraviolet': ('Ultraviolet', ['#bf80ff', '#b570ff', '#cd99ff']),
+ 'citron': (N_("Citron"), ['#d5ff00', '#c1f000', '#e3ff38']),
+ 'laser': (N_("Laser"), ['#1affbe', '#00efa9', '#42ffd0']),
+ 'electric': (N_("Electric"), ['#1aa7ff', '#0098f0', '#36b8ff']),
+ 'fuchsia': (N_("Fuchsia"), ['#ff66b3', '#ff4da6', '#ff80bf']),
+ 'ultraviolet': (N_("Ultraviolet"), ['#bf80ff', '#b570ff', '#cd99ff']),
}
# Same hue and saturation, luminance capped at .20 (over 3:1 on preview wells).
# Authored stops avoid doing colour-space searches in the animation frame loop.
@@ -487,12 +497,12 @@ PACK_IDS = tuple(pack for _module, _name, _effects, packs in DIRECTIONS for pack
def colour_groups(light_choices, with_effects=True):
"""Shared colour catalogue; Mono is independent of every effect family."""
- groups = [('Light', [(value, name) for value, name in light_choices if value != 'mono']),
- ('Mono', [(value, name) for value, (name, _stops) in MONO_PACKS.items()])]
+ groups = [(GROUP_LIGHT, [(value, name) for value, name in light_choices if value != 'mono']),
+ (GROUP_MONO, [(value, name) for value, (name, _stops) in MONO_PACKS.items()])]
if with_effects:
groups.extend((title, [(value, pack(value)[0]) for value in values])
for _module, title, _effects, values in DIRECTIONS)
- groups.append(('Bright', [(value, name) for value, (name, _stops) in BRIGHT_PACKS.items()]))
+ groups.append((GROUP_BRIGHT, [(value, name) for value, (name, _stops) in BRIGHT_PACKS.items()]))
return groups
_loaded = None
@@ -575,7 +585,7 @@ def _locator_arrive(pen, s):
# What a switch plays when the chosen style is Glow or Beam, which have no arrival of their own.
-LOCATOR = Effect("locator", "Ring", "quiet", "A ring in the chosen colours closes onto the pointer.",
+LOCATOR = Effect("locator", N_("Ring"), "quiet", N_("A ring in the chosen colours closes onto the pointer."),
lambda pen, s: None, _locator_arrive, 0.0, 0.72)
@@ -681,13 +691,13 @@ def _classic_depart(beam):
CLASSIC = {
- "glow": Effect("glow", "Glow", "quiet", "A band of light that deepens the harder you push.",
+ "glow": Effect("glow", N_("Glow"), "quiet", N_("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", "medium", "A thin line with a comet of light running along it.",
+ "beam": Effect("beam", N_("Beam"), "medium", N_("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.",
+ "aperture", N_("Aperture"), "showpiece",
+ N_("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,
),
@@ -715,10 +725,10 @@ def switch_style_groups():
"""The Design pages' choices for SWITCH_STYLES, as (group title or None, ((value, name), ...)),
the effects grouped by direction as the style tiles are. Only the first group when the effects
cannot load; the overlay has already said why."""
- groups = [(None, (("match", "Same as crossing"), ("locator", "Ring")))]
+ groups = [(None, (("match", N_("Same as crossing")), ("locator", N_("Ring"))))]
try:
_load()
- light = (("Light", (("aperture", CLASSIC["aperture"].name),)),)
+ light = ((N_("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:
@@ -1192,15 +1202,15 @@ def _still_key(effect):
# 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"))
-SIZES = (("small", "Small"), ("medium", "Medium"), ("large", "Large"))
+LENGTHS = (("short", N_("Short")), ("normal", N_("Normal")), ("long", N_("Long")))
+SIZES = (("small", N_("Small")), ("medium", N_("Medium")), ("large", N_("Large")))
PACES = {"short": 0.5, "normal": 1.0, "long": 2.0}
_SIZE_FRACTIONS = {"small": 0.03, "medium": 0.045, "large": 0.06}
DESIGN_READOUT_WIDTH = 58
_PACE_STEPS = (0.5, 1.0, 2.0)
# The Design pages' Frame rate: each machine plays every effect at its own display's refresh, or a
# half or a quarter of it.
-FRAME_RATES = (("display", "Match display", 1), ("half", "Half", 2), ("quarter", "Quarter", 4))
+FRAME_RATES = (("display", N_("Match display"), 1), ("half", N_("Half"), 2), ("quarter", N_("Quarter"), 4))
_PACE_PRESETS = ("short", "normal", "long")
_SIZE_STOPS = (0.03, 0.045, 0.06)
_SIZE_PRESETS = ("small", "medium", "large")
diff --git a/core/fx_folio.py b/core/fx_folio.py
index 6e161fa..505421d 100644
--- a/core/fx_folio.py
+++ b/core/fx_folio.py
@@ -1,6 +1,7 @@
"""Folio: a scored edge lifts into paper folds and lays itself flat on arrival."""
import math
+from core.i18n import N_
from .effects import Effect, clamp, ease_out, effect_depth_scale, lerp
from .fx_material import stroke, surface
@@ -92,15 +93,15 @@ def _make(id_, name, level, blurb):
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."),
+ _make("crease", N_("Crease"), 0, N_("A small paper crease lifts under pressure, parts, then settles flat where you arrive.")),
+ _make("pleat", N_("Pleat"), 1, N_("Six alternating folds gather at the edge, slide apart and unfold on the other screen.")),
+ _make("concertina", N_("Concertina"), 2, N_("A scored paper fan rises along the boundary, opens a passage and folds itself away behind you.")),
]
PACKS = {
- "moss": ("Moss", ["#72965b", "#bfd0a0", "#465e3b"]),
- "plum": ("Plum", ["#9b6b9e", "#d2b5ce", "#8b6095"]),
- "vellum": ("Vellum", ["#c69a60", "#f0ddac", "#88674c"]),
- "carbon_copy": ("Carbon copy", ["#6688ae", "#bbcad9", "#344d72"]),
- "marbled": ("Marbled", ["#bd6858", "#6c9691", "#e1bb78"]),
+ "moss": (N_("Moss"), ["#72965b", "#bfd0a0", "#465e3b"]),
+ "plum": (N_("Plum"), ["#9b6b9e", "#d2b5ce", "#8b6095"]),
+ "vellum": (N_("Vellum"), ["#c69a60", "#f0ddac", "#88674c"]),
+ "carbon_copy": (N_("Carbon copy"), ["#6688ae", "#bbcad9", "#344d72"]),
+ "marbled": (N_("Marbled"), ["#bd6858", "#6c9691", "#e1bb78"]),
}
diff --git a/core/fx_ink.py b/core/fx_ink.py
index 96c9471..c856029 100644
--- a/core/fx_ink.py
+++ b/core/fx_ink.py
@@ -3,6 +3,7 @@ blooming into fluid wash on arrival.
"""
import math
+from core.i18n import N_
from . import effects
@@ -929,30 +930,30 @@ def _sumi_bloom_arrive(ctx, s):
EFFECTS = [
effects.Effect(
- "capillary", "Capillary", "quiet",
- "A soft pigment meniscus swells against the boundary with viscous surface tension. On "
+ "capillary", N_("Capillary"), "quiet",
+ N_("A soft pigment meniscus swells against the boundary with viscous surface tension. On "
"breakthrough, it releases cleanly and diffuses as a calm, translucent wash on the "
- "arrival screen.",
+ "arrival screen."),
_capillary_depart, _capillary_arrive, 0.45, 0.50,
),
effects.Effect(
- "viscous_drop", "Viscous drop", "medium",
- "An organic ink droplet gathers at the pointer, flattening against the glass edge before "
+ "viscous_drop", N_("Viscous drop"), "medium",
+ N_("An organic ink droplet gathers at the pointer, flattening against the glass edge before "
"necking through the seam. On arrival, it splashes into a multi-lobed pigment bloom that "
- "bleeds outward.",
+ "bleeds outward."),
_viscous_drop_depart, _viscous_drop_arrive, 0.55, 0.60,
),
effects.Effect(
- "sumi_bloom", "Sumi bloom", "showpiece",
- "Dense calligraphic ink pulls from the boundary into a viscous bridge that necks and "
+ "sumi_bloom", N_("Sumi bloom"), "showpiece",
+ N_("Dense calligraphic ink pulls from the boundary into a viscous bridge that necks and "
"snaps through the seam. It arrives as an ink-in-water vortex bloom, unfurling delicate "
- "pigment filaments that dissolve into the screen.",
+ "pigment filaments that dissolve into the screen."),
_sumi_bloom_depart, _sumi_bloom_arrive, 0.70, 0.75,
),
]
PACKS = {
- "indigo_ink": ("Indigo ink", ["#16243b", "#253d66", "#3f639e", "#6891ce", "#a8c5ed"]),
- "matcha": ("Matcha", ["#233818", "#3e5c2c", "#638a44", "#92b86e", "#cde6b0"]),
- "terracotta": ("Terracotta", ["#4d1f16", "#7c3423", "#b35338", "#d97b5d", "#f3b59f"]),
+ "indigo_ink": (N_("Indigo ink"), ["#16243b", "#253d66", "#3f639e", "#6891ce", "#a8c5ed"]),
+ "matcha": (N_("Matcha"), ["#233818", "#3e5c2c", "#638a44", "#92b86e", "#cde6b0"]),
+ "terracotta": (N_("Terracotta"), ["#4d1f16", "#7c3423", "#b35338", "#d97b5d", "#f3b59f"]),
}
diff --git a/core/fx_instrument.py b/core/fx_instrument.py
index 2d20347..ea5987b 100644
--- a/core/fx_instrument.py
+++ b/core/fx_instrument.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import math
from types import SimpleNamespace
+from core.i18n import N_
from .effects import Effect, clamp, lerp
@@ -708,37 +709,37 @@ def rangefinder_dial(ctx, s, C, c, locked, flash, alpha):
EFFECTS = [
Effect(
- "rule", "Rule", "quiet",
- "A fine ruler rises along the edge round the pointer and lights outward one division at a "
+ "rule", N_("Rule"), "quiet",
+ N_("A fine ruler rises along the edge round the pointer and lights outward one division at a "
"time as the push builds, the three quarter detents marked long. At breakthrough it closes "
"on the pointer in four clicks; on the other screen a short register mark sits where you "
- "came in and a four-arm cross steps in three clicks onto the landing point.",
+ "came in and a four-arm cross steps in three clicks onto the landing point."),
rule_depart, rule_arrive, 0.45, 0.6,
),
Effect(
- "gauge", "Gauge", "medium",
- "A half dial seated on the edge at the pointer, a quarter dial in the corner and a "
+ "gauge", N_("Gauge"), "medium",
+ N_("A half dial seated on the edge at the pointer, a quarter dial in the corner and a "
"graduated collar round the notch, whose needle clicks round sixteen detents as the push "
"builds. At breakthrough an iris shuts over the dial in four steps; on the other screen a "
"graduated ring contracts onto the landing point, turning one graduation per click, and "
- "flashes as it locks.",
+ "flashes as it locks."),
gauge_depart, gauge_arrive, 0.6, 0.7,
),
Effect(
- "rangefinder", "Rangefinder", "showpiece",
- "A long scale runs along the edge and a pair of caliper jaws closes on the pointer in "
+ "rangefinder", N_("Rangefinder"), "showpiece",
+ N_("A long scale runs along the edge and a pair of caliper jaws closes on the pointer in "
"detents, lighting the divisions it passes, while three tally lamps light at each quarter. "
"At breakthrough shutter blades slide in from both ends and a bright slit at the pointer "
"shuts; on the far screen the jaws open outward from the entry point as a graduated "
- "reticle with corner brackets steps in, turns and locks onto the landing point.",
+ "reticle with corner brackets steps in, turns and locks onto the landing point."),
rangefinder_depart, rangefinder_arrive, 0.8, 0.8,
),
]
PACKS = {
- "ruby": ("Ruby", ["#ef4471", "#d32859", "#ff9ab5"]),
- "cobalt": ("Cobalt", ["#478df5", "#2a6dd3", "#a4caff"]),
- "phosphor": ("Phosphor", ["#3dff7f", "#1f9e52", "#caffdc"]),
- "sodium": ("Sodium", ["#ffa51f", "#c46a12", "#ffe0a3"]),
- "contrast": ("Contrast", ["#f0e442", "#56b4e9", "#ffffff"]),
+ "ruby": (N_("Ruby"), ["#ef4471", "#d32859", "#ff9ab5"]),
+ "cobalt": (N_("Cobalt"), ["#478df5", "#2a6dd3", "#a4caff"]),
+ "phosphor": (N_("Phosphor"), ["#3dff7f", "#1f9e52", "#caffdc"]),
+ "sodium": (N_("Sodium"), ["#ffa51f", "#c46a12", "#ffe0a3"]),
+ "contrast": (N_("Contrast"), ["#f0e442", "#56b4e9", "#ffffff"]),
}
diff --git a/core/fx_membrane.py b/core/fx_membrane.py
index dbefab7..d3a34c5 100644
--- a/core/fx_membrane.py
+++ b/core/fx_membrane.py
@@ -5,6 +5,7 @@ healing behind you.
import math
from types import SimpleNamespace
+from core.i18n import N_
from . import effects
@@ -507,31 +508,31 @@ def _make(id_, name, intensity, blurb, depart_seconds, arrive_seconds, P):
EFFECTS = [
- _make("skin", "Skin", "quiet",
- "A single iridescent hairline sits just inside the edge and dimples under the pointer as "
+ _make("skin", N_("Skin"), "quiet",
+ N_("A single iridescent hairline sits just inside the edge and dimples under the pointer as "
"you push, thinning and shifting colour. It parts at the pointer and the two ends pull "
"back; on the other screen the same hairline closes behind the pointer and one ripple "
- "spreads out.",
+ "spreads out."),
0.45, 0.6,
{"departSeconds": 0.45, "arriveSeconds": 0.6, "g": 6, "L": 110, "lw": 2.0, "fringes": 1,
"sp": 0, "retract": 300, "curl": 3, "sheen": False, "beads": False, "waves": False,
"aL": 84, "gap0": 16, "bulge": 9, "rings": [58], "still": [40], "stagger": 0,
"ringDur": 0.5, "disc": False, "aWave": False}),
- _make("film", "Film", "medium",
- "A band of interference fringes, one added at each quarter tick, crowds and thins into the "
+ _make("film", N_("Film"), "medium",
+ N_("A band of interference fringes, one added at each quarter tick, crowds and thins into the "
"dent under the pointer, so the band itself is the pressure meter. At breakthrough the film "
"tears and each fringe peels back with a curled rim; on the other side the skin bulges in "
- "around the arriving pointer, springs back, heals, and throws two ripples.",
+ "around the arriving pointer, springs back, heals, and throws two ripples."),
0.55, 0.7,
{"departSeconds": 0.55, "arriveSeconds": 0.7, "g": 7, "L": 150, "lw": 2.2, "fringes": 4,
"sp": 3.6, "retract": 330, "curl": 5, "sheen": False, "beads": False, "waves": False,
"aL": 110, "gap0": 26, "bulge": 14, "rings": [74, 104], "still": [44, 80],
"stagger": 0.09, "ringDur": 0.55, "disc": False, "aWave": False}),
- _make("rupture", "Rupture", "showpiece",
- "The whole edge becomes a visible soap film with a sheen behind its fringes; every tick "
+ _make("rupture", N_("Rupture"), "showpiece",
+ N_("The whole edge becomes a visible soap film with a sheen behind its fringes; every tick "
"sends a shudder along it, and at breakthrough it bursts, the torn rims racing away along "
"the edge carrying beads of film. The arrival opens a set of Newton's rings around the "
- "entry point while the skin bulges in, heals and sends a surface wave along the edge.",
+ "entry point while the skin bulges in, heals and sends a surface wave along the edge."),
0.7, 0.8,
{"departSeconds": 0.7, "arriveSeconds": 0.8, "g": 8, "L": 220, "lw": 2.6, "fringes": 4,
"sp": 4, "retract": 420, "curl": 6, "sheen": True, "beads": True, "waves": True,
@@ -540,9 +541,9 @@ EFFECTS = [
]
PACKS = {
- "opal": ("Opal", ["#527cda", "#ac8cd2", "#d985b0", "#7eade0"]),
- "sea_glass": ("Sea glass", ["#48b8a0", "#8bd6b5", "#388f91", "#b4dfb0"]),
- "oil_slick": ("Oil slick", ["#8a4dff", "#2f7dff", "#16c6b0", "#9fdc4a", "#f0c23c", "#e8477f"]),
- "soap_bubble": ("Soap bubble", ["#ffd98e", "#ff9cc2", "#c3a6ff", "#8fcfff", "#9ef2cf"]),
- "pearl": ("Pearl", ["#fbf4e8", "#f2c9d6", "#c6dcf2", "#d9f0dc", "#ffffff"]),
+ "opal": (N_("Opal"), ["#527cda", "#ac8cd2", "#d985b0", "#7eade0"]),
+ "sea_glass": (N_("Sea glass"), ["#48b8a0", "#8bd6b5", "#388f91", "#b4dfb0"]),
+ "oil_slick": (N_("Oil slick"), ["#8a4dff", "#2f7dff", "#16c6b0", "#9fdc4a", "#f0c23c", "#e8477f"]),
+ "soap_bubble": (N_("Soap bubble"), ["#ffd98e", "#ff9cc2", "#c3a6ff", "#8fcfff", "#9ef2cf"]),
+ "pearl": (N_("Pearl"), ["#fbf4e8", "#f2c9d6", "#c6dcf2", "#d9f0dc", "#ffffff"]),
}
diff --git a/core/fx_selvedge.py b/core/fx_selvedge.py
index d24509f..787ce1d 100644
--- a/core/fx_selvedge.py
+++ b/core/fx_selvedge.py
@@ -1,6 +1,7 @@
"""Selvedge: tension opens a woven seam; the threads stay continuous and mend behind you."""
import math
+from core.i18n import N_
from .effects import Effect, clamp, ease_out, effect_depth_scale
from .fx_material import stroke, surface
@@ -82,15 +83,15 @@ def _make(id_, name, level, blurb):
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."),
+ _make("thread", N_("Thread"), 0, N_("Two fine yarns tighten, part for the pointer and stitch the seam closed behind it.")),
+ _make("weave", N_("Weave"), 1, N_("A woven border gathers tension, opens between its strands and gently mends on arrival.")),
+ _make("jacquard", N_("Jacquard"), 2, N_("A diamond-patterned textile tightens across the edge, opens its weave and settles behind you.")),
]
PACKS = {
- "woad": ("Woad", ["#8277b3", "#7268a4", "#c3b9df"]),
- "saffron": ("Saffron", ["#d48238", "#976025", "#efc18a"]),
- "flax": ("Flax", ["#cfb885", "#8a9c84", "#efdfb8"]),
- "madder": ("Madder", ["#c45b68", "#873d57", "#e5b09b"]),
- "tide": ("Tide", ["#58a9a3", "#547498", "#b1d1c1"]),
+ "woad": (N_("Woad"), ["#8277b3", "#7268a4", "#c3b9df"]),
+ "saffron": (N_("Saffron"), ["#d48238", "#976025", "#efc18a"]),
+ "flax": (N_("Flax"), ["#cfb885", "#8a9c84", "#efdfb8"]),
+ "madder": (N_("Madder"), ["#c45b68", "#873d57", "#e5b09b"]),
+ "tide": (N_("Tide"), ["#58a9a3", "#547498", "#b1d1c1"]),
}
diff --git a/core/fx_sparks.py b/core/fx_sparks.py
index 46408b7..4a24d66 100644
--- a/core/fx_sparks.py
+++ b/core/fx_sparks.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import math
from types import SimpleNamespace
+from core.i18n import N_
from . import effects
from .effects import TAU, clamp, lerp
@@ -448,29 +449,29 @@ def effect(id_, name, intensity, blurb, depart_cfg, arrive_cfg):
EFFECTS = [
effect(
- "flint", "Flint", "quiet",
- "A single hot point at the pointer draws in a few close sparks as you push, snaps them "
+ "flint", N_("Flint"), "quiet",
+ N_("A single hot point at the pointer draws in a few close sparks as you push, snaps them "
"through the edge, and a pinch of sparks pops out where you land. Small enough to leave on "
- "all day.",
+ "all day."),
dict(N=8, R=40, align=False, len0=2, len1=5, crawl=0, arcs=False, flash=0, core=13,
implode=0.14, departSeconds=0.4, still=5, stillR=(8, 16)),
dict(M=12, V=420, drag=7, G=260, life=0.45, branch=0, pop=11, arriveSeconds=0.45),
),
effect(
- "filings", "Filings", "medium",
- "Scattered sparks swing round to point at the pointer and creep in like iron filings to a "
+ "filings", N_("Filings"), "medium",
+ N_("Scattered sparks swing round to point at the pointer and creep in like iron filings to a "
"magnet, the edge warming beside it; at breakthrough they are sucked through the point, and "
- "on the other screen the same sparks are thrown back out and fall.",
+ "on the other screen the same sparks are thrown back out and fall."),
dict(N=24, R=72, align=True, len0=2.5, len1=8, crawl=0, arcs=False, flash=70, core=18,
implode=0.2, departSeconds=0.55, still=9, stillR=(12, 26)),
dict(M=26, V=500, drag=6.5, G=320, life=0.62, branch=0, pop=20, arriveSeconds=0.65),
),
effect(
- "discharge", "Discharge", "showpiece",
- "The boundary charges up: sparks crawl along it and forty filings wheel in, with a crackle "
+ "discharge", N_("Discharge"), "showpiece",
+ N_("The boundary charges up: sparks crawl along it and forty filings wheel in, with a crackle "
"arcing to the pointer at every tick. At breakthrough the whole charge implodes through the "
"point with a last arc; where it lands it goes off like a sparkler, stars splitting as they "
- "fall.",
+ "fall."),
dict(N=40, R=104, align=True, len0=3, len1=11, crawl=8, arcs=True, flash=120, core=26,
implode=0.24, departSeconds=0.75, still=13, stillR=(14, 34)),
dict(M=30, V=600, drag=6, G=260, life=0.72, branch=9, pop=30, arriveSeconds=0.78),
@@ -478,9 +479,9 @@ EFFECTS = [
]
PACKS = {
- "arc": ("Arc", ["#69c8ff", "#269de8", "#b5e5ff", "#456ad0"]),
- "magnesium": ("Magnesium", ["#c98bff", "#9255da", "#ead2ff", "#b064e8"]),
- "ember": ("Ember", ["#ffe4ad", "#ffb04a", "#ff6a24", "#d8321a", "#8e1a10"]),
- "forge": ("Forge", ["#fff4dc", "#ffc15e", "#ff7f2a", "#b8c4d2", "#5d7896"]),
- "sparkler_gold": ("Sparkler gold", ["#ffffff", "#fff1bf", "#ffd35c", "#f0a531"]),
+ "arc": (N_("Arc"), ["#69c8ff", "#269de8", "#b5e5ff", "#456ad0"]),
+ "magnesium": (N_("Magnesium"), ["#c98bff", "#9255da", "#ead2ff", "#b064e8"]),
+ "ember": (N_("Ember"), ["#ffe4ad", "#ffb04a", "#ff6a24", "#d8321a", "#8e1a10"]),
+ "forge": (N_("Forge"), ["#fff4dc", "#ffc15e", "#ff7f2a", "#b8c4d2", "#5d7896"]),
+ "sparkler_gold": (N_("Sparkler gold"), ["#ffffff", "#fff1bf", "#ffd35c", "#f0a531"]),
}
diff --git a/core/fx_warp.py b/core/fx_warp.py
index 9bc829b..5cb7baa 100644
--- a/core/fx_warp.py
+++ b/core/fx_warp.py
@@ -3,13 +3,14 @@ the pointer's trail into speed lines, arriving as a streak that decelerates into
"""
import math
+from core.i18n import N_
from . import effects
PACKS = {
- "neon": ("Neon", ["#ff0055", "#00ffcc", "#ffcc00"]),
- "vaporwave": ("Vaporwave", ["#ff71ce", "#01cdfe", "#05ffa1", "#b967ff", "#fffb96"]),
- "cyber": ("Cyber", ["#fcee0a", "#00f0ff", "#ff003c"]),
+ "neon": (N_("Neon"), ["#ff0055", "#00ffcc", "#ffcc00"]),
+ "vaporwave": (N_("Vaporwave"), ["#ff71ce", "#01cdfe", "#05ffa1", "#b967ff", "#fffb96"]),
+ "cyber": (N_("Cyber"), ["#fcee0a", "#00f0ff", "#ff003c"]),
}
@@ -282,10 +283,10 @@ def _wormhole_arrive(ctx, s):
EFFECTS = [
- effects.Effect("light_slit", "Light slit", "quiet", "A subtle slit opens, pulling in faint trails.",
+ effects.Effect("light_slit", N_("Light slit"), "quiet", N_("A subtle slit opens, pulling in faint trails."),
_light_slit_depart, _light_slit_arrive, 0.4, 0.4),
- effects.Effect("hyperdrive", "Hyperdrive", "medium", "Speed lines accelerate towards the portal.",
+ effects.Effect("hyperdrive", N_("Hyperdrive"), "medium", N_("Speed lines accelerate towards the portal."),
_hyperdrive_depart, _hyperdrive_arrive, 0.6, 0.6),
- effects.Effect("wormhole", "Wormhole", "showpiece", "A dynamic stretching grid of light.",
+ effects.Effect("wormhole", N_("Wormhole"), "showpiece", N_("A dynamic stretching grid of light."),
_wormhole_depart, _wormhole_arrive, 0.8, 0.8),
]
diff --git a/core/i18n.py b/core/i18n.py
new file mode 100644
index 0000000..15e6617
--- /dev/null
+++ b/core/i18n.py
@@ -0,0 +1,287 @@
+"""Beamer's display language: gettext catalogues with British English as the source.
+
+Every user-visible string is written in British English and wrapped where it is used:
+``tr("Hide addresses")``, ``trn("{n} machine", "{n} machines", n).format(n=n)``, and
+``trc("menu", "Open")`` where one English word needs two translations. A string defined at
+import time (a module constant, a table of names) is marked with ``N_()`` and translated where it
+is shown, with ``tr(CONSTANT)``, because the language is installed after imports and before the
+first window. Names, addresses and anything else a person typed are never passed through ``tr()``:
+they go into a template as a ``{field}`` instead, so a machine called "Home" is never translated.
+
+Catalogues are ``locales/<code>.po`` beside VERSION, read with the standard library only. The
+English catalogue is the template (``locales/beamer.pot``) that ``tools/i18n_extract.py`` writes;
+a language is one more ``.po`` file and one line in ``LANGUAGES``. The US spelling of English
+stays where it was, in core.locale, applied at the widgets' text setters.
+"""
+
+from __future__ import annotations
+
+import ast
+import ctypes
+import gettext as _gettext
+import io
+import os
+import re
+import struct
+import sys
+from pathlib import Path
+
+
+# Code -> the language's own name for itself, shown in the Language choice whatever the current
+# language is, so a person who cannot read the current one can still find theirs.
+LANGUAGES = {
+ "en": "English",
+ "it": "Italiano",
+}
+# Not a language: every string bracketed and a third longer, so a test can find text that never
+# went through tr() and see where longer languages run out of room. Only BEAMER_LANGUAGE sets it.
+PSEUDO = "qps"
+AUTOMATIC = "auto"
+SOURCE = "en"
+
+_translations: _gettext.NullTranslations = _gettext.NullTranslations()
+_language = SOURCE
+
+
+def N_(message: str) -> str:
+ """Mark a string for the catalogue without translating it yet."""
+ return message
+
+
+def tr(message: str) -> str:
+ return _translations.gettext(message)
+
+
+def matches_translation(text: str, *templates: str) -> bool:
+ """Recognise a formatted translated template without interpreting its field values."""
+ for template in templates:
+ parts = re.split(r"\{[^{}]+\}", tr(template))
+ if re.fullmatch(".*?".join(re.escape(part) for part in parts), text, re.DOTALL):
+ return True
+ return False
+
+
+def trn(singular: str, plural: str, n: int) -> str:
+ return _translations.ngettext(singular, plural, n)
+
+
+def trc(context: str, message: str) -> str:
+ return _translations.pgettext(context, message)
+
+
+def joined(items) -> str:
+ """Names as one phrase in the current language: "Mac", "Mac and PC", "Mac, PC and Laptop"."""
+ items = [str(item) for item in items]
+ if len(items) < 2:
+ return "".join(items)
+ # Translators: the separator between all but the last two names in a list, "Mac, PC and Laptop".
+ head = trc("list", ", ").join(items[:-1])
+ # Translators: the last two names of a list; {first} may itself be several names.
+ return trc("list", "{first} and {last}").format(first=head, last=items[-1])
+
+
+def language() -> str:
+ """The installed language's code."""
+ return _language
+
+
+def locales_dir() -> Path:
+ # py2app sets RESOURCEPATH and PyInstaller _MEIPASS; from source and in the Flatpak, the
+ # folder sits beside core/, as VERSION does.
+ for root in (os.environ.get("RESOURCEPATH"), getattr(sys, "_MEIPASS", None)):
+ if root and (Path(root) / "locales").is_dir():
+ return Path(root) / "locales"
+ # __spec__.origin, not __file__: py2app's detect_dunder_file recipe copies the whole package of
+ # any module naming __file__ into the bundle as loose source, core's tests with it, and those
+ # import mac_app, which then copies the build folder into itself (14-10-2026).
+ return Path(__spec__.origin).resolve().parent.parent / "locales"
+
+
+def _unquote(token: str) -> str:
+ # A .po string is a C string literal; for the escapes .po files use, \" \\ \n \t, that is
+ # also a Python one.
+ return ast.literal_eval(token)
+
+
+def parse_po(text: str) -> list[dict]:
+ """Every entry of a .po file, the header included, as {msgctxt, msgid, msgid_plural, msgstr: [..], flags, comments}."""
+ entries, entry, field = [], None, None
+
+ def finish():
+ if entry is not None and "msgid" in entry:
+ entries.append(entry)
+
+ for raw in text.splitlines():
+ line = raw.strip()
+ if not line:
+ continue
+ if line.startswith("#"):
+ if entry is not None and "msgid" in entry:
+ finish()
+ entry = None
+ entry = entry or {"msgstr": {}, "flags": set(), "comments": []}
+ if line.startswith("#,"):
+ entry["flags"].update(flag.strip() for flag in line[2:].split(","))
+ else:
+ entry["comments"].append(raw)
+ continue
+ if line.startswith('"'):
+ value = _unquote(line)
+ if field[0] == "msgstr":
+ entry["msgstr"][field[1]] += value
+ else:
+ entry[field[0]] += value
+ continue
+ keyword, _space, rest = line.partition(" ")
+ if keyword in ("msgctxt", "msgid") and entry is not None and "msgid" in entry:
+ finish()
+ entry = None
+ entry = entry or {"msgstr": {}, "flags": set(), "comments": []}
+ if keyword.startswith("msgstr"):
+ index = int(keyword[7:-1]) if keyword.startswith("msgstr[") else 0
+ entry["msgstr"][index] = _unquote(rest)
+ field = ("msgstr", index)
+ elif keyword in ("msgctxt", "msgid", "msgid_plural"):
+ entry[keyword] = _unquote(rest)
+ field = (keyword, None)
+ else:
+ raise ValueError(f"unreadable .po line: {raw!r}")
+ finish()
+ for item in entries:
+ item["msgstr"] = [item["msgstr"][i] for i in sorted(item["msgstr"])]
+ return entries
+
+
+def _mo_bytes(entries: list[dict]) -> bytes:
+ # The .mo layout from the GNU gettext manual, so the standard library's GNUTranslations reads
+ # plural forms from the catalogue's own Plural-Forms header. Building it in memory keeps the
+ # .po the only file there is: nothing to compile, nothing to fall out of step.
+ pairs = {}
+ for entry in entries:
+ if "fuzzy" in entry["flags"] or (entry["msgid"] and not any(entry["msgstr"])):
+ continue
+ key = entry["msgid"]
+ if "msgid_plural" in entry:
+ key += "\0" + entry["msgid_plural"]
+ if "msgctxt" in entry:
+ key = entry["msgctxt"] + "\x04" + key
+ pairs[key.encode()] = "\0".join(entry["msgstr"]).encode()
+ keys = sorted(pairs)
+ ids = strs = b""
+ offsets = []
+ for key in keys:
+ offsets.append((len(key), len(ids), len(pairs[key]), len(strs)))
+ ids += key + b"\0"
+ strs += pairs[key] + b"\0"
+ start = 7 * 4 + 16 * len(keys)
+ table = []
+ for id_len, id_at, str_len, str_at in offsets:
+ table.append((id_len, start + id_at, str_len, start + len(ids) + str_at))
+ head = struct.pack("Iiiiiii", 0x950412DE, 0, len(keys), 7 * 4, 7 * 4 + 8 * len(keys), 0, 0)
+ return (head + b"".join(struct.pack("ii", a, b) for a, b, _c, _d in table)
+ + b"".join(struct.pack("ii", c, d) for _a, _b, c, d in table) + ids + strs)
+
+
+class _Pseudo(_gettext.NullTranslations):
+ _ACCENTS = str.maketrans("aeiouAEIOU", "àéîõüÀÉÎÕÜ")
+
+ def _wrap(self, text: str) -> str:
+ parts = re.split(r"(\{[^{}]*\})", text)
+ body = "".join(part if part.startswith("{") else part.translate(self._ACCENTS) for part in parts)
+ return "⟦" + body + "·" * (len(text) // 3) + "⟧"
+
+ def gettext(self, message):
+ return self._wrap(message)
+
+ def ngettext(self, singular, plural, n):
+ return self._wrap(singular if n == 1 else plural)
+
+ def pgettext(self, context, message):
+ return self._wrap(message)
+
+
+def load(code: str) -> _gettext.NullTranslations:
+ if code == SOURCE:
+ return _gettext.NullTranslations()
+ if code == PSEUDO:
+ return _Pseudo()
+ path = locales_dir() / f"{code}.po"
+ entries = parse_po(path.read_text(encoding="utf-8"))
+ return _gettext.GNUTranslations(io.BytesIO(_mo_bytes(entries)))
+
+
+def _mac_languages() -> list[str]:
+ from Foundation import NSLocale
+
+ return [str(code) for code in NSLocale.preferredLanguages() or ()]
+
+
+def _windows_languages() -> list[str]:
+ count, size = ctypes.c_ulong(), ctypes.c_ulong()
+ get = ctypes.windll.kernel32.GetUserPreferredUILanguages
+ if not get(8, ctypes.byref(count), None, ctypes.byref(size)): # MUI_LANGUAGE_NAME
+ return []
+ buffer = ctypes.create_unicode_buffer(size.value)
+ if not get(8, ctypes.byref(count), buffer, ctypes.byref(size)):
+ return []
+ return [code for code in buffer[:size.value].split("\0") if code]
+
+
+def _linux_languages() -> list[str]:
+ # gettext's own order: LANGUAGE is a list and wins, unless the locale itself is C/POSIX.
+ for key in ("LC_ALL", "LC_MESSAGES", "LANG"):
+ value = os.environ.get(key)
+ if value:
+ if value.split(".")[0] in ("C", "POSIX"):
+ return []
+ listed = os.environ.get("LANGUAGE")
+ return (listed.split(":") if listed else []) + [value]
+ return []
+
+
+def system_languages() -> list[str]:
+ """The person's preferred languages, most preferred first, as the operating system lists them."""
+ try:
+ if sys.platform == "darwin":
+ return _mac_languages()
+ if sys.platform == "win32":
+ return _windows_languages()
+ return _linux_languages()
+ except (AttributeError, OSError, ImportError, ValueError):
+ return []
+
+
+def _base(code: str) -> str:
+ return code.replace("-", "_").split("_")[0].split(".")[0].split("@")[0].lower()
+
+
+def resolve(choice: str | None, preferred: list[str] | None = None) -> str:
+ """The language to show for a setting of `choice`: the code itself, or for Automatic the first
+ of the system's preferred languages Beamer has, as macOS picks an app's language."""
+ forced = os.environ.get("BEAMER_LANGUAGE")
+ if forced in LANGUAGES or forced == PSEUDO:
+ return forced
+ if choice in LANGUAGES:
+ return choice
+ for code in system_languages() if preferred is None else preferred:
+ base = _base(code)
+ if base in LANGUAGES:
+ return base
+ return SOURCE
+
+
+def install(choice: str | None = AUTOMATIC) -> str:
+ """Install the language for `choice` ("auto" or a code) and return its code. A catalogue that
+ cannot be read leaves the app in English rather than stopping it starting."""
+ global _translations, _language
+ code = resolve(choice)
+ try:
+ _translations = load(code)
+ except (OSError, ValueError, SyntaxError):
+ code, _translations = SOURCE, _gettext.NullTranslations()
+ _language = code
+ return code
+
+
+def is_source() -> bool:
+ return _language == SOURCE
diff --git a/core/keytable.py b/core/keytable.py
index f48f9ea..66ecb1c 100644
--- a/core/keytable.py
+++ b/core/keytable.py
@@ -53,6 +53,14 @@ def wire_name(physical: str, own_platform: str, peer_platform: str, style: Union
return table.get(physical, physical)
+def tap_messages(name: str, down: bool) -> list:
+ """The input-method keys have no reliable release, so send a complete tap on press only."""
+ if name not in ("hangul", "hanja") or not down:
+ return []
+ data = {"key": name}
+ return [{"type": "keydown", "data": dict(data)}, {"type": "keyup", "data": dict(data)}]
+
+
# A Linux sender reads evdev codes (linux/input-event-codes.h). Modifiers first, then the named
# keys of section 7 that have a code. The numpad Enter is `enter`, so two codes share it.
EVDEV_NAMES = {
@@ -61,6 +69,7 @@ EVDEV_NAMES = {
56: "alt", 100: "alt_r",
42: "shift", 54: "shift_r",
58: "caps_lock",
+ 122: "hangul", 123: "hanja",
14: "backspace", 15: "tab", 28: "enter", 96: "enter", 1: "esc", 57: "space",
111: "delete", 110: "insert", 102: "home", 107: "end", 104: "page_up", 109: "page_down",
105: "left", 106: "right", 103: "up", 108: "down",
@@ -84,7 +93,7 @@ EVDEV_US.update(zip(range(0x1E, 0x2A), "asdfghjkl;'`"))
EVDEV_US.update(zip(range(0x2B, 0x36), "\\zxcvbnm,./"))
SPEC_NAMES = frozenset(
- {"shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r", "caps_lock",
+ {"shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r", "caps_lock", "hangul", "hanja",
"backspace", "tab", "enter", "esc", "space", "delete", "insert", "home", "end", "page_up", "page_down",
"left", "right", "up", "down", "menu", "print_screen", "pause", "num_lock", "scroll_lock",
"browser_back", "browser_forward", "browser_stop", "browser_home", "browser_refresh", "search",
diff --git a/core/link.py b/core/link.py
index 61cad83..cf299c5 100644
--- a/core/link.py
+++ b/core/link.py
@@ -24,6 +24,7 @@ import time
from core import peerlist
from core import protocol
from core import receiver
+from core.i18n import tr
from core.response_time import ResponseTime
LOGGER = logging.getLogger("Beamer")
@@ -64,12 +65,12 @@ def connection_ended(exc, name):
"""What a failed connect says, in the words 1.4.x used, naming the peer."""
number = getattr(exc, "errno", None)
if number in (51, 64, 65, errno.EHOSTUNREACH, errno.ENETUNREACH):
- return LinkEnded(f"{name} is unreachable from this machine. Check that both can communicate on the local network.", "unreachable")
+ return LinkEnded(tr("{name} is unreachable from this machine. Check that both can communicate on the local network.").format(name=name), "unreachable")
if number in (61, errno.ECONNREFUSED):
- return LinkEnded(f"{name} is reachable, but Beamer is not listening on this port.", "refused")
+ return LinkEnded(tr("{name} is reachable, but Beamer is not listening on this port.").format(name=name), "refused")
if isinstance(exc, (socket.timeout, TimeoutError)):
- return LinkEnded(f"{name} did not answer before the connection timed out.", "timeout")
- return LinkEnded(f"Connection failed: {exc}", "failed")
+ return LinkEnded(tr("{name} did not answer before the connection timed out.").format(name=name), "timeout")
+ return LinkEnded(tr("Connection failed: {error}").format(error=exc), "failed")
class OutboundLink:
@@ -246,7 +247,7 @@ class OutboundLink:
peer_id=entry.get("id"), host=entry.get("host"))
except Exception:
shown = ""
- return shown or entry.get("host") or "The other machine"
+ return shown or entry.get("host") or tr("The other machine")
# The thread
@@ -264,7 +265,7 @@ class OutboundLink:
self._wake.clear()
continue
if entry is None:
- self._report(False, "This pairing was removed", "removed")
+ self._report(False, tr("This pairing was removed"), "removed")
return
target = self._target(entry)
shape = (entry.get("host"), entry.get("port"), entry.get("id"))
@@ -311,7 +312,7 @@ class OutboundLink:
if self.kind != "forgotten":
LOGGER.info("%s has closed every handshake for %d seconds; it no longer has this pairing",
name, FORGOTTEN_AFTER_SECONDS)
- self._report(False, f"{name} no longer has this pairing: use Re-pair on Overview", "forgotten")
+ self._report(False, tr("{name} no longer has this pairing: use Re-pair on Overview").format(name=name), "forgotten")
wait = max(wait, FORGOTTEN_RETRY_SECONDS)
else:
self._report(False, ended.text, ended.kind)
@@ -326,7 +327,7 @@ class OutboundLink:
closed_since = None
LOGGER.exception("the link to %s failed", self._name(entry))
if tried is None and not self._stop.is_set():
- self._report(False, "The link failed", "failed")
+ self._report(False, tr("The link failed"), "failed")
if self._stop.is_set():
break
self._wake.wait(wait)
@@ -370,25 +371,25 @@ class OutboundLink:
try:
sock = self._tunnel()
except OSError as tunnel_exc:
- raise LinkEnded("macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command.", "blocked") from tunnel_exc
+ raise LinkEnded(tr("macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command."), "blocked") from tunnel_exc
self.via_tunnel = True
- self.status = f"Connecting to {host}:{port}"
+ self.status = tr("Connecting to {host}:{port}").format(host=host, port=port)
with self._lock:
self._pending = sock
if self._stop.is_set():
- raise LinkEnded("This link was stopped", "off")
+ raise LinkEnded(tr("This link was stopped"), "off")
deadline = time.monotonic() + HANDSHAKE_SECONDS
fields = self._handshake(_Interruptible(sock, self._stop), entry, host, deadline, direct)
if self._stop.is_set():
- raise LinkEnded("This link was stopped", "off")
+ raise LinkEnded(tr("This link was stopped"), "off")
except LinkEnded:
self._forget_pending(sock)
raise
except (socket.timeout, TimeoutError):
self._forget_pending(sock)
if self._answered:
- raise LinkEnded(f"{name} stopped responding", "stopped") from None
- raise LinkEnded(f"{name} did not answer as a Beamer: it is probably running one from before version 4", "not_beamer") from None
+ raise LinkEnded(tr("{name} stopped responding").format(name=name), "stopped") from None
+ raise LinkEnded(tr("{name} did not answer as a Beamer: it is probably running one from before version 4").format(name=name), "not_beamer") from None
except (protocol.ConnectionClosed, ConnectionError):
self._forget_pending(sock)
raise LinkEnded(self._closed_text(entry), "closed") from None
@@ -397,10 +398,10 @@ class OutboundLink:
raise connection_ended(exc, name) from None
except protocol.AuthenticationError:
self._forget_pending(sock)
- raise LinkEnded(f"{name} could not be authenticated: something on the path altered the link", "unauthenticated") from None
+ raise LinkEnded(tr("{name} could not be authenticated: something on the path altered the link").format(name=name), "unauthenticated") from None
except protocol.ProtocolError as exc:
self._forget_pending(sock)
- raise LinkEnded(f"{name} did not answer like Beamer: {exc}", "failed") from None
+ raise LinkEnded(tr("{name} did not answer like Beamer: {error}").format(name=name, error=exc), "failed") from None
self._answered = True
sock.settimeout(READ_SECONDS)
with self._lock:
@@ -427,8 +428,8 @@ class OutboundLink:
def _closed_text(self, entry):
name = self._name(entry)
if not entry.get("linked"):
- return f"Update Beamer on {name} to 1.5.0; if it is up to date, pair the two again"
- return f"{name} closed the connection: it may have removed this machine, or be too busy to answer"
+ return tr("Update Beamer on {name} to 1.5.0; if it is up to date, pair the two again").format(name=name)
+ return tr("{name} closed the connection: it may have removed this machine, or be too busy to answer").format(name=name)
def _handshake(self, sock, entry, host, deadline, direct):
name = self._name(entry)
@@ -443,14 +444,14 @@ class OutboundLink:
preamble = protocol.recv_link_preamble(sock, deadline)
except protocol.VersionMismatch as exc:
if exc.peer_version is None:
- raise LinkEnded(f"{name} did not answer as a Beamer", "not_beamer") from None
+ raise LinkEnded(tr("{name} did not answer as a Beamer").format(name=name), "not_beamer") from None
if exc.peer_version < protocol.LINK_VERSION:
- raise LinkEnded(f"Update Beamer on {name}: it is older than this one", "older") from None
- raise LinkEnded(f"{name} runs a newer Beamer: update Beamer on this machine", "newer") from None
+ raise LinkEnded(tr("Update Beamer on {name}: it is older than this one").format(name=name), "older") from None
+ raise LinkEnded(tr("{name} runs a newer Beamer: update Beamer on this machine").format(name=name), "newer") from None
try:
session.accept_preamble(preamble)
except protocol.PreambleRefused:
- raise LinkEnded(f"A different Beamer answered at {host}", "different") from None
+ raise LinkEnded(tr("A different Beamer answered at {host}").format(host=host), "different") from None
hello = protocol.hello_v6(
own_id, identity["name"], identity["platform"], identity["app"], identity["caps"], int(identity.get("port") or 0), self._hardware_towards(host, identity))
sock.settimeout(max(0.001, deadline - time.monotonic()))
@@ -459,10 +460,10 @@ class OutboundLink:
welcome = protocol.read_welcome(protocol.recv_first_msg(sock, session, deadline))
except protocol.HelloRefused as refused:
if refused.error == protocol.ERROR_WRONG_ID:
- raise LinkEnded(f"{name} has this pairing under another machine: use Re-pair on Overview.", "wrong_id", stop_dialling=True) from None
- raise LinkEnded(f"{name} could not read what this machine sent first; Beamer on the two machines may differ", "unreadable") from None
+ raise LinkEnded(tr("{name} has this pairing under another machine: use Re-pair on Overview.").format(name=name), "wrong_id", stop_dialling=True) from None
+ raise LinkEnded(tr("{name} could not read what this machine sent first; Beamer on the two machines may differ").format(name=name), "unreadable") from None
except (protocol.InvalidWelcome, protocol.NotAnObject):
- raise LinkEnded(f"A different Beamer answered at {host}", "different") from None
+ raise LinkEnded(tr("A different Beamer answered at {host}").format(host=host), "different") from None
changes = {"name": welcome["name"], "platform": welcome["platform"]}
if welcome["hw"] is not None:
changes["hw"] = welcome["hw"]
@@ -472,11 +473,11 @@ class OutboundLink:
outcome, _ = self._book.admit(self.key_id, own_id, welcome["id"], changes)
except Exception:
LOGGER.exception("Could not save what the link to %s taught", name)
- raise LinkEnded(f"Could not save what {name} told this machine", "failed") from None
+ raise LinkEnded(tr("Could not save what {name} told this machine").format(name=name), "failed") from None
if outcome == receiver.GONE:
- raise LinkEnded("This pairing was removed", "removed")
+ raise LinkEnded(tr("This pairing was removed"), "removed")
if outcome == receiver.WRONG_ID:
- raise LinkEnded(f"A different Beamer answered at {host}", "different")
+ raise LinkEnded(tr("A different Beamer answered at {host}").format(host=host), "different")
sock.settimeout(READ_SECONDS)
welcome["own_caps"] = identity["caps"]
welcome["session"] = session
@@ -504,11 +505,12 @@ class OutboundLink:
name = self._name(entry)
writer = threading.Thread(target=self._write, args=(sock, session), name="Beamer-link-writer", daemon=True)
writer.start()
- way = " via the secure macOS 27 fallback" if self.via_tunnel else ""
+ message = (tr("Connected to {name} via the secure macOS 27 fallback").format(name=name) if self.via_tunnel
+ else tr("Connected to {name}").format(name=name))
self.dialled = (self._dialled_to, self._dialled_port)
- self._report(True, f"Connected to {name}{way}", "connected")
+ self._report(True, message, "connected")
self._call(1, fields)
- reason, kind = f"{name} closed the connection", "closed"
+ reason, kind = tr("{name} closed the connection").format(name=name), "closed"
try:
self._read(sock, session, name)
except LinkEnded as ended:
@@ -516,9 +518,9 @@ class OutboundLink:
except (protocol.ConnectionClosed, ConnectionError):
pass
except protocol.AuthenticationError:
- reason, kind = f"{name} could not be authenticated: something on the path altered the link", "unauthenticated"
+ reason, kind = tr("{name} could not be authenticated: something on the path altered the link").format(name=name), "unauthenticated"
except (OSError, protocol.ProtocolError) as exc:
- reason, kind = f"The link to {name} failed: {exc}", "failed"
+ reason, kind = tr("The link to {name} failed: {error}").format(name=name, error=exc), "failed"
finally:
if self._drop_reason is not None:
reason, kind, self._drop_reason = self._drop_reason, "failed", None
@@ -578,7 +580,7 @@ class OutboundLink:
if length - 20 > protocol.SMALL_MESSAGE_BYTES:
self._begin_ack_pause(began or now)
elif now - self._last_rx > SILENCE_SECONDS:
- raise LinkEnded(f"{name} stopped responding", "stopped")
+ raise LinkEnded(tr("{name} stopped responding").format(name=name), "stopped")
while len(buffer) >= protocol.HEADER_SIZE:
length = int.from_bytes(buffer[:protocol.HEADER_SIZE], "big")
if length < protocol.MIN_FRAME_BYTES or length > protocol.MAX_FRAME_BYTES:
@@ -586,7 +588,7 @@ class OutboundLink:
if len(buffer) < protocol.HEADER_SIZE + length:
break
if now - began > protocol.FRAME_COMPLETE_SECONDS:
- raise LinkEnded(f"{name} took too long to send one message", "stopped")
+ raise LinkEnded(tr("{name} took too long to send one message").format(name=name), "stopped")
body = bytes(buffer[protocol.HEADER_SIZE:protocol.HEADER_SIZE + length])
del buffer[:protocol.HEADER_SIZE + length]
plain = session.open_raw(body)
@@ -604,7 +606,7 @@ class OutboundLink:
if next_length - 20 > protocol.SMALL_MESSAGE_BYTES:
self._begin_ack_pause(began or now)
if buffer and now - began > protocol.FRAME_COMPLETE_SECONDS:
- raise LinkEnded(f"{name} took too long to send one message", "stopped")
+ raise LinkEnded(tr("{name} took too long to send one message").format(name=name), "stopped")
self._tick(self._clock())
def _large_due(self, began):
@@ -662,16 +664,16 @@ class OutboundLink:
"%s stopped acknowledging input: oldest seq %d, last acked seq %d, %d unacknowledged",
self.peer_name, oldest[0], last_acked, pending,
)
- raise LinkEnded(f"{self.peer_name} stopped acknowledging input", "stalled")
+ raise LinkEnded(tr("{name} stopped acknowledging input").format(name=self.peer_name), "stalled")
if self._writing and now - self._last_progress > STALL_SECONDS:
- raise LinkEnded(f"{self._name(self.entry())} stopped accepting data", "stopped")
+ raise LinkEnded(tr("{name} stopped accepting data").format(name=self._name(self.entry())), "stopped")
if now - self._checked_at >= 1.0:
self._checked_at = now
entry = self.entry()
if entry is None:
- raise LinkEnded("This pairing was removed", "removed")
+ raise LinkEnded(tr("This pairing was removed"), "removed")
if entry.get("send") is not True:
- raise LinkEnded("Sending to this machine was switched off", "off")
+ raise LinkEnded(tr("Sending to this machine was switched off"), "off")
if self._response_time_enabled:
if now >= self._next_response_probe:
self._next_response_probe = now + PING_SECONDS
diff --git a/core/locale.py b/core/locale.py
index 6bda3f1..c45a49a 100644
--- a/core/locale.py
+++ b/core/locale.py
@@ -68,8 +68,10 @@ def is_us_region() -> bool:
def americanise(text: str) -> str:
- """Convert British spellings in text intended for display on a US system."""
- if not is_us_region() or not isinstance(text, str):
+ """Convert British spellings in text intended for display on a US system, when Beamer is in English."""
+ from core import i18n
+
+ if not isinstance(text, str) or not i18n.is_source() or not is_us_region():
return text
def replace(match: re.Match) -> str:
diff --git a/core/peerlist.py b/core/peerlist.py
index 358e793..85e438e 100644
--- a/core/peerlist.py
+++ b/core/peerlist.py
@@ -10,6 +10,7 @@ import time
from typing import Optional
from core import pairing, protocol
+from core.i18n import tr
class RefusalThrottle:
@@ -135,9 +136,9 @@ def dormant_reason(entry: dict) -> Optional[str]:
return None
reason = entry.get("dormant_reason")
return {
- "wrong_id": "The saved pairing now identifies a different machine.",
- "forgotten": "The other machine no longer has this pairing.",
- }.get(reason, "This pairing needs to be set up again.")
+ "wrong_id": tr("The saved pairing now identifies a different machine."),
+ "forgotten": tr("The other machine no longer has this pairing."),
+ }.get(reason, tr("This pairing needs to be set up again."))
def paired_ids(peers: list, exclude: Optional[str] = None) -> list:
@@ -216,49 +217,46 @@ def day(paired_at) -> str:
return time.strftime("%d-%m-%Y", time.localtime(paired_at))
-def _since(entry: dict) -> str:
- when = day(entry.get("paired_at"))
- return f", since {when}" if when else ""
-
-
def pairing_error_text(error: Exception, name: str) -> str:
"""A requester's failure, said to its user; `name` is how the machine is shown (its label, or
"That machine" when it is not known yet, which starts a sentence)."""
if isinstance(error, pairing.AlreadyPaired):
entry = error.entry
if entry is None:
- return "That is this machine, not another one."
+ return tr("That is this machine, not another one.")
label = _name(entry) or name
- return f"{label} is already paired with this machine{_since(entry)}. Remove it from the list first to pair again."
+ when = day(entry.get("paired_at"))
+ if when:
+ return tr("{name} is already paired with this machine, since {when}. Remove it from the list first to pair again.").format(name=label, when=when)
+ return tr("{name} is already paired with this machine. Remove it from the list first to pair again.").format(name=label)
reason = str(error)
if reason == pairing.ERROR_NOT_PAIRING:
- return f"{name} is not showing a code. Show one in Beamer on it, then try again."
+ return tr("{name} is not showing a code. Show one in Beamer on it, then try again.").format(name=name)
if reason == pairing.ERROR_REFUSED:
- return f"That code was not accepted, and {name} has cancelled it. Show a new one there to try again."
+ return tr("That code was not accepted, and {name} has cancelled it. Show a new one there to try again.").format(name=name)
if reason == pairing.ERROR_VERSION:
- return f"{name} runs an older Beamer. Update Beamer on it to 1.5.0, then pair again."
+ return tr("{name} runs an older Beamer. Update Beamer on it to 1.5.0, then pair again.").format(name=name)
if reason == "no_answer":
- return f"{name} did not answer. Check both machines are on the same network, then try again."
+ return tr("{name} did not answer. Check both machines are on the same network, then try again.").format(name=name)
if reason == pairing.ERROR_FULL:
- return (f"Either this machine or {name} already has {pairing.MAX_PEERS} machines paired, the most "
- "Beamer keeps. Remove one, then try again.")
+ return tr("Either this machine or {name} already has {n} machines paired, the most Beamer keeps. Remove one, then try again.").format(name=name, n=pairing.MAX_PEERS)
if reason == pairing.ERROR_KNOWN:
- return f"{name} already has this machine paired. Remove this machine from its list there, then pair again."
+ return tr("{name} already has this machine paired. Remove this machine from its list there, then pair again.").format(name=name)
if reason == "not_saved":
- return "Pairing finished, but Beamer could not save it on this machine. Try again in a moment."
+ return tr("Pairing finished, but Beamer could not save it on this machine. Try again in a moment.")
if reason == "busy":
- return "Another pairing is still finishing. Try again in a moment."
- return f"Pairing failed: {reason}."
+ return tr("Another pairing is still finishing. Try again in a moment.")
+ return tr("Pairing failed: {reason}.").format(reason=reason)
def refusal_text(why: str, name: str, other: Optional[str]) -> Optional[str]:
"""The alert for an `owned` or `busy` refusal, naming the machine in the way when known."""
if why == "owned":
- return (f"Can't cross to {name}: it is being driven from {other}." if other else
- f"Can't cross to {name}: another machine is driving it.")
+ return (tr("Can't cross to {name}: it is being driven from {other}.").format(name=name, other=other) if other else
+ tr("Can't cross to {name}: another machine is driving it.").format(name=name))
if why == "busy":
- return (f"Can't cross to {name}: it is driving {other}." if other else
- f"Can't cross to {name}: it is driving another machine.")
+ return (tr("Can't cross to {name}: it is driving {other}.").format(name=name, other=other) if other else
+ tr("Can't cross to {name}: it is driving another machine.").format(name=name))
return None
@@ -268,21 +266,23 @@ def host_outcome_text(outcome: Optional[str], entry: Optional[dict]) -> str:
a code is live or after a deliberate cancel."""
name = _name(entry or {}) or "A machine"
if outcome == "paired":
- return f"Paired with {name}."
+ return tr("Paired with {name}.").format(name=name)
if outcome == "refused":
- return "A wrong code was tried, so this code was cancelled. Show a new one to try again."
+ return tr("A wrong code was tried, so this code was cancelled. Show a new one to try again.")
if outcome == "version":
- return "A machine on an older Beamer tried to pair. Update Beamer on it to 1.5.0, then show a new code."
+ return tr("A machine on an older Beamer tried to pair. Update Beamer on it to 1.5.0, then show a new code.")
if outcome == "expired":
- return "The code expired. Show a new one."
+ return tr("The code expired. Show a new one.")
if outcome == "known":
if entry is None:
- return "That machine gave this machine's own identity, so nothing was paired. Show a new code to try again."
- return f"{name} is already paired here{_since(entry)}. Remove it from the list first to pair again."
+ return tr("That machine gave this machine's own identity, so nothing was paired. Show a new code to try again.")
+ if day(entry.get("paired_at")):
+ return tr("{name} is already paired here, since {when}. Remove it from the list first to pair again.").format(name=name, when=day(entry.get("paired_at")))
+ return tr("{name} is already paired here. Remove it from the list first to pair again.").format(name=name)
if outcome == "known_there":
- return "That machine may already be paired here, or the code was wrong. Show a new code to try again."
+ return tr("That machine may already be paired here, or the code was wrong. Show a new code to try again.")
if outcome == "full":
- return f"This machine already has {pairing.MAX_PEERS} machines paired, the most Beamer keeps. Remove one, then show a new code."
+ return tr("This machine already has {n} machines paired, the most Beamer keeps. Remove one, then show a new code.").format(n=pairing.MAX_PEERS)
if outcome == "not_saved":
- return "Beamer could not save the pairing on this machine, so it did not complete. Show a new code to try again."
+ return tr("Beamer could not save the pairing on this machine, so it did not complete. Show a new code to try again.")
return ""
diff --git a/core/profiles.py b/core/profiles.py
new file mode 100644
index 0000000..d643dfd
--- /dev/null
+++ b/core/profiles.py
@@ -0,0 +1,902 @@
+"""Pure crossing profiles, migration, and independently stamped desk registers.
+
+Only the live projection contains permissions or connection details. Rows and wire
+messages are constructed field by field, never by copying a peer entry.
+"""
+
+import copy
+import hashlib
+import json
+import time
+
+from core import peerlist, protocol, settings_sync, ways
+from core.i18n import joined, tr
+
+FORMAT = 1
+DESK_ID = protocol.id_text(bytes(16))
+MAX_PROFILES = 8
+MAX_HELD = 64
+PRUNED_KEPT = 4 * MAX_HELD
+MAX_DESK_BYTES = 48 * 1024
+AHEAD = 600
+APP_VERSION = "1.5.5"
+UPGRADE_PENDING = "_crossing_profiles_upgrade_pending"
+
+
+def _now(now):
+ return int(time.time() if now is None else now)
+
+
+def _json(value):
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
+
+
+def frames(desk):
+ """A desk message packed register by register into frames of at most MAX_DESK_BYTES, so only a
+ single register is ever bounded (a row of 32 peers, a picture of 33 tiles, both far below it):
+ the whole desk never is, and two valid desks always merge. Each frame is read and taken alone."""
+ result, frame, size = [], {}, 0
+ for path, register in _paths(desk):
+ one = {}
+ _store(one, path, register)
+ length = len(_json(one))
+ if frame and size + length > MAX_DESK_BYTES:
+ result.append(frame)
+ frame, size = {}, 0
+ _store(frame, path, register)
+ size += length
+ return result + ([frame] if frame else [])
+
+
+def desk_size(settings):
+ """The largest single register this desk holds, which is what MAX_DESK_BYTES bounds."""
+ # Every crossing event measures its result, so this reads the registers in place: copying the
+ # desk to measure it cost more than most events.
+ return max((len(_json(_nest(path, register)))
+ for path, register in _paths(settings.get("crossing_desk", {}))), default=0)
+
+
+def removed(desk, profile_id):
+ """Whether a profile's tombstone takes effect: never for the active profile."""
+ profile = desk.get("profiles", {}).get(profile_id)
+ return (not isinstance(profile, dict) or profile.get("removed") is not None
+ and profile_id != desk.get("active", {}).get("value"))
+
+
+def prune_removed(settings, limit):
+ """Drop whole removed profiles, oldest tombstone first (ties by id), until at most `limit` are
+ held: the same rule on every machine, so desks still agree. Their ids are kept, never sent, so
+ a late delta for one is ignored rather than making it again without its tombstone."""
+ profiles, own = settings["crossing_desk"].get("profiles", {}), settings["crossing_own"]
+ while len(profiles) > limit:
+ candidates = [pid for pid in profiles if removed(settings["crossing_desk"], pid)]
+ if not candidates:
+ break
+ oldest = min(candidates, key=lambda pid: (_pair(profiles[pid].get("removed")), pid))
+ del profiles[oldest]
+ own["pruned"] = [*pruned(settings), oldest][-PRUNED_KEPT:]
+
+
+def pruned(settings):
+ held = settings.get("crossing_own", {}).get("pruned")
+ return [pid for pid in held if isinstance(pid, str)] if isinstance(held, list) else []
+
+
+def row_entry(settings, peer):
+ entry = ways._entry(settings, peer) or {}
+ # A malformed local JSON must still be recoverable; the legacy reader assumes
+ # thirds is iterable, whereas a hand-edited file need not satisfy that.
+ if isinstance(entry.get("ways"), dict) and not isinstance(entry["ways"].get("thirds", []), (list, tuple)):
+ settings = copy.deepcopy(settings)
+ ways._entry(settings, peer)["ways"].pop("thirds", None)
+ return {"ways": ways._read_intent(settings, peer), "notch_return": entry.get("notch_return") is True}
+
+
+def live_row(settings, send_only=True):
+ return {entry["id"]: row_entry(settings, entry["id"])
+ for entry in settings.get("peers", []) if isinstance(entry, dict) and ways._zoned(entry)
+ and (not send_only or entry.get("send", True) is True)}
+
+
+def canonical_row(row):
+ if not isinstance(row, dict):
+ return {}
+ scratch = {"peers": [{"id": peer, "port": 24820,
+ "ways": value.get("ways", {}), "notch_return": value.get("notch_return") is True}
+ for peer, value in row.items() if isinstance(peer, str) and peer
+ and isinstance(value, dict)]}
+ return live_row(scratch)
+
+
+def register(value, now, by, held=None, floor=0):
+ return {"value": copy.deepcopy(value), "set_at": max(_now(now), (held or {}).get("set_at", 0) + 1, floor),
+ "by": by}
+
+
+def _pair(reg):
+ return ((reg or {}).get("set_at", -1), settings_sync._id((reg or {}).get("by", "")) or b"")
+
+
+def _blank_desk():
+ return {"format": FORMAT, "on": {"value": False, "set_at": 0, "by": ""},
+ "active": {"value": DESK_ID, "set_at": 0, "by": ""},
+ "profiles": {DESK_ID: {"name": {"value": "Desk", "set_at": 0, "by": ""},
+ "removed": None, "home": {"shake": {"value": True, "set_at": 0, "by": ""},
+ "sensitivity": {"value": 100, "set_at": 0, "by": ""}}, "rows": {}}},
+ "status": {}}
+
+
+def same_ways_on(settings):
+ return settings.get("crossing_desk", {}).get("on", {}).get("value") is True
+
+
+def in_force(settings):
+ own = settings["crossing_own"]
+ desk = settings["crossing_desk"]
+ if not same_ways_on(settings) or own.get("use_own") is True:
+ return own["row"], False
+ profile = desk["profiles"].get(desk["active"]["value"], {})
+ return profile.get("rows", {}).get(settings.get("machine_id"), {}).get("value", {}), True
+
+
+def archive(settings, row, why, now, by=None):
+ row = canonical_row(row)
+ ident = hashlib.sha256(_json(row)).hexdigest()
+ item = {"id": ident, "why": why, "at": _now(now), "row": row}
+ if by is not None:
+ item["by"] = by
+ saved = settings["crossing_own"].setdefault("saved", [])
+ saved[:] = [entry for entry in saved if entry.get("id") != ident]
+ saved.append(item)
+
+
+def _archive_edit(settings, row, key, now):
+ editing = settings["crossing_own"].setdefault("editing", {})
+ if not editing.get(key):
+ archive(settings, row, "edited", now)
+ editing[key] = True
+
+
+def put_row(settings, profile_id, machine, row, now, why="edited", by=None, stamp=None):
+ desk = settings["crossing_desk"]
+ rows = desk["profiles"][profile_id].setdefault("rows", {})
+ held = rows.get(machine)
+ if machine == settings.get("machine_id"):
+ if held is not None:
+ if why == "edited":
+ _archive_edit(settings, held["value"], profile_id, now)
+ else:
+ archive(settings, held["value"], why, now, by=by)
+ if why != "edited":
+ settings["crossing_own"].setdefault("editing", {}).pop(profile_id, None)
+ author = settings.get("machine_id", "") if by is None else by
+ reg = register(canonical_row(row), now, author, held, floor=desk["on"]["set_at"] + 1)
+ if stamp is not None:
+ reg["set_at"] = stamp
+ rows[machine] = reg
+ return ("row", profile_id, machine)
+
+
+def _local_shape(own, desk):
+ def row_shape(row):
+ return (isinstance(row, dict) and all(isinstance(peer, str) and isinstance(entry, dict)
+ and isinstance(entry.get("ways"), dict) and type(entry.get("notch_return", False)) is bool
+ for peer, entry in row.items()))
+ shape = (isinstance(own, dict) and type(own.get("format")) is int and own["format"] == FORMAT
+ and type(own.get("use_own")) is bool and type(own.get("shake")) is bool
+ and type(own.get("shake_sensitivity", 100)) is int
+ and 50 <= own.get("shake_sensitivity", 100) <= 200
+ and row_shape(own.get("row")) and row_shape(own.get("applied"))
+ and isinstance(own.get("saved"), list)
+ and all(isinstance(item, dict) and row_shape(item.get("row"))
+ and isinstance(item.get("id"), str) and type(item.get("at")) is int
+ and isinstance(item.get("why"), str) for item in own["saved"])
+ and isinstance(desk, dict) and type(desk.get("format")) is int and desk["format"] == FORMAT
+ and isinstance(desk.get("on"), dict) and type(desk["on"].get("value")) is bool
+ and isinstance(desk.get("active"), dict) and isinstance(desk.get("profiles"), dict)
+ and isinstance(desk.get("status"), dict)
+ and isinstance(desk["active"].get("value"), str)
+ and desk["active"].get("value") in desk["profiles"]
+ and all(isinstance(p, dict) and isinstance(p.get("rows"), dict)
+ and isinstance(p.get("home"), dict)
+ and all(isinstance(r, dict) and isinstance(r.get("value"), dict)
+ for r in p["rows"].values()) for p in desk["profiles"].values()))
+ if not shape or not isinstance(own.get("editing", {}), dict):
+ return False
+ if any(not _profile_id(pid) for pid in desk["profiles"]):
+ return False
+ for path, reg in _paths(desk):
+ if not _valid_stamp(reg, settings_sync.MAX_STAMP):
+ return False
+ kind, value = path[0], reg.get("value")
+ if kind == "active" and not _profile_id(value):
+ return False
+ if kind == "name" and (not isinstance(value, str) or not 1 <= len(value.strip()) <= 32):
+ return False
+ if kind == "home" and not (path[2] == "shake" and type(value) is bool
+ or path[2] == "sensitivity" and type(value) is int and 50 <= value <= 200):
+ return False
+ if kind == "row" and (protocol.read_id(path[2]) is None or not _valid_row(value)):
+ return False
+ if kind == "status" and (reg["by"] != path[1] or not _valid_status(value)):
+ return False
+ if kind == "picture" and _picture(reg) is None:
+ return False
+ return True
+
+
+def before_load(raw, *, now=None):
+ saved = copy.deepcopy(raw)
+ now = _now(now)
+ notes = []
+ own, desk = saved.get("crossing_own"), saved.get("crossing_desk")
+ if not _local_shape(own, desk):
+ for key in ("crossing_own", "crossing_desk"):
+ if key in saved:
+ aside = key + "_unreadable"
+ if aside in saved:
+ saved.setdefault(aside + "_history", []).append(saved[aside])
+ saved[aside] = saved[key]
+ row = live_row(saved, send_only=False)
+ saved["crossing_own"] = dict(format=FORMAT, use_own=False, row=row, shake=True,
+ shake_sensitivity=100,
+ applied=copy.deepcopy(row), saved=[])
+ saved["crossing_desk"] = _blank_desk()
+ archive(saved, row, "upgrade", now)
+ saved[UPGRADE_PENDING] = True
+ return saved, ["upgraded"]
+ own["row"] = canonical_row(own["row"])
+ own["applied"] = canonical_row(own["applied"])
+ own.setdefault("shake_sensitivity", 100)
+ current = live_row(saved, send_only=False)
+ changed = {peer: entry for peer, entry in current.items()
+ if peer in own["applied"] and entry != own["applied"][peer]}
+ if changed:
+ archive(saved, own["row"], "older_version", now)
+ own["row"].update(copy.deepcopy(changed))
+ own["use_own"] = True
+ own.setdefault("editing", {}).pop("own", None)
+ notes.append("older_version")
+ for peer, entry in current.items():
+ if peer not in own["applied"] and peer not in own["row"]:
+ own["row"][peer] = entry
+ # The loader has acknowledged these changes; reconcile must not misattribute
+ # them to a fresh page edit or send them back into the shared desk.
+ own["applied"] = current
+ return saved, notes
+
+
+def after_load(settings, *, platform, capable=(), now=None, app=APP_VERSION):
+ saved = copy.deepcopy(settings)
+ if saved.pop(UPGRADE_PENDING, False):
+ saved["crossing_own"]["row"] = live_row(saved, send_only=False)
+ saved["crossing_own"]["applied"] = live_row(saved, send_only=False)
+ return reconcile(saved, platform=platform, capable=capable, now=now, app=app)
+
+
+def apply_transitions(settings, before_desk, now):
+ desk, own = settings["crossing_desk"], settings["crossing_own"]
+ machine = settings.get("machine_id", "")
+ was_on = before_desk["on"]["value"] is True
+ is_on = desk["on"]["value"] is True
+ old_id, active = before_desk["active"]["value"], desk["active"]["value"]
+ paths = []
+ if was_on and not is_on and not own["use_own"]:
+ old = before_desk["profiles"].get(old_id, {}).get("rows", {}).get(machine)
+ if old is not None:
+ archive(settings, own["row"], "sync_off", now)
+ own["row"] = canonical_row(old["value"])
+ own.setdefault("editing", {}).pop("own", None)
+ profile = desk["profiles"].get(active)
+ if profile is None:
+ return paths
+ row = profile.setdefault("rows", {}).get(machine)
+ if not was_on and is_on and (row is None or row["set_at"] <= desk["on"]["set_at"]):
+ paths.append(put_row(settings, active, machine, own["row"], now, why="seeded",
+ stamp=desk["on"]["set_at"]))
+ elif is_on and row is None:
+ paths.append(put_row(settings, active, machine, own["row"], now, why="seeded", stamp=0))
+ if old_id != active and was_on and not own["use_own"]:
+ old = before_desk["profiles"].get(old_id, {}).get("rows", {}).get(machine)
+ if old:
+ archive(settings, old["value"], "replaced_by", now, by=desk["active"]["by"])
+ return paths
+
+
+def reconcile(settings, *, platform, capable=(), live=None, gone=None, now=None, app=APP_VERSION):
+ saved = copy.deepcopy(settings)
+ if "crossing_own" not in saved or saved.get(UPGRADE_PENDING):
+ return saved, []
+ now = _now(now)
+ own, desk = saved["crossing_own"], saved["crossing_desk"]
+ active, machine = desk["active"]["value"], saved.get("machine_id", "")
+ # The caller's desk is the one before: apply_transitions only reads it, and `saved` is a copy.
+ paths = apply_transitions(saved, settings["crossing_desk"], now)
+ row, shared = in_force(saved)
+ row = canonical_row(row)
+ # Every desktop peer is captured, whether or not this machine sends to it, so an edit made while
+ # sending is off is never projected over when it is turned back on.
+ current, applied = live_row(saved, send_only=False), canonical_row(own.get("applied", {}))
+ edits = {peer: value for peer, value in current.items() if peer in applied and value != applied[peer]}
+ updates = {peer: value for peer, value in current.items() if peer not in row}
+ updates.update(edits)
+ if updates:
+ if shared:
+ updated = {**row, **updates}
+ paths.append(put_row(saved, active, machine, updated, now))
+ row = updated
+ else:
+ if edits:
+ _archive_edit(saved, row, "own", now)
+ row.update(copy.deepcopy(updates))
+ own["row"] = row
+ entries = {entry["id"]: entry for entry in saved.get("peers", [])
+ if isinstance(entry, dict) and ways._zoned(entry) and entry.get("send", True) is True}
+ for peer, intent in row.items():
+ if peer in entries:
+ entries[peer]["ways"] = copy.deepcopy(intent["ways"])
+ entries[peer]["ways"]["notch"] = platform == "mac" and intent["ways"]["notch"]
+ entries[peer]["notch_return"] = intent["notch_return"]
+ # One notch, by exactly the rule every crossing event applies first (crossing_state._initial):
+ # ways.notch_holder, the first machine in peer order that is in use, not left out and not dormant.
+ # A different rule here would have each event untick what this ticks, and the next reconcile would
+ # take that for a person's edit.
+ holder = ways.notch_holder(saved)
+ if holder is not None:
+ for entry in saved.get("peers", []):
+ if ways._zoned(entry) and entry.get("id") != holder and isinstance(entry.get("ways"), dict):
+ entry["ways"]["notch"] = False
+ changed = live_row(saved, send_only=False) != current
+ if changed:
+ layout = saved.get("layout") or ways.derive_layout(saved)
+ result = ways.compile_layout(saved, layout, platform=platform, capable=capable,
+ live=live, gone=gone, now=now)
+ if result.get("accepted"):
+ saved = result["settings"]
+ own, desk = saved["crossing_own"], saved["crossing_desk"]
+ own["applied"] = live_row(saved, send_only=False)
+ peer_ids = {p.get("id") for p in saved.get("peers", []) if isinstance(p, dict)}
+ held_row = desk["profiles"][active].get("rows", {}).get(machine)
+ value = {"app": app, "platform": platform, "in_force": "desk" if shared else "own", "profile": active,
+ "row": [held_row["set_at"], held_row["by"]] if shared and held_row else None,
+ "waiting": [peer for peer in row if peer not in peer_ids]}
+ held = desk["status"].get(machine)
+ if held is None or held.get("value") != value:
+ desk["status"][machine] = register(value, now, machine, held)
+ paths.append(("status", machine))
+ return saved, list(dict.fromkeys(paths))
+
+
+def reconciled(settings, *, platform, app=APP_VERSION):
+ """True only when reconcile would give these settings back as they are (by ==) and send nothing:
+ reconcile's own steps, read without copying. A machine relaying a burst meets this on nearly
+ every message, and reconcile's copy of the whole settings was most of what each one cost. False
+ whenever any step would write, so the caller runs reconcile itself."""
+ if "crossing_own" not in settings or settings.get(UPGRADE_PENDING):
+ return False
+ own, desk = settings["crossing_own"], settings["crossing_desk"]
+ active, machine = desk["active"]["value"], settings.get("machine_id", "")
+ profile = desk["profiles"].get(active)
+ if not isinstance(profile, dict) or not isinstance(profile.get("rows"), dict):
+ return False
+ # apply_transitions, with nothing having changed since: only seeding this machine's row.
+ if desk["on"]["value"] is True and profile["rows"].get(machine) is None:
+ return False
+ row, shared = in_force(settings)
+ row = canonical_row(row)
+ current, applied = live_row(settings, send_only=False), canonical_row(own.get("applied", {}))
+ if any(peer not in row or peer in applied and value != applied[peer] for peer, value in current.items()):
+ return False
+ # The in-force row projected onto the peers, then the notch unticked from all but its holder.
+ entries = {entry["id"]: entry for entry in settings.get("peers", [])
+ if isinstance(entry, dict) and ways._zoned(entry) and entry.get("send", True) is True}
+ for peer, intent in row.items():
+ entry = entries.get(peer)
+ if entry is None:
+ continue
+ projected = {**intent["ways"], "notch": platform == "mac" and intent["ways"]["notch"]}
+ if entry.get("ways") != projected or entry.get("notch_return", None) != intent["notch_return"]:
+ return False
+ holder = ways.notch_holder(settings)
+ if holder is not None and any(
+ ways._zoned(entry) and entry.get("id") != holder and isinstance(entry.get("ways"), dict)
+ and entry["ways"].get("notch") is not False for entry in settings.get("peers", [])):
+ return False
+ if own.get("applied") != current:
+ return False
+ peer_ids = {p.get("id") for p in settings.get("peers", []) if isinstance(p, dict)}
+ held_row = profile["rows"].get(machine)
+ value = {"app": app, "platform": platform, "in_force": "desk" if shared else "own", "profile": active,
+ "row": [held_row["set_at"], held_row["by"]] if shared and held_row else None,
+ "waiting": [peer for peer in row if peer not in peer_ids]}
+ held = desk.get("status", {}).get(machine)
+ return held is not None and held.get("value") == value
+
+
+def _profile_id(value):
+ return value == DESK_ID or protocol.read_id(value) is not None
+
+
+def _valid_stamp(reg, now):
+ if not isinstance(reg, dict) or type(reg.get("set_at")) is not int:
+ return False
+ stamp, by = reg["set_at"], reg.get("by")
+ return (0 <= stamp <= settings_sync.MAX_STAMP and stamp <= now + AHEAD
+ and (by == "" and stamp == 0 or protocol.read_id(by) is not None))
+
+
+def _valid_row(row):
+ if not isinstance(row, dict) or len(row) > 32:
+ return False
+ for peer, entry in row.items():
+ if protocol.read_id(peer) is None or not isinstance(entry, dict) or not isinstance(entry.get("ways"), dict):
+ return False
+ intent = entry["ways"]
+ if set(entry) - {"ways", "notch_return"} or set(intent) - {"edge", "thirds", "edges", "corner", "corner_at", "corners", "notch"}:
+ return False
+ if any(type(intent[key]) is not bool for key in ("edge", "corner", "notch") if key in intent):
+ return False
+ if "notch_return" in entry and type(entry["notch_return"]) is not bool:
+ return False
+ for key, choices in (("thirds", ways.PARTS), ("edges", ways.EDGES), ("corners", ways.CORNERS)):
+ if key in intent:
+ picked = intent[key]
+ if (not isinstance(picked, list) or key == "thirds" and not picked
+ or any(not isinstance(v, str) or v not in choices for v in picked)
+ or len(picked) != len(set(picked))):
+ return False
+ if "corner_at" in intent and intent["corner_at"] not in ways.CORNERS:
+ return False
+ return True
+
+
+def _valid_status(value):
+ return (isinstance(value, dict) and "row" in value
+ and isinstance(value.get("app"), str) and len(value["app"]) <= 64
+ and value.get("platform") in ("mac", "pc", "windows", "linux")
+ and value.get("in_force") in ("own", "desk") and _profile_id(value.get("profile"))
+ and isinstance(value.get("waiting"), list) and len(value["waiting"]) <= 32
+ and all(protocol.read_id(peer) is not None for peer in value["waiting"])
+ and (value.get("row") is None or isinstance(value["row"], list) and len(value["row"]) == 2
+ and type(value["row"][0]) is int and 0 <= value["row"][0] <= settings_sync.MAX_STAMP
+ and (value["row"][1] == "" or protocol.read_id(value["row"][1]) is not None)))
+
+
+def _picture(reg):
+ tiles = reg.get("tiles")
+ if not isinstance(tiles, dict) or len(tiles) > 33:
+ return None
+ result = {}
+ for peer, tile in tiles.items():
+ if (protocol.read_id(peer) is None or not isinstance(tile, dict)
+ or any(type(tile.get(key)) is not int for key in ("x", "y", "w", "h"))
+ or tile["w"] <= 0 or tile["h"] <= 0):
+ return None
+ result[peer] = {key: tile[key] for key in ("x", "y", "w", "h")}
+ offsets = tile.get("display_offsets", {})
+ if (not isinstance(offsets, dict) or len(offsets) > 16 or any(
+ not isinstance(key, str) or not key.isascii() or not 1 <= len(key) <= 64
+ or not isinstance(offset, dict) or any(type(offset.get(k)) is not int for k in ("x", "y"))
+ for key, offset in offsets.items())):
+ return None
+ if offsets:
+ result[peer]["display_offsets"] = {key: {k: offset[k] for k in ("x", "y")}
+ for key, offset in offsets.items()}
+ return {"set_at": reg["set_at"], "by": reg["by"], "tiles": result}
+
+
+def _paths(desk):
+ for key in ("on", "active"):
+ if key in desk:
+ yield (key,), desk[key]
+ for pid, profile in desk.get("profiles", {}).items():
+ for key in ("name", "removed", "picture"):
+ if profile.get(key) is not None:
+ yield (key, pid), profile[key]
+ for key, value in profile.get("home", {}).items():
+ yield ("home", pid, key), value
+ for machine, row in profile.get("rows", {}).items():
+ yield ("row", pid, machine), row
+ for machine, status in desk.get("status", {}).items():
+ yield ("status", machine), status
+
+
+def _nest(path, value):
+ """`value` alone at `path`, shaped as _store would place it in an empty desk, not copied."""
+ kind = path[0]
+ if kind in ("on", "active"):
+ return {kind: value}
+ if kind == "status":
+ return {"status": {path[1]: value}}
+ if kind in ("row", "home"):
+ return {"profiles": {path[1]: {"rows" if kind == "row" else "home": {path[2]: value}}}}
+ return {"profiles": {path[1]: {kind: value}}}
+
+
+def _store(desk, path, value):
+ kind = path[0]
+ if kind in ("on", "active"):
+ desk[kind] = copy.deepcopy(value)
+ elif kind == "status":
+ desk.setdefault("status", {})[path[1]] = copy.deepcopy(value)
+ else:
+ profile = desk.setdefault("profiles", {}).setdefault(path[1], {})
+ if kind in ("row", "home"):
+ profile.setdefault("rows" if kind == "row" else "home", {})[path[2]] = copy.deepcopy(value)
+ else:
+ profile[kind] = copy.deepcopy(value)
+
+
+def changed_paths(before, after):
+ """The register paths whose register differs between two desks (each a desk_message), for
+ sending whatever changed a desk, whichever event changed it."""
+ held = dict(_paths(before or {}))
+ return [path for path, register in _paths(after or {}) if held.get(path) != register]
+
+
+def desk_message(settings, paths=None):
+ desk = settings.get("crossing_desk", {})
+ if paths is None:
+ return copy.deepcopy({key: value for key, value in desk.items() if key != "format"})
+ selected = {tuple(path) for path in paths}
+ result = {}
+ for path, value in _paths(desk):
+ if path in selected:
+ _store(result, path, value)
+ return result
+
+
+def read_desk_state(data, now=None):
+ now = _now(now)
+ if not settings_sync._valid_envelope(data, now):
+ return None
+ desk = data.get("desk")
+ if not isinstance(desk, dict):
+ return None
+ try:
+ if len(_json(desk)) > MAX_DESK_BYTES:
+ return None
+ except (TypeError, ValueError, UnicodeError):
+ return None
+ clean = {}
+ # Structural containers are checked before walking them; each leaf stands alone.
+ source = {key: desk[key] for key in ("on", "active") if key in desk}
+ source["status"] = desk.get("status") if isinstance(desk.get("status"), dict) else {}
+ source["profiles"] = {}
+ if isinstance(desk.get("profiles"), dict):
+ for pid, profile in desk["profiles"].items():
+ if not _profile_id(pid) or not isinstance(profile, dict):
+ continue
+ source["profiles"][pid] = {key: profile[key] for key in ("name", "removed", "picture") if key in profile}
+ for key in ("home", "rows"):
+ if isinstance(profile.get(key), dict):
+ source["profiles"][pid][key] = profile[key]
+ for path, reg in _paths(source):
+ if not _valid_stamp(reg, now):
+ continue
+ kind, value = path[0], reg.get("value")
+ good = False
+ if kind == "on":
+ good = type(value) is bool
+ elif kind == "active":
+ good = _profile_id(value)
+ elif kind == "name":
+ good = isinstance(value, str) and 1 <= len(value.strip()) <= 32
+ if good:
+ value = value.strip()
+ elif kind == "removed":
+ _store(clean, path, {"set_at": reg["set_at"], "by": reg["by"]})
+ continue
+ elif kind == "home":
+ good = (path[2] == "shake" and type(value) is bool
+ or path[2] == "sensitivity" and type(value) is int and 50 <= value <= 200)
+ elif kind == "row":
+ good = protocol.read_id(path[2]) is not None and _valid_row(value)
+ if good:
+ value = canonical_row(value)
+ elif kind == "status":
+ good = protocol.read_id(path[1]) is not None and reg["by"] == path[1] and _valid_status(value)
+ if good:
+ value = {key: value[key] for key in ("app", "platform", "in_force", "profile", "row", "waiting")}
+ elif kind == "picture":
+ picture = _picture(reg)
+ if picture is not None:
+ _store(clean, path, picture)
+ continue
+ if good:
+ _store(clean, path, {"value": copy.deepcopy(value), "set_at": reg["set_at"], "by": reg["by"]})
+ return clean
+
+
+def _sort_incoming(desk, incoming, gone, machine):
+ """The incoming registers merge_desk takes, each with its register, and the paths it answers
+ because this desk holds them newer. Read only."""
+ held = dict(_paths(desk))
+ taken, answer = [], []
+ for path, reg in _paths(incoming):
+ if path[0] not in ("on", "active", "status") and path[1] in gone:
+ continue
+ old = held.get(path)
+ if path == ("active",) and reg["value"] in gone:
+ if _pair(reg) > _pair(old):
+ taken.append((path, reg))
+ answer.append(path)
+ elif path[0] == "status" and path[1] == machine:
+ if old is not None and _pair(old) > _pair(reg):
+ answer.append(path)
+ elif _pair(reg) > _pair(old):
+ taken.append((path, reg))
+ elif _pair(old) > _pair(reg):
+ answer.append(path)
+ return taken, answer
+
+
+def merge_desk(settings, state, *, source, now=None, borrow=False):
+ """Take the newer registers of a desk `state` from `source`: (settings, paths, forward, answer,
+ accepted, reason). With `borrow`, a merge that changes nothing hands back `settings` itself, not
+ a copy, for a caller that copies what it keeps."""
+ now = _now(now)
+ unchanged = (lambda: settings) if borrow else (lambda: copy.deepcopy(settings))
+ entry = ways._entry(settings, source)
+ if (entry is None or entry.get("allow_drive") is not True or entry.get("linked") is not True
+ or peerlist.dormant_reason(entry) is not None):
+ return unchanged(), [], {}, {}, False, "not_allowed"
+ incoming = read_desk_state({"on": False, "set_at": 0, "by": "", "desk": state}, now)
+ if incoming is None:
+ return unchanged(), [], {}, {}, False, "invalid_desk"
+ machine, gone = settings.get("machine_id", ""), set(pruned(settings))
+ # The caller's desk is the one before: nothing below writes to `settings`.
+ before = settings["crossing_desk"]
+ taken, answer = _sort_incoming(before, incoming, gone, machine)
+ active = before["active"]["value"]
+ if (not taken and active in before["profiles"] and len(before["profiles"]) <= MAX_HELD
+ and all(isinstance(p, dict) and "rows" in p and "home" in p for p in before["profiles"].values())
+ and not (before["on"]["value"] is True and before["profiles"][active]["rows"].get(machine) is None)):
+ # A duplicate or a stale register, the most of what a mesh relays: the full path below would
+ # copy everything only to change nothing (no container to add, nothing to prune or seed).
+ return unchanged(), [], {}, desk_message(settings, answer), True, ""
+ saved = copy.deepcopy(settings)
+ desk = saved["crossing_desk"]
+ held = dict(_paths(before))
+ for path, reg in taken:
+ if path == ("active",) and reg["value"] in gone:
+ desk["active"] = register(desk["active"]["value"], now, machine, held=desk["active"],
+ floor=reg["set_at"] + 1)
+ continue
+ old = held.get(path)
+ if path[0] == "row" and path[2] == machine and old is not None:
+ archive(saved, old["value"], "replaced_by", now, by=reg["by"])
+ saved["crossing_own"].setdefault("editing", {}).pop(path[1], None)
+ _store(desk, path, reg)
+ taken = [path for path, _ in taken]
+ # Independently forwarded deltas can precede the profile's name/home. Keep
+ # their active stamp and an empty container so later metadata can complete it.
+ active = desk["active"]["value"]
+ desk["profiles"].setdefault(active, {"rows": {}, "home": {}})
+ for profile in desk["profiles"].values():
+ profile.setdefault("rows", {})
+ profile.setdefault("home", {})
+ # MAX_PROFILES limits making one here; two machines apart can each make one, and their union is
+ # still taken, or the desk could never agree. Tombstones past MAX_HELD go oldest first, by the
+ # same rule on every machine, so MAX_HELD only stops a peer flooding the file with live ones.
+ prune_removed(saved, MAX_HELD)
+ if len(desk["profiles"]) > MAX_HELD:
+ return unchanged(), [], {}, {}, False, "desk_full"
+ forward = desk_message(saved, taken)
+ reply = desk_message(saved, answer)
+ paths = apply_transitions(saved, before, now)
+ return saved, paths, forward, reply, True, ""
+
+
+def _shelved_peers(settings):
+ return {entry.get("id") for entry in settings.get("peers", [])
+ if entry.get("left_out") is True or entry.get("in_use", True) is False
+ or peerlist.dormant_reason(entry) is not None}
+
+
+def machines_on_desk(settings):
+ shelved = _shelved_peers(settings)
+ found = [settings.get("machine_id", "")]
+ found.extend(entry.get("id") for entry in settings.get("peers", [])
+ if ways._zoned(entry) and entry.get("id") not in shelved)
+ desk = settings.get("crossing_desk", {})
+ found.extend(desk.get("status", {}))
+ for pid, profile in desk.get("profiles", {}).items():
+ if not removed(desk, pid):
+ found.extend(profile.get("rows", {}))
+ for row in profile.get("rows", {}).values():
+ found.extend(row.get("value", {}))
+ return list(dict.fromkeys(peer for peer in found if peer and peer not in shelved))
+
+
+def view_row(settings, machine):
+ if machine == settings.get("machine_id"):
+ return copy.deepcopy(in_force(settings)[0])
+ desk = settings["crossing_desk"]
+ return copy.deepcopy(desk["profiles"][desk["active"]["value"]].get("rows", {}).get(machine, {}).get("value", {}))
+
+
+def view_platform(settings, machine):
+ """"mac" or "pc", for drawing a machine's row: its own status says, else this machine's guess."""
+ if machine == settings.get("machine_id"):
+ return "mac" if settings.get("crossing_desk", {}).get("status", {}).get(machine, {}).get(
+ "value", {}).get("platform") == "mac" else "pc"
+ status = settings.get("crossing_desk", {}).get("status", {}).get(machine, {}).get("value", {})
+ if status.get("platform"):
+ return "mac" if status["platform"] == "mac" else "pc"
+ return "mac" if (ways._entry(settings, machine) or {}).get("platform") in ("mac", "macos") else "pc"
+
+
+def view_settings(settings, machine):
+ """Settings shaped as `machine` would hold them, so its desk row is drawn by the same ledger and
+ ways.reach as this machine's own: its id, the shared picture, and one entry per other machine in
+ the picture carrying that row's ways. Built field by field: no token, address or permission."""
+ if machine == settings.get("machine_id"):
+ return copy.deepcopy(settings)
+ row = view_row(settings, machine)
+ # Machines not yet in the stored picture sit where the derived layout puts them, as the map
+ # and ways.reach draw them, so none drops out of another machine's view.
+ layout = {**ways.derive_layout(settings, gap=0), **copy.deepcopy(settings.get("layout", {}))}
+ peers = []
+ shelved = _shelved_peers(settings)
+ for ident in layout:
+ if ident == machine:
+ continue
+ intent = row.get(ident) or {"ways": ways._read_intent({"peers": []}, ident), "notch_return": False}
+ contact = ways._rect_contact(layout[machine], layout[ident]) if machine in layout else None
+ peers.append({"id": ident, "name": _name(settings, ident), "port": 24820, "send": True,
+ "allow_drive": True, "in_use": True,
+ **({"left_out": True} if ident in shelved else {}),
+ "side": contact[0] if contact and contact[0] in ways.EDGES else "",
+ "ways": copy.deepcopy(intent["ways"]), "notch_return": intent.get("notch_return") is True})
+ return {"schema": 6, "machine_id": machine, "name": _name(settings, machine), "peers": peers,
+ "zones": [], "layout": layout, "layout_set_at": settings.get("layout_set_at", 0),
+ "layout_by": settings.get("layout_by", "")}
+
+
+def tile_word(settings, machine, *, linked, caps):
+ """The status word on a machine's tile while Same ways is on: Desk, Own, Offline, or Older for a
+ machine without profiles. Empty while Same ways is off."""
+ if not same_ways_on(settings):
+ return ""
+ if machine == settings.get("machine_id"):
+ return tr("Desk") if in_force(settings)[1] else tr("Own")
+ if "profiles" not in caps:
+ # Translators: on a map tile, a machine running a Beamer too old to share ways. Keep it short.
+ return tr("Older")
+ if not linked:
+ return tr("Offline")
+ status = settings.get("crossing_desk", {}).get("status", {}).get(machine, {}).get("value", {})
+ return tr("Own") if status.get("in_force") == "own" else tr("Desk")
+
+
+def _name(settings, machine):
+ if machine == settings.get("machine_id"):
+ return settings.get("name") or tr("This machine")
+ entry = ways._entry(settings, machine) or {}
+ tile = settings.get("layout", {}).get(machine, {})
+ return peerlist._name(entry) or tile.get("name") or machine
+
+
+def machine_line(settings, machine, *, linked, caps, last_heard):
+ """The line under a machine's name on the Crossing page. Its status is restamped only when it
+ changes, so `last_heard` is the time its link came up only while no desk message has arrived
+ from it on that link; the caller passes None once one has."""
+ if "profiles" not in caps:
+ return tr("An older Beamer. Its ways are set on it; update it to set them here. Read only")
+ if not linked:
+ return tr("Offline. It takes these when it next connects")
+ desk = settings["crossing_desk"]
+ status = desk.get("status", {}).get(machine)
+ if status is None:
+ return tr("Sending…")
+ if isinstance(last_heard, (int, float)) and status["set_at"] < last_heard:
+ # This machine's own clock: zoneinfo needs tzdata, which Windows' Python does not ship.
+ when = time.strftime("%d-%m-%Y %H:%M", time.localtime(status["set_at"]))
+ return tr("Last heard {time}").format(time=when)
+ value = status["value"]
+ if value.get("in_force") == "own":
+ return tr("Keeps its own ways. The desk's are saved for when it uses them")
+ if value.get("waiting"):
+ return tr("Needs pairing with {name}").format(name=joined([_name(settings, p) for p in value["waiting"]]))
+ row = desk["profiles"][desk["active"]["value"]].get("rows", {}).get(machine)
+ if (row is None or value.get("profile") != desk["active"]["value"]
+ or value.get("row") != [row["set_at"], row["by"]]):
+ return tr("Sending…")
+ if machine == settings.get("machine_id"):
+ off = [p for p in row["value"] if (ways._entry(settings, p) or {}).get("send") is False]
+ if off:
+ return tr("{name} is off on that machine").format(name=joined([_name(settings, p) for p in off]))
+ return tr("Uses the desk's ways")
+
+
+def no_way_back(settings, machine):
+ desk = settings["crossing_desk"]
+ status = desk.get("status", {})
+ def known_row(ident):
+ value = status.get(ident, {}).get("value")
+ if ident != settings.get("machine_id") and not value and not view_row(settings, ident):
+ # Neither a status nor a desk row (Same ways off, an older Beamer): unknown, not a wall.
+ return None
+ if ident != settings.get("machine_id") and value:
+ if value.get("in_force") == "own":
+ return None # Own rows never travel; absence of knowledge is not a wall.
+ reg = desk["profiles"].get(value.get("profile"), {}).get("rows", {}).get(ident)
+ if reg is None or value.get("row") != [reg["set_at"], reg["by"]]:
+ return None
+ return reg["value"]
+ return view_row(settings, ident)
+ def zones_from(ident):
+ row = known_row(ident)
+ if row is None:
+ return None
+ peers = []
+ shelved = _shelved_peers(settings)
+ for peer, intent in row.items():
+ entry = {"id": peer, "port": 24820, "send": True, **copy.deepcopy(intent)}
+ if ident == settings.get("machine_id"):
+ actual = ways._entry(settings, peer)
+ if actual is None or actual.get("send", True) is False:
+ continue
+ for key in ("send", "in_use", "left_out", "side", "dormant"):
+ if key in actual:
+ entry[key] = actual[key]
+ if peerlist.dormant_reason(actual) is not None:
+ entry["in_use"] = False
+ elif peer in shelved:
+ entry["left_out"] = True
+ peers.append(entry)
+ synthetic = {"machine_id": ident, "peers": peers, "layout": copy.deepcopy(settings.get("layout", {}))}
+ platform = status.get(ident, {}).get("value", {}).get("platform", "pc")
+ compiled = ways.compile_layout(synthetic, synthetic["layout"], platform=platform,
+ capable=set(synthetic["layout"]), now=0)
+ return [zone for zone in compiled.get("settings", {}).get("zones", []) if not zone.get("off")]
+ outgoing = zones_from(machine)
+ if outgoing is None:
+ return []
+ result = []
+ for target in dict.fromkeys(zone["peer"] for zone in outgoing):
+ back = zones_from(target)
+ if back is not None and not any(zone.get("peer") == machine and zone.get("kind") in ("edge", "part")
+ for zone in back):
+ result.append(_name(settings, target))
+ return result
+
+
+def saved_list(settings):
+ return sorted(copy.deepcopy(settings.get("crossing_own", {}).get("saved", [])),
+ key=lambda entry: entry["at"], reverse=True)
+
+
+def shake_on(settings):
+ if not same_ways_on(settings):
+ return settings["crossing_own"]["shake"] is True
+ desk = settings["crossing_desk"]
+ return desk["profiles"][desk["active"]["value"]].get("home", {}).get("shake", {}).get("value", True) is True
+
+
+def shake_sensitivity(settings):
+ if not same_ways_on(settings):
+ value = settings.get("crossing_own", {}).get("shake_sensitivity", 100)
+ else:
+ desk = settings.get("crossing_desk", {})
+ profile = desk.get("profiles", {}).get(desk.get("active", {}).get("value"), {})
+ value = profile.get("home", {}).get("sensitivity", {}).get("value", 100)
+ return value if type(value) is int and 50 <= value <= 200 else 100
+
+
+def profile_list(settings):
+ profiles = settings["crossing_desk"]["profiles"]
+ desk = settings["crossing_desk"]
+ active = {pid: p for pid, p in profiles.items() if not removed(desk, pid) and p.get("name")}
+ result = []
+ for pid, profile in active.items():
+ name = profile["name"]["value"]
+ stamps = [reg["set_at"] for _, reg in _paths({"profiles": {pid: profile}}) if reg["set_at"]]
+ made = min(stamps, default=0)
+ label = name
+ if sum(p["name"]["value"] == name for p in active.values()) > 1:
+ date = time.strftime("%d-%m-%Y", time.localtime(made))
+ label = tr("{name} · {date}").format(name=name, date=date)
+ result.append({"id": pid, "name": name, "label": label, "made": made})
+ return result
diff --git a/core/protocol.py b/core/protocol.py
index dbe72a1..cf9a3d6 100644
--- a/core/protocol.py
+++ b/core/protocol.py
@@ -373,7 +373,8 @@ def _inflated_within(stream, budget):
def settings_msg(data: dict) -> dict:
"""Same on all machines: whether it is on, its stamp and, while on, the shared values, as
settings_sync.message_data builds them. Sent on every change while on and announced on every
- new connection; an older Beamer ignores the type."""
+ new connection. Profile registers use settings_sync.desk_message_data for a
+ separate frame; older peers never receive that optional member."""
return {"type": MSG_SETTINGS, "data": dict(data)}
diff --git a/core/receiver.py b/core/receiver.py
index 4e97056..b3f2c34 100644
--- a/core/receiver.py
+++ b/core/receiver.py
@@ -18,6 +18,7 @@ from typing import Callable, Optional, Tuple
from . import return_edge as crossing
from . import peerlist
from . import protocol
+from .i18n import tr, trc
from .response_time import ResponseTime
@@ -601,7 +602,7 @@ class LinkResponder:
thread = threading.Thread(target=self._server_thread, args=(port, stop_event), name="Beamer-v6-server", daemon=True)
self._stop_event, self._thread, self._port = stop_event, thread, port
self._requested_running = True
- self._set_status(ServerState.WAITING, f"Starting on port {port}")
+ self._set_status(ServerState.WAITING, tr("Starting on port {port}").format(port=port))
thread.start()
def stop(self) -> None:
@@ -624,7 +625,7 @@ class LinkResponder:
with self._lock:
if self._thread is thread:
self._thread = self._stop_event = self._listener = None
- self._set_status(ServerState.STOPPED, "Listening stopped")
+ self._set_status(ServerState.STOPPED, tr("Listening stopped"))
def _server_thread(self, port: int, stop_event: threading.Event) -> None:
try:
@@ -667,7 +668,7 @@ class LinkResponder:
except Exception as exc:
if not stop_event.is_set():
LOGGER.exception("The version 6 listener failed")
- self._set_status(ServerState.ERROR, f"Listener failed: {exc}")
+ self._set_status(ServerState.ERROR, tr("Listener failed: {error}").format(error=exc))
finally:
with self._lock:
listener = self._listener
@@ -690,7 +691,7 @@ class LinkResponder:
if not reported:
reported = True
LOGGER.error("Cannot listen on port %s: %s", port, exc)
- self._set_status(ServerState.ERROR, f"Another program is using port {port} — change the port on the Connection page")
+ self._set_status(ServerState.ERROR, tr("Another program is using port {port} — change the port on the Connection page").format(port=port))
stop_event.wait(BIND_RETRY_SECONDS)
return None
@@ -796,9 +797,9 @@ class LinkResponder:
self._answer(connection, host, protocol.legacy_version_reply() if version is None else protocol.short_reply())
who = peerlist.label_for(self._settings_now()[0], host=host) or host
if version is not None and version > protocol.LINK_VERSION:
- detail = f"{who} runs a newer Beamer: update Beamer on this machine"
+ detail = tr("{name} runs a newer Beamer: update Beamer on this machine").format(name=who)
else:
- detail = f"Update Beamer on {who}: it is older than this one"
+ detail = tr("Update Beamer on {name}: it is older than this one").format(name=who)
LOGGER.warning("%s speaks wire version %r; answered and closed", host, version)
with self._lock:
linked = bool(self._links)
@@ -1036,7 +1037,7 @@ class LinkResponder:
return
link.input_error_at = now
who = peerlist.label_for(self._settings_now()[0], peer_id=protocol.id_text(link.peer_id)) or link.name
- self._set_status(ServerState.CONNECTED, f"Input error from {who}; see log")
+ self._set_status(ServerState.CONNECTED, tr("Input error from {name}; see log").format(name=who))
def _inject_timed_locked(self, link: _Link, read: dict) -> None:
began = time.monotonic()
@@ -1196,7 +1197,12 @@ class LinkResponder:
and zone.get("off") is not True
and zone.get("display") == display and zone.get("side") == side
for zone in zones)
- if has_way and not arrival_covered:
+ # A driver left out here has no zone, yet its input must still have a way home: with
+ # none, every push went on to another machine and back (14-10-2026). A driver whose
+ # edge is merely off keeps no way back, as that is the user's choice for this side.
+ left_out = any(isinstance(entry, dict) and entry.get("id") == peer and entry.get("left_out") is True
+ for entry in peers or ())
+ if (has_way or left_out) and not arrival_covered:
active_zones.append({"peer": peer, "kind": "edge", "display": display,
"side": side, "target_side": crossing.OPPOSITE[side]})
previous = self._armed
@@ -1616,7 +1622,27 @@ class LinkResponder:
display_map = getattr(desktop, "display_map", lambda: {})()
x, y = crossing.arrival_position(desktop.monitors(), focus["edge"], focus["offset"],
focus.get("display"), focus.get("side"), display_map)
- desktop.set_cursor_position(x, y)
+ def placed() -> None:
+ # Windows can defer the warp until GameInput releases the foreground.
+ with self._lock:
+ if self._visit == visit and self._owner is link:
+ for _peer, model in self._armed:
+ model.start_grace()
+
+ def place_if_current(place):
+ with self._lock:
+ if self._visit == visit and self._owner is link:
+ return place()
+ return None
+
+ place_with_callback = getattr(desktop, "set_cursor_position_with_callback", None)
+ if place_with_callback is None:
+ def place():
+ desktop.set_cursor_position(x, y)
+ placed()
+ place_if_current(place)
+ else:
+ place_with_callback(x, y, placed, place_if_current=place_if_current)
LOGGER.info("%s's pointer arrived at this machine's %s edge", link.name,
focus.get("side") if focus.get("display") else focus["edge"])
self._callback("arrival", focus["edge"], x, y)
@@ -1645,7 +1671,7 @@ class LinkResponder:
return
self._unlocking.set()
LOGGER.info("%s's input arrived at a locked machine; asking the provider to unlock", link.name)
- self._set_status(ServerState.CONNECTED, "Unlocking Windows…")
+ self._set_status(ServerState.CONNECTED, tr("Unlocking Windows…"))
threading.Thread(target=self._unlock_worker, args=(unlock, link), name="Beamer-v6-unlock", daemon=True).start()
def _unlock_worker(self, unlock, link: _Link) -> None:
@@ -1661,7 +1687,7 @@ class LinkResponder:
if unlocked or self._owner is not link:
self._report()
else:
- self._set_status(ServerState.CONNECTED, "Windows is locked — unlock it at the PC")
+ self._set_status(ServerState.CONNECTED, tr("Windows is locked — unlock it at the PC"))
def _home_if_locked(self, link: _Link) -> None:
"""An owner left driving a machine on its lock screen is sent home,
@@ -1749,9 +1775,9 @@ class LinkResponder:
peers = self._settings_now()[0]
names = sorted(peerlist.label_for(peers, peer_id=protocol.id_text(link.peer_id)) or link.name for link in links)
if names:
- self._set_status(ServerState.CONNECTED, "Connected to " + ", ".join(names))
+ self._set_status(ServerState.CONNECTED, tr("Connected to {names}").format(names=trc("list", ", ").join(names)))
else:
- self._set_status(ServerState.WAITING, f"Waiting on port {port}")
+ self._set_status(ServerState.WAITING, tr("Waiting on port {port}").format(port=port))
def _set_status(self, state: ServerState, detail: str) -> None:
try:
diff --git a/core/settings_sync.py b/core/settings_sync.py
index b4288f6..371d76c 100644
--- a/core/settings_sync.py
+++ b/core/settings_sync.py
@@ -22,11 +22,13 @@ screen, whether a full-screen app holds the edges, appearance, and per-system ke
"""
import base64
+import copy
import binascii
import re
import time
from . import effects
+from .i18n import N_, tr, trc
from .protocol import MACHINE_ID_SIZE, MAX_PEERS
TRIGGER_STYLES = ("double_tap", "hold")
@@ -43,10 +45,13 @@ DESIGN_KEYS = ("glow_style", "glow_colour", "effect_length", "effect_size", "eff
"effect_size_fraction", "frame_rate", "shortcut_arrival", "shortcut_arrival_style")
GROUP_KEYS = {"crossing": CROSSING_GROUP_KEYS, "design": DESIGN_KEYS, "shortcut": SHORTCUT_KEYS, "names": ()}
ALL_GROUPS = tuple(GROUP_KEYS)
-DESIGN_UNAVAILABLE = "Design not available yet: connect to this machine with Beamer 1.5.0 beta.6 or later."
-NEEDS_DESIGN_SYNC = "Needs beta.6 or later"
-OLD_PEER_NOTE = "A connected machine is unavailable until it has beta.6 or later."
-NO_MACHINE_CONNECTED = "No paired machine is connected."
+DESIGN_UNAVAILABLE = N_("Design not available yet: connect to this machine with Beamer 1.5.0 beta.6 or later.")
+NEEDS_DESIGN_SYNC = N_("Needs beta.6 or later")
+OLD_PEER_NOTE = N_("A connected machine is unavailable until it has beta.6 or later.")
+NO_MACHINE_CONNECTED = N_("No paired machine is connected.")
+GROUP_LABELS = {"crossing": N_("Crossing"), "design": N_("Design"), "shortcut": N_("Shortcut"), "names": N_("Names")}
+SHARED_LABELS = {"Resistance": N_("Resistance"), "drag protection": N_("drag protection"),
+ "Shortcut": N_("Shortcut")}
MAX_STAMP = 2 ** 53 - 2
DAY = 24 * 60 * 60
@@ -406,6 +411,8 @@ def layout_recipients(peers, source=None):
def for_capabilities(data, capabilities):
"""Drop optional settings members a peer did not advertise support for."""
result = dict(data)
+ if "profiles" not in capabilities:
+ result.pop("desk", None)
if "layout" not in capabilities:
result.pop("layout", None)
elif "displays" not in capabilities and isinstance(result.get("layout"), dict):
@@ -419,6 +426,14 @@ def for_capabilities(data, capabilities):
return result
+def desk_message_data(envelope_data, desk):
+ """Repeat only the settings envelope, keeping the bounded desk in its own frame."""
+ result = {key: copy.deepcopy(envelope_data[key]) for key in ("on", "set_at", "by", "groups")
+ if key in envelope_data}
+ result["desk"] = copy.deepcopy(desk)
+ return result
+
+
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
@@ -510,10 +525,10 @@ def follow_note(rows):
or None when one can. Offline machines are not listed, so they never set it."""
reasons = [why_not for _entry, why_not in rows]
if not reasons:
- return NO_MACHINE_CONNECTED
+ return tr(NO_MACHINE_CONNECTED)
if None in reasons:
return None
- return OLD_PEER_NOTE if NEEDS_DESIGN_SYNC in reasons else DESIGN_UNAVAILABLE
+ return tr(OLD_PEER_NOTE if NEEDS_DESIGN_SYNC in reasons else DESIGN_UNAVAILABLE)
STOP_FOLLOWING = "Stop following"
@@ -530,7 +545,7 @@ def follow_lock(following, same_on, desktops):
def following_banner(name):
- return f"Following {name}'s design"
+ return tr("Following {name}'s design").format(name=name)
def design_change_stamp(current, incoming, set_at_here, source_state, own_id, now=None):
@@ -847,9 +862,10 @@ SHARED_PAGES = ("crossing", "design")
def group_note(groups, on):
if not on:
- return "Off: each machine keeps its current values."
+ return tr("Off: each machine keeps its current values.")
selected = normalise_groups(groups)
- return "Shares " + ", ".join(group.capitalize() for group in selected) + " with compatible paired machines."
+ names = trc("list", ", ").join(tr(GROUP_LABELS[group]) for group in selected)
+ return tr("Shares {groups} with compatible paired machines.").format(groups=names)
def who(labels):
@@ -871,30 +887,29 @@ def scope(page, who, on, own, platform="", groups=None):
if "shortcut" in selected:
shared.append("Shortcut")
if not shared:
- return own
- return ", ".join(shared) + " stay in step. Ways and jump keys below are local; each side is shared with its paired machine."
- return "Resistance, drag protection and Shortcut stay in step. Ways and jump keys below are local; each side is shared with its paired machine."
+ return tr(own)
+ return tr("{shared} stay in step. Ways and jump keys below are local; each side is shared with its paired machine.").format(
+ shared=trc("list", ", ").join(tr(SHARED_LABELS[item]) for item in shared))
+ return tr("Resistance, drag protection and Shortcut stay in step. Ways and jump keys below are local; each side is shared with its paired machine.")
if "design" not in selected:
- return own
- text = "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local."
+ return tr(own)
if platform == "mac":
- text += " Notch and trackpad controls stay local."
- return text
- return own
+ return tr("Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local. Notch and trackpad controls stay local.")
+ return tr("Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local.")
+ return tr(own)
def switch_note(who, on, peer_too_old):
"""The note under Overview's Same on all machines switch; `who` names the machines it keeps in step with."""
if peer_too_old:
- return f"{who}'s Beamer is too old to keep settings in step. Update it to turn this on."
+ return tr("{name}'s Beamer is too old to keep settings in step. Update it to turn this on.").format(name=who)
if not on:
- return "Off: each machine keeps its current values; previous separate values are not restored."
- with_machines = "compatible paired machines" if who == "every paired machine" else f"compatible versions of {who}"
- return "Shares resistance, drag protection, Shortcut and six animation settings with " + with_machines + "."
+ return tr("Off: each machine keeps its current values; previous separate values are not restored.")
+ with_machines = tr("compatible paired machines") if who == "every paired machine" else tr("compatible versions of {name}").format(name=who)
+ return tr("Shares resistance, drag protection, Shortcut and six animation settings with {machines}.").format(machines=with_machines)
def switch_detail(platform=""):
- text = "Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine."
if platform == "mac":
- text += " Notch and trackpad controls stay on this Mac."
- return text
+ return tr("Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine. Notch and trackpad controls stay on this Mac.")
+ return tr("Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine.")
diff --git a/core/shake.py b/core/shake.py
new file mode 100644
index 0000000..8f30551
--- /dev/null
+++ b/core/shake.py
@@ -0,0 +1,192 @@
+"""Clock-free shake-to-come-home detection for relative mouse motion."""
+
+from collections import deque
+
+
+# Capture units differ by backend and device; these are hardware-tuned starting values, not inches.
+STROKE_MAC = 48.0
+STROKE_WINDOWS = 192.0
+STROKE_X11 = 192.0
+STROKE_WAYLAND = 48.0
+
+
+def stroke_at_sensitivity(stroke, sensitivity):
+ """Scale the capture backend's stroke length by the shared 50–200% preference."""
+ return float(stroke) * 100 / int(sensitivity)
+
+_WINDOW = 0.650
+_PAUSE = 0.120
+_ARM_DELAY = 0.300
+_SCROLL_QUIET = 0.250
+_REFRACTORY = 1.500
+_TURN_FRACTION = 0.25
+_EPSILON = 1e-9
+
+
+class ShakeDetector:
+ def __init__(self, stroke=48.0):
+ self.stroke = float(stroke)
+ self._armed_at = None
+ self._cooldown_until = 0.0
+ self._scroll_until = 0.0
+ self._held = False
+ self._events = deque()
+ self.reset()
+
+ def arm(self, t):
+ # The 1.5 s after a shake still holds: crossing straight back out must not re-arm it early.
+ self._armed_at = float(t) + _ARM_DELAY
+ self._held = False
+ self._scroll_until = 0.0
+ self.reset()
+
+ def set_stroke(self, stroke):
+ stroke = float(stroke)
+ if stroke != self.stroke:
+ self.stroke = stroke
+ self.reset()
+
+ def disarm(self):
+ self._armed_at = None
+ self._held = False
+ self.reset()
+
+ def reset(self):
+ self._events.clear()
+ self._samples = []
+ self._axis = None
+ self._position = 0.0
+ self._cross = 0.0
+ self._event_count = 0
+ self._direction = 0
+ self._anchor = None
+ self._extreme = None
+ self._reverse = 0.0
+ self._strokes = deque()
+ self._last_t = None
+
+ def scroll(self, t):
+ self.reset()
+ self._scroll_until = float(t) + _SCROLL_QUIET
+
+ def held(self, t, anything_held):
+ self.reset()
+ self._held = bool(anything_held)
+
+ def motion(self, t, dx, dy):
+ t, dx, dy = float(t), float(dx), float(dy)
+ if self._armed_at is None or self._held:
+ return False
+ if t < self._armed_at or t < self._cooldown_until or t < self._scroll_until:
+ self.reset()
+ return False
+ if self._last_t is not None and t - self._last_t >= _PAUSE:
+ self.reset()
+ self._last_t = t
+ if dx == 0 and dy == 0:
+ return False
+
+ self._events.append((t, dx, dy))
+ while self._events and t - self._events[0][0] > _WINDOW:
+ self._events.popleft()
+ x_travel = sum(abs(event[1]) for event in self._events)
+ y_travel = sum(abs(event[2]) for event in self._events)
+ axis = 0 if x_travel >= y_travel else 1
+ if self._axis is not None and axis != self._axis:
+ self.reset()
+ self._events.append((t, dx, dy))
+ axis = 0 if abs(dx) >= abs(dy) else 1
+ if self._axis is None:
+ self._axis = axis
+
+ along = dx if self._axis == 0 else dy
+ across = dy if self._axis == 0 else dx
+ if not self._samples:
+ self._samples.append((t, self._position, self._cross, self._event_count))
+ self._position += along
+ self._cross += abs(across)
+ self._event_count += 1
+ self._samples.append((t, self._position, self._cross, self._event_count))
+
+ if self._direction == 0:
+ if along:
+ self._direction = 1 if along > 0 else -1
+ self._anchor = 0
+ self._extreme = 1
+ return False
+
+ if self._direction * (self._position - self._samples[self._extreme][1]) > 0:
+ self._extreme = len(self._samples) - 1
+ self._reverse = 0.0
+ else:
+ self._reverse = max(
+ 0.0,
+ -self._direction * (self._position - self._samples[self._extreme][1]),
+ )
+
+ if self._reverse < self.stroke * _TURN_FRACTION:
+ return False
+
+ extreme = self._samples[self._extreme]
+ anchor = self._samples[self._anchor]
+ stroke_events = max(0, extreme[3] - anchor[3])
+ stroke = {
+ "start": anchor[1],
+ "start_t": anchor[0],
+ "end": extreme[1],
+ "distance": abs(extreme[1] - anchor[1]),
+ "duration": max(0.0, extreme[0] - anchor[0]),
+ "events": stroke_events,
+ "cross": max(0.0, extreme[2] - anchor[2]),
+ "turn_t": t,
+ }
+ self._strokes.append(stroke)
+ while self._strokes and t - self._strokes[0]["start_t"] > _WINDOW:
+ self._strokes.popleft()
+
+ fired = self._qualifies()
+ self._anchor = self._extreme
+ self._direction *= -1
+ self._reverse = 0.0
+ self._extreme = self._anchor
+ self._samples = self._samples[self._anchor:]
+ self._anchor = 0
+ self._extreme = 0
+ if fired:
+ self._cooldown_until = t + _REFRACTORY
+ self.reset()
+ self._last_t = t
+ return True
+ return False
+
+ def _qualifies(self):
+ if len(self._strokes) < 4:
+ return False
+ strokes = list(self._strokes)[-4:]
+ if any(
+ s["distance"] + _EPSILON < self.stroke
+ or not 0.030 - _EPSILON <= s["duration"] <= 0.200 + _EPSILON
+ or s["events"] < 2
+ or s["distance"] / s["duration"] + _EPSILON < 6 * self.stroke
+ for s in strokes
+ ):
+ return False
+ total = sum(s["distance"] for s in strokes)
+ if total + _EPSILON < 5 * self.stroke:
+ return False
+ if abs(strokes[-1]["end"] - strokes[0]["start"]) > 2 * self.stroke + _EPSILON:
+ return False
+ if sum(s["cross"] for s in strokes) > total / 2 + _EPSILON:
+ return False
+ return True
+
+
+class HomeHold:
+ def __init__(self):
+ self._last_motion = None
+
+ def motion(self, t):
+ self._last_motion = float(t)
+
+ def blocks(self, t):
+ return self._last_motion is not None and float(t) < self._last_motion + 0.200
diff --git a/core/tests/app_methods.py b/core/tests/app_methods.py
index 21b5c27..f1f1788 100644
--- a/core/tests/app_methods.py
+++ b/core/tests/app_methods.py
@@ -12,5 +12,8 @@ def load_methods(relative_path, class_name, names, namespace):
for method in methods:
method.decorator_list = []
module = ast.Module(body=methods, type_ignores=[])
+ from core import i18n
+ for name in ("tr", "trn", "trc", "N_", "joined", "matches_translation"):
+ namespace.setdefault(name, getattr(i18n, name))
exec(compile(module, str(path), "exec"), namespace)
return type(class_name, (), {name: namespace[name] for name in names})
diff --git a/core/tests/crossing_harness.py b/core/tests/crossing_harness.py
index f997813..bedb1cc 100644
--- a/core/tests/crossing_harness.py
+++ b/core/tests/crossing_harness.py
@@ -138,7 +138,7 @@ class Hand:
def connect(self, other):
link = Initiator(other.machine, self.desk.own, key(self.desk.own, other.own))
welcome = link.handshake(hello=link.hello(id=self.desk.own, name=self.desk.name,
- platform=self.desk.platform_name, caps=list(CAPS)))
+ platform=self.desk.platform_name, caps=list(self.desk.caps)))
with self.lock:
self.links[text(other.own)] = link
self.capabilities[text(other.own)] = set(welcome["caps"])
@@ -245,7 +245,7 @@ class Desk:
"""One machine. `platform` is "mac" or "pc"; `displays` maps the app's display keys to their
rectangles in its own pixels (points on a Mac)."""
- def __init__(self, net, own, name, platform, displays, tile=(160, 100)):
+ def __init__(self, net, own, name, platform, displays, tile=(160, 100), profiles=False):
self.net = net
self.own = own
self.id = text(own)
@@ -254,8 +254,10 @@ class Desk:
self.platform_name = "macos" if platform == "mac" else "windows"
self.screen = Screen(displays)
self.tile_size = tile
+ self.profiles = profiles
+ self.caps = CAPS + ["profiles"] if profiles else list(CAPS)
self.lock = threading.RLock()
- self.machine = Machine([], [], caps=CAPS, desktop=self.screen, own=own, name=name)
+ self.machine = Machine([], [], caps=self.caps, desktop=self.screen, own=own, name=name)
self.machine.settings.data.update({"layout": {}, "layout_set_at": 0, "layout_by": "",
"same_on_both": False})
self.machine.book = receiver.PeerBook(self.machine.settings.load, self.machine.settings.save, self.lock)
@@ -333,8 +335,9 @@ class Net:
self.desks = {}
self.shells = shells
- def add(self, name, platform, displays, seed, tile=(160, 100)):
- desk = Desk(self, ident(seed), name, platform, displays, tile)
+ def add(self, name, platform, displays, seed, tile=(160, 100), profiles=False):
+ """`profiles` makes it a 1.5.5 desk: it advertises `profiles` and its shell syncs the desk."""
+ desk = Desk(self, ident(seed), name, platform, displays, tile, profiles)
self.test.addCleanup(desk.hand.close)
desk.shell = self.shells[platform](desk)
self.test.addCleanup(desk.shell.stop)
diff --git a/core/tests/crossing_shells.py b/core/tests/crossing_shells.py
index 8ce4bc2..431d9fa 100644
--- a/core/tests/crossing_shells.py
+++ b/core/tests/crossing_shells.py
@@ -6,10 +6,12 @@ The harness uses real responders, owners and wire messages beneath these shells.
"""
import copy
+import json
import threading
import time
+import traceback
-from core import crossing_state, protocol, return_edge, settings_sync, ways
+from core import crossing_state, profiles, protocol, return_edge, settings_sync, ways
SNAP_RADIUS = 12
@@ -23,6 +25,10 @@ class Shell:
self.handled_count = 0
self.lock = threading.RLock()
self.refused = []
+ self.refused_desks = []
+ self.skew = 0
+ self.frames = []
+ self.errors = []
callbacks = desk.machine.responder._callbacks
callbacks["arrangement"] = self._arrangement_arrived
callbacks["settings"] = self._settings_arrived
@@ -42,19 +48,68 @@ class Shell:
def current(self):
return copy.deepcopy(self.desk.settings)
+ def now(self):
+ """This machine's clock, `skew` seconds off the real one."""
+ return time.time() + self.skew
+
def _args(self):
- return dict(platform=self.platform, live=self.live, gone=self.gone, now=time.time())
+ return dict(platform=self.platform, live=self.live, gone=self.gone, now=self.now())
def _send(self, peer, message):
if self.desk.hand.send(peer, message):
self.sent_count += 1
+ data = message.get("data") or {}
+ self.frames.append({"peer": peer, "type": message.get("type"), "desk": "desk" in data,
+ "size": len(json.dumps(message, separators=(",", ":")).encode("utf-8"))})
return True
return False
+ # Desk sync, as the 1.5.5 apps do it. A desk that does not advertise `profiles` keeps
+ # the 1.5.3 behaviour: no crossing_own, nothing sent or taken.
+
+ def profile_aware(self):
+ return self.desk.profiles
+
+ def load(self, settings):
+ """The apps' load path: profiles.before_load, the app's normalisation (the PC's
+ crossing_state.migrate), profiles.after_load."""
+ saved, _ = profiles.before_load(settings, now=self.now())
+ saved = crossing_state.migrate(saved, self.platform)["settings"]
+ saved, _ = profiles.after_load(saved, platform=self.platform, now=self.now())
+ settings.clear()
+ settings.update(saved)
+
+ def profile_peers(self, exclude=None):
+ """Linked peers that advertise `profiles`, never `exclude`."""
+ return [peer for peer in self.desk.hand.links if peer != exclude
+ and "profiles" in self.desk.hand.capabilities.get(peer, ())]
+
+ def send_desk(self, peers, desk):
+ if not desk:
+ return
+ envelope = settings_sync.message_data(False, self.current().get("same_set_at", 0), {}, by=self.desk.id)
+ frames = profiles.frames(desk)
+ for peer in peers:
+ for frame in frames:
+ self._send(peer, protocol.settings_msg(settings_sync.desk_message_data(envelope, frame)))
+
+ def send_desk_outcome(self, outcome, source=None):
+ if not self.profile_aware():
+ return
+ if outcome["send_desk"]:
+ self.send_desk(self.profile_peers(), profiles.desk_message(outcome["settings"], outcome["send_desk"]))
+ if outcome["forward"]:
+ self.send_desk(self.profile_peers(exclude=source), outcome["forward"])
+ if outcome["answer"] and source is not None and source in self.profile_peers():
+ self.send_desk([source], outcome["answer"])
+
def _arrangement_arrived(self, peer, read):
try:
with self.lock:
self.on_arrangement(protocol.id_text(peer), read)
+ except Exception:
+ self.errors.append(traceback.format_exc())
+ raise
finally:
self.handled_count += 1
@@ -62,6 +117,9 @@ class Shell:
try:
with self.lock:
self.on_settings(protocol.id_text(peer), data)
+ except Exception:
+ self.errors.append(traceback.format_exc())
+ raise
finally:
self.handled_count += 1
@@ -74,15 +132,18 @@ class Shell:
self.send_same()
if outcome["forward_picture"] and arrived is not None:
self.send_same(exclude=source, data=arrived)
+ self.send_desk_outcome(outcome, source)
if outcome["changed"]:
self.after_change()
return outcome
def paired(self, settings):
outcome = crossing_state.paired(settings, platform=self.platform,
- own_displays=self.desk.screen.display_map(), now=time.time())
+ own_displays=self.desk.screen.display_map(), now=self.now())
settings.clear()
settings.update(outcome["settings"])
+ if self.profile_aware():
+ self.load(settings)
def same_state(self):
settings = self.current()
@@ -105,8 +166,10 @@ class Shell:
def link_up(self, other):
with self.lock:
outcome = crossing_state.link_up(self.current(), other.id, platform=self.platform,
- own_displays=self.desk.screen.display_map(), now=time.time(), capable=self.capable())
+ own_displays=self.desk.screen.display_map(), now=self.now(), capable=self.capable())
self.carry_out(outcome)
+ if self.profile_aware() and other.id in self.profile_peers():
+ self.send_desk([other.id], profiles.desk_message(self.current()))
def tell(self, peer):
settings = self.current()
@@ -205,10 +268,37 @@ class Shell:
return self.carry_out(crossing_state.put_back(self.current(), other.id,
capable=self.capable(), **self._args()))
+ # What a person does on the Crossing page's profile controls.
+
+ def _desk_event(self, event, *args, capable=True, **kwargs):
+ with self.lock:
+ kwargs.update(platform=self.platform, now=self.now())
+ if capable:
+ kwargs.update(capable=self.capable(), live=self.live, gone=self.gone)
+ outcome = event(self.current(), *args, **kwargs)
+ self.carry_out(outcome)
+ return outcome
+
+ def same_ways(self, on):
+ return self._desk_event(crossing_state.set_same_ways, bool(on))
+
+ def own_ways(self, use_own):
+ return self._desk_event(crossing_state.set_own_ways, bool(use_own))
+
+ def edit_other(self, machine, peer, **choices):
+ return self._desk_event(crossing_state.edit_other, getattr(machine, "id", machine),
+ getattr(peer, "id", peer), capable=False, **choices)
+
+ def new_profile(self, name):
+ return self._desk_event(crossing_state.new_profile, name, capable=False)
+
+ def switch_profile(self, profile_id):
+ return self._desk_event(crossing_state.switch_profile, profile_id)
+
def displays_changed(self):
with self.lock:
return self.carry_out(crossing_state.displays_changed(self.current(), platform=self.platform,
- own_displays=self.desk.screen.display_map(), now=time.time(),
+ own_displays=self.desk.screen.display_map(), now=self.now(),
capable=self.capable()))
def on_arrangement(self, peer, read):
@@ -217,6 +307,19 @@ class Shell:
return self.carry_out(outcome)["changed"]
def on_settings(self, peer, data):
+ if "desk" in data:
+ if not self.profile_aware():
+ return False
+ state = profiles.read_desk_state(data, now=self.now())
+ if state is None:
+ return False
+ entry = ways._entry(self.current(), peer)
+ outcome = crossing_state.desk_arrived(
+ self.current(), state, source=peer, linked=bool(entry and entry.get("linked") is True),
+ capable=self.capable(), **self._args())
+ if not outcome["accepted"]:
+ self.refused_desks.append((peer, outcome["reason"]))
+ return self.carry_out(outcome, source=peer)["changed"]
state = settings_sync.read_layout_state(data)
if state is None:
return False
diff --git a/core/tests/responder_harness.py b/core/tests/responder_harness.py
index ad9de8e..d6ba3c3 100644
--- a/core/tests/responder_harness.py
+++ b/core/tests/responder_harness.py
@@ -248,6 +248,8 @@ class Initiator:
self.peer = peer
self.token = key or TOKENS[peer]
self.sock = socket.create_connection(("127.0.0.1", machine.port), timeout=5)
+ # As core/link.py's initiator: with Nagle on, a burst waits on the first frame's ACK.
+ self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.session = protocol.LinkSession(self.token, protocol.ROLE_INITIATOR)
self.inbox = queue.Queue()
self.seen = []
diff --git a/core/tests/settings_behaviour.py b/core/tests/settings_behaviour.py
index d5d905e..74444dc 100644
--- a/core/tests/settings_behaviour.py
+++ b/core/tests/settings_behaviour.py
@@ -15,6 +15,7 @@ from typing import Optional
from unittest import TestCase
from core import protocol, settings_sync, ways, peerlist
+from core.i18n import tr
from core.tests.app_methods import load_methods
ROOT = Path(__file__).resolve().parents[2]
@@ -171,8 +172,19 @@ def reflect_shortcut_visibility(app, platform):
platform=system_platform,
OWN_PLATFORM="windows",
TRIGGER_KEYS=SimpleNamespace(get=stop))
+ namespace["profiles"] = importlib.import_module("core.profiles")
+ namespace["tr"] = importlib.import_module("core.i18n").tr
cls = load_methods("win_app/kvm_bridge_win.py", "WindowsApplication", ["_reflect_ways"], namespace)
app._crossing_settings = lambda: {"machine_id": app._config.machine_id, "peers": [], "zones": []}
+ # Crossing profiles (1.5.5): Same ways off, so the page shows this machine's own settings.
+ app._profile_settings = app._crossing_settings
+ app._crossing_view_settings = app._crossing_settings
+ app._reflect_profiles = lambda _settings: None
+ app._profile_remote = lambda: False
+ app._profile_machine_name = lambda _settings, peer: peer
+ app._profile_live = lambda _peer: False
+ app._profile_caps = lambda _peer, _settings: set()
+ app._profile_read_only = lambda: False
app._crossing_machines = lambda: []
app._chosen_machine = lambda: None
app._rebuild_machine_choice = lambda values: None
@@ -260,7 +272,7 @@ def status_fixture(platform, caps, cached=False, following=False, offline=()):
app.cfg().design_follow_peer = IDS[0] if following else ""
app._design_peer_caps = lambda: caps
app._lock_followed_design = lambda entry, name: setattr(app, "locked_to", entry)
- namespace = dict(settings_sync=settings_sync, peerlist=peerlist, protocol=protocol)
+ namespace = dict(settings_sync=settings_sync, peerlist=peerlist, protocol=protocol, tr=tr)
if platform == "mac":
class MenuChoice:
def __init__(self, choices, **kwargs):
diff --git a/core/tests/test_arrival_grace.py b/core/tests/test_arrival_grace.py
index 78f3fa8..3bd3838 100644
--- a/core/tests/test_arrival_grace.py
+++ b/core/tests/test_arrival_grace.py
@@ -1,5 +1,6 @@
import collections
import logging
+import threading
import unittest
from types import SimpleNamespace
from unittest import mock
@@ -40,6 +41,18 @@ class ReturnEdgeArrivalGrace(unittest.TestCase):
self.assertEqual(outcome.action, return_edge.CROSS)
+ def test_all_wrapped_edges_hold_briefly_then_allow_a_deliberate_push(self):
+ for side, pointer, delta in (("left", (0, 50), (-20, 0)),
+ ("right", (99, 50), (20, 0)),
+ ("top", (50, 0), (0, -20)),
+ ("bottom", (50, 99), (0, 20))):
+ with self.subTest(side=side):
+ edge = return_edge.ReturnEdge(side, resistance_px=10, clock=self.clock)
+ edge.start_grace()
+ self.assertEqual(edge.feed(MONITORS, pointer, *delta).action, return_edge.HOLD)
+ self.clock.now += return_edge.ARRIVAL_GRACE_SECONDS + 0.01
+ self.assertEqual(edge.feed(MONITORS, pointer, *delta).action, return_edge.CROSS)
+
def test_four_pixels_inward_ends_grace(self):
self.edge.start_grace()
self.assertEqual(self.edge.feed(MONITORS, (95, 50), -4, 0).action, return_edge.PASS)
@@ -118,7 +131,89 @@ class ReturnEdgeArrivalGrace(unittest.TestCase):
self.assertEqual(self._take({"stay": False, "edge": "right", "offset": 0.5}),
(return_edge.HOLD, return_edge.HOLD))
- def _take(self, how):
+ def test_edge_take_protects_the_old_pointer_before_placement(self):
+ self.assertEqual(self._take({"stay": False, "edge": "right", "offset": 0.5}, land=False),
+ (return_edge.HOLD, return_edge.HOLD))
+
+ def test_arrival_grace_starts_when_the_pointer_is_placed(self):
+ edge = return_edge.ReturnEdge("left", resistance_px=10, clock=self.clock)
+ edge.start_grace()
+ original_arrival = edge._arrival_at
+ link = SimpleNamespace(peer_id=b"owner-peer-id!!!", name="Owner")
+ pending = []
+
+ def set_cursor_position_with_callback(x, y, on_placed, *, place_if_current):
+ pending.append(lambda: place_if_current(on_placed))
+ self.clock.now += return_edge.ARRIVAL_GRACE_SECONDS + 0.05
+
+ desktop = SimpleNamespace(monitors=lambda: MONITORS, display_map=lambda: {},
+ set_cursor_position_with_callback=set_cursor_position_with_callback)
+ responder_instance = receiver.LinkResponder.__new__(receiver.LinkResponder)
+ responder_instance._lock = threading.RLock()
+ responder_instance._owner = link
+ responder_instance._visit = 1
+ responder_instance._arriving_visit = 1
+ responder_instance._armed = [(protocol.id_text(link.peer_id), edge)]
+ responder_instance._callbacks = {"arrival": mock.Mock()}
+
+ with mock.patch.object(receiver.LinkResponder, "_desktop_module", return_value=desktop), \
+ mock.patch.object(receiver.LinkResponder, "_begin_unlock"):
+ responder_instance._land(link, {"edge": "left", "offset": 0.5}, 1)
+
+ self.assertEqual(edge._arrival_at, original_arrival)
+
+ pending.pop()()
+ self.assertEqual(edge._arrival_at, self.clock.now)
+ outcome = edge.feed(MONITORS, (0, 50), -10, 0)
+
+ self.assertEqual(outcome.action, return_edge.HOLD)
+
+ def test_visit_cannot_change_between_deferred_validation_and_warp(self):
+ link = SimpleNamespace(name="Owner")
+ responder = receiver.LinkResponder.__new__(receiver.LinkResponder)
+ responder._lock = threading.RLock()
+ responder._owner, responder._visit = link, 1
+ responder._arriving_visit, responder._armed = 1, []
+ responder._callbacks = {"arrival": None}
+ retries, warped_for = [], []
+
+ def warp():
+ def replace_visit_if_unlocked():
+ if responder._lock.acquire(blocking=False):
+ try:
+ responder._owner, responder._visit = None, 2
+ finally:
+ responder._lock.release()
+ contender = threading.Thread(target=replace_visit_if_unlocked)
+ contender.start()
+ contender.join(2)
+ self.assertFalse(contender.is_alive())
+ warped_for.append(responder._visit)
+ return True
+
+ def defer(x, y, placed, *, place_if_current):
+ def retry():
+ def place():
+ result = warp()
+ placed()
+ return result
+ place_if_current(place)
+ retries.append(retry)
+
+ desktop = SimpleNamespace(monitors=lambda: MONITORS, display_map=lambda: {},
+ set_cursor_position_with_callback=defer)
+ with mock.patch.object(receiver.LinkResponder, "_desktop_module", return_value=desktop), \
+ mock.patch.object(receiver.LinkResponder, "_begin_unlock"):
+ responder._land(link, {"edge": "left", "offset": 0.5}, 1)
+ retry = retries.pop()
+ retry()
+ self.assertEqual(warped_for, [1])
+ with responder._lock:
+ responder._owner, responder._visit = None, 2
+ retry()
+ self.assertEqual(warped_for, [1])
+
+ def _take(self, how, land=True):
owner_peer, other_peer = b"owner-peer-id!!!", b"other-peer-id!!!"
owner_peer_id, other_peer_id = protocol.id_text(owner_peer), protocol.id_text(other_peer)
peers = [
@@ -137,6 +232,8 @@ class ReturnEdgeArrivalGrace(unittest.TestCase):
responder_instance._armed = []
responder_instance._zones_live = False
responder_instance._visit = 0
+ responder_instance._lock = threading.RLock()
+ responder_instance._callbacks = {"arrival": None}
responder_instance._clipboard_mark = None
responder_instance._sent_home_for_lock = False
responder_instance._locked_since = None
@@ -145,7 +242,14 @@ class ReturnEdgeArrivalGrace(unittest.TestCase):
link = SimpleNamespace(peer_id=owner_peer, own_id=b"this-machine-id!", name="Owner")
focus = {"reach": (other_peer,), "resistance_px": 10, **how}
- responder_instance._own_locked(link, focus, peers, zones)
+ after = responder_instance._own_locked(link, focus, peers, zones)
+ if not focus["stay"] and land:
+ desktop = SimpleNamespace(monitors=lambda: MONITORS, display_map=lambda: {},
+ set_cursor_position=mock.Mock())
+ with mock.patch.object(receiver.LinkResponder, "_desktop_module", return_value=desktop), \
+ mock.patch.object(receiver.LinkResponder, "_begin_unlock"):
+ for step in after:
+ step()
models = dict(responder_instance._armed)
return (models[owner_peer].feed(MONITORS, (99, 50), 10, 0).action,
diff --git a/core/tests/test_crash_log.py b/core/tests/test_crash_log.py
index 0b7620c..de94800 100644
--- a/core/tests/test_crash_log.py
+++ b/core/tests/test_crash_log.py
@@ -50,26 +50,52 @@ class AThreadThatRaises(unittest.TestCase):
self.assertIs(record.exc_info[0], ValueError)
[email protected](hasattr(os, "kill") and sys.platform != "win32", "a fatal signal is a POSIX test")
+def _run_child(directory, ending):
+ script = (
+ "import os, signal, threading, time\n"
+ "from core import crash_log\n"
+ f"crash_log.install({directory!r}, fatal_signals=True)\n"
+ "def waits_on_the_link():\n"
+ " time.sleep(30)\n"
+ "threading.Thread(target=waits_on_the_link, daemon=True).start()\n"
+ "time.sleep(0.2)\n"
+ + ending
+ )
+ result = subprocess.run([sys.executable, "-c", script], cwd=REPO, capture_output=True, timeout=30)
+ return result, (Path(directory) / "crash.log").read_text(encoding="utf-8")
+
+
+# Not on macOS: a real fatal signal there makes ReportCrash put a crash report and its dialog on
+# the desktop of whoever is at the Mac, every run (14-10-2026). The Mac test below proves the same
+# wiring without dying.
[email protected](sys.platform.startswith("linux"), "a real fatal signal runs on Linux only")
class AFatalSignal(unittest.TestCase):
def test_leaves_the_python_stack_of_every_thread_in_crash_log(self):
with tempfile.TemporaryDirectory() as directory:
- script = (
- "import os, signal, threading, time\n"
- "from core import crash_log\n"
- f"crash_log.install({directory!r}, fatal_signals=True)\n"
- "def waits_on_the_link():\n"
- " time.sleep(30)\n"
- "threading.Thread(target=waits_on_the_link, daemon=True).start()\n"
- "time.sleep(0.2)\n"
- "os.kill(os.getpid(), signal.SIGSEGV)\n"
- )
- result = subprocess.run([sys.executable, "-c", script], cwd=REPO, capture_output=True, timeout=30)
- self.assertNotEqual(result.returncode, 0)
- text = (Path(directory) / "crash.log").read_text(encoding="utf-8")
+ result, text = _run_child(directory, "os.kill(os.getpid(), signal.SIGSEGV)\n")
+ self.assertNotEqual(result.returncode, 0)
self.assertIn("Segmentation fault", text)
self.assertIn("waits_on_the_link", text)
[email protected](sys.platform == "darwin", "the Mac's quiet stand-in for the fatal signal")
+class TheFatalSignalHandlerOnTheMac(unittest.TestCase):
+ def test_is_armed_and_writes_every_threads_stack_to_crash_log(self):
+ # faulthandler's own dump into the very descriptor the fatal handler writes to: the stack
+ # the signal would leave, with no process dying and nothing for ReportCrash to see.
+ ending = (
+ "import faulthandler, sys\n"
+ "assert faulthandler.is_enabled()\n"
+ "faulthandler.dump_traceback(file=crash_log._fault_file, all_threads=True)\n"
+ "crash_log._fault_file.flush()\n"
+ "sys.exit(3)\n"
+ )
+ with tempfile.TemporaryDirectory() as directory:
+ result, text = _run_child(directory, ending)
+ self.assertEqual(result.returncode, 3, result.stderr)
+ self.assertIn("waits_on_the_link", text)
+ self.assertIn("Current thread", text)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/core/tests/test_crossing_state.py b/core/tests/test_crossing_state.py
index 7a2ee70..72f342b 100644
--- a/core/tests/test_crossing_state.py
+++ b/core/tests/test_crossing_state.py
@@ -565,6 +565,17 @@ class CrossingStateTests(unittest.TestCase):
self.assertIn(A, out["tell"])
self.assertTrue(ways.has_way(out["settings"], A))
+ def test_a_relayed_picture_without_our_tile_is_not_answered(self):
+ # A-B-C with A and C unpaired: each end used to restamp the picture the other end sent
+ # through B, which lacks the receiver's tile, and the pair exchanged them for ever.
+ held = self.state().paired(settings(), platform="mac", own_displays=DISPLAYS, now=100)["settings"]
+ state = dict(set_at=200, by=B, tiles={A: tile(160, displays={"0": dict(x=0, y=0, w=3840, h=2160)}),
+ B: tile(320)})
+ out = self.state().receive_picture(held, state, source=B, capable={OWN, A, B},
+ own_displays=DISPLAYS, **self.args())
+ self.assertFalse(out["send_picture"])
+ self.assertTrue(out["forward_picture"])
+
def test_migration_keeps_a_whole_edge_in_use_over_a_pick_left_on_an_off_part_zone(self):
# AGY review, 10-10: the page showed the whole edge, so migration must not shrink it to the pick.
held = settings()
diff --git a/core/tests/test_i18n.py b/core/tests/test_i18n.py
new file mode 100644
index 0000000..d0d1794
--- /dev/null
+++ b/core/tests/test_i18n.py
@@ -0,0 +1,128 @@
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+from core import i18n, locale
+
+
+RUSSIAN = r'''msgid ""
+msgstr ""
+"Content-Type: text/plain; charset=UTF-8\n"
+"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
+
+#. a note for the translator
+#: mac_app/pages.py:1
+msgid "Open"
+msgstr "Открыть"
+
+msgctxt "switch"
+msgid "Off"
+msgstr "Выкл."
+
+#, python-brace-format
+msgid "{n} machine"
+msgid_plural "{n} machines"
+msgstr[0] "{n} компьютер"
+msgstr[1] "{n} компьютера"
+msgstr[2] "{n} компьютеров"
+
+#, fuzzy
+msgid "Unchecked"
+msgstr "Не проверено"
+
+msgid "Two lines"
+msgstr ""
+"Первая \"строка\"\n"
+"вторая"
+
+msgid "Not yet"
+msgstr ""
+'''
+
+
+class I18nTests(unittest.TestCase):
+ def tearDown(self):
+ i18n.install("en")
+
+ def catalogue(self, text):
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ (Path(folder.name) / "ru.po").write_text(text, encoding="utf-8")
+ patches = [mock.patch.object(i18n, "locales_dir", return_value=Path(folder.name)),
+ mock.patch.dict(i18n.LANGUAGES, {"ru": "Русский"})]
+ for patch in patches:
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def test_a_po_file_reads_with_plurals_contexts_and_continuations(self):
+ self.catalogue(RUSSIAN)
+ self.assertEqual(i18n.install("ru"), "ru")
+ self.assertEqual(i18n.tr("Open"), "Открыть")
+ self.assertEqual(i18n.trc("switch", "Off"), "Выкл.")
+ self.assertEqual(i18n.tr("Off"), "Off")
+ self.assertEqual([i18n.trn("{n} machine", "{n} machines", n).format(n=n) for n in (1, 3, 5, 21)],
+ ["1 компьютер", "3 компьютера", "5 компьютеров", "21 компьютер"])
+ self.assertEqual(i18n.tr("Two lines"), 'Первая "строка"\nвторая')
+
+ def test_fuzzy_and_empty_entries_fall_back_to_english(self):
+ self.catalogue(RUSSIAN)
+ i18n.install("ru")
+ self.assertEqual(i18n.tr("Unchecked"), "Unchecked")
+ self.assertEqual(i18n.tr("Not yet"), "Not yet")
+ self.assertEqual(i18n.tr("Never seen"), "Never seen")
+
+ def test_a_broken_catalogue_leaves_beamer_in_english(self):
+ self.catalogue('msgid "Open"\nnonsense\n')
+ self.assertEqual(i18n.install("ru"), "en")
+ self.assertEqual(i18n.tr("Open"), "Open")
+
+ def test_automatic_takes_the_first_preferred_language_beamer_has(self):
+ with mock.patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("BEAMER_LANGUAGE", None)
+ self.assertEqual(i18n.resolve("auto", ["fr-FR", "it-IT", "en-GB"]), "it")
+ self.assertEqual(i18n.resolve("auto", ["en-US", "it"]), "en")
+ self.assertEqual(i18n.resolve("auto", ["it_IT.UTF-8"]), "it")
+ self.assertEqual(i18n.resolve("auto", ["de"]), "en")
+ self.assertEqual(i18n.resolve("en", ["it"]), "en")
+ self.assertEqual(i18n.resolve("it", ["en"]), "it")
+ self.assertEqual(i18n.resolve("xx", ["it"]), "it")
+
+ def test_the_environment_forces_a_language(self):
+ with mock.patch.dict(os.environ, {"BEAMER_LANGUAGE": "it"}):
+ self.assertEqual(i18n.resolve("en", ["en"]), "it")
+
+ def test_linux_follows_gettext_order(self):
+ with mock.patch.object(sys, "platform", "linux"):
+ with mock.patch.dict(os.environ, {"LANGUAGE": "it:en", "LANG": "en_GB.UTF-8"}, clear=True):
+ self.assertEqual(i18n.system_languages(), ["it", "en", "en_GB.UTF-8"])
+ with mock.patch.dict(os.environ, {"LANGUAGE": "it", "LANG": "C.UTF-8"}, clear=True):
+ self.assertEqual(i18n.system_languages(), [])
+
+ def test_pseudo_language_brackets_and_keeps_fields(self):
+ with mock.patch.dict(os.environ, {"BEAMER_LANGUAGE": i18n.PSEUDO}):
+ i18n.install("auto")
+ text = i18n.tr("Beam to {name}")
+ self.assertTrue(text.startswith("⟦") and text.endswith("⟧"))
+ self.assertEqual(text.format(name="Mac").count("Mac"), 1)
+
+ def test_joined_lists_names(self):
+ self.assertEqual(i18n.joined([]), "")
+ self.assertEqual(i18n.joined(["Mac"]), "Mac")
+ self.assertEqual(i18n.joined(["Mac", "PC"]), "Mac and PC")
+ self.assertEqual(i18n.joined(["Mac", "PC", "Laptop"]), "Mac, PC and Laptop")
+
+ def test_us_spelling_only_while_in_english(self):
+ with mock.patch.object(locale, "is_us_region", return_value=True):
+ self.assertEqual(locale.americanise("Colour"), "Color")
+ self.catalogue(RUSSIAN)
+ i18n.install("ru")
+ self.assertEqual(locale.americanise("Colour"), "Colour")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_i18n_coverage.py b/core/tests/test_i18n_coverage.py
new file mode 100644
index 0000000..cd354b3
--- /dev/null
+++ b/core/tests/test_i18n_coverage.py
@@ -0,0 +1,197 @@
+"""Every user-visible string goes through core.i18n, and the catalogues are complete.
+
+Read from the source, not imported, so it runs on every platform without AppKit or Qt. Any prose
+literal handed to any call must be marked, tr("...") or N_("..."), so that the extractor finds it,
+unless the call is one that never reaches a screen: a raise, a logger, an exception class, or a
+name in NOT_SHOWN. A helper that calls tr() on its argument is not enough on its own, since the
+extractor only sees literals inside tr()/N_(); its callers pass N_("...") or tr("..."). A tr()
+evaluated at import time, before the language is installed, fails too.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+SOURCES = ("core", "mac_app", "win_app")
+MARKERS = {"tr", "trn", "trc", "N_"}
+WORD = re.compile(r"[A-Za-z]{2,}")
+# One lowercase word with no space is an identifier (a palette ink, a style role, a selector
+# "relaunch:", a unit "ms", a D-Bus method), never a sentence a person reads.
+IDENTIFIER = re.compile(r"^[a-z_][A-Za-z0-9_.:/-]*$")
+LOGGERS = re.compile(r"^(_?log|_?logger|LOG|LOGGER|logging|_LOG)$")
+# Exceptions carry diagnostics for the log; where one is shown, its caller shows a translated
+# sentence instead.
+EXCEPTION = re.compile(r"(Error|Exception|Refused|Abandoned|Warning)$")
+# Text that stays English in every language, wherever it appears.
+ALLOWED = {
+ "Beamer", # the product's name
+}
+# Calls whose string arguments are never shown: system and library names, paths, registry keys,
+# HTTP/WMI selectors, log diagnostics, style values and in-memory list/struct-building operations.
+NOT_SHOWN = {
+ "getattr", "hasattr", "setattr", "startswith", "endswith", "join", "split", "replace", "format", "encode",
+ "Thread", "ArgumentParser", "add_argument", "setStyleSheet", "setObjectName", "setProperty",
+ "OpenKey", "QueryValueEx", "SetValueEx", "DeleteValue", "ExecQuery", "Dispatch", "fromData", "save",
+ "filterWithName_", "AXUIElementCopyAttributeValue", "AXUIElementSetAttributeValue", "NSClassFromString",
+ "has_extension", "get_extension_major", "request", "call", "get_dbus_method", "dlopen", "LoadLibrary",
+ "run", "Popen", "check_output", "check_call", "compile", "match", "search", "sub", "fullmatch",
+ "get", "pop", "setdefault", "environ", "Path", "open", "write", "print",
+ "_warn_once", "_fail", "drop", "_connection_failed", "set_redirecting",
+ # Its arguments are templates matched against shown text, already in the catalogue from where
+ # that text is made.
+ "matches_translation",
+ "pack", "warning", "append", "__init__", "find_library", "setValue_forHTTPHeaderField_",
+ "loadBundle", "lookUpClass", "protocolNamed", "normalize", "lookup", "len",
+ "dispatch", "ExecMethod_", "Methods_", "persistentDomainForName_",
+ "beginActivityWithOptions_reason_", "asset_path", "CreateMutexW", "QKeySequence",
+ "_turn_off_clashes", "exception", "_force_local", "stringForKey_", "open_dbus_connection", "update",
+}
+
+
+def source_files():
+ for folder in SOURCES:
+ yield from sorted((ROOT / folder).glob("*.py"))
+
+
+def _name(func) -> str:
+ return func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else ""
+
+
+def _owner(func) -> str:
+ receiver = func.value if isinstance(func, ast.Attribute) else None
+ return receiver.attr if isinstance(receiver, ast.Attribute) else receiver.id if isinstance(receiver, ast.Name) else ""
+
+
+def _prose_text(text: str) -> bool:
+ text = text.strip()
+ return (bool(WORD.search(text)) and not IDENTIFIER.match(text) and text not in ALLOWED
+ and (" " in text or text[:1].isupper()))
+
+
+def _prose(node) -> bool:
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ return _prose_text(node.value)
+ if isinstance(node, ast.JoinedStr):
+ return _prose_text("".join(part.value for part in node.values if isinstance(part, ast.Constant)))
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Mod)):
+ return _prose(node.left) or _prose(node.right)
+ if isinstance(node, ast.IfExp):
+ return _prose(node.body) or _prose(node.orelse)
+ return False
+
+
+def _not_shown(node: ast.Call, parent, parents, exception_classes) -> bool:
+ name = _name(node.func)
+ if name == "__init__" and name in NOT_SHOWN:
+ ancestor = parent
+ while ancestor is not None and not isinstance(ancestor, ast.ClassDef):
+ ancestor = parents.get(ancestor)
+ return ancestor is not None and ancestor.name in exception_classes
+ return (name in MARKERS or name in NOT_SHOWN or isinstance(parent, ast.Raise)
+ or bool(EXCEPTION.search(name)) or bool(LOGGERS.match(_owner(node.func))))
+
+
+def hard_coded(path: Path) -> list[str]:
+ tree = ast.parse(path.read_text(encoding="utf-8"), str(path))
+ parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)}
+ bases = {node.name: {_name(base) for base in node.bases} for node in ast.walk(tree)
+ if isinstance(node, ast.ClassDef)}
+ exception_classes = {name for name, parent_names in bases.items()
+ if parent_names & {"Exception", "BaseException"}}
+ while True:
+ children = {name for name, parent_names in bases.items() if parent_names & exception_classes}
+ if children <= exception_classes:
+ break
+ exception_classes |= children
+ found = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or _not_shown(node, parents.get(node), parents, exception_classes):
+ continue
+ for arg in list(node.args) + [keyword.value for keyword in node.keywords]:
+ if _prose(arg):
+ found.append(f"{path.relative_to(ROOT).as_posix()}:{arg.lineno}: {_name(node.func)}({ast.unparse(arg)[:70]})")
+ return found
+
+
+def unreadable_tr(path: Path) -> list[str]:
+ """tr() over text built at runtime, f"..." or "..." + x, which the extractor cannot read, so
+ it never reaches the catalogue: the template goes in tr() and the values in .format()."""
+ tree = ast.parse(path.read_text(encoding="utf-8"), str(path))
+ found = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Call) and _name(node.func) in MARKERS and node.args:
+ text = node.args[1] if _name(node.func) == "trc" and len(node.args) > 1 else node.args[0]
+ if isinstance(text, (ast.JoinedStr, ast.BinOp)):
+ found.append(f"{path.relative_to(ROOT).as_posix()}:{node.lineno}: {ast.unparse(node)[:80]}")
+ return found
+
+
+def unmarked_choice_names(path: Path) -> list[str]:
+ """("key", "Shown name") pairs, the shape of every choice table, whose name is not marked:
+ the table is shown as it stands, so its names must reach the catalogue through N_() or tr()."""
+ tree = ast.parse(path.read_text(encoding="utf-8"), str(path))
+ found = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Tuple) and len(node.elts) == 2:
+ key, name = node.elts
+ if (isinstance(key, ast.Constant) and isinstance(key.value, str) and (key.value == "" or IDENTIFIER.match(key.value))
+ and isinstance(name, ast.Constant) and isinstance(name.value, str) and _prose_text(name.value)
+ and name.value[:1].isupper()):
+ found.append(f"{path.relative_to(ROOT).as_posix()}:{node.lineno}: {ast.unparse(node)[:80]}")
+ return found
+
+
+def import_time_tr(path: Path) -> list[str]:
+ """tr() calls that run when the module is imported: at module level, in a class body, or in a
+ default argument, all of which run before the language is installed."""
+ tree = ast.parse(path.read_text(encoding="utf-8"), str(path))
+ found = []
+
+ def visit(node, in_function):
+ if isinstance(node, ast.Call) and _name(node.func) in {"tr", "trn", "trc"} and not in_function:
+ found.append(f"{path.relative_to(ROOT).as_posix()}:{node.lineno}")
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
+ for default in node.args.defaults + [d for d in node.args.kw_defaults if d is not None]:
+ visit(default, in_function)
+ for child in (node.body if isinstance(node.body, list) else [node.body]):
+ visit(child, True)
+ return
+ for child in ast.iter_child_nodes(node):
+ visit(child, in_function)
+
+ visit(tree, False)
+ return found
+
+
+class I18nCoverageTests(unittest.TestCase):
+ def test_no_hard_coded_user_visible_strings(self):
+ found = [line for path in source_files() for line in hard_coded(path)]
+ self.assertEqual(found, [], "mark these with tr() or N_() from core.i18n:\n" + "\n".join(found))
+
+ def test_translated_text_is_a_literal_the_extractor_can_read(self):
+ found = [line for path in source_files() for line in unreadable_tr(path)]
+ self.assertEqual(found, [], "put the template in tr() and the values in .format():\n" + "\n".join(found))
+
+ def test_choice_tables_mark_their_names(self):
+ found = [line for path in source_files() for line in unmarked_choice_names(path)]
+ self.assertEqual(found, [], "mark these names with N_() and show them through tr():\n" + "\n".join(found))
+
+ def test_no_translation_at_import_time(self):
+ found = [line for path in source_files() for line in import_time_tr(path)]
+ self.assertEqual(found, [], "mark these with N_() and call tr() where the text is shown:\n" + "\n".join(found))
+
+ def test_catalogues_are_current_and_complete(self):
+ result = subprocess.run([sys.executable, str(ROOT / "tools" / "i18n_extract.py"), "--check"],
+ capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_keytable.py b/core/tests/test_keytable.py
index 7d534b4..1b57fc0 100644
--- a/core/tests/test_keytable.py
+++ b/core/tests/test_keytable.py
@@ -65,9 +65,29 @@ class TableTests(unittest.TestCase):
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"):
+ for name in ("shift", "shift_r", "caps_lock", "hangul", "hanja", "a", "enter", "f13"):
self.assertEqual(keytable.wire_name(name, "windows", "macos", "mac_layout"), name)
+ def test_input_method_keys_keep_their_names_in_every_direction_and_style(self):
+ for name in ("hangul", "hanja"):
+ for own in ("windows", "linux", "macos"):
+ for peer in ("windows", "linux", "macos"):
+ for style in keytable.STYLES:
+ self.assertEqual(keytable.wire_name(name, own, peer, style), name)
+ self.assertEqual({"hangul", "hanja"} & keytable.SPEC_NAMES, {"hangul", "hanja"})
+ self.assertFalse({"hangul", "hanja"} & set(MODS))
+ self.assertEqual(keytable.EVDEV_NAMES[122], "hangul")
+ self.assertEqual(keytable.EVDEV_NAMES[123], "hanja")
+
+ def test_input_method_taps_are_down_then_up_only_on_press(self):
+ for name in ("hangul", "hanja"):
+ with self.subTest(name=name):
+ self.assertEqual(keytable.tap_messages(name, True), [
+ {"type": "keydown", "data": {"key": name}},
+ {"type": "keyup", "data": {"key": name}},
+ ])
+ self.assertEqual(keytable.tap_messages(name, False), [])
+
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_profile_events.py b/core/tests/test_profile_events.py
new file mode 100644
index 0000000..c9f48c1
--- /dev/null
+++ b/core/tests/test_profile_events.py
@@ -0,0 +1,270 @@
+import copy
+import unittest
+
+from core import crossing_state, profiles, protocol, ways
+
+
+OWN, PEER, OTHER = (protocol.id_text(bytes([n]) * 16) for n in (1, 2, 3))
+ALL = ["start", "middle", "end"]
+
+
+def tile(x=0, y=0, w=160, h=100, **extra):
+ return {"x": x, "y": y, "w": w, "h": h, **extra}
+
+
+def base():
+ default = {"edge": True, "thirds": ALL[:], "edges": [], "corner": False,
+ "corner_at": "top_left", "corners": [], "notch": False}
+ row = {PEER: {"ways": copy.deepcopy(default), "notch_return": False}}
+ own_profile = {
+ "name": {"value": "Desk", "set_at": 0, "by": ""}, "removed": None,
+ "home": {"shake": {"value": True, "set_at": 0, "by": ""}},
+ "rows": {OWN: {"set_at": 10, "by": OWN, "value": copy.deepcopy(row)}},
+ }
+ return {
+ "machine_id": OWN,
+ "peers": [{"id": PEER, "port": 24820, "side": "right", "send": True,
+ "ways": copy.deepcopy(row[PEER]["ways"]), "notch_return": False}],
+ "zones": [], "layout": {OWN: tile(), PEER: tile(160)},
+ "layout_set_at": 10, "layout_by": OWN,
+ "crossing_desk": {"format": 1, "on": {"value": True, "set_at": 20, "by": OWN},
+ "active": {"value": profiles.DESK_ID, "set_at": 0, "by": ""},
+ "profiles": {profiles.DESK_ID: own_profile}, "status": {}},
+ "crossing_own": {"format": 1, "use_own": False, "row": copy.deepcopy(row),
+ "shake": True, "applied": copy.deepcopy(row), "saved": []},
+ }
+
+
+class ProfileEventTests(unittest.TestCase):
+ def test_existing_crossing_events_reconcile_and_report_desk_paths(self):
+ held = base()
+ out = crossing_state.edit_ways(held, PEER, thirds=["start"], platform="mac",
+ live=lambda _: True, gone=lambda _: False, now=40)
+ row = out["settings"]["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"][OWN]
+ self.assertEqual(row["value"][PEER]["ways"]["thirds"], ["start"])
+ self.assertIn(("row", profiles.DESK_ID, OWN), out["send_desk"])
+ self.assertEqual(out["settings"]["crossing_own"]["applied"],
+ profiles.live_row(out["settings"]))
+
+ def test_turning_same_on_seeds_without_changing_live_crossings(self):
+ held = base()
+ held["crossing_desk"]["on"] = {"value": False, "set_at": 30, "by": OWN}
+ held["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"].pop(OWN)
+ before = profiles.live_row(held)
+ out = crossing_state.set_same_ways(held, True, platform="mac", now=40)
+ self.assertTrue(out["accepted"])
+ self.assertEqual(profiles.live_row(out["settings"]), before)
+ row = out["settings"]["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"][OWN]
+ self.assertEqual(row["value"], before)
+ self.assertEqual(row["set_at"], 40)
+
+ def test_own_override_is_local_and_share_mine_writes_the_active_desk_row(self):
+ held = base()
+ enabled = crossing_state.set_own_ways(held, True, platform="mac", now=41)
+ self.assertTrue(enabled["settings"]["crossing_own"]["use_own"])
+ edited = crossing_state.edit_ways(enabled["settings"], PEER, edge=False, platform="mac",
+ live=lambda _: True, gone=lambda _: False, now=42)
+ changed = edited["settings"]["crossing_own"]["row"]
+ shared = crossing_state.share_mine(edited["settings"], platform="mac", now=43)
+ row = shared["settings"]["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"][OWN]
+ self.assertEqual(row["value"], changed)
+ self.assertTrue(any(path[0] == "row" for path in shared["send_desk"]))
+
+ def test_edit_other_changes_only_the_target_machine_row(self):
+ held = base()
+ target_row = {OWN: {"ways": {"edge": True, "thirds": ALL[:], "edges": [],
+ "corner": False, "corner_at": "top_left",
+ "corners": [], "notch": False}, "notch_return": False}}
+ held["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"][OTHER] = {
+ "set_at": 5, "by": OWN, "value": target_row}
+ out = crossing_state.edit_other(held, OTHER, OWN, thirds=["end"], platform="mac", now=50)
+ row = out["settings"]["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"][OTHER]
+ self.assertEqual(row["value"][OWN]["ways"]["thirds"], ["end"])
+ self.assertEqual(profiles.live_row(out["settings"]), profiles.live_row(held))
+
+ def test_edit_other_keeps_the_last_thirds_choice_and_refuses_a_held_corner(self):
+ held = base()
+ row = {OWN: {"ways": {"edge": True, "thirds": ["middle"], "edges": [],
+ "corner": False, "corner_at": "top_left", "corners": [],
+ "notch": False}, "notch_return": False},
+ PEER: {"ways": {"edge": True, "thirds": ALL[:], "edges": [],
+ "corner": True, "corner_at": "top_left",
+ "corners": ["top_left"], "notch": False},
+ "notch_return": False}}
+ held["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"][OTHER] = {
+ "set_at": 5, "by": OWN, "value": row}
+ kept = crossing_state.edit_other(held, OTHER, OWN, thirds=[], platform="mac", now=50)
+ self.assertEqual(kept["settings"]["crossing_desk"]["profiles"][profiles.DESK_ID]
+ ["rows"][OTHER]["value"][OWN]["ways"]["thirds"], ["middle"])
+ refused = crossing_state.edit_other(held, OTHER, OWN, corner=True,
+ corner_at="top_left", platform="mac", now=51)
+ self.assertFalse(refused["accepted"])
+ self.assertEqual(refused["settings"], held)
+
+ def test_edit_other_ignores_notch_controls_for_a_non_mac_target(self):
+ held = base()
+ held["crossing_desk"]["status"][OTHER] = {"set_at": 1, "by": OTHER,
+ "value": {"app": "1.5.4", "platform": "windows", "in_force": "desk",
+ "profile": profiles.DESK_ID, "row": None, "waiting": []}}
+ held["crossing_desk"]["profiles"][profiles.DESK_ID]["rows"][OTHER] = {
+ "set_at": 5, "by": OWN,
+ "value": {OWN: {"ways": {"edge": True, "thirds": ALL[:], "edges": [],
+ "corner": False, "corner_at": "top_left", "corners": [],
+ "notch": False}, "notch_return": False}}}
+ out = crossing_state.edit_other(held, OTHER, OWN, notch=True, notch_return=True,
+ platform="mac", now=50)
+ intent = (out["settings"]["crossing_desk"]["profiles"][profiles.DESK_ID]
+ ["rows"][OTHER]["value"][OWN])
+ self.assertFalse(intent["ways"]["notch"])
+ self.assertFalse(intent["notch_return"])
+
+ def test_other_row_edits_and_share_mine_are_refused_while_sync_is_off(self):
+ held = base()
+ held["crossing_desk"]["on"] = {"value": False, "set_at": 30, "by": OWN}
+ edited = crossing_state.edit_other(held, OTHER, OWN, edge=False, now=40)
+ shared = crossing_state.share_mine(held, now=41)
+ self.assertFalse(edited["accepted"])
+ self.assertFalse(shared["accepted"])
+ self.assertEqual(edited["settings"], held)
+ self.assertEqual(shared["settings"], held)
+
+ def test_profile_switch_snapshots_old_picture_and_activates_new_picture(self):
+ held = base()
+ held["layout"][OWN]["display_offsets"] = {"0": {"x": 50, "y": 0}}
+ held["layout"][OWN]["displays"] = {"0": tile()}
+ held["peers"].append({"id": OTHER, "port": 24820, "side": "right", "send": True,
+ "ways": copy.deepcopy(held["peers"][0]["ways"])})
+ held["layout"][OTHER] = tile(320)
+ held["crossing_desk"]["profiles"][profiles.DESK_ID]["picture"] = None
+ created = crossing_state.new_profile(held, "Sofa", now=50)
+ sofa = next(pid for pid in created["settings"]["crossing_desk"]["profiles"]
+ if pid != profiles.DESK_ID)
+ created["settings"]["crossing_desk"]["profiles"][sofa]["picture"] = {
+ "set_at": 50, "by": OWN,
+ "tiles": {OWN: {**tile(), "display_offsets": {"unplugged": {"x": 5, "y": 0}}},
+ PEER: tile(160)}}
+ switched = crossing_state.switch_profile(created["settings"], sofa, platform="mac", now=60)
+ desk = switched["settings"]["crossing_desk"]["profiles"][profiles.DESK_ID]
+ self.assertEqual(desk["picture"]["tiles"][OWN]["x"], 0)
+ self.assertEqual(desk["picture"]["tiles"][OWN]["display_offsets"], {"0": {"x": 50, "y": 0}})
+ self.assertEqual(switched["settings"]["crossing_desk"]["active"]["value"], sofa)
+ # Kept while active so every machine's desk is the same; not read until it is left again.
+ self.assertIn("picture", switched["settings"]["crossing_desk"]["profiles"][sofa])
+ self.assertTrue(switched["send_picture"])
+ self.assertNotIn("display_offsets", switched["settings"]["layout"][OWN])
+ self.assertIn("displays", switched["settings"]["layout"][OWN])
+ self.assertEqual(switched["settings"]["layout"][OTHER]["x"], 320)
+
+ def test_shake_setting_changes_the_in_force_register(self):
+ held = base()
+ held["crossing_own"]["use_own"] = True
+ out = crossing_state.set_shake(held, False, now=70)
+ self.assertFalse(profiles.shake_on(out["settings"]))
+ self.assertIn(("home", profiles.DESK_ID, "shake"), out["send_desk"])
+
+ def test_shake_sensitivity_is_profile_synced_and_local_when_same_ways_is_off(self):
+ held = base()
+ out = crossing_state.set_shake_sensitivity(held, 150, now=70)
+ self.assertTrue(out["accepted"])
+ self.assertEqual(profiles.shake_sensitivity(out["settings"]), 150)
+ self.assertIn(("home", profiles.DESK_ID, "sensitivity"), out["send_desk"])
+
+ held["crossing_desk"]["on"]["value"] = False
+ local = crossing_state.set_shake_sensitivity(held, 75, now=71)
+ self.assertEqual(profiles.shake_sensitivity(local["settings"]), 75)
+ self.assertNotIn(("home", profiles.DESK_ID, "sensitivity"), local["send_desk"])
+
+ def test_shake_sensitivity_rejects_values_outside_the_control_range(self):
+ for value in (49, 201, True):
+ with self.subTest(value=value):
+ self.assertFalse(crossing_state.set_shake_sensitivity(base(), value, now=70)["accepted"])
+
+ def test_shake_sensitivity_delta_reaches_peer_without_overwriting_local_preference(self):
+ edited = crossing_state.set_shake_sensitivity(base(), 150, now=70)
+ target = base()
+ target["crossing_own"]["shake_sensitivity"] = 80
+ target["peers"][0].update(allow_drive=True, linked=True)
+ packet = profiles.desk_message(edited["settings"], edited["send_desk"])
+ received, *_ = profiles.merge_desk(target, packet, source=PEER, now=71)
+ self.assertEqual(profiles.shake_sensitivity(received), 150)
+ loaded, _ = profiles.before_load(received, now=72)
+ self.assertEqual(profiles.shake_sensitivity(loaded), 150)
+ local = crossing_state.set_same_ways(loaded, False, now=73)["settings"]
+ self.assertEqual(profiles.shake_sensitivity(local), 80)
+
+ def test_new_profile_carries_the_active_shake_sensitivity(self):
+ held = crossing_state.set_shake_sensitivity(base(), 150, now=70)["settings"]
+ created = crossing_state.new_profile(held, "Studio", now=71)
+ profile_id = next(pid for pid in created["settings"]["crossing_desk"]["profiles"]
+ if pid != profiles.DESK_ID)
+ self.assertEqual(profiles.shake_sensitivity(created["settings"]), 150)
+ self.assertEqual(created["settings"]["crossing_desk"]["profiles"][profile_id]
+ ["home"]["sensitivity"]["value"], 150)
+ self.assertIn(("home", profile_id, "sensitivity"), created["send_desk"])
+
+ def test_same_ways_toggle_sends_the_register_even_when_a_seed_is_also_written(self):
+ held = base()
+ held["crossing_desk"]["on"] = {"value": False, "set_at": 30, "by": OWN}
+ out = crossing_state.set_same_ways(held, True, platform="mac", now=40)
+ self.assertIn(("on",), out["send_desk"])
+
+ def test_event_rolls_back_when_the_mutation_exceeds_the_desk_size_cap(self):
+ created = crossing_state.new_profile(base(), "Sofa", now=70)
+ held = created["settings"]
+ sofa = next(pid for pid in held["crossing_desk"]["profiles"] if pid != profiles.DESK_ID)
+ held["crossing_desk"]["status"][OTHER] = {
+ "set_at": 1, "by": OTHER,
+ "value": {"app": "x" * profiles.MAX_DESK_BYTES, "platform": "mac",
+ "in_force": "desk", "profile": profiles.DESK_ID,
+ "row": None, "waiting": []}}
+ out = crossing_state.switch_profile(held, sofa, platform="mac", now=71)
+ self.assertFalse(out["accepted"])
+ self.assertEqual(out["reason"], "desk_full")
+ self.assertEqual(out["settings"], held)
+ self.assertFalse(out["send_picture"])
+ self.assertFalse(out["forward_picture"])
+ self.assertEqual(out["forward"], {})
+ self.assertEqual(out["answer"], {})
+ self.assertEqual(out["tell"], [])
+
+ def test_forward_contains_only_registers_taken_from_the_peer(self):
+ held = base()
+ held["crossing_desk"]["on"] = {"value": False, "set_at": 30, "by": OWN}
+ held["peers"][0].update(allow_drive=True, linked=True)
+ received_on = {"value": True, "set_at": 90, "by": PEER}
+ out = crossing_state.desk_arrived(held, {"on": received_on}, source=PEER,
+ platform="mac", now=100)
+ self.assertTrue(out["accepted"])
+ self.assertEqual(out["forward"], {"on": received_on})
+ self.assertIn(("row", profiles.DESK_ID, OWN), out["send_desk"])
+
+ def test_desk_arrival_is_refused_from_a_peer_that_cannot_drive(self):
+ held = base()
+ held["peers"][0]["allow_drive"] = False
+ state = profiles.desk_message(held)
+ out = crossing_state.desk_arrived(held, state, source=PEER, platform="mac", now=80)
+ self.assertFalse(out["accepted"])
+ self.assertEqual(out["reason"], "untrusted")
+ self.assertEqual(out["settings"], held)
+
+ def test_saved_row_restore_archives_the_row_it_replaces(self):
+ held = base()
+ old = copy.deepcopy(held["crossing_own"]["row"])
+ old[PEER]["ways"]["edge"] = False
+ profiles.archive(held, old, "edited", 11)
+ saved_id = held["crossing_own"]["saved"][0]["id"]
+ out = crossing_state.restore_saved(held, saved_id, platform="mac", now=90)
+ self.assertFalse(out["settings"]["crossing_own"]["row"][PEER]["ways"]["edge"])
+ self.assertGreaterEqual(len(out["settings"]["crossing_own"]["saved"]), 2)
+
+ def test_deleting_saved_row_does_not_change_live_or_desk_state(self):
+ held = base()
+ profiles.archive(held, held["crossing_own"]["row"], "edited", 11)
+ saved_id = held["crossing_own"]["saved"][0]["id"]
+ out = crossing_state.delete_saved(held, saved_id)
+ self.assertEqual(out["settings"]["crossing_own"]["saved"], [])
+ self.assertEqual(profiles.live_row(out["settings"]), profiles.live_row(held))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_profiles.py b/core/tests/test_profiles.py
new file mode 100644
index 0000000..274d887
--- /dev/null
+++ b/core/tests/test_profiles.py
@@ -0,0 +1,925 @@
+"""Synthetic crossing rows and registers; no desktop imports or real settings."""
+
+import copy
+import random
+import unittest
+
+from core import protocol, settings_sync, ways
+
+A, B, C, P = [protocol.id_text(bytes([n]) * 16) for n in (1, 2, 3, 4)]
+
+
+def raw():
+ return dict(schema=6, machine_id=A, peers=[dict(id=B, port=24820, send=True,
+ allow_drive=True, linked=True, side="right", ways=dict(edge=False, thirds=["start"],
+ edges=["left"], corner=False, notch=False))], zones=[],
+ layout={A: dict(x=0, y=0, w=160, h=100), B: dict(x=160, y=0, w=160, h=100)})
+
+
+class ProfilesTests(unittest.TestCase):
+ def api(self):
+ from core import profiles
+ return profiles
+
+ def upgraded(self):
+ p = self.api()
+ saved, notes = p.before_load(raw(), now=100)
+ self.assertIn("upgraded", notes)
+ return p.after_load(saved, platform="mac", now=100)[0]
+
+ def test_upgrade_and_normalisation_do_not_lose_raw_ways(self):
+ p = self.api()
+ original = raw()
+ saved, _ = p.before_load(original, now=100)
+ self.assertEqual(saved["crossing_own"]["saved"][0]["row"], p.live_row(original))
+ saved["peers"][0]["ways"]["notch"] = True
+ saved, _ = p.after_load(saved, platform="mac", now=100)
+ self.assertEqual(saved["crossing_own"]["row"], p.live_row(saved))
+ self.assertNotIn("crossing_own", original)
+
+ def test_reconcile_captures_local_edit_once_and_applied_is_actual(self):
+ p = self.api()
+ saved = self.upgraded()
+ previous = copy.deepcopy(saved["crossing_own"]["row"])
+ saved["peers"][0]["ways"]["edge"] = True
+ saved, paths = p.reconcile(saved, platform="mac", now=101)
+ self.assertTrue(saved["crossing_own"]["row"][B]["ways"]["edge"])
+ self.assertEqual(saved["crossing_own"]["applied"], p.live_row(saved))
+ self.assertIn(previous, [x["row"] for x in saved["crossing_own"]["saved"]])
+ count = len(saved["crossing_own"]["saved"])
+ saved["peers"][0]["ways"]["thirds"] = ["end"]
+ saved, _ = p.reconcile(saved, platform="mac", now=102)
+ self.assertEqual(count, len(saved["crossing_own"]["saved"]))
+
+ def test_edit_while_sending_is_off_is_kept_when_it_is_turned_back_on(self):
+ # Review of ccce011e, finding 1: the edit was never captured and was projected over.
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"].append(dict(id=C, port=24820, send=True, ways={"edge": False}))
+ saved["peers"][0]["send"] = False
+ saved, _ = p.reconcile(saved, platform="mac", now=101)
+ saved["peers"][0]["ways"]["thirds"] = ["end"]
+ saved["peers"][0]["notch_return"] = True
+ saved, _ = p.reconcile(saved, platform="mac", now=102)
+ self.assertEqual(saved["crossing_own"]["row"][B]["ways"]["thirds"], ["end"])
+ self.assertTrue(saved["crossing_own"]["row"][B]["notch_return"])
+ self.assertFalse(saved["crossing_own"]["row"][C]["ways"]["edge"])
+ saved["peers"][0]["send"] = True
+ saved, _ = p.reconcile(saved, platform="mac", now=103)
+ self.assertEqual(saved["peers"][0]["ways"]["thirds"], ["end"])
+ self.assertTrue(saved["peers"][0]["notch_return"])
+
+ def test_edit_while_sending_is_off_in_an_older_beamer_is_kept(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"][0]["send"] = False
+ saved, _ = p.reconcile(saved, platform="mac", now=101)
+ saved["peers"][0]["ways"]["thirds"] = ["end"]
+ saved, notes = p.before_load(saved, now=102)
+ self.assertIn("older_version", notes)
+ saved["peers"][0]["send"] = True
+ saved, _ = p.after_load(saved, platform="mac", now=102)
+ self.assertEqual(saved["peers"][0]["ways"]["thirds"], ["end"])
+
+ def test_a_left_out_machine_never_takes_the_notch_from_one_in_use(self):
+ # Review finding 4: row order gave the notch to a left-out machine and cleared the active one's.
+ from core import crossing_state
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"].insert(0, dict(id=C, port=24820, send=True, left_out=True,
+ ways=dict(edge=False, notch=False)))
+ saved, _ = p.reconcile(saved, platform="mac", now=101)
+ saved = crossing_state.set_same_ways(saved, True, platform="mac", now=102)["settings"]
+ desk = saved["crossing_desk"]
+ row = copy.deepcopy(desk["profiles"][p.DESK_ID]["rows"][A]["value"])
+ row = {C: row[C], B: row[B]}
+ row[C]["ways"]["notch"] = row[B]["ways"]["notch"] = True
+ desk["profiles"][p.DESK_ID]["rows"][A] = dict(value=row, set_at=200, by=B)
+ saved, _ = p.reconcile(saved, platform="mac", now=201)
+ live = {entry["id"]: entry["ways"]["notch"] for entry in saved["peers"]}
+ self.assertEqual(live, {C: False, B: True})
+ self.assertEqual([zone["peer"] for zone in saved["zones"] if zone.get("kind") == "notch"], [B])
+ again, _ = p.reconcile(saved, platform="mac", now=202)
+ self.assertEqual(again["peers"], saved["peers"])
+
+ def test_profiles_made_apart_still_merge(self):
+ # Review finding 2: two machines each making an eighth profile rejected each other's desk.
+ from core import crossing_state
+ p = self.api()
+ base = self.upgraded()
+ base["peers"][0].update(linked=True, allow_drive=True)
+ for n in range(6):
+ base = crossing_state.new_profile(base, f"P{n}", platform="mac", now=110 + n)["settings"]
+ one = crossing_state.new_profile(base, "Mine", platform="mac", now=120)["settings"]
+ two = crossing_state.new_profile(base, "Theirs", platform="mac", now=121)["settings"]
+ self.assertEqual(len(p.profile_list(one)), 8)
+ for frame in p.frames(p.desk_message(two)):
+ merged = crossing_state.desk_arrived(one, frame, source=B, platform="mac", now=130)
+ self.assertTrue(merged["accepted"], merged["reason"])
+ one = merged["settings"]
+ self.assertEqual(len(p.profile_list(one)), 9)
+ self.assertTrue(all(len(p._json(f)) <= p.MAX_DESK_BYTES for f in p.frames(p.desk_message(one))))
+
+ def test_a_profile_grown_on_two_machines_apart_still_travels_and_merges(self):
+ # Re-review, finding 2: whole-profile frames could outgrow the frame bound once merged.
+ p = self.api()
+ peers = [protocol.id_text(bytes([n]) * 15 + b"\x01") for n in range(10, 42)]
+ row = {peer: {"ways": {"edge": True, "thirds": ["start", "middle", "end"], "edges": ["left", "top"],
+ "corner": True, "corner_at": "top_left", "corners": ["top_left", "bottom_right"],
+ "notch": False}, "notch_return": False} for peer in peers}
+ machines = [protocol.id_text(bytes([n]) * 15 + b"\x02") for n in range(50, 82)]
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True)
+ rows = {m: dict(value=copy.deepcopy(row), set_at=300 + i, by=B) for i, m in enumerate(machines)}
+ desk = {"profiles": {p.DESK_ID: {"rows": rows}}}
+ sent = p.frames(desk)
+ self.assertGreater(len(sent), 1)
+ self.assertTrue(all(len(p._json(frame)) <= p.MAX_DESK_BYTES for frame in sent))
+ for frame in sent:
+ saved, *_rest, accepted, reason = p.merge_desk(saved, frame, source=B, now=400)
+ self.assertTrue(accepted, reason)
+ self.assertEqual(set(saved["crossing_desk"]["profiles"][p.DESK_ID]["rows"]) & set(machines), set(machines))
+ self.assertLess(p.desk_size(saved), p.MAX_DESK_BYTES)
+
+ def test_making_profiles_prunes_removed_profiles_at_receiver_limit(self):
+ from core import crossing_state
+ p = self.api()
+ saved = self.upgraded()
+ for n in range(p.MAX_HELD - 1):
+ out = crossing_state.new_profile(saved, f"P{n}", platform="mac", now=500 + 2 * n)
+ self.assertTrue(out["accepted"], out["reason"])
+ saved = out["settings"]
+ pid = next(pid for pid, profile in saved["crossing_desk"]["profiles"].items()
+ if profile.get("name", {}).get("value") == f"P{n}")
+ saved = crossing_state.remove_profile(saved, pid, platform="mac", now=501 + 2 * n)["settings"]
+ desk = saved["crossing_desk"]
+ self.assertEqual(len(desk["profiles"]), p.MAX_HELD)
+ self.assertEqual([pid for pid in desk["profiles"] if not p.removed(desk, pid)], [p.DESK_ID])
+
+ out = crossing_state.new_profile(saved, "After cleanup", platform="mac", now=700)
+ self.assertTrue(out["accepted"], out["reason"])
+ self.assertLessEqual(len(out["settings"]["crossing_desk"]["profiles"]), p.MAX_HELD)
+
+ def test_merging_oversize_tombstone_unions_is_order_independent(self):
+ from core import crossing_state
+ p = self.api()
+
+ def tombstones(start, count):
+ return {protocol.id_text(bytes([n]) * 16): {"removed": {"set_at": n % 10 + 10, "by": B}}
+ for n in range(start, start + count)}
+
+ left = {"profiles": tombstones(10, 40)}
+ right = {"profiles": tombstones(60, 40)}
+ results = []
+ for order in ((left, right), (right, left)):
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True)
+ for state in order:
+ saved, *_rest, accepted, reason = p.merge_desk(saved, state, source=B, now=200)
+ self.assertTrue(accepted, reason)
+ results.append(saved["crossing_desk"]["profiles"])
+
+ self.assertEqual(set(results[0]), set(results[1]))
+ self.assertEqual(len(results[0]), p.MAX_HELD)
+ self.assertIn(p.DESK_ID, results[0])
+ all_tombstones = left["profiles"] | right["profiles"]
+ retained = sorted(all_tombstones, key=lambda pid: (
+ all_tombstones[pid]["removed"]["set_at"], pid))[-(p.MAX_HELD - 1):]
+ self.assertEqual(set(results[0]) - {p.DESK_ID}, set(retained))
+
+ def test_pruning_never_drops_the_active_profile(self):
+ p = self.api()
+ settings = {"crossing_own": {}, "crossing_desk": {"active": {"value": P}, "profiles": {
+ P: {"removed": {"set_at": 0, "by": B}},
+ A: {"removed": {"set_at": 1, "by": B}},
+ B: {"removed": {"set_at": 2, "by": B}},
+ }}}
+
+ p.prune_removed(settings, 2)
+
+ profiles = settings["crossing_desk"]["profiles"]
+ self.assertIn(P, profiles)
+ self.assertNotIn(A, profiles)
+ self.assertIn(B, profiles)
+ self.assertEqual(p.pruned(settings), [A])
+
+ def test_a_late_delta_for_a_pruned_profile_does_not_bring_it_back(self):
+ # Sol review: Q prunes the oldest tombstone, then that profile's own name arrives late.
+ p = self.api()
+ ids = [protocol.id_text(bytes([n]) * 16) for n in range(1, 66)]
+ oldest, others, q = ids[0], ids[1:63], ids[63]
+ tombs = {"profiles": {pid: {"removed": {"set_at": 10 + n, "by": B}}
+ for n, pid in enumerate([oldest, *others])}}
+ name = {"profiles": {oldest: {"name": {"value": "Old", "set_at": 5, "by": B}}}}
+ new = {"profiles": {q: {"name": {"value": "Q", "set_at": 150, "by": B}}}}
+ results = []
+ for order in ((tombs, new, name), (tombs, name, new)):
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True)
+ for state in order:
+ saved, *_rest, accepted, reason = p.merge_desk(saved, state, source=B, now=200)
+ self.assertTrue(accepted, reason)
+ results.append(saved["crossing_desk"]["profiles"])
+ self.assertEqual(set(results[0]), set(results[1]))
+ self.assertNotIn(oldest, results[0])
+ self.assertIn(q, results[0])
+
+ def test_a_late_active_register_for_a_pruned_profile_is_rejected(self):
+ from core import crossing_state
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True)
+ saved["crossing_desk"]["profiles"][p.DESK_ID]["home"]["shake"] = dict(
+ value=False, set_at=100, by=A)
+ saved = crossing_state.set_same_ways(saved, True, platform="mac", now=100)["settings"]
+ made = crossing_state.new_profile(saved, "Q", platform="mac", now=101)
+ self.assertTrue(made["accepted"], made["reason"])
+ saved = made["settings"]
+ q = saved["crossing_desk"]["profiles"].keys() - {p.DESK_ID}
+ self.assertEqual(len(q), 1)
+ q = q.pop()
+ selected = crossing_state.switch_profile(saved, q, platform="mac", now=102)
+ self.assertTrue(selected["accepted"], selected["reason"])
+ saved = selected["settings"]
+ previous = p.DESK_ID
+ returned = crossing_state.switch_profile(saved, previous, platform="mac", now=103)
+ self.assertTrue(returned["accepted"], returned["reason"])
+ saved = crossing_state.remove_profile(returned["settings"], q, platform="mac", now=104)["settings"]
+
+ tombstones = {protocol.id_text(bytes([n]) * 16): {
+ "removed": {"set_at": 200 + n, "by": B}}
+ for n in range(1, p.MAX_HELD)}
+ saved, _, _, _, accepted, reason = p.merge_desk(
+ saved, {"profiles": tombstones}, source=B, now=400)
+ self.assertTrue(accepted, reason)
+ self.assertIn(q, p.pruned(saved))
+ self.assertNotIn(q, saved["crossing_desk"]["profiles"])
+ before_active = copy.deepcopy(saved["crossing_desk"]["active"])
+ before_shake = p.shake_on(saved)
+
+ newer = {"active": {"value": q, "set_at": before_active["set_at"] + 50, "by": B},
+ "profiles": {q: {"name": {"value": "Q", "set_at": 900, "by": B},
+ "home": {"shake": {"value": False, "set_at": 900, "by": B}}}}}
+ merged, _, forward, answer, accepted, reason = p.merge_desk(
+ saved, newer, source=B, now=1000)
+ self.assertTrue(accepted, reason)
+ self.assertEqual(merged["crossing_desk"]["active"]["value"], previous)
+ self.assertGreater(merged["crossing_desk"]["active"]["set_at"], newer["active"]["set_at"])
+ self.assertNotIn(q, merged["crossing_desk"]["profiles"])
+ self.assertEqual(forward["active"]["value"], previous)
+ self.assertGreater(forward["active"]["set_at"], newer["active"]["set_at"])
+ self.assertEqual(answer["active"]["value"], previous)
+ self.assertGreater(answer["active"]["set_at"], newer["active"]["set_at"])
+ self.assertEqual(p.shake_on(merged), before_shake)
+
+ older = {"active": {"value": q, "set_at": before_active["set_at"] - 1, "by": B}}
+ unchanged, _, _, older_reply, accepted, reason = p.merge_desk(
+ saved, older, source=B, now=1001)
+ self.assertTrue(accepted, reason)
+ self.assertEqual(unchanged["crossing_desk"]["active"], before_active)
+ self.assertEqual(older_reply["active"], before_active)
+
+ def test_merge_still_refuses_live_profile_overflow(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True)
+ live = {protocol.id_text(bytes([n]) * 16): {
+ "name": {"value": f"P{n}", "set_at": n, "by": B}}
+ for n in range(1, p.MAX_HELD + 1)}
+
+ result = p.merge_desk(saved, {"profiles": live}, source=B, now=200)
+
+ self.assertFalse(result[4])
+ self.assertEqual(result[5], "desk_full")
+
+ def test_notch_from_a_received_row_is_stable_through_events(self):
+ # reconcile and _initial must agree, or each event's untick reads as a page edit and is sent.
+ from core import crossing_state
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"].append(dict(id=C, port=24820, send=True, ways=dict(edge=False, notch=False)))
+ saved, _ = p.reconcile(saved, platform="mac", now=101)
+ saved = crossing_state.set_same_ways(saved, True, platform="mac", now=102)["settings"]
+ desk = saved["crossing_desk"]
+ row = copy.deepcopy(desk["profiles"][p.DESK_ID]["rows"][A]["value"])
+ row[B]["ways"]["notch"] = row[C]["ways"]["notch"] = True
+ desk["profiles"][p.DESK_ID]["rows"][A] = dict(value=row, set_at=200, by=B)
+ saved, _ = p.reconcile(saved, platform="mac", now=201)
+ held = copy.deepcopy(desk["profiles"][p.DESK_ID]["rows"][A])
+ for now in (202, 203):
+ out = crossing_state.link_up(saved, B, platform="mac", own_displays={}, now=now)
+ self.assertEqual(out["settings"]["crossing_desk"]["profiles"][p.DESK_ID]["rows"][A], held)
+ self.assertNotIn(("row", p.DESK_ID, A), [tuple(x) for x in out["send_desk"]])
+ saved = out["settings"]
+
+ def test_another_machines_row_draws_through_the_same_ledger_reach(self):
+ from core import crossing_state
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True, name="PC")
+ saved = crossing_state.set_same_ways(saved, True, platform="mac", now=101)["settings"]
+ row = {A: {"ways": {"edge": True, "thirds": ["middle"], "edges": [], "corner": False,
+ "corner_at": "top_left", "corners": [], "notch": False}, "notch_return": False}}
+ saved["crossing_desk"]["profiles"][p.DESK_ID]["rows"][B] = dict(value=row, set_at=200, by=B)
+ view = p.view_settings(saved, B)
+ self.assertEqual(view["machine_id"], B)
+ self.assertNotIn("token", view["peers"][0])
+ self.assertEqual(view["peers"][0]["side"], "left")
+ held = ways.ways(view, A)
+ self.assertEqual((held["side"], held["parts"]), ("left", ["middle"]))
+ sides = ways.reach(view, A, platform=p.view_platform(saved, B))["sides"]
+ self.assertEqual(sides["left"]["state"], "contact")
+ self.assertEqual(p.tile_word(saved, A, linked=True, caps=()), "Desk")
+ self.assertEqual(p.tile_word(saved, B, linked=True, caps=("profiles",)), "Desk")
+ self.assertEqual(p.tile_word(saved, B, linked=False, caps=("profiles",)), "Offline")
+ self.assertEqual(p.tile_word(saved, B, linked=True, caps=()), "Older")
+
+ def test_same_ways_views_shelf_a_left_out_peer_with_its_stale_tile(self):
+ from core import crossing_state
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True, name="Rig", side="left")
+ saved["peers"].append(dict(id=C, port=24821, send=True, allow_drive=True, linked=True,
+ left_out=True, ways=dict(edge=True, thirds=list(ways.PARTS),
+ edges=[], corner=False, notch=False)))
+ saved["layout"] = {
+ A: dict(x=-640, y=-50, w=160, h=100),
+ B: dict(x=-820, y=-50, w=180, h=112),
+ C: dict(x=-800, y=-50, w=160, h=100),
+ }
+ saved["zones"] = [{"peer": B, "kind": "edge", "side": "left"}]
+ own_zones = copy.deepcopy(saved["zones"])
+ saved = crossing_state.set_same_ways(saved, True, platform="mac", now=102)["settings"]
+
+ self.assertTrue(next(peer for peer in saved["peers"] if peer["id"] == C)["left_out"])
+ self.assertEqual(saved["zones"], own_zones)
+ viewed = p.view_settings(saved, B)
+ states = ways.compile_layout(viewed, viewed["layout"], platform="mac", now=103)["tiles"]
+ self.assertNotEqual(states.get(A, {}).get("state"), "overlap")
+ self.assertNotEqual(states.get(B, {}).get("state"), "overlap")
+ self.assertEqual(states[C]["state"], "dormant")
+ self.assertNotIn(C, p.machines_on_desk(saved))
+ self.assertIn(B, p.machines_on_desk(saved))
+
+ def test_received_desk_view_shelves_a_peer_left_out_here(self):
+ from core import crossing_state
+ p = self.api()
+ sender = self.upgraded()
+ sender["peers"][0].update(linked=True, allow_drive=True, name="Rig", side="left")
+ sender["peers"].append(dict(id=C, port=24821, send=True, allow_drive=True, linked=True,
+ left_out=True, ways=dict(edge=True, thirds=list(ways.PARTS),
+ edges=[], corner=False, notch=False)))
+ sender["layout"] = {
+ A: dict(x=-640, y=-50, w=160, h=100),
+ B: dict(x=-820, y=-50, w=180, h=112),
+ C: dict(x=-800, y=-50, w=160, h=100),
+ }
+ sender = crossing_state.set_same_ways(sender, True, platform="mac", now=102)["settings"]
+ receiver_raw = copy.deepcopy(raw())
+ receiver_raw["machine_id"] = B
+ receiver_raw["peers"] = [
+ dict(id=A, port=24820, send=True, allow_drive=True, linked=True, side="right",
+ ways=dict(edge=True, thirds=list(ways.PARTS), edges=[], corner=False, notch=False)),
+ dict(id=C, port=24821, send=True, allow_drive=True, linked=True, left_out=True,
+ ways=dict(edge=True, thirds=list(ways.PARTS), edges=[], corner=False, notch=False)),
+ ]
+ receiver_raw["layout"] = {
+ B: dict(x=-820, y=-50, w=180, h=112),
+ A: dict(x=-640, y=-50, w=160, h=100),
+ C: dict(x=-800, y=-50, w=160, h=100),
+ }
+ receiver, _ = p.before_load(receiver_raw, now=100)
+ receiver = p.after_load(receiver, platform="pc", now=101)[0]
+ receiver_zones = copy.deepcopy(receiver["zones"])
+ received = crossing_state.desk_arrived(
+ receiver, p.desk_message(sender), source=A, platform="pc", now=103)["settings"]
+
+ self.assertEqual(received["zones"], receiver_zones)
+ viewed = p.view_settings(received, A)
+ states = ways.compile_layout(viewed, viewed["layout"], platform="pc", now=104)["tiles"]
+ self.assertNotEqual(states.get(A, {}).get("state"), "overlap")
+ self.assertNotEqual(states.get(B, {}).get("state"), "overlap")
+ self.assertEqual(states[C]["state"], "dormant")
+ self.assertTrue(next(peer for peer in received["peers"] if peer["id"] == C)["left_out"])
+ self.assertIn(A, p.machines_on_desk(received))
+ self.assertNotIn(C, p.machines_on_desk(received))
+
+ def test_no_way_back_ignores_a_shelved_peers_stale_tile(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True, side="left")
+ saved["peers"].append(dict(id=C, port=24821, send=True, left_out=True,
+ ways=dict(edge=True, thirds=list(ways.PARTS), edges=[], corner=False, notch=False)))
+ saved["crossing_own"]["row"][B]["ways"].update(edge=True, thirds=list(ways.PARTS))
+ from core import crossing_state
+ saved = crossing_state.set_same_ways(saved, True, platform="mac", now=102)["settings"]
+ remote_row = dict(
+ value=p.canonical_row({
+ A: {"ways": {"edge": True, "thirds": list(ways.PARTS), "edges": [],
+ "corner": False, "notch": False}},
+ C: {"ways": {"edge": True, "thirds": list(ways.PARTS), "edges": [],
+ "corner": False, "notch": False}},
+ }),
+ set_at=200, by=B)
+ saved["crossing_desk"]["profiles"][p.DESK_ID]["rows"][B] = remote_row
+ saved["crossing_desk"]["status"][B] = dict(set_at=201, by=B, value={
+ "platform": "pc", "app": "1.5.5", "in_force": "desk", "profile": p.DESK_ID,
+ "row": [200, B], "waiting": [],
+ })
+ saved["layout"] = {
+ A: dict(x=-640, y=-50, w=160, h=100),
+ B: dict(x=-820, y=-50, w=180, h=112),
+ C: dict(x=-640, y=-50, w=160, h=100),
+ }
+
+ self.assertEqual(p.no_way_back(saved, A), [])
+
+ def test_removal_and_switch_in_either_order_leave_the_same_desk(self):
+ # Review finding 3: a removal arriving before the switch away from it was erased.
+ p = self.api()
+ desk = {"on": dict(value=True, set_at=100, by=B), "active": dict(value=P, set_at=101, by=B),
+ "profiles": {p.DESK_ID: {"removed": dict(set_at=102, by=B)},
+ P: {"name": dict(value="Sofa", set_at=99, by=B), "rows": {}, "home": {}}}}
+ switch = {"active": desk["active"], "profiles": {P: desk["profiles"][P]}}
+ removal = {"profiles": {p.DESK_ID: desk["profiles"][p.DESK_ID]}}
+ results = []
+ for order in ((switch, removal), (removal, switch)):
+ saved = self.upgraded()
+ saved["peers"][0].update(linked=True, allow_drive=True)
+ for part in order:
+ saved, *_rest, accepted, reason = p.merge_desk(saved, part, source=B, now=200)
+ self.assertTrue(accepted, reason)
+ results.append(saved["crossing_desk"]["profiles"])
+ self.assertEqual(results[0], results[1])
+ self.assertEqual(results[0][p.DESK_ID]["removed"], dict(set_at=102, by=B))
+
+ def test_old_version_edits_override_without_writing_desk(self):
+ p = self.api()
+ saved = self.upgraded()
+ desk = copy.deepcopy(saved["crossing_desk"])
+ saved["peers"][0]["ways"]["edge"] = True
+ saved, notes = p.before_load(saved, now=101)
+ self.assertIn("older_version", notes)
+ self.assertTrue(saved["crossing_own"]["use_own"])
+ self.assertEqual(saved["crossing_desk"], desk)
+
+ def test_wire_invalid_row_drops_alone_and_ahead_bound(self):
+ p = self.api()
+ row = p.live_row(raw())
+ invalid = copy.deepcopy(row)
+ invalid[B]["ways"]["thirds"] = []
+ data = dict(on=False, set_at=0, by="", desk=dict(on=dict(value=True, set_at=700, by=A),
+ profiles={p.DESK_ID: dict(rows={A: dict(value=invalid, set_at=1, by=A),
+ B: dict(value=row, set_at=2, by=B)})}, status={}))
+ parsed = p.read_desk_state(data, now=100)
+ self.assertNotIn(A, parsed["profiles"][p.DESK_ID]["rows"])
+ self.assertIn(B, parsed["profiles"][p.DESK_ID]["rows"])
+ self.assertIn("on", parsed)
+ data["desk"]["on"]["set_at"] += 1
+ self.assertNotIn("on", p.read_desk_state(data, now=100))
+
+ def test_wire_size_and_capability_and_separate_envelope(self):
+ p = self.api()
+ data = dict(on=False, set_at=0, by="", layout={"large": "picture"}, design_sync={},
+ desk={"padding": "x" * p.MAX_DESK_BYTES})
+ self.assertIsNone(p.read_desk_state(data, now=100))
+ self.assertNotIn("desk", settings_sync.for_capabilities(data, ()))
+ packet = settings_sync.desk_message_data(data, {"on": {"value": True}})
+ self.assertEqual(set(packet), {"on", "set_at", "by", "desk"})
+
+ def test_unreadable_objects_are_kept_aside(self):
+ p = self.api()
+ saved = raw()
+ saved.update(crossing_own=[1], crossing_desk="bad")
+ saved, notes = p.before_load(saved, now=100)
+ self.assertEqual(saved["crossing_own_unreadable"], [1])
+ self.assertEqual(saved["crossing_desk_unreadable"], "bad")
+ self.assertIn("upgraded", notes)
+
+ def test_partial_profile_delta_survives_reload(self):
+ p = self.api()
+ saved = self.upgraded()
+ state = {"profiles": {P: {"rows": {C: dict(value={}, set_at=101, by=B)}}}}
+ saved, _, _, _, accepted, _ = p.merge_desk(saved, state, source=B, now=101)
+ self.assertTrue(accepted)
+ loaded, notes = p.before_load(saved, now=102)
+ self.assertEqual(notes, [])
+ self.assertIn(P, loaded["crossing_desk"]["profiles"])
+
+ def test_bad_nested_register_is_preserved_not_executed(self):
+ p = self.api()
+ for path in ("on", "status", "row", "active"):
+ with self.subTest(path=path):
+ saved = self.upgraded()
+ desk = saved["crossing_desk"]
+ if path in ("on", "active"):
+ desk[path]["set_at"] = "bad"
+ elif path == "status":
+ desk["status"][A]["set_at"] = "bad"
+ else:
+ desk["profiles"][p.DESK_ID]["rows"][A] = dict(value={}, set_at="bad", by=A)
+ loaded, notes = p.before_load(saved, now=102)
+ self.assertIn("upgraded", notes)
+ self.assertIn("crossing_desk_unreadable", loaded)
+ p.after_load(loaded, platform="pc", now=102)
+
+ def test_gap_fill_does_not_consume_first_edit_archive(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"].append(dict(id=C, port=24820, send=True, ways={"edge": False}))
+ saved, _ = p.reconcile(saved, platform="mac", now=101)
+ before_edit = copy.deepcopy(saved["crossing_own"]["row"])
+ saved["peers"][0]["ways"]["edge"] = True
+ saved, _ = p.reconcile(saved, platform="mac", now=102)
+ self.assertIn(before_edit, [item["row"] for item in saved["crossing_own"]["saved"]])
+
+ def test_register_merge_forward_answer_tie_and_no_echo(self):
+ p = self.api()
+ saved = self.upgraded()
+ pid = p.DESK_ID
+ state = {"profiles": {pid: {"rows": {A: dict(value=p.live_row(saved), set_at=101, by=B)}}}}
+ saved, _, forward, answer, accepted, _ = p.merge_desk(saved, state, source=B, now=101)
+ self.assertTrue(accepted)
+ self.assertEqual(forward, state)
+ self.assertEqual(answer, {})
+ same, paths, forward, answer, _, _ = p.merge_desk(saved, state, source=B, now=101)
+ self.assertEqual((paths, forward, answer), ([], {}, {}))
+ older = copy.deepcopy(state)
+ older["profiles"][pid]["rows"][A]["by"] = A
+ _, _, forward, answer, _, _ = p.merge_desk(saved, older, source=B, now=101)
+ self.assertEqual(forward, {})
+ self.assertEqual(answer, state)
+ newer = copy.deepcopy(state)
+ newer["profiles"][pid]["rows"][A]["by"] = C
+ newer["profiles"][pid]["rows"][A]["value"][B]["ways"]["edge"] = True
+ saved, _, forward, _, _, _ = p.merge_desk(saved, newer, source=B, now=101)
+ self.assertEqual(forward, newer)
+ self.assertEqual(saved["crossing_own"]["saved"][-1]["why"], "replaced_by")
+
+ def test_duplicate_delivery_keeps_a_pending_local_edit_and_does_not_echo_again(self):
+ from core import crossing_state as events
+ from unittest import mock
+ p = self.api()
+ saved = events.set_same_ways(self.upgraded(), True, platform="mac", now=101)["settings"]
+ incoming = p.desk_message(saved)
+ saved["peers"][0]["ways"]["thirds"] = ["end"]
+ before = copy.deepcopy(saved)
+
+ out = events.desk_arrived(saved, incoming, source=B, platform="mac", now=102)
+ self.assertEqual(saved, before, "receiving must not mutate the caller's settings")
+ self.assertEqual(p.in_force(out["settings"])[0][B]["ways"]["thirds"], ["end"])
+ self.assertIn(("row", p.DESK_ID, A), out["send_desk"])
+ self.assertEqual(out["answer"]["profiles"][p.DESK_ID]["rows"][A]["value"][B]["ways"]["thirds"],
+ ["end"])
+ settled = out["settings"]
+ with mock.patch.object(p, "reconcile", wraps=p.reconcile) as reconcile:
+ again = events.desk_arrived(settled, p.desk_message(settled), source=B, platform="mac", now=103)
+ self.assertLessEqual(reconcile.call_count, 1, "a duplicate must not repeat the full projection")
+ self.assertFalse(again["changed"])
+ self.assertEqual((again["send_desk"], again["forward"], again["answer"]), ([], {}, {}))
+ again["settings"]["peers"][0]["ways"]["thirds"].append("start")
+ self.assertEqual(p.live_row(settled)[B]["ways"]["thirds"], ["end"])
+
+ def test_reconciled_holds_exactly_where_reconcile_would_change_nothing(self):
+ from core import crossing_state as events
+ p = self.api()
+ settled = events.set_same_ways(self.upgraded(), True, platform="mac", now=101)["settings"]
+
+ def variant(change):
+ changed = copy.deepcopy(settled)
+ change(changed)
+ return changed
+
+ cases = {
+ "settled": settled,
+ "a pending local edit": variant(lambda s: s["peers"][0]["ways"].update(thirds=["end"])),
+ "notch_return missing": variant(lambda s: s["peers"][0].pop("notch_return")),
+ "applied missing": variant(lambda s: s["crossing_own"].pop("applied")),
+ "a new machine": variant(lambda s: s["peers"].append(
+ dict(id=C, port=24820, send=True, ways={"edge": False}))),
+ "own row missing": variant(lambda s: s["crossing_desk"]["profiles"][p.DESK_ID]["rows"].pop(A)),
+ "an older app in status": variant(
+ lambda s: s["crossing_desk"]["status"][A]["value"].update(app="1.5.4")),
+ "own ways in force": variant(lambda s: s["crossing_own"].update(use_own=True)),
+ "sync off": variant(lambda s: s["crossing_desk"]["on"].update(value=False)),
+ }
+ for platform in ("mac", "pc"):
+ for name, settings in cases.items():
+ with self.subTest(name, platform=platform):
+ before = copy.deepcopy(settings)
+ again, paths = p.reconcile(settings, platform=platform, now=102)
+ self.assertEqual(p.reconciled(settings, platform=platform),
+ again == settings and paths == [])
+ self.assertEqual(settings, before)
+ self.assertTrue(p.reconciled(settled, platform="mac"))
+
+ def test_a_merge_that_takes_nothing_lends_the_settings_back(self):
+ from core import crossing_state as events
+ p = self.api()
+ settled = events.set_same_ways(self.upgraded(), True, platform="mac", now=101)["settings"]
+ held = p.desk_message(settled)
+ stale, newer = copy.deepcopy(held), copy.deepcopy(held)
+ stale["profiles"][p.DESK_ID]["rows"][A]["set_at"] -= 1
+ newer["profiles"][p.DESK_ID]["rows"][A].update(set_at=held["profiles"][p.DESK_ID]["rows"][A]["set_at"] + 1,
+ by=B)
+ for name, state in (("duplicate", held), ("stale", stale), ("newer", newer)):
+ with self.subTest(name):
+ before = copy.deepcopy(settled)
+ lent = p.merge_desk(settled, state, source=B, now=102, borrow=True)
+ copied = p.merge_desk(settled, state, source=B, now=102)
+ self.assertEqual(settled, before, "merging must not mutate the caller's settings")
+ self.assertEqual(lent, copied)
+ self.assertIsNot(copied[0], settled)
+ self.assertEqual(lent[0] is settled, name != "newer")
+ self.assertTrue(lent[2], "the newer row is forwarded")
+ self.assertTrue(p.merge_desk(settled, stale, source=B, now=102, borrow=True)[3], "the stale row is answered")
+
+ def test_active_removal_is_void_and_other_tombstones_survive(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["crossing_desk"]["profiles"][P] = copy.deepcopy(saved["crossing_desk"]["profiles"][p.DESK_ID])
+ state = {"profiles": {pid: {"removed": dict(set_at=101, by=B)} for pid in (P, p.DESK_ID)}}
+ saved, _, forward, _, _, _ = p.merge_desk(saved, state, source=B, now=101)
+ # The active profile's tombstone is kept, so every machine holds the same desk, but is void.
+ self.assertEqual(saved["crossing_desk"]["profiles"][p.DESK_ID]["removed"]["set_at"], 101)
+ self.assertFalse(p.removed(saved["crossing_desk"], p.DESK_ID))
+ self.assertTrue(p.removed(saved["crossing_desk"], P))
+ self.assertIn(p.DESK_ID, forward["profiles"])
+
+ def test_stale_switch_on_never_reseeds_a_live_desk(self):
+ from core import crossing_state as events
+ p = self.api()
+ saved = events.set_same_ways(self.upgraded(), True, platform="mac", now=101)["settings"]
+ saved = events.edit_ways(saved, B, edge=True, platform="mac", now=102, live=None, gone=None)["settings"]
+ held = copy.deepcopy(saved["crossing_desk"]["profiles"][p.DESK_ID]["rows"][A])
+ state = {"on": dict(value=True, set_at=200, by=B)}
+ out = events.desk_arrived(saved, state, source=B, platform="mac", now=200)
+ self.assertEqual(out["settings"]["crossing_desk"]["profiles"][p.DESK_ID]["rows"][A], held)
+
+ def test_sync_off_keeps_live_and_then_on_keeps_it_again(self):
+ from core import crossing_state as events
+ p = self.api()
+ saved = events.set_same_ways(self.upgraded(), True, platform="mac", now=101)["settings"]
+ saved = events.edit_ways(saved, B, edge=True, platform="mac", now=102, live=None, gone=None)["settings"]
+ before = p.live_row(saved)
+ for enabled in (False, True):
+ saved = events.set_same_ways(saved, enabled, platform="mac", now=103)["settings"]
+ self.assertEqual(p.live_row(saved), before)
+ self.assertTrue(any(item["why"] == "sync_off" for item in saved["crossing_own"]["saved"]))
+
+ def test_notch_resolution_uses_peer_order_and_nonmac_ignores_it(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["peers"].append(dict(id=C, port=24820, send=True, ways={"edge": False}))
+ row = p.live_row(saved)
+ row[B]["ways"]["notch"] = row[C]["ways"]["notch"] = True
+ saved["crossing_own"]["row"] = {C: row[C], B: row[B]}
+ saved["crossing_own"]["applied"] = p.live_row(saved)
+ saved, _ = p.reconcile(saved, platform="mac", now=101)
+ # The receiving machine's peer order decides, as for corners (spec section 4), not row order.
+ self.assertTrue(p.live_row(saved)[B]["ways"]["notch"])
+ self.assertFalse(p.live_row(saved)[C]["ways"]["notch"])
+ self.assertEqual([zone["peer"] for zone in saved["zones"] if zone.get("kind") == "notch"], [B])
+ saved, _ = p.reconcile(saved, platform="pc", now=102)
+ self.assertFalse(any(entry["ways"]["notch"] for entry in p.live_row(saved).values()))
+ self.assertEqual(saved["crossing_own"]["applied"], p.live_row(saved))
+
+ def test_invalid_status_missing_field_is_dropped_alone(self):
+ p = self.api()
+ saved = self.upgraded()
+ status = copy.deepcopy(saved["crossing_desk"]["status"][A])
+ status["value"].pop("row")
+ parsed = p.read_desk_state(dict(on=False, set_at=0, by="", desk={"status": {A: status}}), 101)
+ self.assertEqual(parsed, {})
+
+ def test_no_way_back_checks_actual_contacts_and_permissions(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["crossing_own"]["row"][B]["ways"].update(edge=True, edges=[])
+ # The target has a return edge enabled, but its chosen third misses the contact.
+ back = p.canonical_row({A: {"ways": {"edge": True, "thirds": ["end"]}}})
+ saved["crossing_desk"]["profiles"][p.DESK_ID]["rows"][B] = dict(value=back, set_at=1, by=B)
+ saved["layout"][B] = dict(x=160, y=0, w=160, h=300)
+ self.assertEqual(p.no_way_back(saved, A), [B])
+ saved["layout"][B]["x"] = 400
+ self.assertEqual(p.no_way_back(saved, A), [])
+ saved["layout"][B]["x"] = 160
+ saved["peers"][0]["send"] = False
+ self.assertEqual(p.no_way_back(saved, A), [])
+
+ def test_no_way_back_does_not_warn_about_machines_it_knows_nothing_of(self):
+ # Critique: with Same ways off, and for an older Beamer, every peer was listed.
+ p = self.api()
+ saved = self.upgraded()
+ saved["crossing_own"]["row"][B]["ways"].update(edge=True, edges=[])
+ saved["layout"][B] = dict(x=160, y=0, w=160, h=100)
+ self.assertEqual(p.no_way_back(saved, A), [])
+
+ def test_active_delta_before_profile_name_converges_after_metadata_arrives(self):
+ p = self.api()
+ saved = self.upgraded()
+ active = {"active": dict(value=P, set_at=101, by=B)}
+ saved, _, _, _, _, _ = p.merge_desk(saved, active, source=B, now=101)
+ metadata = {"profiles": {P: dict(name=dict(value="Sofa", set_at=100, by=B),
+ home={"shake": dict(value=True, set_at=100, by=B)}, rows={})}}
+ saved, _, _, _, _, _ = p.merge_desk(saved, metadata, source=B, now=102)
+ self.assertEqual(saved["crossing_desk"]["active"]["value"], P)
+ saved, notes = p.before_load(saved, now=103)
+ self.assertEqual(notes, [])
+
+ def test_rows_never_copy_credentials_permissions_or_addresses(self):
+ p = self.api()
+ saved = raw()
+ saved["peers"][0].update(token="synthetic", host="192.0.2.1", send=True, allow_drive=True)
+ self.assertEqual(set(p.row_entry(saved, B)), {"ways", "notch_return"})
+ row = p.canonical_row({B: {**saved["peers"][0], "notch_return": True}})
+ self.assertEqual(set(row[B]), {"ways", "notch_return"})
+
+ def test_status_stamps_only_change_with_value_and_edits_floor_above_on(self):
+ from core import crossing_state as events
+ p = self.api()
+ saved = self.upgraded()
+ twice, paths = p.reconcile(saved, platform="mac", now=200)
+ self.assertEqual(twice, saved)
+ self.assertEqual(paths, [])
+ saved = events.set_same_ways(saved, True, platform="mac", now=200)["settings"]
+ saved = events.edit_ways(saved, B, edge=True, platform="mac", now=150, live=None, gone=None)["settings"]
+ desk = saved["crossing_desk"]
+ self.assertGreater(desk["profiles"][p.DESK_ID]["rows"][A]["set_at"], desk["on"]["set_at"])
+
+ def test_caller_version_survives_event_reconciliation(self):
+ from core import crossing_state as events
+ p = self.api()
+ saved, _ = p.reconcile(self.upgraded(), platform="mac", now=101, app="1.5.4-test")
+ saved = events.set_same_ways(saved, True, platform="mac", now=102)["settings"]
+ self.assertEqual(saved["crossing_desk"]["status"][A]["value"]["app"], "1.5.4-test")
+
+ def test_archive_deduplicates_content_keeping_latest_attribution(self):
+ p = self.api()
+ saved = self.upgraded()
+ row = saved["crossing_own"]["row"]
+ p.archive(saved, row, "restored", 200, by=B)
+ self.assertEqual(len(saved["crossing_own"]["saved"]), 1)
+ self.assertEqual(saved["crossing_own"]["saved"][0]["at"], 200)
+ self.assertEqual(saved["crossing_own"]["saved"][0]["by"], B)
+
+ def test_profile_limit_and_whole_oversize_receipt(self):
+ from core import crossing_state as events
+ p = self.api()
+ saved = self.upgraded()
+ for n in range(7):
+ out = events.new_profile(saved, f"Place {n}", platform="mac", now=101 + n)
+ self.assertTrue(out["accepted"])
+ saved = out["settings"]
+ out = events.new_profile(saved, "Ninth", platform="mac", now=110)
+ self.assertFalse(out["accepted"])
+ self.assertEqual(out["reason"], "desk_full")
+ self.assertEqual(out["settings"], saved)
+ state = {"padding": "x" * p.MAX_DESK_BYTES, "on": dict(value=True, set_at=110, by=B)}
+ out = events.desk_arrived(saved, state, source=B, platform="mac", now=110)
+ self.assertFalse(out["accepted"])
+ self.assertEqual(out["settings"], saved)
+
+ def test_removed_peer_repair_uses_kept_ways_without_permissions(self):
+ p = self.api()
+ saved = self.upgraded()
+ wanted = copy.deepcopy(saved["crossing_own"]["row"][B])
+ saved["peers"] = []
+ saved, _ = p.reconcile(saved, platform="mac", now=101)
+ self.assertEqual(saved["crossing_own"]["row"][B], wanted)
+ saved["peers"] = [dict(id=B, port=24820, send=True, allow_drive=False, ways={"edge": True})]
+ saved, _ = p.reconcile(saved, platform="mac", now=102)
+ self.assertEqual(p.row_entry(saved, B), wanted)
+ self.assertFalse(saved["peers"][0]["allow_drive"])
+
+ def test_return_warning_uses_the_profile_reported_in_force(self):
+ p = self.api()
+ saved = self.upgraded()
+ saved["crossing_own"]["row"][B]["ways"].update(edge=True, edges=[])
+ desk = saved["crossing_desk"]
+ back = p.canonical_row({A: {"ways": {"edge": True}}})
+ desk["profiles"][p.DESK_ID]["rows"][B] = dict(value=back, set_at=10, by=B)
+ desk["profiles"][P] = dict(rows={B: dict(value={}, set_at=11, by=B)}, home={})
+ desk["status"][B] = dict(set_at=12, by=B, value=dict(platform="pc", in_force="desk", profile=P, row=[11, B]))
+ self.assertEqual(p.no_way_back(saved, A), [B])
+ desk["status"][B]["value"]["in_force"] = "own"
+ self.assertEqual(p.no_way_back(saved, A), [])
+
+ def test_two_machines_seed_different_ways_and_converge(self):
+ from core import crossing_state as events
+ p = self.api()
+ a = self.upgraded()
+ b = raw()
+ b["machine_id"], b["peers"][0]["id"] = B, A
+ b["peers"][0]["ways"].update(edge=True, thirds=["end"], edges=[])
+ b, _ = p.before_load(b, now=100)
+ b, _ = p.after_load(b, platform="pc", now=100)
+ a_live, b_live = p.live_row(a), p.live_row(b)
+ a = events.set_same_ways(a, True, platform="mac", now=101)["settings"]
+ arrival = events.desk_arrived(b, p.desk_message(a), source=A, platform="pc", now=102)
+ b = arrival["settings"]
+ a = events.desk_arrived(a, p.desk_message(b), source=B, platform="mac", now=103)["settings"]
+ self.assertEqual(p.live_row(a), a_live)
+ self.assertEqual(p.live_row(b), b_live)
+ self.assertEqual(a["crossing_desk"]["profiles"], b["crossing_desk"]["profiles"])
+ for own, state in ((A, a), (B, b)):
+ self.assertIn(own, state["crossing_desk"]["profiles"][p.DESK_ID]["rows"])
+
+ def test_offline_row_edit_wins_seed_but_waits_for_local_override(self):
+ from core import crossing_state as events
+ p = self.api()
+ saved = self.upgraded()
+ own = copy.deepcopy(saved["crossing_own"]["row"])
+ wanted = copy.deepcopy(own)
+ wanted[B]["ways"]["edge"] = True
+ state = {"on": dict(value=True, set_at=101, by=B), "profiles": {p.DESK_ID: {
+ "rows": {A: dict(value=wanted, set_at=102, by=B)}}}}
+ saved = events.set_own_ways(saved, True, platform="mac", now=100)["settings"]
+ saved = events.desk_arrived(saved, state, source=B, platform="mac", now=604900)["settings"]
+ self.assertEqual(p.live_row(saved), own)
+ self.assertEqual(saved["crossing_desk"]["profiles"][p.DESK_ID]["rows"][A]["value"], wanted)
+ saved = events.set_own_ways(saved, False, platform="mac", now=604901)["settings"]
+ self.assertEqual(p.live_row(saved), wanted)
+ self.assertEqual(saved["crossing_own"]["row"], own)
+
+ def test_offline_profile_switch_and_recreated_identity_do_not_reuse_old_row(self):
+ from core import crossing_state as events
+ p = self.api()
+ saved = events.set_same_ways(self.upgraded(), True, platform="mac", now=101)["settings"]
+ old = copy.deepcopy(p.in_force(saved)[0])
+ wanted = copy.deepcopy(old)
+ wanted[B]["ways"]["thirds"] = ["end"]
+ profile = dict(name=dict(value="Sofa", set_at=102, by=B), removed=None,
+ home={"shake": dict(value=True, set_at=102, by=B)},
+ rows={A: dict(value=wanted, set_at=103, by=B)})
+ state = {"active": dict(value=P, set_at=104, by=B), "profiles": {P: profile}}
+ saved = events.desk_arrived(saved, state, source=B, platform="mac", now=604900)["settings"]
+ self.assertEqual(p.live_row(saved), wanted)
+ self.assertIn(old, [item["row"] for item in saved["crossing_own"]["saved"]])
+ fresh = raw()
+ fresh["machine_id"] = C
+ fresh, _ = p.before_load(fresh, now=604900)
+ fresh, _ = p.after_load(fresh, platform="mac", now=604900)
+ new_live = p.live_row(fresh)
+ fresh = events.desk_arrived(fresh, p.desk_message(saved), source=B, platform="mac", now=604901)["settings"]
+ self.assertEqual(p.live_row(fresh), new_live)
+ self.assertEqual(fresh["crossing_desk"]["profiles"][P]["rows"][A]["value"], wanted)
+
+ def test_seeded_state_transitions_preserve_replaced_rows_and_projection(self):
+ """Archive boundaries, rather than intermediate edits in one editing session."""
+ from core import crossing_state as events
+ p = self.api()
+ rng = random.Random(154)
+ saved = self.upgraded()
+ protected = []
+ choices = ("remote", "same", "own", "profile", "switch", "remove", "older", "pair", "edit")
+ peer = copy.deepcopy(saved["peers"][0])
+ for step in range(160):
+ now = 1000 + step * 65 + rng.randint(-30, 30)
+ operation = rng.choice(choices)
+ before = copy.deepcopy(p.in_force(saved)[0])
+ if operation == "edit" and saved["peers"]:
+ key = saved["crossing_desk"]["active"]["value"] if p.in_force(saved)[1] else "own"
+ if not saved["crossing_own"].get("editing", {}).get(key):
+ protected.append(before)
+ saved = events.edit_ways(saved, B, edge=bool(rng.randrange(2)), thirds=[rng.choice(ways.PARTS)],
+ platform="mac", live=None, gone=None, now=now)["settings"]
+ elif operation == "remote" and saved["peers"]:
+ pid = saved["crossing_desk"]["active"]["value"]
+ held = saved["crossing_desk"]["profiles"][pid]["rows"].get(A)
+ if held:
+ protected.append(copy.deepcopy(held["value"]))
+ row = p.live_row(raw())
+ row[B]["ways"]["thirds"] = [rng.choice(ways.PARTS)]
+ state = {"profiles": {pid: {"rows": {A: dict(value=row, set_at=now, by=B)}}}}
+ saved = events.desk_arrived(saved, state, source=B, platform="mac", now=now)["settings"]
+ elif operation == "same":
+ protected.append(copy.deepcopy(saved["crossing_own"]["row"]))
+ saved = events.set_same_ways(saved, not p.same_ways_on(saved), platform="mac", now=now)["settings"]
+ elif operation == "own":
+ saved = events.set_own_ways(saved, not saved["crossing_own"]["use_own"], platform="mac", now=now)["settings"]
+ elif operation == "profile":
+ saved = events.new_profile(saved, "Place", platform="mac", now=now)["settings"]
+ elif operation in ("switch", "remove"):
+ ids = [item["id"] for item in p.profile_list(saved)]
+ method = events.switch_profile if operation == "switch" else events.remove_profile
+ saved = method(saved, rng.choice(ids), platform="mac", now=now)["settings"]
+ elif operation == "older" and saved["peers"]:
+ protected.append(copy.deepcopy(saved["crossing_own"]["row"]))
+ saved["peers"][0]["ways"]["edge"] = not saved["peers"][0]["ways"]["edge"]
+ saved, _ = p.before_load(saved, now=now)
+ saved, _ = p.after_load(saved, platform="mac", now=now)
+ elif operation == "pair":
+ saved["peers"] = [] if saved["peers"] else [copy.deepcopy(peer)]
+ saved, _ = p.reconcile(saved, platform="mac", now=now)
+ available = [saved["crossing_own"]["row"], p.live_row(saved)]
+ available += [item["row"] for item in saved["crossing_own"]["saved"]]
+ available += [profile["rows"][A]["value"] for profile in saved["crossing_desk"]["profiles"].values()
+ if A in profile.get("rows", {})]
+ for row in protected:
+ self.assertIn(row, available, (step, operation))
+ self.assertEqual(saved["crossing_own"]["applied"], p.live_row(saved), (step, operation))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_profiles_e2e.py b/core/tests/test_profiles_e2e.py
new file mode 100644
index 0000000..27e53c5
--- /dev/null
+++ b/core/tests/test_profiles_e2e.py
@@ -0,0 +1,767 @@
+"""Crossing profiles end to end (spec 1.5.5 sections 5, 7, 8 and 12): two to four desktops on
+loopback, each a real responder and owner, syncing the desk (`settings.data.desk`) over the real
+encrypted links through the shells in crossing_shells.py, which do what the apps do.
+
+Every case settles the desks and then asserts the same things: they settled within SETTLE_LIMIT, no
+message is still travelling a quarter of a second later (the frame count stops), no `settings` frame
+reaches 64 KiB, the profile-aware desks hold equal `crossing_desk` registers, the pictures and sides
+agree and no zone is malformed."""
+
+import copy
+import sys
+import time
+import unittest
+from unittest import mock
+
+from core import crossing_state, profiles, return_edge, ways
+from core.return_edge import Rect
+from core.tests.crossing_harness import Net, text
+from core.tests.crossing_shells import SHELLS
+from core.tests.responder_harness import entry
+
+SETTLE_LIMIT = 1.0
+QUIET = 0.25
+FRAME_LIMIT = 64 * 1024
+MAC = {"0": Rect(0, 0, 1728, 1117)}
+PC = {"0": Rect(0, 0, 3840, 2160)}
+SPECS = {"A": ("mac", MAC, 90), "B": ("pc", PC, 60), "C": ("pc", {"0": Rect(0, 0, 2560, 1600)}, 120),
+ "D": ("mac", {"0": Rect(0, 0, 1512, 982)}, 150)}
+DESK = profiles.DESK_ID
+MEASURED = {}
+
+
+def tearDownModule():
+ for name, (settle, frames) in sorted(MEASURED.items()):
+ print(f"{name}: slowest settle {settle:.3f}s, {frames} frames", file=sys.stderr)
+
+
+def desk_state(desk):
+ state = copy.deepcopy(desk.settings["crossing_desk"])
+ state.pop("format", None)
+ for profile in state["profiles"].values():
+ if profile.get("removed") is None:
+ profile.pop("removed", None)
+ return state
+
+
+def rows(desk, pid=DESK):
+ return {machine: reg["value"] for machine, reg in
+ desk.settings["crossing_desk"]["profiles"][pid]["rows"].items()}
+
+
+def spot(tile):
+ return tuple(tile[key] for key in ("x", "y", "w", "h"))
+
+
+def own_row(desk):
+ return copy.deepcopy(desk.settings["crossing_own"]["row"])
+
+
+def live(desk):
+ return profiles.live_row(desk.settings)
+
+
+def zones(desks):
+ return {desk.name: copy.deepcopy(desk.settings["zones"]) for desk in desks}
+
+
+def archived(desk, row):
+ return any(item["row"] == profiles.canonical_row(row) for item in desk.settings["crossing_own"]["saved"])
+
+
+class Mesh(unittest.TestCase):
+ def setUp(self):
+ grace = mock.patch.object(return_edge, "ARRIVAL_GRACE_SECONDS", 0.0)
+ grace.start()
+ self.addCleanup(grace.stop)
+ self.net = Net(self, SHELLS)
+ self.worst = 0.0
+ self.sent_before = 0
+ self.addCleanup(self.record)
+
+ def record(self):
+ MEASURED[self.id().rsplit(".", 2)[-2] + "." + self.id().rsplit(".", 1)[-1]] = (self.worst, self.frames())
+
+ def build(self, names, pairs=None, plain=()):
+ """Desks `names`, paired as `pairs` (strings like "AB"; every pair by default). Those in
+ `plain` are 1.5.3-style: no `profiles` capability and no crossing_own."""
+ partial = pairs is not None
+ pairs = pairs or [one + two for i, one in enumerate(names) for two in names[i + 1:]]
+ self.d = {}
+ for name in names:
+ platform, displays, seed = SPECS[name]
+ self.d[name] = self.net.add(name, platform, displays, seed, profiles=name not in plain)
+ self.pairs = [(self.d[p[0]], self.d[p[1]]) for p in pairs]
+ for desk in self.d.values():
+ partners = [other for one, two in self.pairs for other in (one, two)
+ if desk in (one, two) and other is not desk]
+ with desk.lock:
+ settings = copy.deepcopy(desk.settings)
+ settings["peers"] = [entry(other.own, other.name, token=self.key(desk, other),
+ platform=other.platform_name, linked=False,
+ paired_with=[third.id for third in partners if third is not other]
+ + [desk.id])
+ for other in partners]
+ for item in settings["peers"]:
+ item["side"] = ""
+ settings["zones"] = []
+ if partial:
+ settings.update(self.whole_picture(names))
+ desk.shell.paired(settings)
+ desk.save(settings)
+ for desk in self.d.values():
+ desk.machine.start()
+ self.addCleanup(desk.machine.stop)
+ desk.started = True
+ for one, two in self.pairs:
+ self.link(one, two)
+ for one, two in self.pairs:
+ one.shell.link_up(two)
+ two.shell.link_up(one)
+ self.settle("built")
+ return [self.d[name] for name in names]
+
+ def whole_picture(self, names):
+ """Every desk of a chain holds the same complete picture from the start: two machines that
+ are not paired never learn each other's tile through the middle one, and the cases here are
+ about the desk rows, not about how a chain's pictures merge."""
+ tiles = {}
+ for number, name in enumerate(names):
+ desk = self.d[name]
+ tiles[desk.id] = {"x": number * 160, "y": 0, "w": 160, "h": 100,
+ "displays": {key: {"x": rect.x, "y": rect.y, "w": rect.width, "h": rect.height}
+ for key, rect in desk.screen.displays.items()}}
+ return {"layout": tiles, "layout_set_at": 5, "layout_by": self.d[names[0]].id}
+
+ @staticmethod
+ def key(one, two):
+ from core.tests.crossing_harness import key
+ return key(one.own, two.own)
+
+ def link(self, one, two):
+ one.hand.connect(two)
+ two.hand.connect(one)
+
+ def unlink(self, gone):
+ """`gone` drops off the network: every link to and from it closes."""
+ for one, two in self.pairs:
+ if gone in (one, two):
+ one.hand.drop(two)
+ two.hand.drop(one)
+
+ def relink(self, back):
+ mine = [(one, two) for one, two in self.pairs if back in (one, two)]
+ for one, two in mine:
+ self.link(one, two)
+ for one, two in mine:
+ one.shell.link_up(two)
+ two.shell.link_up(one)
+
+ def frames(self):
+ return sum(len(desk.shell.frames) for desk in self.d.values())
+
+ def desk_frames(self):
+ return [frame for desk in self.d.values() for frame in desk.shell.frames if frame["desk"]]
+
+ def settle(self, label=""):
+ started = time.monotonic()
+ self.assertTrue(self.net.settle(SETTLE_LIMIT), f"{label}: the desks did not settle")
+ took = time.monotonic() - started
+ self.worst = max(self.worst, took)
+ sent = self.frames()
+ time.sleep(QUIET)
+ self.assertTrue(self.net.settle(SETTLE_LIMIT), f"{label}: the desks did not settle again")
+ self.assertEqual(self.frames(), sent, f"{label}: messages were still being sent after settling")
+ for desk in self.d.values():
+ self.assertEqual(desk.shell.errors, [], f"{label}: {desk.name} raised")
+ biggest = max((frame["size"] for desk in self.d.values() for frame in desk.shell.frames), default=0)
+ self.assertLess(biggest, FRAME_LIMIT, f"{label}: a frame of {biggest} bytes")
+ self.assertLess(max((f["size"] for f in self.desk_frames()), default=0), profiles.MAX_DESK_BYTES)
+ self.assertEqual(self.net.bad_zones(), [], label)
+ return took
+
+ def aware(self, *names):
+ return [desk for desk in self.d.values() if desk.profiles and (not names or desk.name in names)]
+
+ def assert_converged(self, label="", names=()):
+ desks = self.aware(*names)
+ first = desk_state(desks[0])
+ for desk in desks[1:]:
+ self.assertEqual(desk_state(desk), first, f"{label}: {desk.name} differs from {desks[0].name}")
+
+ def assert_agree(self, label=""):
+ self.assertEqual(self.net.views_agree(), [], label)
+ self.assertEqual(self.net.bad_zones(), [], label)
+
+ def place(self, on, moved, side, shift=0):
+ own = on.settings["layout"][on.id]
+ tile = on.settings["layout"].get(moved.id) or {"w": moved.tile_size[0], "h": moved.tile_size[1]}
+ w, h = tile["w"], tile["h"]
+ x, y = {"left": (own["x"] - w, own["y"] + (own["h"] - h) // 2 + shift),
+ "right": (own["x"] + own["w"], own["y"] + (own["h"] - h) // 2 + shift),
+ "top": (own["x"] + (own["w"] - w) // 2 + shift, own["y"] - h),
+ "bottom": (own["x"] + (own["w"] - w) // 2 + shift, own["y"] + own["h"])}[side]
+ self.assertTrue(on.shell.drop(moved, x, y))
+
+ def arrange(self, first, others):
+ """`others` round `first` on its map, then every desk given its own odd ways so that
+ no row is the default."""
+ for other, side in zip(others, ("right", "left", "top")):
+ self.place(first, other, side)
+ self.settle("arranged")
+ for number, desk in enumerate(self.d.values()):
+ for peer in self.d.values():
+ if peer is not desk and desk.peer(peer) is not None:
+ parts = [["start"], ["middle"], ["end"], ["start", "end"]][(number + len(peer.name)) % 4]
+ desk.shell.edit(peer, ["part"], parts=parts)
+ self.settle("odd ways")
+
+ def turn_on(self, desk):
+ self.assertTrue(desk.shell.same_ways(True)["accepted"])
+ self.settle("same ways on")
+
+ def make_profile(self, desk, name):
+ known = set(desk.settings["crossing_desk"]["profiles"])
+ self.assertTrue(desk.shell.new_profile(name)["accepted"])
+ (pid,) = set(desk.settings["crossing_desk"]["profiles"]) - known
+ self.settle(f"{name} made")
+ return pid
+
+
+class SameWaysChangesNothing(Mesh):
+ def check(self, names):
+ desks = self.build(names)
+ self.arrange(desks[0], desks[1:])
+ self.assert_agree("before")
+ before_zones, before_live = zones(desks), {d.name: live(d) for d in desks}
+ before_own = {d.name: own_row(d) for d in desks}
+ self.turn_on(desks[-1])
+ self.assert_agree("after")
+ self.assert_converged("on")
+ self.assertEqual(zones(desks), before_zones, "a zone moved when Same ways went on")
+ for desk in desks:
+ self.assertEqual(live(desk), before_live[desk.name], desk.name)
+ self.assertEqual(own_row(desk), before_own[desk.name], f"{desk.name}'s own row")
+ self.assertEqual(profiles.in_force(desk.settings), (before_own[desk.name], True), desk.name)
+ for other in desks:
+ self.assertEqual(rows(desk)[other.id], before_own[other.name],
+ f"{desk.name} holds {other.name}'s row as its previous own row")
+ return desks
+
+ def test_two_machines(self):
+ for desk in self.check("AB"):
+ self.assertFalse(desk.shell.refused_desks)
+
+ def test_three_machines(self):
+ self.check("ABC")
+
+ def test_four_machines(self):
+ self.check("ABCD")
+
+ def test_each_machine_turns_it_on_from_its_own_page(self):
+ desks = self.build("ABC")
+ self.arrange(desks[0], desks[1:])
+ before = zones(desks)
+ self.turn_on(desks[2])
+ self.assert_converged()
+ self.assertEqual(zones(desks), before)
+ self.assertEqual(desk_state(desks[0])["on"]["by"], desks[2].id)
+
+ def test_a_stale_machine_turning_it_on_again_seeds_nobody(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ self.turn_on(a)
+ self.assertTrue(b.shell.edit_other(a, c, thirds=["end"])["accepted"])
+ self.settle("edit")
+ held = desk_state(a)
+ c.shell.skew = -60
+ c.shell.same_ways(True)
+ self.settle("again")
+ self.assertEqual(desk_state(a)["on"], held["on"])
+ self.assertEqual(rows(a)[a.id], rows(c)[a.id])
+ self.assertEqual(rows(a)[a.id][c.id]["ways"]["thirds"], ["end"])
+
+
+class Edits(Mesh):
+ def test_an_edit_arrives_is_in_force_and_the_old_row_is_archived(self):
+ a, b = self.build("AB")
+ self.place(a, b, "right")
+ self.settle("placed")
+ self.assertTrue(a.shell.edit(b, ["edge"], edges=["right"]))
+ self.assertTrue(b.shell.edit(a, ["edge"], edges=["left"]))
+ self.settle("ways")
+ self.turn_on(a)
+ previous = own_row(b)
+ self.assertTrue(self.net.push(b, "left", 0.1) is a, "the whole edge crosses before the edit")
+ self.net.shortcut(b)
+ out = a.shell.edit_other(b, a, thirds=["end"])
+ self.assertTrue(out["accepted"])
+ self.settle("edit")
+ self.assert_converged()
+ self.assertEqual(ways.ways(b.settings, a.id)["parts"], ["end"])
+ row, desk_in_force = profiles.in_force(b.settings)
+ self.assertTrue(desk_in_force)
+ self.assertEqual(row[a.id]["ways"]["thirds"], ["end"])
+ self.assertEqual(own_row(b), previous, "the edit never reaches B's own row")
+ self.assertTrue(archived(b, previous), "B's previous row is in its archive")
+ self.assertEqual(rows(b)[b.id][a.id]["ways"]["thirds"], ["end"])
+ self.assertIs(self.net.push(b, "left", 0.1), b, "the start third is now a wall")
+ self.assertIs(self.net.push(b, "left", 0.9), a, "the end third crosses")
+ self.net.shortcut(b)
+ self.assert_agree()
+
+ def edits_reach_everyone(self, names):
+ desks = self.build(names)
+ self.arrange(desks[0], desks[1:])
+ self.turn_on(desks[0])
+ for number, editor in enumerate(desks):
+ target = desks[(number + 1) % len(desks)]
+ peer = desks[(number + 2) % len(desks)]
+ previous = copy.deepcopy(rows(target)[target.id])
+ self.assertTrue(editor.shell.edit_other(target, peer, thirds=["middle"], edge=True)["accepted"])
+ self.settle(f"{editor.name} edits {target.name}")
+ self.assert_converged(f"{editor.name} edits {target.name}")
+ self.assertEqual(ways.ways(target.settings, peer.id)["parts"], ["middle"])
+ self.assertEqual(profiles.in_force(target.settings)[1], True)
+ self.assertTrue(archived(target, previous), f"{target.name}'s row before {editor.name}'s edit")
+ self.assert_agree()
+
+ def test_edits_from_any_machine_reach_the_others_in_three(self):
+ self.edits_reach_everyone("ABC")
+
+ def test_edits_from_any_machine_reach_the_others_in_four(self):
+ self.edits_reach_everyone("ABCD")
+
+ def test_concurrent_edits_to_one_row_converge_to_the_newer(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ self.turn_on(a)
+ b.shell.skew = 10
+ a.shell.edit_other(c, b, thirds=["start"])
+ b.shell.edit_other(c, a, thirds=["end"])
+ self.settle("concurrent")
+ self.assert_converged()
+ held = self.d["C"].settings["crossing_desk"]["profiles"][DESK]["rows"][c.id]
+ self.assertEqual(held["by"], b.id, "the later clock's whole row won")
+ self.assertEqual(held["value"][a.id]["ways"]["thirds"], ["end"])
+ self.assertEqual(ways.ways(c.settings, a.id)["parts"], ["end"])
+
+ def test_concurrent_edits_to_different_rows_both_land(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ self.turn_on(a)
+ a.shell.edit_other(c, b, thirds=["start"])
+ b.shell.edit_other(a, c, thirds=["end"])
+ c.shell.edit_other(b, a, thirds=["middle"])
+ self.settle("concurrent")
+ self.assert_converged()
+ self.assertEqual(rows(a)[c.id][b.id]["ways"]["thirds"], ["start"])
+ self.assertEqual(rows(a)[a.id][c.id]["ways"]["thirds"], ["end"])
+ self.assertEqual(rows(a)[b.id][a.id]["ways"]["thirds"], ["middle"])
+ self.assertEqual(ways.ways(c.settings, b.id)["parts"], ["start"])
+ self.assertEqual(ways.ways(a.settings, c.id)["parts"], ["end"])
+ self.assertEqual(ways.ways(b.settings, a.id)["parts"], ["middle"])
+
+ def test_a_burst_of_edits_from_four_machines_settles(self):
+ desks = self.build("ABCD")
+ self.arrange(desks[0], desks[1:])
+ self.turn_on(desks[0])
+ for round_ in range(3):
+ for number, editor in enumerate(desks):
+ target = desks[(number + 1 + round_) % 4]
+ peer = desks[(number + 2 + round_) % 4]
+ if target is peer or target is editor:
+ continue
+ editor.shell.edit_other(target, peer, thirds=[["start"], ["middle"], ["end"]][round_])
+ self.settle("burst")
+ self.assert_converged()
+ self.assert_agree()
+
+
+class Chains(Mesh):
+ def test_b_edits_a_towards_c_while_b_is_not_paired_with_c(self):
+ a, b, c = self.build("ABC", pairs=["AB", "AC"])
+ self.place(a, b, "right")
+ self.place(a, c, "left")
+ self.settle("placed")
+ self.turn_on(b)
+ self.assertEqual(rows(c)[b.id], own_row(b), "B's seed reached C through A")
+ self.assertTrue(b.shell.edit_other(a, c, thirds=["end"], edge=True)["accepted"])
+ self.settle("edit")
+ self.assert_converged()
+ self.assertEqual(ways.ways(a.settings, c.id)["parts"], ["end"], "A applies it: it is paired with C")
+ self.assertEqual(rows(c)[a.id][c.id]["ways"]["thirds"], ["end"])
+ self.assertEqual(desk_state(a)["status"][a.id]["value"]["waiting"], [])
+ self.assertEqual(profiles.machine_line(b.settings, a.id, linked=True, caps={"profiles"},
+ last_heard=None), "Uses the desk's ways")
+ self.assertIsNone(b.peer(c))
+
+ def test_a_waits_for_a_machine_it_is_not_paired_with(self):
+ a, b, c = self.build("ABC", pairs=["AB", "BC"])
+ self.place(b, a, "left")
+ self.place(b, c, "right")
+ self.settle("placed")
+ self.turn_on(b)
+ live_before = live(a)
+ self.assertTrue(b.shell.edit_other(a, c, thirds=["end"], edge=True)["accepted"])
+ self.settle("edit")
+ self.assert_converged()
+ self.assertEqual(live(a), live_before, "nothing to apply to a machine it does not have")
+ self.assertEqual(rows(c)[a.id][c.id]["ways"]["thirds"], ["end"])
+ self.assertEqual(desk_state(b)["status"][a.id]["value"]["waiting"], [c.id])
+ line = profiles.machine_line(b.settings, a.id, linked=True, caps={"profiles"}, last_heard=None)
+ self.assertTrue(line.startswith("Needs pairing with"), line)
+ self.assertEqual(desk_state(b)["status"][b.id]["value"]["waiting"], [])
+ self.assertIsNone(a.peer(c))
+
+ def test_a_chain_of_four_syncs_end_to_end(self):
+ a, b, c, d = self.build("ABCD", pairs=["AB", "BC", "CD"])
+ self.turn_on(a)
+ self.assert_converged("on")
+ self.assertTrue(d.shell.edit_other(a, b, thirds=["middle"])["accepted"])
+ self.settle("edit")
+ self.assert_converged()
+ self.assertEqual(ways.ways(a.settings, b.id)["parts"], ["middle"])
+
+
+class Offline(Mesh):
+ def test_a_machine_offline_takes_the_edit_when_it_comes_back(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ self.turn_on(a)
+ previous = own_row(c)
+ held = live(c)
+ self.unlink(c)
+ self.assertTrue(a.shell.edit_other(c, b, thirds=["end"], edge=True)["accepted"])
+ self.settle("a edits")
+ self.assertTrue(b.shell.edit_other(c, a, thirds=["start"], edge=True)["accepted"])
+ self.settle("offline")
+ self.assertEqual(live(c), held, "C has heard nothing")
+ self.assertEqual(rows(a)[c.id], rows(b)[c.id])
+ self.assertNotEqual(rows(a)[c.id], rows(c)[c.id])
+ self.relink(c)
+ self.settle("back")
+ self.assert_converged()
+ self.assertEqual(ways.ways(c.settings, a.id)["parts"], ["start"])
+ self.assertEqual(ways.ways(c.settings, b.id)["parts"], ["end"])
+ self.assertEqual(own_row(c), previous, "its own row never moved")
+ self.assertTrue(archived(c, previous))
+ self.assert_agree()
+
+ def test_edits_made_on_both_sides_of_the_gap_converge_to_the_newer(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ self.turn_on(a)
+ self.unlink(c)
+ a.shell.edit_other(c, b, thirds=["end"])
+ self.settle("away")
+ time.sleep(1.1)
+ c.shell.edit(b, ["part"], parts=["start"])
+ self.settle("c edits itself")
+ self.relink(c)
+ self.settle("back")
+ self.assert_converged()
+ self.assertEqual(rows(a)[c.id][b.id]["ways"]["thirds"], ["start"], "the later edit wins whoever made it")
+ self.assertEqual(ways.ways(c.settings, b.id)["parts"], ["start"])
+
+ def test_the_offline_machine_catches_up_on_a_new_profile_too(self):
+ a, b, c = self.build("ABC")
+ self.turn_on(a)
+ self.unlink(c)
+ pid = self.make_profile(a, "Sofa")
+ a.shell.switch_profile(pid)
+ self.settle("switched")
+ self.relink(c)
+ self.settle("back")
+ self.assert_converged()
+ self.assertEqual(c.settings["crossing_desk"]["active"]["value"], pid)
+ self.assert_agree()
+
+
+class ClockSkew(Mesh):
+ def test_a_minute_either_way_changes_nothing_that_matters(self):
+ a, b, c = self.build("ABC")
+ a.shell.skew, b.shell.skew, c.shell.skew = 60, 0, -60
+ self.arrange(a, [b, c])
+ before = zones([a, b, c])
+ self.turn_on(a)
+ self.assertEqual(zones([a, b, c]), before)
+ # The machine 120 s behind the one that switched on: its edit still beats every seed.
+ self.assertTrue(c.shell.edit_other(b, a, thirds=["end"], edge=True)["accepted"])
+ self.settle("behind edits")
+ self.assert_converged()
+ self.assertEqual(ways.ways(b.settings, a.id)["parts"], ["end"])
+ for first, second in ((a, c), (c, a)):
+ second_choice = ["start"] if first is a else ["middle"]
+ first.shell.edit_other(b, a, thirds=["start"])
+ self.settle(f"{first.name} then {second.name}")
+ second.shell.edit_other(b, a, thirds=second_choice)
+ self.settle(f"{second.name} after {first.name}")
+ self.assert_converged()
+ self.assertEqual(ways.ways(b.settings, a.id)["parts"], second_choice,
+ f"{second.name}'s edit came after {first.name}'s and wins whatever the clocks say")
+ self.assert_agree()
+
+ def test_concurrent_edits_a_minute_apart_go_to_the_later_clock_everywhere(self):
+ a, b, c = self.build("ABC")
+ a.shell.skew, c.shell.skew = -60, 60
+ self.arrange(a, [b, c])
+ self.turn_on(b)
+ a.shell.edit_other(b, c, thirds=["start"])
+ c.shell.edit_other(b, a, thirds=["end"])
+ self.settle("concurrent")
+ self.assert_converged()
+ self.assertEqual(rows(a)[b.id][a.id]["ways"]["thirds"], ["end"])
+ self.assertEqual(desk_state(a)["profiles"][DESK]["rows"][b.id]["by"], c.id)
+
+
+class PlainMiddle(Mesh):
+ def test_a_machine_without_profiles_relays_nothing_and_is_unaffected(self):
+ a, m, c = self.build("ABC", pairs=["AB", "BC"], plain=("B",))
+ self.place(m, a, "left")
+ self.place(m, c, "right")
+ self.settle("placed")
+ self.assert_agree()
+ picture = copy.deepcopy(m.settings["layout"])
+ m_before = copy.deepcopy(m.settings)
+ a.shell.same_ways(True)
+ self.settle("on")
+ a.shell.edit_other(c, a, thirds=["end"])
+ self.settle("edit")
+ self.assertEqual(desk_state(c)["on"]["value"], False, "the desk did not cross a machine without profiles")
+ self.assertNotIn("crossing_desk", m.settings)
+ self.assertNotIn("crossing_own", m.settings)
+ self.assertEqual(m.settings, m_before)
+ self.assertFalse([f for f in a.shell.frames if f["desk"] and f["peer"] == m.id])
+ self.assertFalse([f for f in m.shell.frames if f["desk"]])
+ self.assertEqual(m.settings["layout"], picture)
+ self.assertIs(self.net.push(a, "right"), m, "layout and crossing carry on across it")
+ self.net.shortcut(a)
+ self.assert_agree()
+
+ def test_with_a_direct_link_the_desk_still_syncs_and_the_plain_machine_is_untouched(self):
+ a, m, c = self.build("ABC", plain=("B",))
+ self.place(a, m, "right")
+ self.place(a, c, "left")
+ self.settle("placed")
+ m_before = copy.deepcopy(m.settings)
+ a.shell.same_ways(True)
+ a.shell.edit_other(c, a, thirds=["end"])
+ self.settle("edit")
+ self.assert_converged()
+ self.assertEqual(ways.ways(c.settings, a.id)["parts"], ["end"])
+ self.assertEqual(m.settings, m_before)
+ self.assertEqual(m.shell.refused_desks, [])
+ self.assert_agree()
+
+
+class Override(Mesh):
+ def test_override_holds_b_until_it_turns_it_off(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ self.turn_on(a)
+ own = own_row(b)
+ held, held_zones = live(b), copy.deepcopy(b.settings["zones"])
+ self.assertTrue(b.shell.own_ways(True)["accepted"])
+ self.settle("override")
+ self.assertEqual(b.settings["zones"], held_zones)
+ self.assertTrue(a.shell.edit_other(b, a, thirds=["end"], edge=True)["accepted"])
+ self.assertTrue(c.shell.edit_other(b, c, thirds=["middle"], edge=True)["accepted"])
+ self.settle("edits")
+ self.assert_converged()
+ self.assertEqual(live(b), held, "B's crossing did not move")
+ self.assertEqual(b.settings["zones"], held_zones)
+ self.assertEqual(own_row(b), own)
+ self.assertEqual(rows(b)[b.id][a.id]["ways"]["thirds"], ["end"], "the desk row took the edit")
+ self.assertEqual(profiles.in_force(b.settings)[1], False)
+ a.shell.own_ways(False)
+ self.settle("a's own page")
+ self.assertTrue(b.settings["crossing_own"]["use_own"], "no message turns B's override off")
+ self.assertTrue(b.shell.own_ways(False)["accepted"])
+ self.settle("override off")
+ self.assertEqual(ways.ways(b.settings, a.id)["parts"], ["end"])
+ self.assertEqual(ways.ways(b.settings, c.id)["parts"], ["middle"])
+ self.assertEqual(own_row(b), own, "its own row is still what it was")
+ self.assert_agree()
+
+ def test_sharing_mine_sends_the_own_row_to_the_desk(self):
+ a, b = self.build("AB")
+ self.place(a, b, "right")
+ self.settle("placed")
+ self.turn_on(a)
+ b.shell.own_ways(True)
+ b.shell.edit(a, ["part"], parts=["start"])
+ self.settle("own edit")
+ self.assertNotEqual(rows(a)[b.id], own_row(b))
+ out = crossing_state.share_mine(b.shell.current(), platform=b.shell.platform, now=b.shell.now())
+ b.shell.carry_out(out)
+ self.settle("shared")
+ self.assert_converged()
+ self.assertEqual(rows(a)[b.id], own_row(b))
+ self.assertEqual(rows(a)[b.id][a.id]["ways"]["thirds"], ["start"])
+
+
+class OffAndOn(Mesh):
+ def test_off_then_on_moves_nobodys_zones(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ self.turn_on(a)
+ a.shell.edit_other(c, a, thirds=["end"], edge=True)
+ b.shell.edit_other(a, b, thirds=["middle"], edge=True)
+ self.settle("edits")
+ desks = [a, b, c]
+ before = zones(desks)
+ before_live = {d.name: live(d) for d in desks}
+ rows_before = copy.deepcopy(rows(a))
+ self.assertTrue(b.shell.same_ways(False)["accepted"])
+ self.settle("off")
+ self.assertEqual(zones(desks), before)
+ for desk in desks:
+ self.assertFalse(profiles.same_ways_on(desk.settings))
+ self.assertEqual(live(desk), before_live[desk.name])
+ self.assertEqual(own_row(desk), rows_before[desk.id], f"{desk.name} keeps what it crossed by as its own")
+ self.assertTrue(a.shell.same_ways(True)["accepted"])
+ self.settle("on again")
+ self.assert_converged()
+ self.assertEqual(zones(desks), before)
+ for desk in desks:
+ self.assertEqual(live(desk), before_live[desk.name])
+ self.assertEqual(rows(desk)[desk.id], rows_before[desk.id])
+ self.assert_agree()
+
+
+class Switching(Mesh):
+ def test_a_switch_carries_the_picture_and_a_switch_back_restores_it(self):
+ a, b, c = self.build("ABC")
+ self.place(a, b, "right")
+ self.place(a, c, "left")
+ self.settle("placed")
+ self.turn_on(a)
+ desk_picture = {d.name: copy.deepcopy(d.settings["layout"]) for d in (a, b, c)}
+ sofa = self.make_profile(a, "Sofa")
+ self.assert_converged()
+ self.assertEqual(rows(b, sofa), rows(b), "a new profile starts from the active one's rows")
+ a.shell.switch_profile(sofa)
+ self.settle("to Sofa")
+ self.assertTrue(all(d.settings["crossing_desk"]["active"]["value"] == sofa for d in (a, b, c)))
+ self.place(a, c, "bottom")
+ self.settle("moved in Sofa")
+ sofa_picture = copy.deepcopy(a.settings["layout"])
+ self.assertNotEqual(spot(sofa_picture[c.id]), spot(desk_picture["A"][c.id]))
+ self.assert_agree("sofa")
+ b.shell.switch_profile(DESK)
+ self.settle("back to Desk")
+ self.assert_converged()
+ self.assert_agree("desk")
+ for d in (a, b, c):
+ self.assertEqual(spot(d.settings["layout"][c.id]), spot(desk_picture["A"][c.id]), d.name)
+ a.shell.switch_profile(sofa)
+ self.settle("to Sofa again")
+ self.assert_agree("sofa again")
+ self.assertEqual(spot(c.settings["layout"][c.id]), spot(sofa_picture[c.id]))
+
+ def test_a_drop_in_flight_during_a_switch_converges(self):
+ a, b, c = self.build("ABC")
+ self.place(a, b, "right")
+ self.place(a, c, "left")
+ self.settle("placed")
+ self.turn_on(a)
+ sofa = self.make_profile(a, "Sofa")
+ own = b.settings["layout"][b.id]
+ a.shell.switch_profile(sofa)
+ b.shell.drop(c, own["x"], own["y"] + own["h"])
+ c.shell.edit_other(a, b, thirds=["end"])
+ self.settle("racing")
+ self.assert_converged()
+ self.assert_agree()
+ self.assertEqual({d.settings["crossing_desk"]["active"]["value"] for d in (a, b, c)}, {sofa})
+ self.assertEqual(len({tuple(sorted((k, v["x"], v["y"]) for k, v in d.settings["layout"].items()))
+ for d in (a, b, c)}), 1, "one picture everywhere")
+ a.shell.switch_profile(DESK)
+ self.settle("home")
+ self.assert_converged()
+ self.assert_agree()
+
+ def test_a_removed_profile_stays_removed_for_the_machine_that_was_away(self):
+ a, b, c = self.build("ABC")
+ self.turn_on(a)
+ sofa = self.make_profile(a, "Sofa")
+ self.unlink(c)
+ a.shell.switch_profile(sofa)
+ a.shell.switch_profile(DESK)
+ out = crossing_state.remove_profile(a.shell.current(), sofa, platform="mac", now=a.shell.now())
+ self.assertTrue(out["accepted"])
+ a.shell.carry_out(out)
+ self.settle("removed")
+ self.relink(c)
+ self.settle("back")
+ self.assert_converged()
+ self.assertIsNotNone(c.settings["crossing_desk"]["profiles"][sofa]["removed"])
+
+class Refusal(Mesh):
+ def test_a_desk_from_a_peer_that_may_not_drive_is_refused(self):
+ a, b = self.build("AB")
+ self.place(a, b, "right")
+ self.settle("placed")
+ settings = copy.deepcopy(b.settings)
+ settings["peers"][0]["allow_drive"] = False
+ b.save(settings)
+ held = copy.deepcopy(b.settings)
+ a.shell.same_ways(True)
+ a.shell.edit_other(b, a, thirds=["end"])
+ self.settle("sent")
+ self.assertTrue(b.shell.refused_desks)
+ self.assertEqual({reason for _, reason in b.shell.refused_desks}, {"untrusted"})
+ self.assertEqual(b.settings["crossing_desk"], held["crossing_desk"])
+ self.assertEqual(b.settings["zones"], held["zones"])
+ self.assertEqual(b.settings["peers"], held["peers"])
+ self.assertTrue(profiles.same_ways_on(a.settings))
+
+ def test_what_a_trusted_peer_relays_is_taken_whoever_made_it(self):
+ a, b, c = self.build("ABC")
+ self.arrange(a, [b, c])
+ settings = copy.deepcopy(b.settings)
+ for item in settings["peers"]:
+ if item["id"] == a.id:
+ item["allow_drive"] = False
+ b.save(settings)
+ a.shell.same_ways(True)
+ self.settle("on")
+ self.assertTrue(profiles.same_ways_on(b.settings), "C relayed it")
+ self.assertIn((a.id, "untrusted"), b.shell.refused_desks)
+ a.shell.edit_other(b, c, thirds=["end"])
+ self.settle("edit")
+ self.assertEqual(ways.ways(b.settings, c.id)["parts"], ["end"])
+
+
+class TileResizeConvergence(Mesh):
+ def test_resizing_one_tile_converges_and_crosses_into_its_matching_span(self):
+ a, b, c = self.build("ABC")
+ self.place(a, b, "top")
+ self.place(a, c, "left")
+ self.settle("clear resize area")
+ own = a.settings["layout"][a.id]
+ tiles = copy.deepcopy(a.settings["layout"])
+ resized = ways.resize_tile(tiles[b.id], 320)
+ resized.update(x=own["x"] + own["w"], y=own["y"] + own["h"] - resized["h"])
+ tiles[b.id] = resized
+ with a.shell.lock:
+ outcome = crossing_state.drop(a.shell.current(), tiles, b.id,
+ capable=a.shell.capable(), snap_radius=0, **a.shell._args())
+ self.assertTrue(outcome["accepted"])
+ a.shell.carry_out(outcome)
+ self.settle("resized")
+ self.assert_agree("resized")
+ for desk in (a, b, c):
+ self.assertEqual((desk.settings["layout"][b.id]["w"],
+ desk.settings["layout"][b.id]["h"]), (320, 200), desk.name)
+ edge = next(zone for zone in a.settings["zones"]
+ if zone["peer"] == b.id and zone["kind"] == "edge")
+ self.assertEqual(edge["target_span"], [0.5, 1.0])
+ self.assertIs(self.net.push(a, "right", 0.75), b)
+ landed = b.screen.placed[-1]
+ self.assertGreater(landed[1], b.screen.displays["0"].y + b.screen.displays["0"].height / 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_profiles_migration.py b/core/tests/test_profiles_migration.py
new file mode 100644
index 0000000..cec8520
--- /dev/null
+++ b/core/tests/test_profiles_migration.py
@@ -0,0 +1,374 @@
+"""Settings-load migration and its backup boundary for Crossing profiles."""
+
+import copy
+import importlib
+import json
+import os
+import subprocess
+import sys
+import tarfile
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "win_app"))
+
+
+class GuiImportBlocked(ImportError):
+ pass
+
+
+class BlockGuiImports:
+ # Importing objc and AppKit registers nothing with the WindowServer, so the Mac legs run on a Mac;
+ # BEAMER_TEST_NO_APPKIT=1 (a sandbox that refuses them) skips those legs instead.
+ blocked = {"PySide2", "PySide6", "PyQt5", "PyQt6", "qtpy", "tkinter"} | (
+ {"AppKit", "objc"} if os.environ.get("BEAMER_TEST_NO_APPKIT") == "1" else set())
+
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname.split(".", 1)[0] in self.blocked:
+ raise GuiImportBlocked("blocked before import: " + fullname)
+
+
+# Installed only around this module's own imports: left in place it would refuse GUI imports to
+# every module the shared Windows suite (win_app/tests/test_core.py) imports after this one.
+_BLOCKER = BlockGuiImports()
+sys.meta_path.insert(0, _BLOCKER)
+try:
+ from core import profiles
+ from core import crossing_state
+ from core.tests.test_profiles import raw as profiles_raw
+finally:
+ sys.meta_path.remove(_BLOCKER)
+
+
+def _profileless(settings):
+ result = copy.deepcopy(settings)
+ result.pop("crossing_own", None)
+ result.pop("crossing_desk", None)
+ return result
+
+
+class MigrationBackupTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(dir=ROOT)
+ self.addCleanup(self.tmp.cleanup)
+ self.folder = Path(self.tmp.name)
+
+ _mac_module = None
+
+ def _mac_store_and_153_file(self):
+ # Loaded once per process: an Objective-C class cannot be defined twice, so the Mac modules
+ # are never purged and re-imported between tests.
+ if MigrationBackupTests._mac_module is None:
+ if sys.platform != "darwin":
+ # Not even attempted: a failed import still leaves mac_app's config and crossing
+ # modules in sys.modules for the rest of a shared suite.
+ self.skipTest("Mac SettingsStore leg runs on macOS only")
+ old_path = sys.path[:]
+ sys.meta_path.insert(0, _BLOCKER)
+ try:
+ sys.path.insert(0, str(ROOT / "mac_app"))
+ MigrationBackupTests._mac_module = importlib.import_module("settings_store")
+ except ImportError as exc:
+ # Off the Mac there is no PyObjC, and another module's blocker is an ImportError too;
+ # the Windows and Linux legs still run.
+ self.skipTest(f"Mac SettingsStore leg skipped: {exc}")
+ finally:
+ sys.meta_path.remove(_BLOCKER)
+ sys.path[:] = old_path
+ settings_store = MigrationBackupTests._mac_module
+ store = settings_store.SettingsStore(self.folder / "settings.json")
+ normalised = store.load_settings()
+ raw = _profileless(normalised)
+ original = json.dumps(raw, indent=2, ensure_ascii=False).encode("utf-8") + b"\n"
+ store.path.write_bytes(original)
+ return store, original, settings_store
+
+ def _windows_file(self):
+ import app_config
+ path = self.folder / "settings.json"
+ settings = app_config.load_settings(path)
+ raw = _profileless(settings)
+ original = json.dumps(raw, indent=2).encode("utf-8") + b"\n"
+ path.write_bytes(original)
+ return app_config, path, original
+
+ def _assert_backup_before_write(self, path, original, writer):
+ backup = path.with_name("settings.json.before-1.5.5")
+ self.assertEqual(path.read_bytes(), original, "load alone must leave a 1.5.3 file byte-for-byte intact")
+ writer()
+ self.assertEqual(backup.read_bytes(), original)
+ loaded = json.loads(path.read_text(encoding="utf-8"))
+ self.assertIn("crossing_own", loaded)
+ backup.write_bytes(b"existing backup")
+ writer()
+ self.assertEqual(backup.read_bytes(), b"existing backup", "an existing backup is never overwritten")
+
+ def test_windows_upgrade_backup_is_made_once_before_first_save(self):
+ app_config, path, original = self._windows_file()
+ settings = app_config.load_settings(path)
+ self._assert_backup_before_write(path, original, lambda: app_config.write_settings(path, settings))
+
+ def test_mac_upgrade_backup_is_made_once_before_first_save(self):
+ store, original, _module = self._mac_store_and_153_file()
+ settings = store.load_settings()
+ self._assert_backup_before_write(store.path, original, lambda: store.save_settings(settings))
+
+ def test_windows_backup_failure_leaves_original_settings_untouched(self):
+ app_config, path, original = self._windows_file()
+ settings = app_config.load_settings(path)
+ with mock.patch.object(app_config.shutil, "copyfile", side_effect=OSError("backup denied")):
+ with self.assertRaises(OSError):
+ app_config.write_settings(path, settings)
+ self.assertEqual(path.read_bytes(), original)
+ self.assertFalse(path.with_name("settings.json.before-1.5.5").exists())
+
+ def test_windows_backup_source_read_failure_aborts_save(self):
+ app_config, path, original = self._windows_file()
+ settings = app_config.load_settings(path)
+ real_read_bytes = Path.read_bytes
+
+ def fail_source(this):
+ if this == path:
+ raise OSError("source read denied")
+ return real_read_bytes(this)
+
+ with mock.patch.object(Path, "read_bytes", fail_source):
+ with self.assertRaises(OSError):
+ app_config.write_settings(path, settings)
+ with path.open("rb") as handle:
+ self.assertEqual(handle.read(), original)
+ self.assertFalse(path.with_name("settings.json.before-1.5.5").exists())
+
+ def test_mac_backup_failure_leaves_original_settings_untouched(self):
+ store, original, store_module = self._mac_store_and_153_file()
+ settings = store.load_settings()
+ with mock.patch.object(store_module, "shutil", create=True):
+ store_module.shutil.copyfile.side_effect = OSError("backup denied")
+ with self.assertRaises(Exception):
+ store.save_settings(settings)
+ self.assertEqual(store.path.read_bytes(), original)
+ self.assertFalse(store.path.with_name("settings.json.before-1.5.5").exists())
+
+ def test_mac_backup_source_read_failure_aborts_save(self):
+ store, original, _module = self._mac_store_and_153_file()
+ settings = store.load_settings()
+ real_read_bytes = Path.read_bytes
+
+ def fail_source(this):
+ if this == store.path:
+ raise OSError("source read denied")
+ return real_read_bytes(this)
+
+ with mock.patch.object(Path, "read_bytes", fail_source):
+ with self.assertRaises(OSError):
+ store.save_settings(settings)
+ with store.path.open("rb") as handle:
+ self.assertEqual(handle.read(), original)
+ self.assertFalse(store.path.with_name("settings.json.before-1.5.5").exists())
+
+ def test_windows_row_and_archive_write_fail_together(self):
+ app_config, path, original = self._windows_file()
+ settings = app_config.load_settings(path)
+ settings["crossing_own"]["row"]["synthetic"] = {"ways": {"edge": False}, "notch_return": False}
+ settings["crossing_own"]["saved"].append(
+ {"id": "synthetic", "why": "edited", "at": 100, "row": {"synthetic": {"ways": {}, "notch_return": False}}}
+ )
+ with mock.patch.object(app_config.os, "replace", side_effect=OSError("atomic replace denied")):
+ with self.assertRaises(OSError):
+ app_config.write_settings(path, settings)
+ self.assertEqual(path.read_bytes(), original)
+
+ def test_mac_row_and_archive_write_fail_together(self):
+ store, original, store_module = self._mac_store_and_153_file()
+ settings = store.load_settings()
+ settings["crossing_own"]["row"]["synthetic"] = {"ways": {"edge": False}, "notch_return": False}
+ settings["crossing_own"]["saved"].append(
+ {"id": "synthetic", "why": "edited", "at": 100, "row": {"synthetic": {"ways": {}, "notch_return": False}}}
+ )
+ with mock.patch.object(store_module.os, "replace", side_effect=OSError("atomic replace denied")):
+ with self.assertRaises(Exception):
+ store.save_settings(settings)
+ self.assertEqual(store.path.read_bytes(), original)
+
+
+class MigrationCoreTests(unittest.TestCase):
+ def test_upgrade_archives_raw_crossing_choices_before_normalisation(self):
+ peer = "AQEBAQEBAQEBAQEBAQEBAQ"
+ raw = {
+ "schema": 6,
+ "machine_id": "AgICAgICAgICAgICAgICAg",
+ "peers": [{"id": peer, "send": True, "ways": {"edge": True, "thirds": ["start", "end"]},
+ "notch_return": True}],
+ }
+ settings, notes = profiles.before_load(raw, now=100)
+ self.assertIn("upgraded", notes)
+ self.assertEqual(settings["crossing_own"]["saved"][0]["why"], "upgrade")
+ self.assertEqual(settings["crossing_own"]["saved"][0]["row"], settings["crossing_own"]["row"])
+ self.assertTrue(settings.get("_crossing_profiles_upgrade_pending"))
+
+
+class DowngradeCompatibilityTests(unittest.TestCase):
+ def _frozen_153(self, folder):
+ archive = subprocess.run(
+ ["git", "archive", "be9661d1", "core", "win_app", "mac_app"],
+ cwd=ROOT, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ ).stdout
+ frozen = folder / "frozen"
+ frozen.mkdir()
+ with tarfile.open(fileobj=__import__("io").BytesIO(archive)) as bundle:
+ bundle.extractall(frozen, filter="data")
+ return frozen
+
+ @staticmethod
+ def _gui_blocker():
+ return r'''\
+import sys
+class GuiImportBlocked(RuntimeError):
+ pass
+class BlockGuiImports:
+ blocked = {"PySide2", "PySide6", "PyQt5", "PyQt6", "qtpy", "tkinter"} | (
+ {"AppKit", "objc"} if __import__("os").environ.get("BEAMER_TEST_NO_APPKIT") == "1" else set())
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname.split(".", 1)[0] in self.blocked:
+ raise GuiImportBlocked("blocked before import: " + fullname)
+sys.meta_path.insert(0, BlockGuiImports())
+'''
+
+ def test_153_code_keeps_new_top_level_settings_and_peer_fields(self):
+ """Run the frozen 1.5.3 readers from their own tree in a child interpreter."""
+ with tempfile.TemporaryDirectory(dir=ROOT) as temp:
+ work = Path(temp)
+ frozen = self._frozen_153(work)
+ script = r'''\
+''' + self._gui_blocker() + r'''
+import copy, json, os, pathlib, sys, tempfile
+root = pathlib.Path(sys.argv[1])
+work = pathlib.Path(sys.argv[2])
+sys.path.insert(0, str(root / "win_app"))
+sys.path.insert(0, str(root))
+from core import crossing_state
+mid = lambda n: __import__("base64").urlsafe_b64encode(bytes([n])*16).decode().rstrip("=")
+me, peer = mid(1), mid(2)
+s = {"schema":6,"machine_id":me,"name":"","port":24820,"shortcut":True,"migrated_token_sha256":"",
+ "peers":[{"id":peer,"name":"PC","platform":"windows","token":"t"*43,"host":"192.0.2.5","port":24820,
+ "hw":"","send":True,"allow_drive":True,"in_use":True,"side":"right","side_set_at":1,"side_by":me,
+ "paired_with":[],"paired_at":1,"linked":True,"from_1_4":False,
+ "ways":{"edge":True,"thirds":["start","middle","end"],"edges":[],"corner":True,"corner_at":"top_left",
+ "corners":[],"notch":False},"crossing_future_peer_field":{"keep":True}}],
+ "zones":[],"layout":{me:{"x":0,"y":0,"w":100,"h":100},peer:{"x":100,"y":0,"w":100,"h":100}},
+ "layout_set_at":0,"layout_by":"","crossing_own":{"sentinel":1},"crossing_desk":{"sentinel":2}}
+core = crossing_state.migrate(copy.deepcopy(s), "pc")["settings"]
+assert core["crossing_own"] == {"sentinel":1} and core["crossing_desk"] == {"sentinel":2}
+assert core["peers"][0]["crossing_future_peer_field"] == {"keep":True}
+from app_config import load_settings, write_settings
+folder = pathlib.Path(tempfile.mkdtemp(dir=work)); path = folder / "settings.json"
+path.write_text(json.dumps(core)); loaded = load_settings(path); write_settings(path, loaded)
+win = json.loads(path.read_text())
+assert win["crossing_own"] == {"sentinel":1} and win["crossing_desk"] == {"sentinel":2}
+assert win["peers"][0]["crossing_future_peer_field"] == {"keep":True}
+sys.path.insert(0, str(root / "mac_app"))
+try:
+ from settings_store import SettingsStore
+except (GuiImportBlocked, ImportError) as exc:
+ print("frozen Mac load/save skipped: " + str(exc))
+else:
+ path = folder / "mac-settings.json"; path.write_text(json.dumps(core))
+ store = SettingsStore(path); loaded = store.load_settings(); store.save_settings(loaded)
+ mac = json.loads(path.read_text())
+ assert mac["crossing_own"] == {"sentinel":1} and mac["crossing_desk"] == {"sentinel":2}
+ assert mac["peers"][0]["crossing_future_peer_field"] == {"keep":True}
+ print("core, Windows and Mac 1.5.3 loads/saves kept profile objects and peer fields")
+'''
+ result = subprocess.run(
+ [sys.executable, "-c", script, str(frozen), str(work)], cwd=ROOT,
+ text=True, capture_output=True,
+ )
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ if "Mac load/save skipped" in result.stdout:
+ self.assertTrue("blocked before import: objc" in result.stdout or sys.platform != "darwin",
+ result.stdout)
+ else:
+ self.assertIn("kept profile objects", result.stdout)
+
+ def test_153_round_trips_keep_or_fold_live_crossing_edits(self):
+ with tempfile.TemporaryDirectory(dir=ROOT) as temp:
+ work = Path(temp)
+ frozen = self._frozen_153(work)
+ initial, _ = profiles.before_load(profiles_raw(), now=100)
+ initial = crossing_state.migrate(initial, "mac")["settings"]
+ initial, _ = profiles.after_load(initial, platform="mac", now=100)
+ initial = crossing_state.set_same_ways(initial, True, platform="mac", now=101)["settings"]
+ peer = initial["peers"][0]["id"]
+ self.assertEqual(profiles.in_force(initial)[0], initial["crossing_desk"]["profiles"][
+ initial["crossing_desk"]["active"]["value"]]["rows"][initial["machine_id"]]["value"])
+
+ script = r'''\
+''' + self._gui_blocker() + r'''
+import copy, json, pathlib, sys
+root, path, mode, peer = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), sys.argv[3], sys.argv[4]
+sys.path.insert(0, str(root / "win_app")); sys.path.insert(0, str(root))
+from core import crossing_state
+settings = json.loads(path.read_text(encoding="utf-8"))
+if mode == "normalise":
+ settings["peers"][0]["ways"]["future_in_ways"] = {"ignored": True}
+settings = crossing_state.migrate(settings, "pc")["settings"]
+if mode == "edit":
+ settings = crossing_state.edit_ways(settings, peer, platform="pc", edge=True,
+ live=lambda _p: True, gone=lambda _p: False, now=102)["settings"]
+path.write_text(json.dumps(settings), encoding="utf-8")
+from app_config import load_settings, write_settings
+settings = load_settings(path); write_settings(path, settings)
+sys.path.insert(0, str(root / "mac_app"))
+try:
+ from settings_store import SettingsStore
+except (GuiImportBlocked, ImportError) as exc:
+ print("frozen Mac 1.5.3 load/save skipped: " + str(exc))
+else:
+ store = SettingsStore(path); settings = store.load_settings(); store.save_settings(settings)
+ print("frozen Mac 1.5.3 load/save complete")
+print("frozen 1.5.3 core and Windows round trip complete")
+'''
+ for mode in ("unchanged", "normalise", "edit"):
+ with self.subTest(mode=mode):
+ path = work / f"{mode}.json"
+ path.write_text(json.dumps(initial), encoding="utf-8")
+ result = subprocess.run(
+ [sys.executable, "-c", script, str(frozen), str(path), mode, peer],
+ cwd=ROOT, text=True, capture_output=True,
+ )
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("round trip complete", result.stdout)
+ if "Mac 1.5.3 load/save skipped" in result.stdout:
+ self.assertTrue("blocked before import: objc" in result.stdout or sys.platform != "darwin",
+ result.stdout)
+ old_roundtrip = json.loads(path.read_text(encoding="utf-8"))
+ if mode == "normalise":
+ self.assertNotIn("future_in_ways", old_roundtrip["peers"][0]["ways"])
+ migrated, notes = profiles.before_load(old_roundtrip, now=103)
+ migrated, _ = profiles.after_load(migrated, platform="mac", now=103)
+ self.assertEqual(migrated["crossing_own"]["applied"], profiles.live_row(migrated))
+ if mode == "edit":
+ self.assertIn("older_version", notes)
+ self.assertTrue(migrated["crossing_own"]["use_own"])
+ self.assertEqual(migrated["crossing_own"]["saved"][-1]["why"], "older_version")
+ self.assertTrue(migrated["crossing_own"]["row"][peer]["ways"]["edge"])
+ else:
+ self.assertNotIn("older_version", notes)
+ self.assertFalse(migrated["crossing_own"]["use_own"])
+ self.assertEqual(migrated["crossing_own"]["row"], initial["crossing_own"]["row"])
+
+ def test_malformed_profile_state_is_preserved_under_unreadable_keys(self):
+ raw = {"schema": 6, "machine_id": "AgICAgICAgICAgICAgICAg", "peers": [],
+ "crossing_own": [], "crossing_desk": "bad"}
+ settings, notes = profiles.before_load(raw, now=100)
+ self.assertIn("crossing_own_unreadable", settings)
+ self.assertIn("crossing_desk_unreadable", settings)
+ self.assertIn("upgraded", notes)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_protocol_v6.py b/core/tests/test_protocol_v6.py
index dcdcd26..1fb2ca6 100644
--- a/core/tests/test_protocol_v6.py
+++ b/core/tests/test_protocol_v6.py
@@ -104,6 +104,18 @@ def _open_frame(session, frame):
return session.open(frame[protocol.HEADER_SIZE:])
+class InputMethodKeyFrames(unittest.TestCase):
+ def test_hangul_and_hanja_key_events_round_trip_through_authenticated_frames(self):
+ initiator, responder, _, _ = _pair()
+ for name in ("hangul", "hanja"):
+ for kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):
+ message = protocol.key_msg(kind, name)
+ encoded = protocol.dumps_message(message)
+ opened = _open_frame(responder, initiator.seal(message))
+ self.assertEqual(opened, message)
+ self.assertEqual(protocol.dumps_message(opened), encoded)
+
+
class Tokens(unittest.TestCase):
def test_a_paired_token_is_43_characters_of_one_spelling(self):
self.assertTrue(protocol.is_paired_token(TOKEN))
diff --git a/core/tests/test_responder_ownership.py b/core/tests/test_responder_ownership.py
index c859db9..07f7a67 100644
--- a/core/tests/test_responder_ownership.py
+++ b/core/tests/test_responder_ownership.py
@@ -611,6 +611,27 @@ class WrapWayBack(Case):
self.assertEqual(self.machine.responder._armed, [])
+class LeftOutDriverWayHome(Case):
+ """The Mac on 14-10-2026, compiled from its real settings: Fedora (B here) left out but driving
+ it, and its only edges leading to the rig (C) on the right, top and bottom. A left-out driver
+ had no way home, so every push went on to the rig and back."""
+ zones = [{"peer": protocol.id_text(C), "kind": "edge", "display": "main", "side": side,
+ "target_side": opposite}
+ for side, opposite in (("right", "left"), ("top", "bottom"), ("bottom", "top"))]
+
+ def setUp(self):
+ peers = [entry(B, "Bee", left_out=True, way_back=True), entry(C, "Sea"), entry(D, "Dee")]
+ self.machine = Machine(peers, self.zones).start()
+ self.addCleanup(self.machine.stop)
+
+ def test_the_way_home_is_armed_at_the_arrival_side(self):
+ b = self.link(B)
+ self.own(b, edge="left", offset=0.5, display="main", side="left", reach=[C])
+ self.assertIn((B, "left", "main", "right"),
+ [(peer, model.edge, model.display, model.target_side)
+ for peer, model in self.machine.responder._armed])
+
+
class ZoneModels(unittest.TestCase):
peers = [entry(B, "Bee", side="left"), entry(C, "Sea", side="top"), entry(D, "Dee", side="")]
diff --git a/core/tests/test_shake.py b/core/tests/test_shake.py
new file mode 100644
index 0000000..7b80218
--- /dev/null
+++ b/core/tests/test_shake.py
@@ -0,0 +1,273 @@
+import math
+import random
+import unittest
+
+from core.shake import (HomeHold, ShakeDetector, STROKE_MAC, STROKE_WINDOWS, STROKE_X11,
+ STROKE_WAYLAND, stroke_at_sensitivity)
+
+
+def trace(strokes, rate=125, axis="x", start=0.0, jitter=0.0, noise=0.0, seed=17):
+ """Make constant-speed strokes, preserving each stroke's requested duration."""
+ rng = random.Random(seed)
+ result = []
+ t = start
+ last_event_t = start - 0.000001
+ for direction, distance, duration in strokes:
+ count = max(2, round(duration * rate) + 1)
+ for i in range(1, count + 1):
+ ideal = duration * (i - 1) / (count - 1)
+ dt = ideal + (rng.uniform(-jitter, jitter) if jitter else 0.0)
+ along = direction * distance / count
+ cross_step = rng.uniform(-noise, noise) if noise else 0.0
+ if axis == "x":
+ dx, dy = along, cross_step
+ else:
+ dx, dy = cross_step, along
+ event_t = max(last_event_t + 0.000001, t + dt)
+ result.append((event_t, dx, dy))
+ last_event_t = event_t
+ t += duration
+ if jitter:
+ t += rng.uniform(-jitter, jitter)
+ return result
+
+
+def qualifying_strokes(length=64.0, duration=0.1, direction=1):
+ return [(direction if i % 2 == 0 else -direction, length, duration) for i in range(4)]
+
+
+def qualifying_trace(rate=125, axis="x", direction=1, start=0.31, **kwargs):
+ strokes = qualifying_strokes(direction=direction)
+ strokes.append((direction, 12.001, 0.02))
+ return trace(strokes, rate, axis, start=start, **kwargs)
+
+
+def candidate_trace(lengths, durations, rate=1000, **kwargs):
+ strokes = [(1 if i % 2 == 0 else -1, length, duration)
+ for i, (length, duration) in enumerate(zip(lengths, durations))]
+ strokes.append((1, 12.001, 0.02))
+ return trace(strokes, rate, start=0.31, **kwargs)
+
+
+def run(detector, events):
+ fired = []
+ for t, dx, dy in events:
+ if detector.motion(t, dx, dy):
+ fired.append(t)
+ return fired
+
+
+class ShakeDetectorTests(unittest.TestCase):
+ def test_changing_sensitivity_discards_partial_gesture_and_preserves_cooldown(self):
+ detector = self.detector()
+ events = qualifying_trace()
+ run(detector, events[:30])
+ detector.set_stroke(24)
+ self.assertEqual(run(detector, events[30:]), [])
+ self.assertEqual(len(run(detector, qualifying_trace(start=1.1))), 1)
+ detector.set_stroke(48)
+ self.assertEqual(run(detector, qualifying_trace(start=1.6)), [])
+
+ def test_equal_normalised_motion_fires_at_the_same_time_on_every_backend(self):
+ for stroke in (STROKE_MAC, STROKE_WINDOWS, STROKE_X11, STROKE_WAYLAND):
+ for sensitivity in (50, 100, 150, 200):
+ detector = self.detector(stroke_at_sensitivity(stroke, sensitivity))
+ scale = stroke / 48 * 100 / sensitivity
+ events = [(t, dx * scale, dy * scale) for t, dx, dy in qualifying_trace()]
+ self.assertEqual(run(detector, events), [events[-1][0]])
+
+ def test_sensitivity_scales_the_platform_stroke(self):
+ self.assertEqual(stroke_at_sensitivity(STROKE_MAC, 50), 96)
+ self.assertEqual(stroke_at_sensitivity(STROKE_WINDOWS, 100), STROKE_WINDOWS)
+ self.assertEqual(stroke_at_sensitivity(48, 200), 24)
+
+ def detector(self, stroke=48.0):
+ detector = ShakeDetector(stroke)
+ detector.arm(0.0)
+ return detector
+
+ def test_qualifying_shake_fires_once_at_fourth_turn_across_rates_axes_and_directions(self):
+ for rate in (60, 125, 500, 1000):
+ for axis in ("x", "y"):
+ for direction in (-1, 1):
+ with self.subTest(rate=rate, axis=axis, direction=direction):
+ events = qualifying_trace(rate, axis, direction, jitter=0.001, noise=0.1)
+ fired = run(self.detector(), events)
+ self.assertEqual(len(fired), 1)
+ self.assertEqual(fired[0], events[-1][0])
+
+ def test_three_turns_do_not_fire(self):
+ events = trace(qualifying_strokes()[:3], start=0.31)
+ self.assertEqual(run(self.detector(), events), [])
+
+ def test_turn_needs_net_reverse_travel_of_a_quarter_stroke(self):
+ events = trace([(1, 64, .1)], start=.31)
+ t = events[-1][0]
+ for _ in range(8):
+ t += .01
+ events.append((t, -8, 0))
+ t += .01
+ events.append((t, 8, 0))
+ self.assertEqual(run(self.detector(), events), [])
+
+ def test_each_stroke_needs_at_least_two_motion_events(self):
+ events = [(.31, 60, 0)]
+ for t, dx in ((.33, -7.5), (.35, -7.5), (.37, -15), (.39, -15), (.41, -15),
+ (.43, 7.5), (.45, 7.5), (.47, 15), (.49, 15), (.51, 15),
+ (.53, -7.5), (.55, -7.5), (.57, -15), (.59, -15), (.61, -15),
+ (.63, 7.5), (.65, 7.5)):
+ events.append((t, dx, 0))
+ self.assertEqual(run(self.detector(), events), [])
+
+ def test_sweep_circle_and_single_flick_do_not_fire(self):
+ sweep = trace([(1, 300.0, 0.1)], start=0.31)
+ circle = []
+ for i in range(81):
+ angle0 = 4 * 3.141592653589793 * (i - 1) / 80
+ angle1 = 4 * 3.141592653589793 * i / 80
+ circle.append((.31 + i * .005,
+ 10 * (math.cos(angle1) - math.cos(angle0)),
+ 10 * (math.sin(angle1) - math.sin(angle0))))
+ flick = trace([(1, 200, .03), (-1, 8, .03)], start=0.31)
+ for events in (sweep, circle, flick):
+ with self.subTest(events=len(events)):
+ self.assertEqual(run(self.detector(), events), [])
+
+ def test_slow_back_and_forth_and_fidget_below_stroke_length_do_not_fire(self):
+ slow = trace([(1 if i % 2 == 0 else -1, 64, .25) for i in range(4)] + [(1, 13, .02)],
+ start=0.31)
+ fidget = trace([(1 if i % 2 == 0 else -1, 40, .05) for i in range(4)] + [(1, 13, .02)],
+ start=0.31)
+ self.assertEqual(run(self.detector(), slow), [])
+ self.assertEqual(run(self.detector(), fidget), [])
+
+ def test_stroke_length_threshold(self):
+ lengths = [64.0] * 4
+ lengths[0] = 48.001
+ self.assertEqual(len(run(self.detector(), candidate_trace(lengths, [.1] * 4))), 1)
+ lengths[0] = 47.999
+ self.assertEqual(run(self.detector(), candidate_trace(lengths, [.1] * 4)), [])
+
+ def test_stroke_duration_thresholds(self):
+ durations = [.1] * 4
+ durations[0] = .030001
+ self.assertEqual(len(run(self.detector(), candidate_trace([64.0] * 4, durations))), 1)
+ durations[0] = .029999
+ self.assertEqual(run(self.detector(), candidate_trace([64.0] * 4, durations)), [])
+ durations[0] = .200001
+ self.assertEqual(run(self.detector(), candidate_trace([64.0] * 4, durations)), [])
+ durations[0] = .199999
+ self.assertEqual(len(run(self.detector(), candidate_trace([64.0] * 4, durations))), 1)
+
+ def test_average_speed_threshold(self):
+ lengths = [57.599, 64.0, 64.0, 64.0]
+ durations = [.2, .1, .1, .1]
+ self.assertEqual(run(self.detector(), candidate_trace(lengths, durations)), [])
+ lengths[0] = 57.601
+ self.assertEqual(len(run(self.detector(), candidate_trace(lengths, durations))), 1)
+
+ def test_total_travel_threshold(self):
+ self.assertEqual(run(self.detector(), candidate_trace([59.999] * 4, [.1] * 4)), [])
+ self.assertEqual(len(run(self.detector(), candidate_trace([60.0] * 4, [.1] * 4))), 1)
+
+ def test_endpoint_must_be_within_two_strokes_of_start(self):
+ lengths = [64.0, 64.0, 64.0, 160.0]
+ self.assertEqual(len(run(self.detector(), candidate_trace(lengths, [.1] * 4))), 1)
+ lengths[-1] = 160.001
+ self.assertEqual(run(self.detector(), candidate_trace(lengths, [.1] * 4)), [])
+
+ def test_cross_axis_travel_must_not_exceed_half_along_travel(self):
+ at_limit = trace([(1 if i % 2 == 0 else -1, 60.0, .1) for i in range(4)] + [(1, 12.001, .02)],
+ start=.31, noise=0.0)
+ beyond = trace([(1 if i % 2 == 0 else -1, 60.0, .1) for i in range(4)] + [(1, 12.001, .02)],
+ start=.31, noise=0.0)
+ count = len(at_limit) - 3
+ at_limit = [(t, dx, (120.0 / count) * (1 if i % 2 else -1)) for i, (t, dx, _) in enumerate(at_limit)]
+ beyond = [(t, dx, (120.1 / count) * (1 if i % 2 else -1)) for i, (t, dx, _) in enumerate(beyond)]
+ self.assertEqual(len(run(self.detector(), at_limit)), 1)
+ self.assertEqual(run(self.detector(), beyond), [])
+
+ def test_pause_longer_than_120_ms_resets_the_gesture(self):
+ first = trace(qualifying_strokes()[:2], start=.31)
+ second = trace(qualifying_strokes()[2:] + [(1, 13, .02)], start=.8)
+ self.assertEqual(run(self.detector(), first + second), [])
+
+ def test_pause_threshold(self):
+ for pause, expected in ((.119, 1), (.120, 0), (.121, 0)):
+ first = trace([(1, 60, .03), (-1, 60, .03)], start=.31)
+ second = trace([(1, 60, .03), (-1, 60, .03), (1, 12.001, .02)],
+ start=.37 + pause)
+ with self.subTest(pause=pause):
+ self.assertEqual(len(run(self.detector(), first + second)), expected)
+
+ def test_650_ms_turn_window(self):
+ inside = candidate_trace([60.0] * 4, [.157475] * 4)
+ outside = candidate_trace([60.0] * 4, [.157525] * 4)
+ self.assertEqual(len(run(self.detector(), inside)), 1)
+ self.assertEqual(run(self.detector(), outside), [])
+
+ def test_home_hold_releases_after_two_hundred_ms_quiet(self):
+ hold = HomeHold()
+ hold.motion(1.0)
+ self.assertTrue(hold.blocks(1.199))
+ self.assertFalse(hold.blocks(1.2))
+
+ def test_home_hold_motion_refreshes_quiet_deadline(self):
+ hold = HomeHold()
+ hold.motion(1.0)
+ hold.motion(1.15)
+ self.assertTrue(hold.blocks(1.34))
+ self.assertFalse(hold.blocks(1.35))
+
+ def test_disarmed_motion_never_fires(self):
+ detector = self.detector()
+ detector.disarm()
+ self.assertEqual(run(detector, qualifying_trace()), [])
+
+ def test_motion_before_arm_delay_is_ignored(self):
+ events = qualifying_trace(start=.1)
+ self.assertEqual(run(self.detector(), events), [])
+ self.assertEqual(len(run(self.detector(), qualifying_trace(start=.3))), 1)
+
+ def test_scroll_suppresses_motion_for_250_ms(self):
+ detector = self.detector()
+ detector.scroll(0.31)
+ self.assertEqual(run(detector, trace(qualifying_strokes(), start=0.32)), [])
+
+ def test_scroll_quiet_boundary(self):
+ detector = self.detector()
+ detector.scroll(0.31)
+ self.assertFalse(detector.motion(.5599, 30, 0))
+ self.assertEqual(len(run(detector, qualifying_trace(start=.5601))), 1)
+ detector = self.detector()
+ detector.scroll(0.31)
+ self.assertEqual(len(run(detector, qualifying_trace(start=.56))), 1)
+
+ def test_held_button_or_key_resets_and_ignores_motion_until_released(self):
+ detector = self.detector()
+ detector.held(0.31, True)
+ self.assertEqual(run(detector, qualifying_trace(start=.32)), [])
+ detector.held(1.0, False)
+ self.assertEqual(len(run(detector, qualifying_trace(start=1.01))), 1)
+
+ def test_fires_no_more_than_once_until_rearmed(self):
+ detector = self.detector()
+ first = qualifying_trace()
+ self.assertEqual(len(run(detector, first)), 1)
+ second = qualifying_trace(start=0.8)
+ self.assertEqual(run(detector, second), [])
+ third = qualifying_trace(start=2.23)
+ self.assertEqual(len(run(detector, third)), 1)
+
+ def test_crossing_straight_back_out_keeps_the_one_and_a_half_seconds(self):
+ detector = self.detector()
+ fired = run(detector, qualifying_trace())
+ self.assertEqual(len(fired), 1)
+ detector.disarm()
+ detector.arm(fired[0] + 0.05)
+ self.assertEqual(run(detector, qualifying_trace(start=fired[0] + 0.4)), [])
+ self.assertEqual(len(run(detector, qualifying_trace(start=fired[0] + 1.6))), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_special_keys.py b/core/tests/test_special_keys.py
index 6c75cbb..48cd8c3 100644
--- a/core/tests/test_special_keys.py
+++ b/core/tests/test_special_keys.py
@@ -4,6 +4,12 @@ from core import special_keys
class SpecialKeyWireTests(unittest.TestCase):
+ def test_hangul_and_hanja_names_survive_special_key_translation(self):
+ for key in ("hangul", "hanja"):
+ for own in ("macos", "windows", "linux"):
+ for peer in ("macos", "windows", "linux"):
+ self.assertEqual(special_keys.wire_name(key, own, peer), key)
+
def test_window_switcher_chord_rules(self):
cases = (
("macos", "windows", "tab", {"cmd"}, (("cmd",), "alt")),
diff --git a/core/tests/test_tile_resize.py b/core/tests/test_tile_resize.py
new file mode 100644
index 0000000..5327a1f
--- /dev/null
+++ b/core/tests/test_tile_resize.py
@@ -0,0 +1,202 @@
+"""Pure tile resizing, layout compilation, profile storage and old-peer compatibility."""
+
+import copy
+import io
+import json
+import subprocess
+import sys
+import tarfile
+import tempfile
+import unittest
+from pathlib import Path
+
+
+class GuiImportBlocked(ImportError):
+ pass
+
+
+class BlockGuiImports:
+ blocked = {"AppKit", "objc", "PySide2", "PySide6", "PyQt5", "PyQt6", "qtpy", "tkinter"}
+
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname.split(".", 1)[0] in self.blocked:
+ raise GuiImportBlocked("blocked before import: " + fullname)
+
+
+# Only while core loads: left in place it would refuse GUI imports to every module the shared
+# Windows suite (win_app/tests/test_core.py) imports after this one.
+_BLOCKER = BlockGuiImports()
+sys.meta_path.insert(0, _BLOCKER)
+try:
+ from core import crossing_state, profiles, protocol, ways
+finally:
+ sys.meta_path.remove(_BLOCKER)
+
+ROOT = Path(__file__).resolve().parents[2]
+OWN, A, B = [protocol.id_text(bytes([number]) * 16) for number in (31, 32, 33)]
+
+
+def picture_settings():
+ return {
+ "machine_id": OWN,
+ "peers": [{"id": A, "port": 24820, "side": "right"}],
+ "zones": [],
+ "layout": {
+ OWN: {"x": 0, "y": 0, "w": 160, "h": 100},
+ A: {"x": 160, "y": 0, "w": 160, "h": 100},
+ },
+ "layout_set_at": 1,
+ "layout_by": OWN,
+ }
+
+
+class TileResizeTests(unittest.TestCase):
+ def test_resize_keeps_aspect_position_and_scaled_offsets(self):
+ source = {"x": 12, "y": -7, "w": 160, "h": 100,
+ "displays": {"1": {"x": 1920, "y": 0, "w": 1920, "h": 1080}},
+ "display_offsets": {"1": {"x": 12, "y": -8}}}
+
+ result = ways.resize_tile(source, 240)
+
+ self.assertEqual((result["x"], result["y"], result["w"], result["h"]),
+ (12, -7, 240, 150))
+ self.assertEqual(result["display_offsets"], {"1": {"x": 18, "y": -12}})
+ self.assertEqual(result["displays"], source["displays"])
+ self.assertEqual(source["w"], 160)
+
+ def test_resize_clamps_long_side_and_rounds_dimensions_to_positive_integers(self):
+ source = {"x": 0, "y": 0, "w": 3, "h": 2}
+
+ small = ways.resize_tile(source, 1)
+ large = ways.resize_tile(source, 1000)
+
+ self.assertEqual((small["w"], small["h"]), (40, 27))
+ self.assertEqual((large["w"], large["h"]), (480, 320))
+ self.assertTrue(all(type(value) is int and value >= 1
+ for result in (small, large) for value in (result["w"], result["h"])))
+
+ def test_resize_from_drag_uses_the_larger_proportional_axis_change(self):
+ source = {"x": 10, "y": 20, "w": 160, "h": 100}
+
+ result = ways.resize_from_drag(source, 32, 10)
+
+ self.assertEqual((result["x"], result["y"], result["w"], result["h"]),
+ (10, 20, 192, 120))
+
+ def test_drop_accepts_stamps_and_compiles_resized_tile(self):
+ held = picture_settings()
+ tiles = copy.deepcopy(held["layout"])
+ tiles[A] = {**tiles[A], "w": 240, "h": 150}
+
+ outcome = crossing_state.drop(held, tiles, A, platform="pc", capable={OWN, A},
+ live=lambda _peer: True, gone=lambda _peer: False,
+ now=100, snap_radius=0)
+
+ self.assertTrue(outcome["accepted"])
+ self.assertEqual((outcome["settings"]["layout"][A]["w"],
+ outcome["settings"]["layout"][A]["h"]), (240, 150))
+ self.assertGreater(outcome["settings"]["layout_set_at"], held["layout_set_at"])
+ edge = next(zone for zone in outcome["settings"]["zones"]
+ if zone["peer"] == A and zone["kind"] == "edge")
+ self.assertEqual(edge["side"], "right")
+ self.assertEqual(edge["contact_span"], [0.0, 1.0])
+ self.assertEqual(edge["target_span"], [0.0, 2 / 3])
+
+ def test_taller_resized_peer_maps_contact_to_its_lower_half(self):
+ held = picture_settings()
+ held["layout"][A] = ways.resize_tile(held["layout"][A], 320)
+ held["layout"][A].update(y=-100)
+
+ compiled = ways.compile_layout(held, held["layout"], platform="pc", capable={OWN, A}, now=100)
+
+ edge = next(zone for zone in compiled["settings"]["zones"]
+ if zone["peer"] == A and zone["kind"] == "edge")
+ self.assertEqual(edge["side"], "right")
+ self.assertEqual(edge["contact_span"], [0.0, 1.0])
+ self.assertEqual(edge["target_span"], [0.5, 1.0])
+
+ def test_profile_switch_keeps_each_profile_tile_size(self):
+ loaded, _notes = profiles.before_load({
+ "schema": 6, "machine_id": OWN,
+ "peers": [{"id": A, "port": 24820, "send": True, "allow_drive": True,
+ "linked": True, "side": "right", "ways": {"edge": True}}],
+ "zones": [],
+ "layout": {OWN: {"x": 0, "y": 0, "w": 160, "h": 100},
+ A: {"x": 160, "y": 0, "w": 160, "h": 100}},
+ }, now=100)
+ held, _notes = profiles.after_load(loaded, platform="pc", now=100)
+ first = held["crossing_desk"]["active"]["value"]
+ made = crossing_state.new_profile(held, "Second", platform="pc", now=101)
+ second = next(pid for pid in made["settings"]["crossing_desk"]["profiles"] if pid != first)
+ switched = crossing_state.switch_profile(made["settings"], second, platform="pc", now=102)
+ resized = copy.deepcopy(switched["settings"])
+ resized["layout"][A].update(w=240, h=150)
+
+ back = crossing_state.switch_profile(resized, first, platform="pc", now=103)
+ again = crossing_state.switch_profile(back["settings"], second, platform="pc", now=104)
+
+ self.assertTrue(made["accepted"])
+ self.assertTrue(switched["accepted"])
+ self.assertEqual((back["settings"]["layout"][A]["w"], back["settings"]["layout"][A]["h"]),
+ (160, 100))
+ self.assertEqual((again["settings"]["layout"][A]["w"], again["settings"]["layout"][A]["h"]),
+ (240, 150))
+
+
+class OlderPeerResizeCompatibilityTests(unittest.TestCase):
+ revisions = ("be9661d1", "2dbe44ab")
+
+ def test_old_picture_readers_and_drops_preserve_resized_dimensions(self):
+ script = r'''\
+import base64, copy, sys
+root = sys.argv[1]
+sys.path.insert(0, root)
+from core import crossing_state, settings_sync
+mid = lambda n: base64.urlsafe_b64encode(bytes([n]) * 16).decode().rstrip("=")
+own, resized, moved = mid(41), mid(42), mid(43)
+layout = {
+ own: {"x": 0, "y": 0, "w": 160, "h": 100},
+ resized: {"x": 160, "y": 0, "w": 240, "h": 150},
+ moved: {"x": -160, "y": 0, "w": 160, "h": 100},
+}
+wire = {"on": True, "set_at": 10, "by": own, "layout": {"set_at": 10, "by": own,
+ "tiles": copy.deepcopy(layout)}}
+read = settings_sync.read_layout_state(wire, now=100)
+assert read and read["tiles"][resized]["w"] == 240
+settings = {"machine_id": own, "peers": [
+ {"id": resized, "port": 24820, "side": "right"},
+ {"id": moved, "port": 24820, "side": "left"}],
+ "zones": [], "layout": {own: layout[own], resized: layout[resized]},
+ "layout_set_at": 1, "layout_by": own}
+out = crossing_state.receive_picture(settings, read, source=resized, platform="pc",
+ capable={own, resized, moved}, live=lambda _: True, gone=lambda _: False,
+ own_displays={}, now=100)
+assert out["settings"]["layout"][resized]["w"] == 240
+tiles = copy.deepcopy(out["settings"]["layout"])
+tiles[moved] = {**tiles[moved], "x": -160, "y": 0}
+dropped = crossing_state.drop(out["settings"], tiles, moved, platform="pc",
+ capable={own, resized, moved}, live=lambda _: True, gone=lambda _: False,
+ now=101, snap_radius=0)
+assert dropped["accepted"]
+assert (dropped["settings"]["layout"][resized]["w"],
+ dropped["settings"]["layout"][resized]["h"]) == (240, 150)
+print("old reader, receive_picture and drop kept resized tile at 240x150")
+'''
+ for revision in self.revisions:
+ with self.subTest(revision=revision), tempfile.TemporaryDirectory(dir=ROOT) as temp:
+ archive = subprocess.run(
+ ["git", "archive", revision, "core"], cwd=ROOT, check=True,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ ).stdout
+ frozen = Path(temp) / "frozen"
+ frozen.mkdir()
+ with tarfile.open(fileobj=io.BytesIO(archive)) as bundle:
+ bundle.extractall(frozen, filter="data")
+ result = subprocess.run([sys.executable, "-c", script, str(frozen)], cwd=ROOT,
+ text=True, capture_output=True)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("kept resized tile at 240x150", result.stdout)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/v6_vectors.json b/core/tests/v6_vectors.json
index f3e0458..6f5a6b7 100644
--- a/core/tests/v6_vectors.json
+++ b/core/tests/v6_vectors.json
@@ -1472,6 +1472,8 @@
"f7",
"f8",
"f9",
+ "hangul",
+ "hanja",
"home",
"insert",
"launch_app1",
@@ -1546,6 +1548,8 @@
"114": "volume_down",
"115": "volume_up",
"119": "pause",
+ "122": "hangul",
+ "123": "hanja",
"125": "cmd",
"126": "cmd_r",
"127": "menu",
diff --git a/core/ways.py b/core/ways.py
index 1faf9f0..bbad4cb 100644
--- a/core/ways.py
+++ b/core/ways.py
@@ -13,6 +13,7 @@ import sys
import time
from typing import Callable, Optional
+from core.i18n import N_, joined, tr, trc
from core import peerlist
from core import return_edge
from core.settings_sync import next_stamp
@@ -22,6 +23,16 @@ CORNERS = return_edge.CORNERS
PARTS = return_edge.PARTS
DEFAULT_PARTS = ["middle"]
DEFAULT_CORNER = "top_left"
+EDGE_NAMES = {"left": N_("left"), "right": N_("right"), "top": N_("top"), "bottom": N_("bottom")}
+HERE_NAMES = {"this PC": N_("this PC"), "this Mac": N_("this Mac"), "this computer": N_("this computer")}
+PART_NAMES_LOWER = {"top": N_("top"), "middle": N_("middle"), "bottom": N_("bottom"),
+ "left": N_("left"), "right": N_("right")}
+CORNER_NAMES = {"top_left": N_("Top left"), "top_right": N_("Top right"),
+ "bottom_left": N_("Bottom left"), "bottom_right": N_("Bottom right")}
+CORNER_NAMES_LOWER = {"top_left": N_("top left"), "top_right": N_("top right"),
+ "bottom_left": N_("bottom left"), "bottom_right": N_("bottom right")}
+VERTICAL_PART_NAMES = {"start": N_("Top"), "middle": N_("Middle"), "end": N_("Bottom")}
+HORIZONTAL_PART_NAMES = {"start": N_("Left"), "middle": N_("Middle"), "end": N_("Right")}
# How a notice names each kind of zone.
KIND_WORDS = {"edge": "edge", "part": "part of the edge", "corner": "corner", "notch": "notch"}
_JUMP_MODIFIERS = {"alt", "cmd", "ctrl", "shift"}
@@ -32,12 +43,12 @@ _JUMP_KEYS = {"backspace", "caps_lock", "delete", "down", "end", "enter", "esc",
ATLAS_SENTENCES = {
- "set_elsewhere": "Set on {first} or {second}.",
- "between": "Crosses between {first} and {second}.",
- "gap": "No edge leads to {name}. The shortcut and the menu still reach it.",
- "edge_off": "Edge to {name} is off. Tick Edge to turn it back on.",
- "unpicked": "None of the thirds picked for {name} touch its tile. Click a third along its edge.",
- "overlap": "{first} overlaps {second}. Drag them apart.",
+ "set_elsewhere": N_("Set on {first} or {second}."),
+ "between": N_("Crosses between {first} and {second}."),
+ "gap": N_("No edge leads to {name}. The shortcut and the menu still reach it."),
+ "edge_off": N_("Edge to {name} is off. Tick Edge to turn it back on."),
+ "unpicked": N_("None of the thirds picked for {name} touch its tile. Click a third along its edge."),
+ "overlap": N_("{first} overlaps {second}. Drag them apart."),
}
ATLAS_PARTS = ("start", "middle", "end")
DIAGRAM_THIS = (120.0, 75.0)
@@ -45,6 +56,30 @@ DIAGRAM_OTHER = (112.0, 63.0)
DIAGRAM_GAP = 10.0
DIAGRAM_SPLIT_GAP = 6.0
DIAGRAM_MARGIN = 12.0
+# Machine tiles use map units; manual resizing clamps their longer side to this range.
+RESIZE_MIN = 40
+RESIZE_MAX = 480
+
+
+def resize_tile(tile, long_side):
+ """Return a proportionally resized copy with its origin and display rectangles unchanged."""
+ width, height = tile["w"], tile["h"]
+ target = max(RESIZE_MIN, min(RESIZE_MAX, int(round(long_side))))
+ scale = target / max(width, height)
+ resized = copy.deepcopy(tile)
+ resized["w"] = max(1, int(round(width * scale)))
+ resized["h"] = max(1, int(round(height * scale)))
+ for offset in resized.get("display_offsets", {}).values():
+ offset["x"] = int(round(offset["x"] * scale))
+ offset["y"] = int(round(offset["y"] * scale))
+ return resized
+
+
+def resize_from_drag(tile, dx, dy):
+ """Resize from the bottom-right handle using the larger proportional axis movement."""
+ width, height = tile["w"], tile["h"]
+ change = max((dx / width, dy / height), key=abs)
+ return resize_tile(tile, max(width, height) * (1 + change))
def diagram_layout(width, height, machines):
@@ -828,16 +863,16 @@ def inverse_layout(settings, layout, width=160, height=100, gap=12, peer=None, o
def part_names(edge: str) -> dict:
"""The labels for thirds along an edge, in the direction they run."""
if edge in ("left", "right"):
- return {"start": "Top", "middle": "Middle", "end": "Bottom"}
- return {"start": "Left", "middle": "Middle", "end": "Right"}
+ return VERTICAL_PART_NAMES.copy()
+ return HORIZONTAL_PART_NAMES.copy()
def parts_phrase(edge: str, parts) -> str:
"""The selected thirds in a sentence, defaulting to the middle when none are known."""
names = part_names(edge)
- chosen = [names[part].lower() for part in PARTS if part in parts] or ["middle"]
- joined = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1]
- return f"the {joined} of the {edge} edge"
+ chosen = [tr(PART_NAMES_LOWER[names[part].lower()])
+ for part in PARTS if part in parts] or [tr(PART_NAMES_LOWER["middle"])]
+ return tr("the {parts} of the {edge} edge").format(parts=joined(chosen), edge=tr(EDGE_NAMES.get(edge, edge)) if edge in EDGE_NAMES else edge)
def toggle_part(parts, part, on) -> list:
@@ -925,15 +960,19 @@ def corner_holder(settings: dict, corner: str, exclude: Optional[str] = None) ->
def edge_form_detail(side, methods, parts, here="This Mac") -> str:
"""The Edge way's detail on the Crossing page: which form crosses, or where to place it first."""
if side not in EDGES:
- return f"Place it beside {here} on the map"
+ return tr("Place it beside {here} on the map").format(here=here)
thirds = picked_thirds(methods, parts)
if not thirds:
- return "Whole edge or the thirds you pick"
+ return tr("Whole edge or the thirds you pick")
if len(thirds) == len(PARTS):
- return "Whole edge"
- names = [part_names(side)[part] for part in thirds]
- named = names[0] if len(names) == 1 else " and ".join([", ".join(names[:-1]), names[-1].lower()])
- return f"{named.capitalize()} third{'s' if len(names) > 1 else ''}"
+ return tr("Whole edge")
+ names = [tr(part_names(side)[part])
+ for part in thirds]
+ if len(names) == 1:
+ return tr("{name} third").format(name=names[0])
+ head = joined(names[:-1])
+ last = tr(PART_NAMES_LOWER[part_names(side)[thirds[-1]].lower()])
+ return tr("{first} and {last} thirds").format(first=head, last=last)
def third_stretches(contact, own):
@@ -995,16 +1034,16 @@ def check_jump_key(settings: dict, peer: str, value, trigger_key: str) -> Option
return None
entry = _entry(settings, peer)
if entry is not None and entry.get("port") == 0:
- raise ValueError("a phone cannot be a jump target")
+ raise ValueError(tr("a phone cannot be a jump target"))
if not isinstance(value, str):
- raise ValueError("choose a modifier and one non-modifier key")
+ raise ValueError(tr("choose a modifier and one non-modifier key"))
if not valid_jump_key(value):
- raise ValueError("choose a modifier and one non-modifier key")
+ raise ValueError(tr("choose a modifier and one non-modifier key"))
if _trigger_in_chord(trigger_key, value):
- raise ValueError("that key is the trigger shortcut's: pick a chord without it")
+ raise ValueError(tr("that key is the trigger shortcut's: pick a chord without it"))
for entry in settings.get("peers", []):
if entry.get("id") != peer and jump_key(entry) == value:
- raise ValueError("that key is already assigned to another machine")
+ raise ValueError(tr("that key is already assigned to another machine"))
return value
@@ -1019,7 +1058,7 @@ def check_trigger_key(settings, trigger_key):
for peer in settings.get("peers", []):
chord = jump_key(peer)
if chord and _trigger_in_chord(trigger_key, chord):
- raise ValueError(f"That shortcut clashes with the jump key {chord}; the jump key has been kept.")
+ raise ValueError(tr("That shortcut clashes with the jump key {key}; the jump key has been kept.").format(key=chord))
def shared_trigger_values(settings, values):
@@ -1265,6 +1304,7 @@ def _clashing(settings: dict):
def clash(settings: dict, here: str) -> Optional[str]:
"""The sentence for two zones in use over one stretch of this machine's screen, naming the
machines they lead to, or None when there is no such pair. `here` is "this Mac" or "this PC"."""
+ here = tr(HERE_NAMES[here]) if here in HERE_NAMES else here
found = _clashing(settings)
if found is None:
return None
@@ -1274,20 +1314,27 @@ def clash(settings: dict, here: str) -> Optional[str]:
other = peerlist.label_for(peers, peer_id=second.get("peer")) or peerlist.UNNAMED
scope, part = stretch
if isinstance(scope, tuple) and scope[0] == "display":
- where = f"the {scope[2]} edge of display {scope[1]}"
+ where = tr("the {edge} edge of display {display}").format(edge=tr(EDGE_NAMES[scope[2]]), display=scope[1])
kind = scope[0]
elif isinstance(scope, tuple) and scope[0] == "display_corner":
- where = f"the {part.replace('_', ' ')} corner of display {scope[1]}"
+ where = tr("the {corner} corner of display {display}").format(corner=tr(CORNER_NAMES_LOWER[part]), display=scope[1])
kind = "corner"
else:
- where = {"notch": "the notch", "corner": f"the {part.replace('_', ' ')} corner"}.get(
- scope, f"the {scope} edge")
+ where = (tr("the notch") if scope == "notch" else
+ tr("the {corner} corner").format(corner=tr(CORNER_NAMES_LOWER[part])) if scope == "corner" else
+ tr("the {edge} edge").format(edge=tr(EDGE_NAMES[scope])))
kind = scope
if first.get("peer") == second.get("peer"):
- return f"Two of the ways to {one} cover {where} of {here}. Keep one of them."
- fix = {"notch": "Turn the notch off for one of them.", "corner": "Choose another corner for one of them."}.get(
- kind, "Move one of them to another side, or give each its own thirds of the edge.")
- return f"{one} and {other} would both lead from {where} of {here}. {fix}"
+ # Translators: {where} names the screen region and {here} is this PC or Mac.
+ return tr("Two of the ways to {name} cover {where} of {here}. Keep one of them.").format(name=one, where=where, here=here)
+ if kind == "notch":
+ # Translators: {where} names the screen region and {here} is this PC or Mac.
+ return tr("{first} and {second} would both lead from {where} of {here}. Turn the notch off for one of them.").format(first=one, second=other, where=where, here=here)
+ if kind == "corner":
+ # Translators: {where} names the screen region and {here} is this PC or Mac.
+ return tr("{first} and {second} would both lead from {where} of {here}. Choose another corner for one of them.").format(first=one, second=other, where=where, here=here)
+ # Translators: {where} names the screen region and {here} is this PC or Mac.
+ return tr("{first} and {second} would both lead from {where} of {here}. Move one of them to another side, or give each its own thirds of the edge.").format(first=one, second=other, where=where, here=here)
def _id_bytes(text) -> Optional[bytes]:
@@ -1366,6 +1413,7 @@ def crosses_on_map(settings: dict, peer: str) -> bool:
def blocked_sentence(settings: dict, peer: str, here: str, live: Optional[Callable[[str], bool]] = None) -> str:
"""The Crossing page's sentence for a machine whose side another machine's edge already holds and
that has no way in of its own; "" otherwise, and "" for a holder with no link now, which gives way."""
+ here = tr(HERE_NAMES[here]) if here in HERE_NAMES else here
entry = _entry(settings, peer) or {}
side = entry.get("side")
if side not in EDGES or has_way(settings, peer):
@@ -1377,8 +1425,8 @@ def blocked_sentence(settings: dict, peer: str, here: str, live: Optional[Callab
peers = settings["peers"]
name = peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED
other = peerlist.label_for(peers, peer_id=holder) or peerlist.UNNAMED
- return (f"{name} has no way in: {other} already leads from the {side} edge of {here}. Give each its own "
- "thirds of that edge by moving the machines on the map, or move one to another side.")
+ # Translators: {here} is this PC or Mac; {side} is the side of its screen.
+ return tr("{name} has no way in: {other} already leads from the {side} edge of {here}. Give each its own thirds of that edge by moving the machines on the map, or move one to another side.").format(name=name, other=other, side=tr(EDGE_NAMES[side]), here=here)
def no_way_back_sentence(settings: dict, peer: str) -> str:
@@ -1391,13 +1439,13 @@ def no_way_back_sentence(settings: dict, peer: str) -> str:
other_id = entry.get("way_back_by")
other_bytes = _id_bytes(other_id)
if other_bytes is not None and other_bytes != _id_bytes(settings.get("machine_id")):
- other = peerlist.label_for(settings["peers"], peer_id=other_id) or "another machine"
+ other = peerlist.label_for(settings["peers"], peer_id=other_id) or tr("another machine")
side = entry.get("side")
facing = return_edge.OPPOSITE[side] if side in EDGES else None
- where = f" on its {facing} too" if facing else " too"
- return (f"{name} has {other}{where}, so none of its edges leads back here. On {name}'s Crossing page, "
- "share that side by thirds or move one of them.")
- return f"{name} has no way back to this machine: none of its edges leads here. Its own Crossing page says why."
+ if facing:
+ return tr("{name} has {other} on its {facing} too, so none of its edges leads back here. On {name}'s Crossing page, share that side by thirds or move one of them.").format(name=name, other=other, facing=tr(EDGE_NAMES[facing]))
+ return tr("{name} has {other} too, so none of its edges leads back here. On {name}'s Crossing page, share that side by thirds or move one of them.").format(name=name, other=other)
+ return tr("{name} has no way back to this machine: none of its edges leads here. Its own Crossing page says why.").format(name=name)
def way_back_by(settings: dict, peer: str) -> Optional[str]:
@@ -1458,13 +1506,14 @@ def settle_presence(settings: dict, here: str, live, gone) -> list:
def gone_sentence(settings: dict, peer: str, here: str, gone: Callable[[str], bool]) -> str:
"""The Crossing page's sentence for a machine that has removed this pairing, "" for any other."""
+ here = tr(HERE_NAMES[here]) if here in HERE_NAMES else here
if not gone(peer):
return ""
name = peerlist.label_for(settings["peers"], peer_id=peer) or peerlist.UNNAMED
if has_way(settings, peer):
- return (f"{name} no longer has this pairing. If another machine takes its side, {here} gives it up. "
- f"Remove {name} here and pair the two again.")
- return f"{name} no longer has this pairing, so it has no way in. Remove {name} here and pair the two again."
+ # Translators: {here} is this PC or Mac.
+ return tr("{name} no longer has this pairing. If another machine takes its side, {here} gives it up. Remove {name} here and pair the two again.").format(name=name, here=here)
+ return tr("{name} no longer has this pairing, so it has no way in. Remove {name} here and pair the two again.").format(name=name)
@@ -1588,17 +1637,20 @@ def missing_pairings(settings: dict, peer: str) -> list:
def missing_sentence(settings: dict, peer: str, here: str) -> str:
"""The Crossing page's sentence for `missing_pairings`, "" when there are none."""
+ here = tr(HERE_NAMES[here]) if here in HERE_NAMES else here
missing = missing_pairings(settings, peer)
if not missing:
return ""
peers = settings["peers"]
names = [peerlist.label_for(peers, peer_id=entry.get("id")) or peerlist.UNNAMED for entry in missing]
target = peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED
- drivers = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " or " + names[-1]
if len(names) == 1:
- why = f"{names[0]} is not paired with {target}"
- elif len(names) == 2:
- why = f"neither is paired with {target}"
- else:
- why = f"none of them is paired with {target}"
- return f"While {drivers} drives {here}, this way to {target} does nothing: {why}. Pair them to use it from there too."
+ # Translators: {here} is this PC or Mac; {name} and {target} are machine names.
+ return tr("While {name} drives {here}, this way to {target} does nothing: {name} is not paired with {target}. Pair them to use it from there too.").format(name=names[0], here=here, target=target)
+ if len(names) == 2:
+ drivers = trc("ways alternatives", "{first} or {last}").format(first=names[0], last=names[1])
+ # Translators: {drivers} is a list of machine names; {here} is this PC or Mac.
+ return tr("While {drivers} drives {here}, this way to {target} does nothing: neither is paired with {target}. Pair them to use it from there too.").format(drivers=drivers, here=here, target=target)
+ drivers = trc("ways alternatives", "{head} or {last}").format(head=trc("list", ", ").join(names[:-1]), last=names[-1])
+ # Translators: {drivers} is a list of machine names; {here} is this PC or Mac.
+ return tr("While {drivers} drives {here}, this way to {target} does nothing: none of them is paired with {target}. Pair them to use it from there too.").format(drivers=drivers, here=here, target=target)
diff --git a/flatpak/uk.co.kalkman.beamer.metainfo.xml b/flatpak/uk.co.kalkman.beamer.metainfo.xml
index e54d81c..3151b8e 100644
--- a/flatpak/uk.co.kalkman.beamer.metainfo.xml
+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml
@@ -43,6 +43,9 @@
</screenshots>
<content_rating type="oars-1.1"/>
<releases>
+ <release version="1.5.5" date="2026-10-14">
+ <description><p>Adds layout profiles, shake to come home, resizable machine tiles on the Crossing map, and an Italian translation.</p></description>
+ </release>
<release version="1.5.4" date="2026-10-14">
<description><p>Fixes the shortcut leaving input stranded when it picked a machine that had just turned it away.</p></description>
</release>
diff --git a/locales/beamer.pot b/locales/beamer.pot
new file mode 100644
index 0000000..b4bdb87
--- /dev/null
+++ b/locales/beamer.pot
@@ -0,0 +1,5171 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: Beamer\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: en_GB\n"
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Light"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Mono"
+msgstr ""
+
+#: core/effects.py
+msgid "Bright"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py
+msgid "Quiet"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py
+msgid "Medium"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py
+msgid "Showpiece"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py
+msgid "Ring"
+msgstr ""
+
+#: core/effects.py
+msgid "A ring in the chosen colours closes onto the pointer."
+msgstr ""
+
+#: core/effects.py
+msgid "Membrane"
+msgstr ""
+
+#: core/effects.py
+msgid "Sparks"
+msgstr ""
+
+#: core/effects.py
+msgid "Instrument"
+msgstr ""
+
+#: core/effects.py
+msgid "Folio"
+msgstr ""
+
+#: core/effects.py
+msgid "Selvedge"
+msgstr ""
+
+#: core/effects.py
+msgid "Ink"
+msgstr ""
+
+#: core/effects.py
+msgid "Warp"
+msgstr ""
+
+#: core/effects.py
+msgid "White"
+msgstr ""
+
+#: core/effects.py
+msgid "Silver"
+msgstr ""
+
+#: core/effects.py
+msgid "Graphite"
+msgstr ""
+
+#: core/effects.py
+msgid "Warm grey"
+msgstr ""
+
+#: core/effects.py
+msgid "Citron"
+msgstr ""
+
+#: core/effects.py
+msgid "Laser"
+msgstr ""
+
+#: core/effects.py
+msgid "Electric"
+msgstr ""
+
+#: core/effects.py
+msgid "Fuchsia"
+msgstr ""
+
+#: core/effects.py
+msgid "Ultraviolet"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Glow"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "A band of light that deepens the harder you push."
+msgstr ""
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Beam"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "A thin line with a comet of light running along it."
+msgstr ""
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Aperture"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "A fine lens of light opens under pressure and closes softly behind the arriving pointer."
+msgstr ""
+
+#: core/effects.py
+msgid "Short"
+msgstr ""
+
+#: core/effects.py
+msgid "Normal"
+msgstr ""
+
+#: core/effects.py
+msgid "Long"
+msgstr ""
+
+#: core/effects.py
+msgid "Small"
+msgstr ""
+
+#: core/effects.py
+msgid "Large"
+msgstr ""
+
+#: core/effects.py
+msgid "Match display"
+msgstr ""
+
+#: core/effects.py
+msgid "Half"
+msgstr ""
+
+#: core/effects.py
+msgid "Quarter"
+msgstr ""
+
+#: core/effects.py mac_app/pages.py
+msgid "Same as crossing"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Crease"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "A small paper crease lifts under pressure, parts, then settles flat where you arrive."
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Pleat"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Six alternating folds gather at the edge, slide apart and unfold on the other screen."
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Concertina"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "A scored paper fan rises along the boundary, opens a passage and folds itself away behind you."
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Moss"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Plum"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Vellum"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Carbon copy"
+msgstr ""
+
+#: core/fx_folio.py
+msgid "Marbled"
+msgstr ""
+
+#: core/fx_ink.py
+msgid "Capillary"
+msgstr ""
+
+#: core/fx_ink.py
+msgid "A soft pigment meniscus swells against the boundary with viscous surface tension. On breakthrough, it releases cleanly and diffuses as a calm, translucent wash on the arrival screen."
+msgstr ""
+
+#: core/fx_ink.py
+msgid "Viscous drop"
+msgstr ""
+
+#: core/fx_ink.py
+msgid "An organic ink droplet gathers at the pointer, flattening against the glass edge before necking through the seam. On arrival, it splashes into a multi-lobed pigment bloom that bleeds outward."
+msgstr ""
+
+#: core/fx_ink.py
+msgid "Sumi bloom"
+msgstr ""
+
+#: core/fx_ink.py
+msgid "Dense calligraphic ink pulls from the boundary into a viscous bridge that necks and snaps through the seam. It arrives as an ink-in-water vortex bloom, unfurling delicate pigment filaments that dissolve into the screen."
+msgstr ""
+
+#: core/fx_ink.py
+msgid "Indigo ink"
+msgstr ""
+
+#: core/fx_ink.py
+msgid "Matcha"
+msgstr ""
+
+#: core/fx_ink.py
+msgid "Terracotta"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Rule"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "A fine ruler rises along the edge round the pointer and lights outward one division at a time as the push builds, the three quarter detents marked long. At breakthrough it closes on the pointer in four clicks; on the other screen a short register mark sits where you came in and a four-arm cross steps in three clicks onto the landing point."
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Gauge"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "A half dial seated on the edge at the pointer, a quarter dial in the corner and a graduated collar round the notch, whose needle clicks round sixteen detents as the push builds. At breakthrough an iris shuts over the dial in four steps; on the other screen a graduated ring contracts onto the landing point, turning one graduation per click, and flashes as it locks."
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Rangefinder"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "A long scale runs along the edge and a pair of caliper jaws closes on the pointer in detents, lighting the divisions it passes, while three tally lamps light at each quarter. At breakthrough shutter blades slide in from both ends and a bright slit at the pointer shuts; on the far screen the jaws open outward from the entry point as a graduated reticle with corner brackets steps in, turns and locks onto the landing point."
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Ruby"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Cobalt"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Phosphor"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Sodium"
+msgstr ""
+
+#: core/fx_instrument.py
+msgid "Contrast"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Skin"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "A single iridescent hairline sits just inside the edge and dimples under the pointer as you push, thinning and shifting colour. It parts at the pointer and the two ends pull back; on the other screen the same hairline closes behind the pointer and one ripple spreads out."
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Film"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "A band of interference fringes, one added at each quarter tick, crowds and thins into the dent under the pointer, so the band itself is the pressure meter. At breakthrough the film tears and each fringe peels back with a curled rim; on the other side the skin bulges in around the arriving pointer, springs back, heals, and throws two ripples."
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Rupture"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "The whole edge becomes a visible soap film with a sheen behind its fringes; every tick sends a shudder along it, and at breakthrough it bursts, the torn rims racing away along the edge carrying beads of film. The arrival opens a set of Newton's rings around the entry point while the skin bulges in, heals and sends a surface wave along the edge."
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Opal"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Sea glass"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Oil slick"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Soap bubble"
+msgstr ""
+
+#: core/fx_membrane.py
+msgid "Pearl"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Thread"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Two fine yarns tighten, part for the pointer and stitch the seam closed behind it."
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Weave"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "A woven border gathers tension, opens between its strands and gently mends on arrival."
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Jacquard"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "A diamond-patterned textile tightens across the edge, opens its weave and settles behind you."
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Woad"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Saffron"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Flax"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Madder"
+msgstr ""
+
+#: core/fx_selvedge.py
+msgid "Tide"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Flint"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "A single hot point at the pointer draws in a few close sparks as you push, snaps them through the edge, and a pinch of sparks pops out where you land. Small enough to leave on all day."
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Filings"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Scattered sparks swing round to point at the pointer and creep in like iron filings to a magnet, the edge warming beside it; at breakthrough they are sucked through the point, and on the other screen the same sparks are thrown back out and fall."
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Discharge"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "The boundary charges up: sparks crawl along it and forty filings wheel in, with a crackle arcing to the pointer at every tick. At breakthrough the whole charge implodes through the point with a last arc; where it lands it goes off like a sparkler, stars splitting as they fall."
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Arc"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Magnesium"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Ember"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Forge"
+msgstr ""
+
+#: core/fx_sparks.py
+msgid "Sparkler gold"
+msgstr ""
+
+#: core/fx_warp.py
+msgid "Neon"
+msgstr ""
+
+#: core/fx_warp.py
+msgid "Vaporwave"
+msgstr ""
+
+#: core/fx_warp.py
+msgid "Cyber"
+msgstr ""
+
+#: core/fx_warp.py
+msgid "Light slit"
+msgstr ""
+
+#: core/fx_warp.py
+msgid "A subtle slit opens, pulling in faint trails."
+msgstr ""
+
+#: core/fx_warp.py
+msgid "Hyperdrive"
+msgstr ""
+
+#: core/fx_warp.py
+msgid "Speed lines accelerate towards the portal."
+msgstr ""
+
+#: core/fx_warp.py
+msgid "Wormhole"
+msgstr ""
+
+#: core/fx_warp.py
+msgid "A dynamic stretching grid of light."
+msgstr ""
+
+#. the separator between all but the last two names in a list, "Mac, PC and Laptop".
+#: core/i18n.py core/receiver.py core/settings_sync.py core/ways.py
+msgctxt "list"
+msgid ", "
+msgstr ""
+
+#. the last two names of a list; {first} may itself be several names.
+#: core/i18n.py
+#, python-brace-format
+msgctxt "list"
+msgid "{first} and {last}"
+msgstr ""
+
+#: core/link.py win_app/sender.py
+msgid "The other machine"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "Connection failed: {error}"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} closed the connection: it may have removed this machine, or be too busy to answer"
+msgstr ""
+
+#: core/link.py
+msgid "This pairing was removed"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} is unreachable from this machine. Check that both can communicate on the local network."
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} is reachable, but Beamer is not listening on this port."
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer before the connection timed out."
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "Connecting to {host}:{port}"
+msgstr ""
+
+#: core/link.py
+msgid "This link was stopped"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "Update Beamer on {name} to 1.5.0; if it is up to date, pair the two again"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "Connected to {name} via the secure macOS 27 fallback"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "Connected to {name}"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} closed the connection"
+msgstr ""
+
+#: core/link.py
+msgid "Sending to this machine was switched off"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "A different Beamer answered at {host}"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} stopped acknowledging input"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} stopped accepting data"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer as a Beamer: it is probably running one from before version 4"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} could not be authenticated: something on the path altered the link"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer like Beamer: {error}"
+msgstr ""
+
+#: core/link.py core/receiver.py
+#, python-brace-format
+msgid "{name} runs a newer Beamer: update Beamer on this machine"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} could not read what this machine sent first; Beamer on the two machines may differ"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "Could not save what {name} told this machine"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "The link to {name} failed: {error}"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} took too long to send one message"
+msgstr ""
+
+#: core/link.py
+msgid "The link failed"
+msgstr ""
+
+#: core/link.py
+msgid "macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command."
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} stopped responding"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer as a Beamer"
+msgstr ""
+
+#: core/link.py core/receiver.py
+#, python-brace-format
+msgid "Update Beamer on {name}: it is older than this one"
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} has this pairing under another machine: use Re-pair on Overview."
+msgstr ""
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} no longer has this pairing: use Re-pair on Overview"
+msgstr ""
+
+#: core/peerlist.py
+msgid "This pairing needs to be set up again."
+msgstr ""
+
+#: core/peerlist.py
+msgid "Pairing finished, but Beamer could not save it on this machine. Try again in a moment."
+msgstr ""
+
+#: core/peerlist.py
+msgid "Another pairing is still finishing. Try again in a moment."
+msgstr ""
+
+#: core/peerlist.py
+msgid "A wrong code was tried, so this code was cancelled. Show a new one to try again."
+msgstr ""
+
+#: core/peerlist.py
+msgid "A machine on an older Beamer tried to pair. Update Beamer on it to 1.5.0, then show a new code."
+msgstr ""
+
+#: core/peerlist.py
+msgid "The code expired. Show a new one."
+msgstr ""
+
+#: core/peerlist.py
+msgid "That machine may already be paired here, or the code was wrong. Show a new code to try again."
+msgstr ""
+
+#: core/peerlist.py
+msgid "Beamer could not save the pairing on this machine, so it did not complete. Show a new code to try again."
+msgstr ""
+
+#: core/peerlist.py
+msgid "That is this machine, not another one."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Pairing failed: {reason}."
+msgstr ""
+
+#: core/peerlist.py
+msgid "That machine gave this machine's own identity, so nothing was paired. Show a new code to try again."
+msgstr ""
+
+#: core/peerlist.py
+msgid "The saved pairing now identifies a different machine."
+msgstr ""
+
+#: core/peerlist.py
+msgid "The other machine no longer has this pairing."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired with this machine. Remove it from the list first to pair again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is not showing a code. Show one in Beamer on it, then try again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "That code was not accepted, and {name} has cancelled it. Show a new one there to try again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} runs an older Beamer. Update Beamer on it to 1.5.0, then pair again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} did not answer. Check both machines are on the same network, then try again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Either this machine or {name} already has {n} machines paired, the most Beamer keeps. Remove one, then try again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} already has this machine paired. Remove this machine from its list there, then pair again."
+msgstr ""
+
+#: core/peerlist.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Paired with {name}."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired here. Remove it from the list first to pair again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "This machine already has {n} machines paired, the most Beamer keeps. Remove one, then show a new code."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired with this machine, since {when}. Remove it from the list first to pair again."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: it is being driven from {other}."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: another machine is driving it."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: it is driving {other}."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: it is driving another machine."
+msgstr ""
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired here, since {when}. Remove it from the list first to pair again."
+msgstr ""
+
+#: core/profiles.py
+msgid "Uses the desk's ways"
+msgstr ""
+
+#. on a map tile, a machine running a Beamer too old to share ways. Keep it short.
+#: core/profiles.py
+msgid "Older"
+msgstr ""
+
+#: core/profiles.py mac_app/diagram.py
+msgid "Offline"
+msgstr ""
+
+#: core/profiles.py mac_app/diagram.py win_app/diagram.py
+msgid "Own"
+msgstr ""
+
+#: core/profiles.py mac_app/diagram.py win_app/diagram.py win_app/kvm_bridge_win.py
+msgid "Desk"
+msgstr ""
+
+#: core/profiles.py
+msgid "An older Beamer. Its ways are set on it; update it to set them here. Read only"
+msgstr ""
+
+#: core/profiles.py
+msgid "Offline. It takes these when it next connects"
+msgstr ""
+
+#: core/profiles.py
+msgid "Sending…"
+msgstr ""
+
+#: core/profiles.py
+msgid "Keeps its own ways. The desk's are saved for when it uses them"
+msgstr ""
+
+#: core/profiles.py win_app/kvm_bridge_win.py
+msgid "This machine"
+msgstr ""
+
+#: core/profiles.py
+#, python-brace-format
+msgid "Last heard {time}"
+msgstr ""
+
+#: core/profiles.py
+#, python-brace-format
+msgid "Needs pairing with {name}"
+msgstr ""
+
+#: core/profiles.py
+#, python-brace-format
+msgid "{name} is off on that machine"
+msgstr ""
+
+#: core/profiles.py
+#, python-brace-format
+msgid "{name} · {date}"
+msgstr ""
+
+#: core/receiver.py
+msgid "Listening stopped"
+msgstr ""
+
+#: core/receiver.py
+msgid "Unlocking Windows…"
+msgstr ""
+
+#: core/receiver.py
+msgid "Windows is locked — unlock it at the PC"
+msgstr ""
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Starting on port {port}"
+msgstr ""
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Input error from {name}; see log"
+msgstr ""
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Connected to {names}"
+msgstr ""
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Waiting on port {port}"
+msgstr ""
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Listener failed: {error}"
+msgstr ""
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Another program is using port {port} — change the port on the Connection page"
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Design not available yet: connect to this machine with Beamer 1.5.0 beta.6 or later."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Needs beta.6 or later"
+msgstr ""
+
+#: core/settings_sync.py
+msgid "A connected machine is unavailable until it has beta.6 or later."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "No paired machine is connected."
+msgstr ""
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Crossing"
+msgstr ""
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Design"
+msgstr ""
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shortcut"
+msgstr ""
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Names"
+msgstr ""
+
+#: core/settings_sync.py mac_app/diagram.py mac_app/kvm_bridge_app.py win_app/diagram.py win_app/kvm_bridge_win.py
+msgid "Resistance"
+msgstr ""
+
+#: core/settings_sync.py
+msgid "drag protection"
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Off: each machine keeps its current values."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Off: each machine keeps its current values; previous separate values are not restored."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "compatible paired machines"
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine. Notch and trackpad controls stay on this Mac."
+msgstr ""
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "Following {name}'s design"
+msgstr ""
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "Shares {groups} with compatible paired machines."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Resistance, drag protection and Shortcut stay in step. Ways and jump keys below are local; each side is shared with its paired machine."
+msgstr ""
+
+#: core/settings_sync.py
+msgid "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local. Notch and trackpad controls stay local."
+msgstr ""
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "Shares resistance, drag protection, Shortcut and six animation settings with {machines}."
+msgstr ""
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "{name}'s Beamer is too old to keep settings in step. Update it to turn this on."
+msgstr ""
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "compatible versions of {name}"
+msgstr ""
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "{shared} stay in step. Ways and jump keys below are local; each side is shared with its paired machine."
+msgstr ""
+
+#: core/ways.py win_app/diagram.py
+msgid "left"
+msgstr ""
+
+#: core/ways.py win_app/diagram.py
+msgid "right"
+msgstr ""
+
+#: core/ways.py win_app/diagram.py
+msgid "top"
+msgstr ""
+
+#: core/ways.py win_app/diagram.py
+msgid "bottom"
+msgstr ""
+
+#: core/ways.py
+msgid "this PC"
+msgstr ""
+
+#: core/ways.py
+msgid "this Mac"
+msgstr ""
+
+#: core/ways.py
+msgid "this computer"
+msgstr ""
+
+#: core/ways.py mac_app/diagram.py
+msgid "middle"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Top left"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Top right"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Bottom left"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Bottom right"
+msgstr ""
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "top left"
+msgstr ""
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "top right"
+msgstr ""
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "bottom left"
+msgstr ""
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "bottom right"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py
+msgid "Top"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py
+msgid "Middle"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py
+msgid "Bottom"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py win_app/pages_win.py
+msgid "Left"
+msgstr ""
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py win_app/pages_win.py
+msgid "Right"
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "Set on {first} or {second}."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "Crosses between {first} and {second}."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "No edge leads to {name}. The shortcut and the menu still reach it."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "Edge to {name} is off. Tick Edge to turn it back on."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "None of the thirds picked for {name} touch its tile. Click a third along its edge."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "{first} overlaps {second}. Drag them apart."
+msgstr ""
+
+#: core/ways.py
+msgid "Whole edge or the thirds you pick"
+msgstr ""
+
+#: core/ways.py
+msgid "Whole edge"
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "the {parts} of the {edge} edge"
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {last} thirds"
+msgstr ""
+
+#: core/ways.py
+msgid "a phone cannot be a jump target"
+msgstr ""
+
+#: core/ways.py
+msgid "choose a modifier and one non-modifier key"
+msgstr ""
+
+#: core/ways.py
+msgid "that key is the trigger shortcut's: pick a chord without it"
+msgstr ""
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {second} would both lead from {where} of {here}. Move one of them to another side, or give each its own thirds of the edge."
+msgstr ""
+
+#. {here} is this PC or Mac; {side} is the side of its screen.
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has no way in: {other} already leads from the {side} edge of {here}. Give each its own thirds of that edge by moving the machines on the map, or move one to another side."
+msgstr ""
+
+#: core/ways.py mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "another machine"
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has no way back to this machine: none of its edges leads here. Its own Crossing page says why."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} no longer has this pairing, so it has no way in. Remove {name} here and pair the two again."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgctxt "ways alternatives"
+msgid "{head} or {last}"
+msgstr ""
+
+#. {drivers} is a list of machine names; {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "While {drivers} drives {here}, this way to {target} does nothing: none of them is paired with {target}. Pair them to use it from there too."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "Place it beside {here} on the map"
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} third"
+msgstr ""
+
+#: core/ways.py
+msgid "that key is already assigned to another machine"
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "the {edge} edge of display {display}"
+msgstr ""
+
+#: core/ways.py mac_app/kvm_bridge_app.py mac_app/pages.py
+msgid "the notch"
+msgstr ""
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "Two of the ways to {name} cover {where} of {here}. Keep one of them."
+msgstr ""
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {second} would both lead from {where} of {here}. Turn the notch off for one of them."
+msgstr ""
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {second} would both lead from {where} of {here}. Choose another corner for one of them."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has {other} too, so none of its edges leads back here. On {name}'s Crossing page, share that side by thirds or move one of them."
+msgstr ""
+
+#. {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{name} no longer has this pairing. If another machine takes its side, {here} gives it up. Remove {name} here and pair the two again."
+msgstr ""
+
+#. {here} is this PC or Mac; {name} and {target} are machine names.
+#: core/ways.py
+#, python-brace-format
+msgid "While {name} drives {here}, this way to {target} does nothing: {name} is not paired with {target}. Pair them to use it from there too."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgctxt "ways alternatives"
+msgid "{first} or {last}"
+msgstr ""
+
+#. {drivers} is a list of machine names; {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "While {drivers} drives {here}, this way to {target} does nothing: neither is paired with {target}. Pair them to use it from there too."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "the {corner} corner of display {display}"
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has {other} on its {facing} too, so none of its edges leads back here. On {name}'s Crossing page, share that side by thirds or move one of them."
+msgstr ""
+
+#: core/ways.py
+#, python-brace-format
+msgid "That shortcut clashes with the jump key {key}; the jump key has been kept."
+msgstr ""
+
+#: core/ways.py mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "the {corner} corner"
+msgstr ""
+
+#: core/ways.py win_app/pages_win.py
+#, python-brace-format
+msgid "the {edge} edge"
+msgstr ""
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} does not accept input from this Mac"
+msgstr ""
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} could not read the request to take it"
+msgstr ""
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} refused the input"
+msgstr ""
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "{name} did not answer"
+msgstr ""
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "Lost the link to {name}"
+msgstr ""
+
+#: mac_app/bridge.py
+msgid "Waiting to connect"
+msgstr ""
+
+#: mac_app/bridge.py
+msgid "Settings saved; reconnecting"
+msgstr ""
+
+#: mac_app/bridge.py mac_app/kvm_bridge_app.py mac_app/link_state.py mac_app/wake.py win_app/pages_win.py
+msgid "the other machine"
+msgstr ""
+
+#: mac_app/bridge.py win_app/kvm_bridge_win.py
+msgid "Beamer"
+msgstr ""
+
+#: mac_app/bridge.py
+msgid "Input returned to this Mac"
+msgstr ""
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "Skipped {name}: not connected."
+msgstr ""
+
+#: mac_app/bridge.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Shook home from {name}. Turn this off in Crossing → Way home."
+msgstr ""
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {status}"
+msgstr ""
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{machine} took over {name}"
+msgstr ""
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "Another machine took over {name}"
+msgstr ""
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} could not be reached"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "right of"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "left of"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/pages.py
+msgid "below"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/pages.py
+msgid "above"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "start"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "end"
+msgstr ""
+
+#: mac_app/diagram.py win_app/kvm_bridge_win.py
+msgid "Crosses"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Overlaps"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Drag to connect"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Edge off"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/diagram.py win_app/machines_win.py
+msgid "In the shortcut's cycle"
+msgstr ""
+
+#: mac_app/diagram.py win_app/crossing_ledger.py win_app/diagram.py win_app/sender.py
+msgid "Other machine"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/kvm_bridge_app.py mac_app/machines_panel.py
+msgid "This Mac"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/machines_panel.py
+msgid "Selected"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Drag a corner to resize, or use Option and the arrow keys."
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Whole desk layout"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "No machines paired."
+msgstr ""
+
+#. {third} is one of the three sections along an edge.
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, {side} This Mac, {third} third. {outcome}."
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, {side} This Mac. {outcome}."
+msgstr ""
+
+#. third names are one of the three sections of a screen edge.
+#: mac_app/diagram.py
+msgid "click to turn it off"
+msgstr ""
+
+#. third names are one of the three sections of a screen edge.
+#: mac_app/diagram.py
+msgid "click to turn it on"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "Current pressure {pressure} of {value} pointer units at the {edge} edge."
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "machine"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Not in use"
+msgstr ""
+
+#: mac_app/diagram.py win_app/diagram.py
+msgid "Recentre"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} third: {detail}"
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Rename this Mac on Overview."
+msgstr ""
+
+#: mac_app/diagram.py win_app/diagram.py
+#, python-brace-format
+msgid "Recentre {name}"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "Machine · {id}"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, In the shortcut's cycle"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, {status}"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} is in the shortcut's cycle."
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} is out of the shortcut's cycle."
+msgstr ""
+
+#: mac_app/diagram.py win_app/diagram.py
+#, python-brace-format
+msgid "{name} resized."
+msgstr ""
+
+#: mac_app/diagram.py
+msgid "Set elsewhere"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "No push. Current pressure is 0 of {value} pointer units."
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} · macOS"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{platform} · {status}"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/ledger.py
+#, python-brace-format
+msgid "Beamer {version} · only sees which side"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}: drag a corner to resize, or use Option and the arrow keys."
+msgstr ""
+
+#: mac_app/diagram.py win_app/crossing_ledger.py
+msgid "Computer"
+msgstr ""
+
+#: mac_app/diagram.py mac_app/ledger.py mac_app/link_state.py mac_app/machines.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Linked"
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{label}, {outcome}."
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{label}, {name}, this Mac."
+msgstr ""
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{label}, this Mac."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input on this Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input held on this Mac; crossing is off"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input on another machine"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "About Beamer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hide Beamer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hide Others"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Quit Beamer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Edit"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Undo"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Redo"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Cut"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Copy"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Paste"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Select All"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "View"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Window"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Close"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Minimise"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Shortcut: {style} {key} ·"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Idle"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/machines.py mac_app/machines_panel.py mac_app/widgets.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Everything"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shares every group and can replace local values on this machine."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Older Beamer versions share known Crossing and Design settings without group choices."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Revert"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Start Beamer when you log in"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Open Login Items settings"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Show in Dock"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Show in menu bar"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Check for updates"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Download"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Reverse other machines' scrolling"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Delay"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/ledger.py win_app/crossing_ledger.py win_app/kvm_bridge_win.py
+msgid "Machine"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Send input"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Pause crossing"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hold this Mac's edges while an app on it is full screen"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This screen decides, including when another machine drives it. On, a full-screen app here holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer can go home or onward through the configured ways."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This screen's setting applies to every pointer on it."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hide the pointer on the machine not in use"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same ways on every machine"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Set every machine's ways from this screen. Turning it on changes nothing until you do; each machine's own ways are kept."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Switching moves every machine to this profile's places and ways."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/machines_win.py
+msgid "Machines"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Keep this machine's own ways"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Use the desk's ways"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Share mine with the desk"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac keeps its own ways"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Don't cross while dragging with this Mac's pointer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shake to come home"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Delete…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Profile name"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Cancel"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Earlier ways ▾"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Earlier ways ▴"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "hold"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "double-tap"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Time between taps"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "With Hold, input goes to the last machine."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Nothing yet. Every key and button goes to the machine that has input."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Animate crossings on this Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Show where the pointer lands"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hover to preview"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Length"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Sets the effect's playback time."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Size"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Sets effect depth relative to the shorter screen edge."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Tick as the push builds"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Ticks at"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Try it"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Modifier keys"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hide addresses"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Beamer changes language when it next opens."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Relaunch Beamer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "First paired machine's port"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Accessibility"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Lets Beamer move this Mac's pointer and type on it when another machine drives."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input Monitoring"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Lets Beamer read this keyboard and trackpad, to send them to another machine."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Required"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Grant"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Saved. Connecting…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Current chain: Idle"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac drives other machines"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Other machines drive this Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Profile"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Configuration reloaded"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Beamer is using the config on disk."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Open Beamer's website, kalkmancode.co.uk/beamer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Click a machine on the map to set its ways. The ledger says how it reaches each other machine."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Off: the trackpad stays still while you push."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Switches the moment this Mac's pointer touches the edge. Each screen supplies its own zones."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Custom: the key map in settings.json is kept as it is."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Refused: that position is already occupied."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/link_state.py
+msgid "Not paired"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/machines.py win_app/peers_view.py
+msgid "No address"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Settings"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same on all machines"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "At login"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Updates"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/widgets.py win_app/kvm_bridge_win.py
+msgid "Match design with"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "None"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Appearance"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Another machine's pointer here"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Pointer speed"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Scrolling"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Scroll speed"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Keyboard and pointer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "New profile…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Rename"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This machine kept the ways set while it ran an older Beamer."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "● Crosses"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "● Offline, ways kept"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Back to This Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "The desk is full. Remove an unused profile before adding more ways."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shake sensitivity"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same → Shortcut"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Rename profile"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "New profile"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Save"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Add"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py
+msgid "Drag a machine on the map to where it sits. The ledger says how each one is reached; click a row to pick it on the map."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Click a machine to set its ways · Tab and Return pick one from the keyboard"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "Before Beamer 1.5.5"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "From an older Beamer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "When Same ways went off"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "When Same ways went on"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "Before you changed it"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "Before a restore"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "With Hold, input goes to the first ready machine in order. Choose which machines join the cycle with the tick boxes on their tiles."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Stays on this Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Remove"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "That key is the shortcut; it always stays with Beamer."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "On screen"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Notch style"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Style"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Style for"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Show at"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Frame rate"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Colour"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Trackpad"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/machines_win.py
+msgid "Address"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgctxt "list"
+msgid " or "
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Hold {key}, or push through {ways}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Double-tap {key}, or push through {ways}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Saved. Changes apply as you make them."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Quit Beamer and start it again."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Grant both Mac permissions first."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Current chain: {route}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Granted"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Both granted. Relaunch Beamer so macOS passes it the keyboard."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Resume crossing"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Return input to Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Not yet learned"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Read from the network the first time this Mac connects; nothing to type."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Beamer • Local"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid " macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Once the pointer is through to another machine the notch keeps playing for {seconds} seconds. Outline and Island apply to Glow and Beam; other styles draw their own notch."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Input is on another machine for as long as the key is held. If you jump while holding the shortcut, releasing it brings input home."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Tap twice to switch; tap twice again to come back."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Crossing shares resistance and drag protection. Design shares effects, colour, length, size and arrival animation. Shortcut shares shortcut on/off, trigger key and style, and destination. Names shares this machine's name and paired-machine labels."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Ways: set on the Crossing page · {state}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "With the Dock icon off, Beamer stays in the menu bar and appears in the Dock while its window is open. The Dock and the menu bar are never both off: the one still showing cannot be switched off."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "System"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgctxt "appearance"
+msgid "Light"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Dark"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This window"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "System follows your Mac's light or dark setting."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Pointer speed for another machine's mouse or trackpad while it drives this Mac."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Link"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac's pointer always hides while it drives another machine. On, it also hides after another machine stops driving it, until its own mouse or trackpad moves."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Each chip is a side of this screen; click one to add or remove it. The side a machine touches crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. A corner is a diagonal push, shown as a square on the map. The notch is this Mac only."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This machine's pointer"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Applies when this physical pointer pushes through this screen's ways; visiting pointers are not protected by this switch."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Way home"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shake the mouse or trackpad left and right a few times while you drive another machine, and input comes straight back to the machine you are using."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Push back the way you came: where an edge leads back to This Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "+"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Double-tap"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hold"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "How you press it"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Last machine"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Next in order"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Next among ticked"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shortcut goes to"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "With Hold, input goes to the first ready machine in order."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "These keys and buttons keep working on this Mac while its input is on another machine: a mouse's back button for this Mac's browser, say, or a volume key for its speakers."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Turns crossing and landing animations on or off on this screen. Saved style choices stay in place."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "For shortcut, menu and jump arrivals; requires Animate crossings on this screen."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Outline"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "A line of colour runs round the notch, faster the harder you push."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Island"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "The notch grows as you push, with a meter inside, and flashes as you go through."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Keep animating"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shortcut and menu"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "What plays around the pointer for shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Any colour works with any style. The notch's Outline uses it too; Island keeps Beamer's own cyan."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Every quarter"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Halfway"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Only when through"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Feel it"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same shortcuts"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same positions"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hides every IP and hardware address in this window and its menu."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Automatic"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Language"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Wake-on-LAN"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "A new address or port takes effect when you connect."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Connect"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "On Overview, turn on Start Beamer when you log in. If macOS needs approval, that page shows the status and opens Login Items settings."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Push through {ways}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input capture ready."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Nothing is paired yet. Pairing fills the address and port in."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac drives every machine"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Every machine drives this Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Configuration not reloaded"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Driving {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Driven by {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid ""
+"Beamer {version}\n"
+"Beamer's website"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Plays {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{key}, to where input last went"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "On a PC, Command arrives as Control, so Command-C copies there too, and Control arrives as the Windows key. Between two Macs every key arrives as itself."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "On a PC, each key arrives as the key in its place, so Command arrives as the Windows key. Between two Macs every key arrives as itself."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "On"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Off"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Download Beamer {version}"
+msgstr ""
+
+#. {reason} is the system's reason for refusing the login item.
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "macOS refused: {reason}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Requires approval. Allow Beamer in System Settings, General, Login Items."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Requires approval. Move Beamer to Applications and reopen it before allowing it in Login Items."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{name}'s ways"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Editing {name}'s ways ·"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Jump keys and permissions are set on {name}."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Changes go to {name} at once."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Restore"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Delete"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "The order follows the tiles from top to bottom, then left to right. This Mac is always in the cycle. Choose which machines join the cycle with the tick boxes on their tiles."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "The order follows the tiles from top to bottom, then left to right. This Mac is always in the cycle."
+msgstr ""
+
+#. {name} is the machine name.
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "Remove {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "the {side} edge"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "Hold {key}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "Double-tap {key}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/link_state.py
+#, python-brace-format
+msgid "Waking {name}. It connects on its own once it is up."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Beamer needs both, granted separately. macOS only delivers keyboard events to a process started after the grant, so relaunch Beamer once you have given them."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Settings…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Reload configuration"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Open log folder"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer {version} is available…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer {version}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "This Mac drives {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "{name} drives this Mac"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Same as crossing: {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{name}, {intensity}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "A tick at a quarter, half and three quarters of the push, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "One tick halfway through the push, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Nothing on the way in, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones. This screen's {side} edge lights to show the resistance."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Could not save this Mac's name: {error}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Could not save the machine's name: {error}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Not found. Check Beamer is installed in Applications, then turn it on again."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Could not open Login Items settings: {reason}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{name} has no way back to {machine} except the shortcut and a shake."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "Before {name} changed it"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "{date} · {reason}"
+msgstr ""
+
+#. {detail} is a diagnostic reason supplied by macOS.
+#: mac_app/kvm_bridge_app.py
+msgid "Retrying input capture…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "The address and port of {name}, the first machine paired. Another machine is changed by pairing it again."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Crossing to {name} while it sleeps sends a wake-up packet and waits for it."
+msgstr ""
+
+#. {error} is the system error message.
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Could not save the change: {error}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "{error}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Login item status: {status}. Move Beamer to Applications and open it there to start at login."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Enabled. Beamer will start when you log in."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/wake.py win_app/peers_view.py win_app/sender.py
+#, python-brace-format
+msgid "Waking {name}…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Send input to {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Not registered. Turn on Start Beamer when you log in."
+msgstr ""
+
+#. {detail} is a diagnostic reason supplied by macOS.
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Retrying input capture… {detail}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Wake {name}"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Login item status: {status}."
+msgstr ""
+
+#: mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/machines_win.py
+msgid "Leave out"
+msgstr ""
+
+#: mac_app/ledger.py
+msgid "Return saves, Escape cancels"
+msgstr ""
+
+#: mac_app/ledger.py mac_app/machines_panel.py
+msgid "Only on this Mac"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Place it on the map"
+msgstr ""
+
+#: mac_app/ledger.py
+msgid "No notch"
+msgstr ""
+
+#: mac_app/ledger.py
+msgid "Return through the notch"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Jump"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Clear"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Left out"
+msgstr ""
+
+#: mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/machines_win.py
+msgid "Put back"
+msgstr ""
+
+#: mac_app/ledger.py
+msgid "Machines and crossing ways"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Edges"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Corners"
+msgstr ""
+
+#: mac_app/ledger.py mac_app/previews.py win_app/crossing_ledger.py
+msgid "Notch"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Keys"
+msgstr ""
+
+#: mac_app/ledger.py mac_app/widgets.py win_app/widgets.py
+msgid "Press a key combination…"
+msgstr ""
+
+#: mac_app/ledger.py mac_app/widgets.py win_app/kvm_bridge_win.py win_app/widgets.py
+msgid "Click again to cancel"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py win_app/kvm_bridge_win.py
+msgid "Offline, ways kept"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Left out machines stay paired and linked. The shortcut, menu and clipboard still reach them."
+msgstr ""
+
+#: mac_app/ledger.py
+msgid "Leave this machine out of pointer crossings"
+msgstr ""
+
+#: mac_app/ledger.py
+msgid "Notch, no notch"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Return through the notch, on"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Return through the notch, off"
+msgstr ""
+
+#: mac_app/ledger.py
+msgctxt "switch state"
+msgid "on"
+msgstr ""
+
+#: mac_app/ledger.py
+msgctxt "switch state"
+msgid "off"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Notch, on"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Notch, off"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Push into the notch to reach {name}"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Coming back from {name}, arrive just below the notch"
+msgstr ""
+
+#. {key} is the recorded key combination; {name} is the machine name.
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Press {key} to send input to {name}; press again to bring it home."
+msgstr ""
+
+#: mac_app/ledger.py mac_app/machines_panel.py
+#, python-brace-format
+msgid "Rename {name}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{side} edge"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Left out: Put back to change its ways"
+msgstr ""
+
+#: mac_app/ledger.py
+msgid "unavailable"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "macOS"
+msgstr ""
+
+#: mac_app/ledger.py mac_app/machines.py mac_app/widgets.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Windows"
+msgstr ""
+
+#: mac_app/ledger.py mac_app/machines.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Linux"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "Put back {name}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "Leave out {name}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: touches {name}; click to turn it {state}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, touches {name}, {state}"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner, {state}"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side}, wraps"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge} wraps round to {name}; click to remove"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, wraps round, {state}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{corner} corner: click to turn it off"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{corner} corner: click to turn it on"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{name}'s corner"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "Place {name} beside this Mac first"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "held by {name}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, wraps round, kept"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, {third} third, {state}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge} wraps round to {name} once Edge is on; click to turn Edge on"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: none of it is free just now; click to remove"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: click to wrap round to {name}"
+msgstr ""
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side}, {name}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: {name}'s"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, held by {name}"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{third} third: click to leave it out"
+msgstr ""
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{third} third: click to turn it on"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Beamer keeps trying to reconnect."
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Disconnected"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+msgid "Dropped"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Live"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Waking"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Tunnel"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "On Mac"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Setup"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Pair a machine on Overview and Beamer connects on its own."
+msgstr ""
+
+#. a machine's address and port, as in "192.0.2.20 port 24820".
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{host} port {port}"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Pairing removed"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/pages_win.py win_app/peers_view.py
+msgid "Refused"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Token mismatch"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Version mismatch"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Did not wake"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "No reply"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Blocked"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "macOS 27 blocked direct LAN access. Open Beamer Tunnel from Applications."
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+msgid "Unreachable"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+msgid "Not listening"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "No receiver"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/kvm_bridge_win.py win_app/peers_view.py
+msgid "Waiting"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Looking"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Unlocking"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Paused"
+msgstr ""
+
+#: mac_app/link_state.py
+msgid "Held"
+msgstr ""
+
+#: mac_app/link_state.py mac_app/pages.py win_app/pages_win.py
+msgid "Held: an app is full screen."
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "{status}. Beamer keeps trying to reconnect."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "From {name}"
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name}'s keyboard and pointer are on this Mac. Push its pointer back through the edge it arrived by to send them home."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "Connected to {name} through the macOS 27 tunnel."
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "Connected to {name}."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} no longer has this pairing: remove {name} here and pair the two again."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} refused this Mac's token. Remove it, then pair again to write a fresh one."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} runs a different Beamer from this Mac. Update both to the same version."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} did not answer within a minute of the wake-up packet."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{address} is not answering. {name} may be asleep or off this network."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} answers, but Beamer is not listening on port {port}. Open Beamer on {name}."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} stopped responding. Beamer keeps trying to reconnect."
+msgstr ""
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "Looking for {name}. It connects on its own once Beamer is open there."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} is at its lock screen and is unlocking itself; input follows once the desktop is back."
+msgstr ""
+
+#: mac_app/link_state.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "On {name}"
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "Keyboard and pointer are on {name}. Do the same again to bring them home."
+msgstr ""
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "Connected to {name}. Crossing is held, so you can lean on an edge."
+msgstr ""
+
+#: mac_app/login_item.py
+msgid "Not registered"
+msgstr ""
+
+#: mac_app/login_item.py
+msgid "Enabled"
+msgstr ""
+
+#: mac_app/login_item.py
+msgid "Requires approval"
+msgstr ""
+
+#: mac_app/login_item.py
+msgid "Not found"
+msgstr ""
+
+#: mac_app/login_item.py win_app/kvm_bridge_win.py
+msgid "Unknown"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "iPhone"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Android"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Other"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Needs re-pair"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "NOT IN USE"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Pair again"
+msgstr ""
+
+#: mac_app/machines.py
+msgid "Driving this Mac"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Input here"
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Version"
+msgstr ""
+
+#: mac_app/machines.py mac_app/machines_panel.py win_app/peers_view.py
+#, python-brace-format
+msgid "{address} · port {port}"
+msgstr ""
+
+#: mac_app/machines.py
+#, python-brace-format
+msgid "{name} is not in use on this Mac."
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "{name} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0."
+msgstr ""
+
+#: mac_app/machines.py
+#, python-brace-format
+msgid "{name}'s keyboard and pointer are on this Mac. Push the pointer back through the edge it arrived by to send them home."
+msgstr ""
+
+#: mac_app/machines.py
+#, python-brace-format
+msgid "This Mac's keyboard and pointer are on {name}. Do the same again to bring them home."
+msgstr ""
+
+#: mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "Waiting for {name} to connect."
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "Expires in {n} s"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair nearby"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair a phone"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair a machine"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "No machines paired yet."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Beamer connects to each machine on its own whenever both are running."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Rename this Mac"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Name for this Mac"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Show a code"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "The pairing code as a QR code"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Cancel code"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing digits"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Confirm"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Choose a machine, or type its address, then type the code it shows."
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "In use"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "This Mac drives it"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "It drives this Mac"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Press Pair nearby on the other machine within 60 seconds."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Choose a machine to pair nearby."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Compare all six digits on both machines, then confirm on each."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Waiting for confirmation on the other machine."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing complete."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing expired. Press Pair nearby to try again."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing refused. Use a new window to try again."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "The new peer could not be saved."
+msgstr ""
+
+#. {name} and {address} come from the other machine.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {address}, older Beamer"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "That machine"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Show a code on this Mac"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Enter a code from another machine"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "On this network"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Address of a machine that is not listed"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Not listed? Type its address."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Code shown on the other machine"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Re-pair"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Hide directions"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Directions"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Keep"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Pairing is not available on this Mac."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Connecting to the selected machine…"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/crossing_ledger.py win_app/sender.py
+msgid "Another machine"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Looking for machines running Beamer. Open it on the other machine and it appears here; across a VPN or on guest Wi-Fi it may not, so type its address below."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {address}, showing a code"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {address}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "On the other machine, open Beamer, choose this Mac in its list and type the code."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {state}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Name for {name}"
+msgstr ""
+
+#. {name} is the other machine's chosen name.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Off: no input or settings link to {name}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect."
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "{action} {name}"
+msgstr ""
+
+#. {name} is the other machine's chosen name.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Input moves only when this Mac enables this switch and {name} enables It drives this Mac."
+msgstr ""
+
+#. {name} is the other machine's chosen name.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Input moves only when {name} enables This machine drives it and this Mac enables this switch."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{action} directions for {name}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Remove {name}? It stays paired on that machine until you remove this one there too."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "The QR is hidden while addresses are hidden."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Pairing with {name}…"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Paired with {name}. Connecting…"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "Re-pair {name}"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Left out of the layout. The shortcut and the menu still reach it."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Off: {name} cannot connect or drive this Mac. Turn it back on here to reconnect."
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Hide"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Show"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Confirm removing {name}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Keep {name}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "this machine"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "The same code as a QR, for a phone to scan."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Beamer cannot look for machines: {reason}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Code shown on {name}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "The code is {n} digits."
+msgstr ""
+
+#. {error} is the system error message.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Could not remove it: {error}"
+msgstr ""
+
+#. {error} is the system error message.
+#: mac_app/machines_panel.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Nearby pairing is not available: {error}"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "Not selected"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "No network address found"
+msgstr ""
+
+#: mac_app/machines_panel.py
+msgid "No QR while this Mac has no address."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name} is not showing a code yet. Show one in Beamer on it first."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Six digits, as shown on {name}."
+msgstr ""
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "No QR: {reason}"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "This Mac only."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "The notch is this Mac only."
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Changes apply as you make them."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Closing this window keeps Beamer running in the menu bar."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Simple"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this Mac's input for every destination."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Used on this screen. Shared animation settings may follow another machine; Animate, window appearance, notch and trackpad controls stay on this Mac."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Modifier keys and Stays here belong to this Mac's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Classic"
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Signal"
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Colourful"
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Ocean"
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Sunset"
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Aurora"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "to the left of"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "to the right of"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "This corner crosses its left or right edge."
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "On. Pause it to lean on an edge without switching."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "the edge"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "a corner"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "With only the notch or a corner on, input arrives by the notch's or corner's own side, so this choice does nothing on this Mac; the other machine's own push still follows it."
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Overview"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Where input is, whether each link is up, and the controls you reach for every day. Pair your machines here first."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Permissions"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "macOS must allow Beamer to read this Mac's input and to move its pointer and type when another machine drives it."
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Keyboard"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "How this Mac's modifier keys arrive on other machines, which keys and buttons stay on this Mac, and how fast another machine's pointer moves here. The switch key is on the Crossing page."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad."
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Connection"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Local connection details for the first machine you paired. Pair again to change another machine's entry."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Changes apply as you make them. Closing this window keeps Beamer running in the menu bar."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Where the other machine is"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Not paired yet, so no edge or shortcut moves input until you pair a machine on Overview."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "No machine is driven by this Mac, so edges and the shortcut do nothing."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Not connected to any machine, so edges and the shortcut do nothing yet."
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Only the shortcut is switched on; there is nothing to pause."
+msgstr ""
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "This Mac has no notch, so this only shows how it would look."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{names} already cross from the {side} edge of this Mac. The thirds you pick go to {name}; the rest stay where they are."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Plays Glow"
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Closes onto the pointer"
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{names} already crosses from the {side} edge of this Mac. The thirds you pick go to {name}; the rest stay with {holder}."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "Not placed yet: {names}"
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "Where {name} is"
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing. {name} draws its own form round the notch."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} draws its own form round the notch."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "With only the notch or a corner on, input arrives by the notch's or corner's own side, so this choice does nothing on this Mac; {name}'s own push still follows it."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} is {position} this Mac."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} is not placed yet."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "No way in is on."
+msgstr ""
+
+#: mac_app/pages.py
+msgid "Bring input back"
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing. At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it."
+msgstr ""
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} is unavailable"
+msgstr ""
+
+#: mac_app/previews.py win_app/kvm_bridge_win.py
+msgid "Edge"
+msgstr ""
+
+#: mac_app/previews.py win_app/kvm_bridge_win.py
+msgid "Corner"
+msgstr ""
+
+#: mac_app/wake.py win_app/sender.py
+#, python-brace-format
+msgid "{name} did not wake"
+msgstr ""
+
+#: mac_app/wake.py win_app/sender.py
+msgid "Could not send the wake-up packet"
+msgstr ""
+
+#: mac_app/wake.py win_app/sender.py
+#, python-brace-format
+msgid "{name} is awake — switch again to send input"
+msgstr ""
+
+#: mac_app/widgets.py
+msgid "Press a key…"
+msgstr ""
+
+#: mac_app/widgets.py win_app/kvm_bridge_win.py
+msgid "Click, then press the key"
+msgstr ""
+
+#: mac_app/widgets.py win_app/widgets.py
+msgid "Click, then press a key combination"
+msgstr ""
+
+#: mac_app/widgets.py win_app/kvm_bridge_win.py
+msgid "Add a key or button"
+msgstr ""
+
+#: mac_app/widgets.py win_app/widgets.py
+msgid "Press a key or button…"
+msgstr ""
+
+#: mac_app/widgets.py win_app/kvm_bridge_win.py win_app/widgets.py
+msgid "Click, then press it"
+msgstr ""
+
+#: mac_app/widgets.py win_app/widgets.py
+msgid "Choose a key combination"
+msgstr ""
+
+#: mac_app/widgets.py
+msgid "Add a key or button that stays on this Mac"
+msgstr ""
+
+#. {key} is the key combination recorded by the person.
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "Shortcut key, {key}"
+msgstr ""
+
+#. {key} is the key combination recorded by the person.
+#. {key} is the key combination recorded for a machine.
+#: mac_app/widgets.py win_app/widgets.py
+#, python-brace-format
+msgid "Jump straight here key, {key}"
+msgstr ""
+
+#: mac_app/widgets.py win_app/crossing_ledger.py
+msgid "Set a key"
+msgstr ""
+
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "Digit {n}"
+msgstr ""
+
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "{name} ⌘{key}"
+msgstr ""
+
+#. {name} is a settings page name.
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "{name}, needs attention"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "Return saves, Escape cancels · Only on this PC"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "Clear jump key"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "Return here"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "Leave this machine out of crossings"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "How each machine is reached"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "turn it off"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "turn it on"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "PC"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, {third} third, {state}"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "on"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "off"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{third} third: click to {action}"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+msgid "leave it out"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Choose a key combination to jump to {name} and back."
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, touches {name}, {state}"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner, held by {name}"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: touches {name}; click to {action}"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, wraps round, on"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner, unavailable"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge wraps round to {name}; click to remove"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, wraps round, kept"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Place {name} beside this {platform} first"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner: click to turn it {state}"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge wraps round to {name} once Edge is on; click to turn Edge on"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: none of it is free just now; click to remove"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: {name}'s"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, held by {name}"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, wraps round, off"
+msgstr ""
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: click to wrap round to {name}"
+msgstr ""
+
+#: win_app/diagram.py win_app/kvm_bridge_win.py
+msgid "This PC"
+msgstr ""
+
+#: win_app/diagram.py
+msgid "Tile size can be changed by dragging a corner or pressing Alt+arrow."
+msgstr ""
+
+#: win_app/diagram.py
+msgid "Arrangement"
+msgstr ""
+
+#: win_app/diagram.py
+msgid "Crossing layout"
+msgstr ""
+
+#: win_app/diagram.py
+msgid "at a corner of This PC"
+msgstr ""
+
+#: win_app/diagram.py
+msgid "Crosses."
+msgstr ""
+
+#: win_app/diagram.py
+msgid "THIS PC"
+msgstr ""
+
+#. {name} is a machine name; {position} is relative to this PC; {detail} optionally names the third crossed.
+#: win_app/diagram.py
+#, python-brace-format
+msgid "{name}, {position}{detail}. {result}"
+msgstr ""
+
+#: win_app/diagram.py
+msgctxt "list"
+msgid "; "
+msgstr ""
+
+#: win_app/diagram.py
+msgid "Rename this computer on Overview."
+msgstr ""
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid "{side} of This PC"
+msgstr ""
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid ", {part} third"
+msgstr ""
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid "Current pressure {pressure} of {threshold} pointer units at the {edge} edge."
+msgstr ""
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid "No push. Current pressure is 0 of {threshold} pointer units."
+msgstr ""
+
+#: win_app/firewall_win.py win_app/linux_stand_ins.py
+msgid "Check again"
+msgstr ""
+
+#: win_app/firewall_win.py
+msgid "Fix the firewall"
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Beamer could not read the Windows Firewall: {error}"
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rule for private networks."
+msgstr ""
+
+#: win_app/firewall_win.py
+msgid "Trust this network"
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "{sentence} Beamer is not running as administrator, so it cannot make this change itself: quit Beamer and open it again from the Start menu."
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will say this PC is unreachable. This happens when the installer was run without administrator rights. Fixing it adds the rule for private networks."
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."
+msgstr ""
+
+#: win_app/firewall_win.py
+msgid "this private network"
+msgstr ""
+
+#: win_app/firewall_win.py
+msgid "this network"
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Beamer's firewall rule does not apply on this network (Windows calls it {names}). Fixing it rewrites the rule to cover it."
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for {rules}, so {effects}. Installs made before these rules existed are missing them. Fixing it adds what is missing and leaves the working rules alone."
+msgstr ""
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine discover this PC."
+msgstr ""
+
+#: win_app/global_shortcut_portal.py
+msgid "Send input to another machine"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer's website"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Receiver stopped"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Waiting for a machine"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Machine connected"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Receiver needs attention"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Stopped"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Connected"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Error"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "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."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "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."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "To a Mac: Alt becomes Command and Win becomes Option; Ctrl stays Control."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "These keep working on this PC while its input is on another machine: a mouse's back button for this PC's browser, say, or a volume key for its speakers."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Nothing yet. Every key and button goes to the machine that has input. Add one to keep it here: a mouse's back button for this PC's browser, say, or a volume key for its speakers."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Top-left"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Top-right"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Bottom-left"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Bottom-right"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Mac keyboard layout"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Sets the effect's playback time. Current value: {value}."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Sets effect depth relative to the shorter screen edge. Current value: {value}."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Only on this computer"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Only on this PC"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Linux permissions"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Send input — Input Capture"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Receive input — Remote Desktop"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Tray"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Show in tray"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Keyboard and mouse"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Send input across"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Switch on This PC drives it for a machine above to send input from here."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland the desktop lets input go to another machine only when the pointer pushes through an edge, so this button cannot send it."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Hold this PC's edges while an app on it is full screen"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC's pointer hides while it drives another machine, and after another machine stops driving it, until its own mouse moves."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an edge, so the edges are never held for one and a drag can cross."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "At sign-in"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Start Beamer when you sign in"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Windows could not identify the signed-in account, so start at sign-in is unavailable."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "In the tray, with no window."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Back to This PC"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Earlier ways"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py win_app/pages_win.py
+#, python-brace-format
+msgid "hold {key}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "double-tap {key}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Don't cross while dragging with this PC's pointer"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Switches the moment this PC's pointer touches the edge. Each screen supplies its own zones."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Reverse scrolling from other machines"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Stays on this PC"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland the shortcut only brings input back: the desktop lets input go to another machine only when the pointer pushes through an edge, and keys on the Stays on this PC list cannot stay here while input is away."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Send input out with Super+Shift+B"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "From here, where the double-tap cannot be seen, the key combination pushes the pointer through the edge to the machine the shortcut goes to. The desktop asks once to allow it, and its keyboard settings can change the keys."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "None: this PC keeps its own Design."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "System follows your Linux desktop's light or dark setting."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "System follows Windows' light or dark setting."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Animate crossings on this PC"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Jump arrivals use this screen's landing animation too."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "For shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "For the crossing and the shortcut alike"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Addresses"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC's address"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC's listening port"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Save and reconnect"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Saved."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Linux firewall"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py win_app/linux_stand_ins.py
+msgid "Beamer's firewall check is not yet on Linux."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Windows Firewall"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Checking Windows Firewall…"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Checking…"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Fixing…"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC drives machines"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Machines drive this PC"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "On this PC"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer requests keyboard and pointer access when each Wayland session starts."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Not requested"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Ask again"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Input:"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Delay:"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Start at sign-in needs the same administrator account that runs Beamer."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Each chip is a side of this screen; click one to add or remove it. The side a machine touches crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. A corner is a diagonal push, shown as a square on the map."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Push back the way you came: where an edge leads back to This PC"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC keeps its own ways"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Follows this PC's mouse or trackpad on every screen; each screen supplies its own zones."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "For the trackpad or mouse of whichever machine drives this PC."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "That could not be saved, so the list is unchanged."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Shortcut key"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "That key cannot be the shortcut. Choose a modifier such as Right Ctrl, a function key, or a key like Insert or Scroll Lock."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Sets depth relative to the shorter screen edge."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland the desktop does not let Beamer draw at the edges of the screen, so crossings show no effect on this machine. The other machines still show theirs."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Current chain: {names}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Pairing is not available: this PC's settings could not be read."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "The QR holds this PC's address, so it is not shown while Hide addresses is on."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Hides every IP and hardware address in this window and the tray."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Not known yet"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "With it off, closing the window quits Beamer. Open Beamer again to bring the window back."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "This desktop has no system tray, so Beamer's window is all there is: closing it quits Beamer."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Seam crossings need X11 on Linux."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "These ways could not be saved. Try again."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Shortcut: {shortcut} (set in {link})"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "That position cannot connect this machine."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{value} px"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{value} ms"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "The effects stopped working and are off until Beamer restarts, so crossings show Glow in the same colours. The log says why."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer could not save the removal. Try again in a moment."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "port must be an integer from 1 to 65535"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Save failed"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "<b>Beamer {version}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br><a href=\"{url}\" style=\"color: {colour};\">{link}</a>"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Ready on TCP port {port}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid ""
+"Beamer {version}\n"
+"{link}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "When enabled, a logon task starts Beamer elevated without a UAC prompt, so it can send input to administrator apps."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Only the installed app can start at sign-in."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "These ways could not be changed."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "This desk is full. Remove an unused profile before adding more ways."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{version} · only sees which side"
+msgstr ""
+
+#. {side} is the direction of this screen's edge.
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Follows this PC's mouse or trackpad on every screen; each screen supplies its own zones. This screen's {side} edge lights to show the resistance."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Remove {key}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Pairing is not available: {error}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "This PC's address: {address} · port {port}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer — {status}: {detail}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Could not save this PC's name: {error}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Windows refused: {error}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Nearby pairing could not continue: {error}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Could not reload the configuration: {error}"
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Give the profile a name of 1 to 32 characters."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{blurb} It plays around the pointer when the shortcut or a menu brings input to this PC."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "the change failed: {error}"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Pairing code"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Off on this PC: no input or settings link to this machine. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect."
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "This PC drives it"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Input moves only when this PC enables this switch and the other machine enables It drives this PC."
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "It drives this PC"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Input moves only when the other machine enables This machine drives it and this PC enables this switch."
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "QR code for the pairing code"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Time left"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Nearby pairing status"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Nearby pairing time left"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "No other machine is showing a code yet."
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Address of the other machine"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Code"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Show a code on this PC"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Pairing digits"
+msgstr ""
+
+#: win_app/machines_win.py
+msgid "Pairing…"
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "{name}: {status}"
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Off on this PC: no input or settings link to {name}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect."
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Input moves only when this PC enables this switch and {name} enables It drives this PC."
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Input moves only when {name} enables This PC drives it and this PC enables this switch."
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Selected: {name} · {platform}"
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Remove {name}? {note}"
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Off on this PC: {name} cannot connect or drive it. Turn it back on here to reconnect."
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Pairing digits {digits}"
+msgstr ""
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Pairing code {digits}"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "This PC only."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Closing this window keeps Beamer running in the tray."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Changes apply as you make them. Closing this window keeps Beamer running in the tray."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this PC's input for every destination."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Used on this screen. Shared animation settings may follow another machine; Animate and window appearance stay on this PC."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Modifier keys and Stays here belong to this PC's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Ready"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Unavailable"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "top-left"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "top-right"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "bottom-left"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "bottom-right"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "This PC is always in the shortcut's cycle."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "to the right of this PC"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "to the left of this PC"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "above this PC"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "below this PC"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "The machines paired with this PC, where input is right now, and the controls you reach for every day. Pair a machine here first."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Choose how the pointer or a key moves input to each machine, and how hard the edge pushes back first."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "How this PC's Ctrl and Windows keys arrive on another machine, the keys and buttons that stay here, and how fast another machine's pointer moves here."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "How crossing looks on this PC: the light as you push toward another machine, and where the pointer lands."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "This PC's network access, address and listening port; hide addresses in this window and tray."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Not paired yet, so no edge or shortcut moves input until you pair a machine above."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Above"
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Below"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{place} is not one of this PC's ways in, so this only shows how it would look. Turn it on under Crossing."
+msgstr ""
+
+#. {side} is the direction of the screen edge.
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{names} already cross from the {side} edge of this PC. The thirds you pick go to {name}; the rest stay where they are."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Not learned yet: choose a side here or on {name}."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{key}, twice"
+msgstr ""
+
+#. Several ways to move input, offered as alternatives.
+#: win_app/pages_win.py
+#, python-brace-format
+msgctxt "ways list"
+msgid "{head} or {last}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you {ways}."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "The order follows the tiles from top to bottom, then left to right. This PC is always in the cycle."
+msgstr ""
+
+#: win_app/pages_win.py
+msgid "Choose which machines join the cycle with the tick boxes on their tiles."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{first} {second} {third}"
+msgstr ""
+
+#. {side} is the direction of the screen edge.
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{names} already crosses from the {side} edge of this PC. The thirds you pick go to {name}; the rest stay with {holder}."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Waiting to hear from {name}. This PC cannot push into it until it has connected once."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "This PC does not drive {name}, so edges and the shortcut do nothing."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Not connected to {name}, so edges and the shortcut do nothing yet. Check that it is switched on and lets this PC drive it."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{key}, held"
+msgstr ""
+
+#. Two ways to move input, offered as alternatives.
+#: win_app/pages_win.py
+#, python-brace-format
+msgctxt "ways list"
+msgid "{first} or {last}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Nothing moves input to {name} until this PC knows which side it is on."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Nothing moves input to {name}: choose at least one way below."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you {ways}. The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through {ways}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{action}."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{shortcut}."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Not placed yet: {machines}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{name} is {position}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{first} {second}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you press {key} twice. Its edges and corner wait until this PC knows which side {name} is on."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through the whole {edge} edge"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through {parts}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push diagonally into the {corner} corner"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "No edge or corner leads to {name} yet: choose one below. The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "No edge or corner leads to {name} yet: choose one below."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through {ways} to reach {name}"
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{shortcut}, or {action}."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{machines}."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{line}."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you hold {key}. Its edges and corner wait until this PC knows which side {name} is on."
+msgstr ""
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "press {key} twice"
+msgstr ""
+
+#: win_app/peers_view.py
+msgid "Driving this PC"
+msgstr ""
+
+#: win_app/peers_view.py
+#, python-brace-format
+msgid "{name} is not in use on this PC."
+msgstr ""
+
+#: win_app/peers_view.py
+#, python-brace-format
+msgid "{name}'s keyboard and pointer are on this PC. Push the pointer back through the edge it arrived by to send them home."
+msgstr ""
+
+#: win_app/peers_view.py
+#, python-brace-format
+msgid "This PC's keyboard and pointer are on {name}. Do the same again to bring them home."
+msgstr ""
+
+#: win_app/sender.py
+msgid "Not connected"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} does not accept input from this one"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} sent the input back"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} would not take the input"
+msgstr ""
+
+#: win_app/sender.py
+msgid "Cannot switch — on this desktop input goes to another machine only by pushing the pointer through an edge"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {name} could not be reached"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {name} could not be reached while this PC is being driven"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {reason}"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{other} took over {name}"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} returned the input"
+msgstr ""
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — the desktop did not let Beamer send input to {name}"
+msgstr ""
+
+#: win_app/widgets.py
+msgid "Response time: no fresh measurement"
+msgstr ""
+
+#: win_app/widgets.py
+msgid "Response time: disconnected"
+msgstr ""
+
+#: win_app/widgets.py
+#, python-brace-format
+msgid "{name}, {key}"
+msgstr ""
+
+#: win_app/widgets.py
+#, python-brace-format
+msgid "{name}, {choice}"
+msgstr ""
+
+#: win_app/widgets.py
+#, python-brace-format
+msgid "{name}, selected"
+msgstr ""
diff --git a/locales/it.po b/locales/it.po
new file mode 100644
index 0000000..9f14085
--- /dev/null
+++ b/locales/it.po
@@ -0,0 +1,5246 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: Beamer\n"
+"Language: it\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"X-Beamer-Status: draft, awaiting check\n"
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Light"
+msgstr "Luce"
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Mono"
+msgstr "Mono"
+
+#: core/effects.py
+msgid "Bright"
+msgstr "Vivaci"
+
+#: core/effects.py mac_app/pages.py
+msgid "Quiet"
+msgstr "Discreto"
+
+#: core/effects.py mac_app/pages.py
+msgid "Medium"
+msgstr "Medio"
+
+#: core/effects.py mac_app/pages.py
+msgid "Showpiece"
+msgstr "Spettacolare"
+
+#: core/effects.py mac_app/pages.py
+msgid "Ring"
+msgstr "Anello"
+
+#: core/effects.py
+msgid "A ring in the chosen colours closes onto the pointer."
+msgstr "Un anello nei colori scelti si stringe sul puntatore."
+
+#: core/effects.py
+msgid "Membrane"
+msgstr "Membrana"
+
+#: core/effects.py
+msgid "Sparks"
+msgstr "Scintille"
+
+#: core/effects.py
+msgid "Instrument"
+msgstr "Strumento"
+
+#: core/effects.py
+msgid "Folio"
+msgstr "Folio"
+
+#: core/effects.py
+msgid "Selvedge"
+msgstr "Cimosa"
+
+#: core/effects.py
+msgid "Ink"
+msgstr "Inchiostro"
+
+#: core/effects.py
+msgid "Warp"
+msgstr "Curvatura"
+
+#: core/effects.py
+msgid "White"
+msgstr "Bianco"
+
+#: core/effects.py
+msgid "Silver"
+msgstr "Argento"
+
+#: core/effects.py
+msgid "Graphite"
+msgstr "Grafite"
+
+#: core/effects.py
+msgid "Warm grey"
+msgstr "Grigio caldo"
+
+#: core/effects.py
+msgid "Citron"
+msgstr "Cedro"
+
+#: core/effects.py
+msgid "Laser"
+msgstr "Laser"
+
+#: core/effects.py
+msgid "Electric"
+msgstr "Elettrico"
+
+#: core/effects.py
+msgid "Fuchsia"
+msgstr "Fucsia"
+
+#: core/effects.py
+msgid "Ultraviolet"
+msgstr "Ultravioletto"
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Glow"
+msgstr "Bagliore"
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "A band of light that deepens the harder you push."
+msgstr "Una fascia di luce che si intensifica quanto più spingi."
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Beam"
+msgstr "Raggio"
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "A thin line with a comet of light running along it."
+msgstr "Una linea sottile percorsa da una cometa di luce."
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "Aperture"
+msgstr "Diaframma"
+
+#: core/effects.py mac_app/pages.py win_app/pages_win.py
+msgid "A fine lens of light opens under pressure and closes softly behind the arriving pointer."
+msgstr "Una sottile lente di luce si apre sotto la pressione e si richiude dolcemente dietro il puntatore che arriva."
+
+#: core/effects.py
+msgid "Short"
+msgstr "Breve"
+
+#: core/effects.py
+msgid "Normal"
+msgstr "Normale"
+
+#: core/effects.py
+msgid "Long"
+msgstr "Lunga"
+
+#: core/effects.py
+msgid "Small"
+msgstr "Piccola"
+
+#: core/effects.py
+msgid "Large"
+msgstr "Grande"
+
+#: core/effects.py
+msgid "Match display"
+msgstr "Come lo schermo"
+
+#: core/effects.py
+msgid "Half"
+msgstr "Metà"
+
+#: core/effects.py
+msgid "Quarter"
+msgstr "Un quarto"
+
+#: core/effects.py mac_app/pages.py
+msgid "Same as crossing"
+msgstr "Come il passaggio"
+
+#: core/fx_folio.py
+msgid "Crease"
+msgstr "Piega"
+
+#: core/fx_folio.py
+msgid "A small paper crease lifts under pressure, parts, then settles flat where you arrive."
+msgstr "Una piccola piega di carta si solleva sotto la pressione, si apre e torna piatta dove arrivi."
+
+#: core/fx_folio.py
+msgid "Pleat"
+msgstr "Plissé"
+
+#: core/fx_folio.py
+msgid "Six alternating folds gather at the edge, slide apart and unfold on the other screen."
+msgstr "Sei pieghe alternate si raccolgono sul bordo, si separano e si distendono sull'altro schermo."
+
+#: core/fx_folio.py
+msgid "Concertina"
+msgstr "Fisarmonica"
+
+#: core/fx_folio.py
+msgid "A scored paper fan rises along the boundary, opens a passage and folds itself away behind you."
+msgstr "Un ventaglio di carta segnata si alza lungo il confine, apre un passaggio e si richiude alle tue spalle."
+
+#: core/fx_folio.py
+msgid "Moss"
+msgstr "Muschio"
+
+#: core/fx_folio.py
+msgid "Plum"
+msgstr "Prugna"
+
+#: core/fx_folio.py
+msgid "Vellum"
+msgstr "Pergamena"
+
+#: core/fx_folio.py
+msgid "Carbon copy"
+msgstr "Carta carbone"
+
+#: core/fx_folio.py
+msgid "Marbled"
+msgstr "Marmorizzato"
+
+#: core/fx_ink.py
+msgid "Capillary"
+msgstr "Capillare"
+
+#: core/fx_ink.py
+msgid "A soft pigment meniscus swells against the boundary with viscous surface tension. On breakthrough, it releases cleanly and diffuses as a calm, translucent wash on the arrival screen."
+msgstr "Un morbido menisco di pigmento si gonfia contro il confine con una densa tensione superficiale. Quando cede, si stacca di netto e si diffonde come una velatura calma e traslucida sullo schermo di arrivo."
+
+#: core/fx_ink.py
+msgid "Viscous drop"
+msgstr "Goccia densa"
+
+#: core/fx_ink.py
+msgid "An organic ink droplet gathers at the pointer, flattening against the glass edge before necking through the seam. On arrival, it splashes into a multi-lobed pigment bloom that bleeds outward."
+msgstr "Una goccia d'inchiostro organica si raccoglie sul puntatore, si appiattisce contro il bordo di vetro e poi si strozza attraverso la giuntura. All'arrivo si apre in una fioritura di pigmento a più lobi che si allarga sfumando."
+
+#: core/fx_ink.py
+msgid "Sumi bloom"
+msgstr "Fioritura sumi"
+
+#: core/fx_ink.py
+msgid "Dense calligraphic ink pulls from the boundary into a viscous bridge that necks and snaps through the seam. It arrives as an ink-in-water vortex bloom, unfurling delicate pigment filaments that dissolve into the screen."
+msgstr "Un denso inchiostro calligrafico si tende dal confine in un ponte viscoso che si assottiglia e si spezza attraverso la giuntura. Arriva come un vortice d'inchiostro nell'acqua che si schiude in delicati filamenti di pigmento e si dissolve nello schermo."
+
+#: core/fx_ink.py
+msgid "Indigo ink"
+msgstr "Inchiostro indaco"
+
+#: core/fx_ink.py
+msgid "Matcha"
+msgstr "Matcha"
+
+#: core/fx_ink.py
+msgid "Terracotta"
+msgstr "Terracotta"
+
+#: core/fx_instrument.py
+msgid "Rule"
+msgstr "Righello"
+
+#: core/fx_instrument.py
+msgid "A fine ruler rises along the edge round the pointer and lights outward one division at a time as the push builds, the three quarter detents marked long. At breakthrough it closes on the pointer in four clicks; on the other screen a short register mark sits where you came in and a four-arm cross steps in three clicks onto the landing point."
+msgstr "Un righello sottile si alza lungo il bordo attorno al puntatore e si illumina verso l'esterno una tacca alla volta mentre la spinta cresce, con le tre tacche dei quarti più lunghe. Quando cede si chiude sul puntatore in quattro scatti; sull'altro schermo un breve segno di registro resta dove sei entrato e una croce a quattro bracci arriva in tre scatti sul punto di arrivo."
+
+#: core/fx_instrument.py
+msgid "Gauge"
+msgstr "Quadrante"
+
+#: core/fx_instrument.py
+msgid "A half dial seated on the edge at the pointer, a quarter dial in the corner and a graduated collar round the notch, whose needle clicks round sixteen detents as the push builds. At breakthrough an iris shuts over the dial in four steps; on the other screen a graduated ring contracts onto the landing point, turning one graduation per click, and flashes as it locks."
+msgstr "Un mezzo quadrante poggiato sul bordo accanto al puntatore, un quarto di quadrante nell'angolo e un collare graduato attorno al notch, la cui lancetta scatta lungo sedici tacche mentre la spinta cresce. Quando cede, un'iride si chiude sul quadrante in quattro passi; sull'altro schermo un anello graduato si stringe sul punto di arrivo, ruotando di una tacca a ogni scatto, e lampeggia quando si blocca."
+
+#: core/fx_instrument.py
+msgid "Rangefinder"
+msgstr "Telemetro"
+
+#: core/fx_instrument.py
+msgid "A long scale runs along the edge and a pair of caliper jaws closes on the pointer in detents, lighting the divisions it passes, while three tally lamps light at each quarter. At breakthrough shutter blades slide in from both ends and a bright slit at the pointer shuts; on the far screen the jaws open outward from the entry point as a graduated reticle with corner brackets steps in, turns and locks onto the landing point."
+msgstr "Una lunga scala corre lungo il bordo e un paio di ganasce di calibro si chiude a scatti sul puntatore, illuminando le tacche che attraversa, mentre tre spie si accendono a ogni quarto. Quando cede, le lamelle di un otturatore scorrono dai due lati e una fessura luminosa sul puntatore si chiude; sull'altro schermo le ganasce si aprono dal punto di ingresso mentre un reticolo graduato con staffe agli angoli entra a scatti, ruota e si blocca sul punto di arrivo."
+
+#: core/fx_instrument.py
+msgid "Ruby"
+msgstr "Rubino"
+
+#: core/fx_instrument.py
+msgid "Cobalt"
+msgstr "Cobalto"
+
+#: core/fx_instrument.py
+msgid "Phosphor"
+msgstr "Fosforo"
+
+#: core/fx_instrument.py
+msgid "Sodium"
+msgstr "Sodio"
+
+#: core/fx_instrument.py
+msgid "Contrast"
+msgstr "Contrasto"
+
+#: core/fx_membrane.py
+msgid "Skin"
+msgstr "Pelle"
+
+#: core/fx_membrane.py
+msgid "A single iridescent hairline sits just inside the edge and dimples under the pointer as you push, thinning and shifting colour. It parts at the pointer and the two ends pull back; on the other screen the same hairline closes behind the pointer and one ripple spreads out."
+msgstr "Un unico filo iridescente corre appena dentro il bordo e si incava sotto il puntatore mentre spingi, assottigliandosi e cambiando colore. Si apre sul puntatore e le due estremità si ritirano; sull'altro schermo lo stesso filo si richiude dietro il puntatore e si allarga un'unica increspatura."
+
+#: core/fx_membrane.py
+msgid "Film"
+msgstr "Pellicola"
+
+#: core/fx_membrane.py
+msgid "A band of interference fringes, one added at each quarter tick, crowds and thins into the dent under the pointer, so the band itself is the pressure meter. At breakthrough the film tears and each fringe peels back with a curled rim; on the other side the skin bulges in around the arriving pointer, springs back, heals, and throws two ripples."
+msgstr "Una fascia di frange di interferenza, una in più a ogni quarto, si addensa e si assottiglia nell'incavo sotto il puntatore: è la fascia stessa a misurare la pressione. Quando cede, la pellicola si strappa e ogni frangia si arrotola all'indietro con il bordo ricurvo; dall'altra parte la pelle si gonfia attorno al puntatore che arriva, rimbalza, si richiude e lancia due increspature."
+
+#: core/fx_membrane.py
+msgid "Rupture"
+msgstr "Rottura"
+
+#: core/fx_membrane.py
+msgid "The whole edge becomes a visible soap film with a sheen behind its fringes; every tick sends a shudder along it, and at breakthrough it bursts, the torn rims racing away along the edge carrying beads of film. The arrival opens a set of Newton's rings around the entry point while the skin bulges in, heals and sends a surface wave along the edge."
+msgstr "L'intero bordo diventa una pellicola di sapone visibile, con un riflesso dietro le sue frange; ogni scatto la fa fremere e quando cede scoppia, e i lembi strappati corrono lungo il bordo portando con sé gocce di pellicola. All'arrivo si aprono gli anelli di Newton attorno al punto di ingresso mentre la pelle si gonfia, si richiude e manda un'onda lungo il bordo."
+
+#: core/fx_membrane.py
+msgid "Opal"
+msgstr "Opale"
+
+#: core/fx_membrane.py
+msgid "Sea glass"
+msgstr "Vetro di mare"
+
+#: core/fx_membrane.py
+msgid "Oil slick"
+msgstr "Chiazza d'olio"
+
+#: core/fx_membrane.py
+msgid "Soap bubble"
+msgstr "Bolla di sapone"
+
+#: core/fx_membrane.py
+msgid "Pearl"
+msgstr "Perla"
+
+#: core/fx_selvedge.py
+msgid "Thread"
+msgstr "Filo"
+
+#: core/fx_selvedge.py
+msgid "Two fine yarns tighten, part for the pointer and stitch the seam closed behind it."
+msgstr "Due fili sottili si tendono, si separano per lasciar passare il puntatore e ricuciono la giuntura alle sue spalle."
+
+#: core/fx_selvedge.py
+msgid "Weave"
+msgstr "Trama"
+
+#: core/fx_selvedge.py
+msgid "A woven border gathers tension, opens between its strands and gently mends on arrival."
+msgstr "Un bordo tessuto accumula tensione, si apre tra i suoi fili e si ricuce dolcemente all'arrivo."
+
+#: core/fx_selvedge.py
+msgid "Jacquard"
+msgstr "Jacquard"
+
+#: core/fx_selvedge.py
+msgid "A diamond-patterned textile tightens across the edge, opens its weave and settles behind you."
+msgstr "Un tessuto a motivi di rombi si tende sul bordo, apre la sua trama e si ricompone alle tue spalle."
+
+#: core/fx_selvedge.py
+msgid "Woad"
+msgstr "Guado"
+
+#: core/fx_selvedge.py
+msgid "Saffron"
+msgstr "Zafferano"
+
+#: core/fx_selvedge.py
+msgid "Flax"
+msgstr "Lino"
+
+#: core/fx_selvedge.py
+msgid "Madder"
+msgstr "Robbia"
+
+#: core/fx_selvedge.py
+msgid "Tide"
+msgstr "Marea"
+
+#: core/fx_sparks.py
+msgid "Flint"
+msgstr "Selce"
+
+#: core/fx_sparks.py
+msgid "A single hot point at the pointer draws in a few close sparks as you push, snaps them through the edge, and a pinch of sparks pops out where you land. Small enough to leave on all day."
+msgstr "Un unico punto incandescente sul puntatore attira poche scintille vicine mentre spingi, le fa scattare attraverso il bordo, e un pizzico di scintille esce dove arrivi. Abbastanza discreto da lasciarlo acceso tutto il giorno."
+
+#: core/fx_sparks.py
+msgid "Filings"
+msgstr "Limatura"
+
+#: core/fx_sparks.py
+msgid "Scattered sparks swing round to point at the pointer and creep in like iron filings to a magnet, the edge warming beside it; at breakthrough they are sucked through the point, and on the other screen the same sparks are thrown back out and fall."
+msgstr "Scintille sparse ruotano verso il puntatore e gli si avvicinano come limatura di ferro verso una calamita, mentre il bordo accanto si scalda; quando cede vengono risucchiate attraverso il punto, e sull'altro schermo le stesse scintille vengono lanciate fuori e ricadono."
+
+#: core/fx_sparks.py
+msgid "Discharge"
+msgstr "Scarica"
+
+#: core/fx_sparks.py
+msgid "The boundary charges up: sparks crawl along it and forty filings wheel in, with a crackle arcing to the pointer at every tick. At breakthrough the whole charge implodes through the point with a last arc; where it lands it goes off like a sparkler, stars splitting as they fall."
+msgstr "Il confine si carica: le scintille vi strisciano lungo e quaranta granelli di limatura arrivano roteando, con un arco crepitante verso il puntatore a ogni scatto. Quando cede, l'intera carica implode attraverso il punto con un ultimo arco; dove arriva esplode come una stellina, con stelle che si dividono mentre cadono."
+
+#: core/fx_sparks.py
+msgid "Arc"
+msgstr "Arco"
+
+#: core/fx_sparks.py
+msgid "Magnesium"
+msgstr "Magnesio"
+
+#: core/fx_sparks.py
+msgid "Ember"
+msgstr "Brace"
+
+#: core/fx_sparks.py
+msgid "Forge"
+msgstr "Forgia"
+
+#: core/fx_sparks.py
+msgid "Sparkler gold"
+msgstr "Oro di stellina"
+
+#: core/fx_warp.py
+msgid "Neon"
+msgstr "Neon"
+
+#: core/fx_warp.py
+msgid "Vaporwave"
+msgstr "Vaporwave"
+
+#: core/fx_warp.py
+msgid "Cyber"
+msgstr "Cyber"
+
+#: core/fx_warp.py
+msgid "Light slit"
+msgstr "Fessura di luce"
+
+#: core/fx_warp.py
+msgid "A subtle slit opens, pulling in faint trails."
+msgstr "Si apre una sottile fessura che attira scie appena visibili."
+
+#: core/fx_warp.py
+msgid "Hyperdrive"
+msgstr "Iperguida"
+
+#: core/fx_warp.py
+msgid "Speed lines accelerate towards the portal."
+msgstr "Linee di velocità accelerano verso il portale."
+
+#: core/fx_warp.py
+msgid "Wormhole"
+msgstr "Wormhole"
+
+#: core/fx_warp.py
+msgid "A dynamic stretching grid of light."
+msgstr "Una griglia di luce dinamica che si deforma."
+
+#. the separator between all but the last two names in a list, "Mac, PC and Laptop".
+#: core/i18n.py core/receiver.py core/settings_sync.py core/ways.py
+msgctxt "list"
+msgid ", "
+msgstr ", "
+
+#. the last two names of a list; {first} may itself be several names.
+#: core/i18n.py
+#, python-brace-format
+msgctxt "list"
+msgid "{first} and {last}"
+msgstr "{first} e {last}"
+
+#: core/link.py win_app/sender.py
+msgid "The other machine"
+msgstr "L'altro computer"
+
+#: core/link.py
+#, python-brace-format
+msgid "Connection failed: {error}"
+msgstr "Connessione non riuscita: {error}"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} closed the connection: it may have removed this machine, or be too busy to answer"
+msgstr "{name} ha chiuso la connessione: potrebbe aver rimosso questo computer, o essere troppo occupato per rispondere"
+
+#: core/link.py
+msgid "This pairing was removed"
+msgstr "Questo abbinamento è stato rimosso"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} is unreachable from this machine. Check that both can communicate on the local network."
+msgstr "{name} non è raggiungibile da questo computer. Controlla che entrambi possano comunicare sulla rete locale."
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} is reachable, but Beamer is not listening on this port."
+msgstr "{name} è raggiungibile, ma Beamer non è in ascolto su questa porta."
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer before the connection timed out."
+msgstr "{name} non ha risposto prima che la connessione scadesse."
+
+#: core/link.py
+#, python-brace-format
+msgid "Connecting to {host}:{port}"
+msgstr "Connessione a {host}:{port}"
+
+#: core/link.py
+msgid "This link was stopped"
+msgstr "Questo collegamento è stato interrotto"
+
+#: core/link.py
+#, python-brace-format
+msgid "Update Beamer on {name} to 1.5.0; if it is up to date, pair the two again"
+msgstr "Aggiorna Beamer su {name} alla 1.5.0; se è già aggiornato, abbina di nuovo i due computer"
+
+#: core/link.py
+#, python-brace-format
+msgid "Connected to {name} via the secure macOS 27 fallback"
+msgstr "Connesso a {name} tramite la modalità alternativa sicura di macOS 27"
+
+#: core/link.py
+#, python-brace-format
+msgid "Connected to {name}"
+msgstr "Connesso a {name}"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} closed the connection"
+msgstr "{name} ha chiuso la connessione"
+
+#: core/link.py
+msgid "Sending to this machine was switched off"
+msgstr "L'invio a questo computer è stato disattivato"
+
+#: core/link.py
+#, python-brace-format
+msgid "A different Beamer answered at {host}"
+msgstr "Un altro Beamer ha risposto a {host}"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} stopped acknowledging input"
+msgstr "{name} ha smesso di confermare l'input"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} stopped accepting data"
+msgstr "{name} ha smesso di accettare dati"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer as a Beamer: it is probably running one from before version 4"
+msgstr "{name} non ha risposto come Beamer: probabilmente usa una versione precedente alla 4"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} could not be authenticated: something on the path altered the link"
+msgstr "Impossibile autenticare {name}: qualcosa lungo il percorso ha alterato il collegamento"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer like Beamer: {error}"
+msgstr "{name} non ha risposto come Beamer: {error}"
+
+#: core/link.py core/receiver.py
+#, python-brace-format
+msgid "{name} runs a newer Beamer: update Beamer on this machine"
+msgstr "{name} usa un Beamer più recente: aggiorna Beamer su questo computer"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} could not read what this machine sent first; Beamer on the two machines may differ"
+msgstr "{name} non è riuscito a leggere il primo messaggio di questo computer; le versioni di Beamer sui due computer potrebbero essere diverse"
+
+#: core/link.py
+#, python-brace-format
+msgid "Could not save what {name} told this machine"
+msgstr "Impossibile salvare ciò che {name} ha comunicato a questo computer"
+
+#: core/link.py
+#, python-brace-format
+msgid "The link to {name} failed: {error}"
+msgstr "Il collegamento con {name} non è riuscito: {error}"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} took too long to send one message"
+msgstr "{name} ha impiegato troppo tempo a inviare un messaggio"
+
+#: core/link.py
+msgid "The link failed"
+msgstr "Il collegamento non è riuscito"
+
+#: core/link.py
+msgid "macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command."
+msgstr "macOS 27 ha bloccato l'accesso diretto alla rete locale. Apri /Applications/Beamer Tunnel.command."
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} stopped responding"
+msgstr "{name} ha smesso di rispondere"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} did not answer as a Beamer"
+msgstr "{name} non ha risposto come Beamer"
+
+#: core/link.py core/receiver.py
+#, python-brace-format
+msgid "Update Beamer on {name}: it is older than this one"
+msgstr "Aggiorna Beamer su {name}: è più vecchio di questo"
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} has this pairing under another machine: use Re-pair on Overview."
+msgstr "{name} ha questo abbinamento sotto un altro computer: usa Riabbina in Panoramica."
+
+#: core/link.py
+#, python-brace-format
+msgid "{name} no longer has this pairing: use Re-pair on Overview"
+msgstr "{name} non ha più questo abbinamento: usa Riabbina in Panoramica"
+
+#: core/peerlist.py
+msgid "This pairing needs to be set up again."
+msgstr "Questo abbinamento va configurato di nuovo."
+
+#: core/peerlist.py
+msgid "Pairing finished, but Beamer could not save it on this machine. Try again in a moment."
+msgstr "Abbinamento completato, ma Beamer non è riuscito a salvarlo su questo computer. Riprova tra un momento."
+
+#: core/peerlist.py
+msgid "Another pairing is still finishing. Try again in a moment."
+msgstr "Un altro abbinamento è ancora in corso. Riprova tra un momento."
+
+#: core/peerlist.py
+msgid "A wrong code was tried, so this code was cancelled. Show a new one to try again."
+msgstr "È stato provato un codice errato, quindi questo codice è stato annullato. Mostrane uno nuovo per riprovare."
+
+#: core/peerlist.py
+msgid "A machine on an older Beamer tried to pair. Update Beamer on it to 1.5.0, then show a new code."
+msgstr "Un computer con una versione precedente di Beamer ha provato ad abbinarsi. Aggiorna Beamer su quel computer alla 1.5.0, poi mostra un nuovo codice."
+
+#: core/peerlist.py
+msgid "The code expired. Show a new one."
+msgstr "Il codice è scaduto. Mostrane uno nuovo."
+
+#: core/peerlist.py
+msgid "That machine may already be paired here, or the code was wrong. Show a new code to try again."
+msgstr "Quel computer potrebbe essere già abbinato qui, oppure il codice era errato. Mostra un nuovo codice per riprovare."
+
+#: core/peerlist.py
+msgid "Beamer could not save the pairing on this machine, so it did not complete. Show a new code to try again."
+msgstr "Beamer non è riuscito a salvare l'abbinamento su questo computer, quindi non è stato completato. Mostra un nuovo codice per riprovare."
+
+#: core/peerlist.py
+msgid "That is this machine, not another one."
+msgstr "Quello è questo stesso computer, non un altro."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Pairing failed: {reason}."
+msgstr "Abbinamento non riuscito: {reason}."
+
+#: core/peerlist.py
+msgid "That machine gave this machine's own identity, so nothing was paired. Show a new code to try again."
+msgstr "Quel computer ha fornito l'identità di questo computer, quindi non è stato abbinato nulla. Mostra un nuovo codice per riprovare."
+
+#: core/peerlist.py
+msgid "The saved pairing now identifies a different machine."
+msgstr "L'abbinamento salvato ora identifica un altro computer."
+
+#: core/peerlist.py
+msgid "The other machine no longer has this pairing."
+msgstr "L'altro computer non ha più questo abbinamento."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired with this machine. Remove it from the list first to pair again."
+msgstr "{name} è già abbinato a questo computer. Rimuovilo prima dall'elenco per abbinarlo di nuovo."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is not showing a code. Show one in Beamer on it, then try again."
+msgstr "{name} non sta mostrando un codice. Mostrane uno in Beamer su quel computer, poi riprova."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "That code was not accepted, and {name} has cancelled it. Show a new one there to try again."
+msgstr "Quel codice non è stato accettato e {name} lo ha annullato. Mostrane uno nuovo lì per riprovare."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} runs an older Beamer. Update Beamer on it to 1.5.0, then pair again."
+msgstr "{name} usa una versione precedente di Beamer. Aggiornalo alla 1.5.0, poi abbinalo di nuovo."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} did not answer. Check both machines are on the same network, then try again."
+msgstr "{name} non ha risposto. Controlla che i due computer siano sulla stessa rete, poi riprova."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Either this machine or {name} already has {n} machines paired, the most Beamer keeps. Remove one, then try again."
+msgstr "Questo computer o {name} ha già {n} computer abbinati, il massimo che Beamer gestisce. Rimuovine uno, poi riprova."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} already has this machine paired. Remove this machine from its list there, then pair again."
+msgstr "{name} ha già abbinato questo computer. Rimuovi questo computer dal suo elenco lì, poi abbinalo di nuovo."
+
+#: core/peerlist.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Paired with {name}."
+msgstr "Abbinato a {name}."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired here. Remove it from the list first to pair again."
+msgstr "{name} è già abbinato qui. Rimuovilo prima dall'elenco per abbinarlo di nuovo."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "This machine already has {n} machines paired, the most Beamer keeps. Remove one, then show a new code."
+msgstr "Questo computer ha già {n} computer abbinati, il massimo che Beamer gestisce. Rimuovine uno, poi mostra un nuovo codice."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired with this machine, since {when}. Remove it from the list first to pair again."
+msgstr "{name} è già abbinato a questo computer dal giorno {when}. Rimuovilo prima dall'elenco per abbinarlo di nuovo."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: it is being driven from {other}."
+msgstr "Impossibile passare a {name}: è controllato da {other}."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: another machine is driving it."
+msgstr "Impossibile passare a {name}: lo sta controllando un altro computer."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: it is driving {other}."
+msgstr "Impossibile passare a {name}: sta controllando {other}."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "Can't cross to {name}: it is driving another machine."
+msgstr "Impossibile passare a {name}: sta controllando un altro computer."
+
+#: core/peerlist.py
+#, python-brace-format
+msgid "{name} is already paired here, since {when}. Remove it from the list first to pair again."
+msgstr "{name} è già abbinato qui dal giorno {when}. Rimuovilo prima dall'elenco per abbinarlo di nuovo."
+
+#: core/profiles.py
+msgid "Uses the desk's ways"
+msgstr "Usa le vie della scrivania"
+
+#. on a map tile, a machine running a Beamer too old to share ways. Keep it short.
+#: core/profiles.py
+msgid "Older"
+msgstr "Datato"
+
+#: core/profiles.py mac_app/diagram.py
+msgid "Offline"
+msgstr "Non in linea"
+
+#: core/profiles.py mac_app/diagram.py win_app/diagram.py
+msgid "Own"
+msgstr "Personale"
+
+#: core/profiles.py mac_app/diagram.py win_app/diagram.py win_app/kvm_bridge_win.py
+msgid "Desk"
+msgstr "Scrivania"
+
+#: core/profiles.py
+msgid "An older Beamer. Its ways are set on it; update it to set them here. Read only"
+msgstr "Una versione precedente di Beamer. Le sue vie si impostano lì; aggiornala per impostarle da qui. Sola lettura"
+
+#: core/profiles.py
+msgid "Offline. It takes these when it next connects"
+msgstr "Non in linea. Le riceverà alla prossima connessione"
+
+#: core/profiles.py
+msgid "Sending…"
+msgstr "Invio…"
+
+#: core/profiles.py
+msgid "Keeps its own ways. The desk's are saved for when it uses them"
+msgstr "Mantiene le proprie vie. Quelle della scrivania restano salvate per quando le userà"
+
+#: core/profiles.py win_app/kvm_bridge_win.py
+msgid "This machine"
+msgstr "Questo computer"
+
+#: core/profiles.py
+#, python-brace-format
+msgid "Last heard {time}"
+msgstr "Ultimo contatto {time}"
+
+#: core/profiles.py
+#, python-brace-format
+msgid "Needs pairing with {name}"
+msgstr "Va abbinato a {name}"
+
+#: core/profiles.py
+#, python-brace-format
+msgid "{name} is off on that machine"
+msgstr "{name} è disattivato su quel computer"
+
+#: core/profiles.py
+#, python-brace-format
+msgid "{name} · {date}"
+msgstr "{name} · {date}"
+
+#: core/receiver.py
+msgid "Listening stopped"
+msgstr "Ascolto interrotto"
+
+#: core/receiver.py
+msgid "Unlocking Windows…"
+msgstr "Sblocco di Windows…"
+
+#: core/receiver.py
+msgid "Windows is locked — unlock it at the PC"
+msgstr "Windows è bloccato: sbloccalo dal PC"
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Starting on port {port}"
+msgstr "Avvio sulla porta {port}"
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Input error from {name}; see log"
+msgstr "Errore di input da {name}; vedi il registro"
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Connected to {names}"
+msgstr "Connesso a {names}"
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Waiting on port {port}"
+msgstr "In attesa sulla porta {port}"
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Listener failed: {error}"
+msgstr "Ascolto non riuscito: {error}"
+
+#: core/receiver.py
+#, python-brace-format
+msgid "Another program is using port {port} — change the port on the Connection page"
+msgstr "Un altro programma usa la porta {port}: cambia la porta nella pagina Connessione"
+
+#: core/settings_sync.py
+msgid "Design not available yet: connect to this machine with Beamer 1.5.0 beta.6 or later."
+msgstr "Aspetto non ancora disponibile: collegati a questo computer con Beamer 1.5.0 beta.6 o successivo."
+
+#: core/settings_sync.py
+msgid "Needs beta.6 or later"
+msgstr "Serve la beta.6 o successiva"
+
+#: core/settings_sync.py
+msgid "A connected machine is unavailable until it has beta.6 or later."
+msgstr "Un computer connesso non è disponibile finché non ha la beta.6 o successiva."
+
+#: core/settings_sync.py
+msgid "No paired machine is connected."
+msgstr "Nessun computer abbinato è connesso."
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Crossing"
+msgstr "Passaggio"
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Design"
+msgstr "Aspetto"
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shortcut"
+msgstr "Scorciatoia"
+
+#: core/settings_sync.py mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Names"
+msgstr "Nomi"
+
+#: core/settings_sync.py mac_app/diagram.py mac_app/kvm_bridge_app.py win_app/diagram.py win_app/kvm_bridge_win.py
+msgid "Resistance"
+msgstr "Resistenza"
+
+#: core/settings_sync.py
+msgid "drag protection"
+msgstr "protezione durante il trascinamento"
+
+#: core/settings_sync.py
+msgid "Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine."
+msgstr "I computer connessi con versioni compatibili di Beamer si aggiornano subito; gli altri si allineano quando si riconnettono. Zone, lati, tasti di salto, blocco a schermo intero, attivazione dell'animazione e aspetto della finestra restano su ciascun computer."
+
+#: core/settings_sync.py
+msgid "Off: each machine keeps its current values."
+msgstr "Disattivato: ogni computer mantiene i valori attuali."
+
+#: core/settings_sync.py
+msgid "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local."
+msgstr "Stile, colore, durata, dimensione e animazione di arrivo restano allineati. L'attivazione dell'animazione e l'aspetto della finestra restano locali."
+
+#: core/settings_sync.py
+msgid "Off: each machine keeps its current values; previous separate values are not restored."
+msgstr "Disattivato: ogni computer mantiene i valori attuali; i valori separati precedenti non vengono ripristinati."
+
+#: core/settings_sync.py
+msgid "compatible paired machines"
+msgstr "i computer abbinati compatibili"
+
+#: core/settings_sync.py
+msgid "Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine. Notch and trackpad controls stay on this Mac."
+msgstr "I computer connessi con versioni compatibili di Beamer si aggiornano subito; gli altri si allineano quando si riconnettono. Zone, lati, tasti di salto, blocco a schermo intero, attivazione dell'animazione e aspetto della finestra restano su ciascun computer. I controlli del notch e del trackpad restano su questo Mac."
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "Following {name}'s design"
+msgstr "Segue l'aspetto di {name}"
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "Shares {groups} with compatible paired machines."
+msgstr "Condivide {groups} con i computer abbinati compatibili."
+
+#: core/settings_sync.py
+msgid "Resistance, drag protection and Shortcut stay in step. Ways and jump keys below are local; each side is shared with its paired machine."
+msgstr "Resistenza, protezione durante il trascinamento e Scorciatoia restano allineate. Le vie e i tasti di salto qui sotto sono locali; ogni lato è condiviso con il computer abbinato."
+
+#: core/settings_sync.py
+msgid "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local. Notch and trackpad controls stay local."
+msgstr "Stile, colore, durata, dimensione e animazione di arrivo restano allineati. L'attivazione dell'animazione e l'aspetto della finestra restano locali. I controlli del notch e del trackpad restano locali."
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "Shares resistance, drag protection, Shortcut and six animation settings with {machines}."
+msgstr "Condivide resistenza, protezione durante il trascinamento, Scorciatoia e sei impostazioni dell'animazione con {machines}."
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "{name}'s Beamer is too old to keep settings in step. Update it to turn this on."
+msgstr "Il Beamer di {name} è troppo vecchio per tenere le impostazioni allineate. Aggiornalo per attivare questa opzione."
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "compatible versions of {name}"
+msgstr "le versioni compatibili di {name}"
+
+#: core/settings_sync.py
+#, python-brace-format
+msgid "{shared} stay in step. Ways and jump keys below are local; each side is shared with its paired machine."
+msgstr "Restano allineati: {shared}. Le vie e i tasti di salto qui sotto sono locali; ogni lato è condiviso con il computer abbinato."
+
+#: core/ways.py win_app/diagram.py
+msgid "left"
+msgstr "sinistro"
+
+#: core/ways.py win_app/diagram.py
+msgid "right"
+msgstr "destro"
+
+#: core/ways.py win_app/diagram.py
+msgid "top"
+msgstr "superiore"
+
+#: core/ways.py win_app/diagram.py
+msgid "bottom"
+msgstr "inferiore"
+
+#: core/ways.py
+msgid "this PC"
+msgstr "questo PC"
+
+#: core/ways.py
+msgid "this Mac"
+msgstr "questo Mac"
+
+#: core/ways.py
+msgid "this computer"
+msgstr "questo computer"
+
+#: core/ways.py mac_app/diagram.py
+msgid "middle"
+msgstr "centrale"
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Top left"
+msgstr "in alto a sinistra"
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Top right"
+msgstr "in alto a destra"
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Bottom left"
+msgstr "in basso a sinistra"
+
+#: core/ways.py mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Bottom right"
+msgstr "in basso a destra"
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "top left"
+msgstr "in alto a sinistra"
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "top right"
+msgstr "in alto a destra"
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "bottom left"
+msgstr "in basso a sinistra"
+
+#: core/ways.py mac_app/kvm_bridge_app.py
+msgid "bottom right"
+msgstr "in basso a destra"
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py
+msgid "Top"
+msgstr "Superiore"
+
+#: core/ways.py mac_app/ledger.py
+msgid "Middle"
+msgstr "Centrale"
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py
+msgid "Bottom"
+msgstr "Inferiore"
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py win_app/pages_win.py
+msgid "Left"
+msgstr "Sinistro"
+
+#: core/ways.py mac_app/ledger.py mac_app/pages.py win_app/crossing_ledger.py win_app/pages_win.py
+msgid "Right"
+msgstr "Destro"
+
+#: core/ways.py
+#, python-brace-format
+msgid "Set on {first} or {second}."
+msgstr "Impostato su {first} o {second}."
+
+#: core/ways.py
+#, python-brace-format
+msgid "Crosses between {first} and {second}."
+msgstr "Passa tra {first} e {second}."
+
+#: core/ways.py
+#, python-brace-format
+msgid "No edge leads to {name}. The shortcut and the menu still reach it."
+msgstr "Nessun bordo porta a {name}. La scorciatoia e il menu lo raggiungono comunque."
+
+#: core/ways.py
+#, python-brace-format
+msgid "Edge to {name} is off. Tick Edge to turn it back on."
+msgstr "Il bordo verso {name} è disattivato. Seleziona Bordo per riattivarlo."
+
+#: core/ways.py
+#, python-brace-format
+msgid "None of the thirds picked for {name} touch its tile. Click a third along its edge."
+msgstr "Nessuno dei terzi scelti per {name} tocca il suo riquadro. Fai clic su un terzo lungo il suo bordo."
+
+#: core/ways.py
+#, python-brace-format
+msgid "{first} overlaps {second}. Drag them apart."
+msgstr "{first} si sovrappone a {second}. Trascinali per separarli."
+
+#: core/ways.py
+msgid "Whole edge or the thirds you pick"
+msgstr "Bordo intero o i terzi che scegli"
+
+#: core/ways.py
+msgid "Whole edge"
+msgstr "Bordo intero"
+
+#: core/ways.py
+#, python-brace-format
+msgid "the {parts} of the {edge} edge"
+msgstr "il tratto {parts} del bordo {edge}"
+
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {last} thirds"
+msgstr "Terzi {first} e {last}"
+
+#: core/ways.py
+msgid "a phone cannot be a jump target"
+msgstr "un telefono non può essere una destinazione di salto"
+
+#: core/ways.py
+msgid "choose a modifier and one non-modifier key"
+msgstr "scegli un modificatore e un tasto che non sia un modificatore"
+
+#: core/ways.py
+msgid "that key is the trigger shortcut's: pick a chord without it"
+msgstr "quel tasto fa parte della scorciatoia di attivazione: scegli una combinazione senza di esso"
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {second} would both lead from {where} of {here}. Move one of them to another side, or give each its own thirds of the edge."
+msgstr "{first} e {second} passerebbero entrambi per {where} di {here}. Sposta uno dei due su un altro lato, o assegna a ciascuno i propri terzi del bordo."
+
+#. {here} is this PC or Mac; {side} is the side of its screen.
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has no way in: {other} already leads from the {side} edge of {here}. Give each its own thirds of that edge by moving the machines on the map, or move one to another side."
+msgstr "{name} non ha una via d'ingresso: {other} parte già dal bordo {side} di {here}. Assegna a ciascuno i propri terzi di quel bordo spostando i computer sulla mappa, o sposta uno dei due su un altro lato."
+
+#: core/ways.py mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "another machine"
+msgstr "un altro computer"
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has no way back to this machine: none of its edges leads here. Its own Crossing page says why."
+msgstr "{name} non ha una via di ritorno verso questo computer: nessuno dei suoi bordi porta qui. La sua pagina Passaggio spiega perché."
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} no longer has this pairing, so it has no way in. Remove {name} here and pair the two again."
+msgstr "{name} non ha più questo abbinamento, quindi non ha una via d'ingresso. Rimuovi {name} qui e abbina di nuovo i due computer."
+
+#: core/ways.py
+#, python-brace-format
+msgctxt "ways alternatives"
+msgid "{head} or {last}"
+msgstr "{head} o {last}"
+
+#. {drivers} is a list of machine names; {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "While {drivers} drives {here}, this way to {target} does nothing: none of them is paired with {target}. Pair them to use it from there too."
+msgstr "Mentre {drivers} controlla {here}, questa via verso {target} non fa nulla: nessuno di essi è abbinato a {target}. Abbinali per usarla anche da lì."
+
+#: core/ways.py
+#, python-brace-format
+msgid "Place it beside {here} on the map"
+msgstr "Posizionalo accanto a {here} sulla mappa"
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} third"
+msgstr "Terzo {name}"
+
+#: core/ways.py
+msgid "that key is already assigned to another machine"
+msgstr "quel tasto è già assegnato a un altro computer"
+
+#: core/ways.py
+#, python-brace-format
+msgid "the {edge} edge of display {display}"
+msgstr "il bordo {edge} dello schermo {display}"
+
+#: core/ways.py mac_app/kvm_bridge_app.py mac_app/pages.py
+msgid "the notch"
+msgstr "il notch"
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "Two of the ways to {name} cover {where} of {here}. Keep one of them."
+msgstr "Due delle vie verso {name} coprono {where} di {here}. Tienine una."
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {second} would both lead from {where} of {here}. Turn the notch off for one of them."
+msgstr "{first} e {second} passerebbero entrambi per {where} di {here}. Disattiva il notch per uno dei due."
+
+#. {where} names the screen region and {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{first} and {second} would both lead from {where} of {here}. Choose another corner for one of them."
+msgstr "{first} e {second} passerebbero entrambi per {where} di {here}. Scegli un altro angolo per uno dei due."
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has {other} too, so none of its edges leads back here. On {name}'s Crossing page, share that side by thirds or move one of them."
+msgstr "{name} ha anche {other}, quindi nessuno dei suoi bordi porta qui. Nella pagina Passaggio di {name}, condividi quel lato a terzi o sposta uno dei due."
+
+#. {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "{name} no longer has this pairing. If another machine takes its side, {here} gives it up. Remove {name} here and pair the two again."
+msgstr "{name} non ha più questo abbinamento. Se un altro computer occupa il suo lato, {here} lo cede. Rimuovi {name} qui e abbina di nuovo i due computer."
+
+#. {here} is this PC or Mac; {name} and {target} are machine names.
+#: core/ways.py
+#, python-brace-format
+msgid "While {name} drives {here}, this way to {target} does nothing: {name} is not paired with {target}. Pair them to use it from there too."
+msgstr "Mentre {name} controlla {here}, questa via verso {target} non fa nulla: {name} non è abbinato a {target}. Abbinali per usarla anche da lì."
+
+#: core/ways.py
+#, python-brace-format
+msgctxt "ways alternatives"
+msgid "{first} or {last}"
+msgstr "{first} o {last}"
+
+#. {drivers} is a list of machine names; {here} is this PC or Mac.
+#: core/ways.py
+#, python-brace-format
+msgid "While {drivers} drives {here}, this way to {target} does nothing: neither is paired with {target}. Pair them to use it from there too."
+msgstr "Mentre {drivers} controlla {here}, questa via verso {target} non fa nulla: nessuno dei due è abbinato a {target}. Abbinali per usarla anche da lì."
+
+#: core/ways.py
+#, python-brace-format
+msgid "the {corner} corner of display {display}"
+msgstr "l'angolo {corner} dello schermo {display}"
+
+#: core/ways.py
+#, python-brace-format
+msgid "{name} has {other} on its {facing} too, so none of its edges leads back here. On {name}'s Crossing page, share that side by thirds or move one of them."
+msgstr "{name} ha anche {other} sul suo lato {facing}, quindi nessuno dei suoi bordi porta qui. Nella pagina Passaggio di {name}, condividi quel lato a terzi o sposta uno dei due."
+
+#: core/ways.py
+#, python-brace-format
+msgid "That shortcut clashes with the jump key {key}; the jump key has been kept."
+msgstr "Quella scorciatoia coincide con il tasto di salto {key}; è stato mantenuto il tasto di salto."
+
+#: core/ways.py mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "the {corner} corner"
+msgstr "l'angolo {corner}"
+
+#: core/ways.py win_app/pages_win.py
+#, python-brace-format
+msgid "the {edge} edge"
+msgstr "il bordo {edge}"
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} does not accept input from this Mac"
+msgstr "{name} non accetta input da questo Mac"
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} could not read the request to take it"
+msgstr "{name} non è riuscito a leggere la richiesta di controllo"
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} refused the input"
+msgstr "{name} ha rifiutato l'input"
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "{name} did not answer"
+msgstr "{name} non ha risposto"
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "Lost the link to {name}"
+msgstr "Collegamento con {name} perso"
+
+#: mac_app/bridge.py
+msgid "Waiting to connect"
+msgstr "In attesa di connessione"
+
+#: mac_app/bridge.py
+msgid "Settings saved; reconnecting"
+msgstr "Impostazioni salvate; riconnessione"
+
+#: mac_app/bridge.py mac_app/kvm_bridge_app.py mac_app/link_state.py mac_app/wake.py win_app/pages_win.py
+msgid "the other machine"
+msgstr "l'altro computer"
+
+#: mac_app/bridge.py win_app/kvm_bridge_win.py
+msgid "Beamer"
+msgstr "Beamer"
+
+#: mac_app/bridge.py
+msgid "Input returned to this Mac"
+msgstr "L'input è tornato a questo Mac"
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "Skipped {name}: not connected."
+msgstr "{name} saltato: non connesso."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/bridge.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Shook home from {name}. Turn this off in Crossing → Way home."
+msgstr "Tornato da {name} scuotendo il puntatore. Disattivalo in Passaggio → Via di casa."
+
+#: mac_app/bridge.py win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {status}"
+msgstr "Impossibile passare: {status}"
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{machine} took over {name}"
+msgstr "{machine} ha preso il controllo di {name}"
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "Another machine took over {name}"
+msgstr "Un altro computer ha preso il controllo di {name}"
+
+#: mac_app/bridge.py
+#, python-brace-format
+msgid "{name} could not be reached"
+msgstr "Impossibile raggiungere {name}"
+
+#: mac_app/diagram.py
+msgid "right of"
+msgstr "a destra di"
+
+#: mac_app/diagram.py
+msgid "left of"
+msgstr "a sinistra di"
+
+#: mac_app/diagram.py mac_app/pages.py
+msgid "below"
+msgstr "sotto"
+
+#: mac_app/diagram.py mac_app/pages.py
+msgid "above"
+msgstr "sopra"
+
+#: mac_app/diagram.py
+msgid "start"
+msgstr "iniziale"
+
+#: mac_app/diagram.py
+msgid "end"
+msgstr "finale"
+
+#: mac_app/diagram.py win_app/kvm_bridge_win.py
+msgid "Crosses"
+msgstr "Passa"
+
+#: mac_app/diagram.py
+msgid "Overlaps"
+msgstr "Si sovrappone"
+
+#: mac_app/diagram.py
+msgid "Drag to connect"
+msgstr "Trascina per collegare"
+
+#: mac_app/diagram.py
+msgid "Edge off"
+msgstr "Bordo disattivato"
+
+#: mac_app/diagram.py mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/diagram.py win_app/machines_win.py
+msgid "In the shortcut's cycle"
+msgstr "Nel ciclo della scorciatoia"
+
+#: mac_app/diagram.py win_app/crossing_ledger.py win_app/diagram.py win_app/sender.py
+msgid "Other machine"
+msgstr "Altro computer"
+
+#: mac_app/diagram.py mac_app/kvm_bridge_app.py mac_app/machines_panel.py
+msgid "This Mac"
+msgstr "Questo Mac"
+
+#: mac_app/diagram.py mac_app/machines_panel.py
+msgid "Selected"
+msgstr "Selezionato"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/diagram.py
+msgid "Drag a corner to resize, or use Option and the arrow keys."
+msgstr "Trascina un angolo per ridimensionare, oppure usa Opzione e i tasti freccia."
+
+#: mac_app/diagram.py
+msgid "Whole desk layout"
+msgstr "Disposizione completa della scrivania"
+
+#: mac_app/diagram.py
+msgid "No machines paired."
+msgstr "Nessun computer abbinato."
+
+#. {third} is one of the three sections along an edge.
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, {side} This Mac, {third} third. {outcome}."
+msgstr "{name}, {side} questo Mac, terzo {third}. {outcome}."
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, {side} This Mac. {outcome}."
+msgstr "{name}, {side} questo Mac. {outcome}."
+
+#. third names are one of the three sections of a screen edge.
+#: mac_app/diagram.py
+msgid "click to turn it off"
+msgstr "fai clic per disattivarlo"
+
+#. third names are one of the three sections of a screen edge.
+#: mac_app/diagram.py
+msgid "click to turn it on"
+msgstr "fai clic per attivarlo"
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "Current pressure {pressure} of {value} pointer units at the {edge} edge."
+msgstr "Pressione attuale {pressure} su {value} unità del puntatore sul bordo {edge}."
+
+#: mac_app/diagram.py
+msgid "machine"
+msgstr "computer"
+
+#: mac_app/diagram.py
+msgid "Not in use"
+msgstr "Non in uso"
+
+#: mac_app/diagram.py win_app/diagram.py
+msgid "Recentre"
+msgstr "Ricentra"
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} third: {detail}"
+msgstr "Terzo {name}: {detail}"
+
+#: mac_app/diagram.py
+msgid "Rename this Mac on Overview."
+msgstr "Rinomina questo Mac in Panoramica."
+
+#: mac_app/diagram.py win_app/diagram.py
+#, python-brace-format
+msgid "Recentre {name}"
+msgstr "Ricentra {name}"
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "Machine · {id}"
+msgstr "Computer · {id}"
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, In the shortcut's cycle"
+msgstr "{name}, nel ciclo della scorciatoia"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}, {status}"
+msgstr "{name}, {status}"
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} is in the shortcut's cycle."
+msgstr "{name} è nel ciclo della scorciatoia."
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} is out of the shortcut's cycle."
+msgstr "{name} è fuori dal ciclo della scorciatoia."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/diagram.py win_app/diagram.py
+#, python-brace-format
+msgid "{name} resized."
+msgstr "{name} ridimensionato."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/diagram.py
+msgid "Set elsewhere"
+msgstr "Impostato altrove"
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "No push. Current pressure is 0 of {value} pointer units."
+msgstr "Nessuna spinta. La pressione attuale è 0 su {value} unità del puntatore."
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name} · macOS"
+msgstr "{name} · macOS"
+
+#: mac_app/diagram.py mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{platform} · {status}"
+msgstr "{platform} · {status}"
+
+#: mac_app/diagram.py mac_app/ledger.py
+#, python-brace-format
+msgid "Beamer {version} · only sees which side"
+msgstr "Beamer {version} · vede solo il lato"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{name}: drag a corner to resize, or use Option and the arrow keys."
+msgstr "{name}: trascina un angolo per ridimensionare, oppure usa Opzione e i tasti freccia."
+
+#: mac_app/diagram.py win_app/crossing_ledger.py
+msgid "Computer"
+msgstr "Computer"
+
+#: mac_app/diagram.py mac_app/ledger.py mac_app/link_state.py mac_app/machines.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Linked"
+msgstr "Collegato"
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{label}, {outcome}."
+msgstr "{label}, {outcome}."
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{label}, {name}, this Mac."
+msgstr "{label}, {name}, questo Mac."
+
+#: mac_app/diagram.py
+#, python-brace-format
+msgid "{label}, this Mac."
+msgstr "{label}, questo Mac."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input on this Mac"
+msgstr "Input su questo Mac"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input held on this Mac; crossing is off"
+msgstr "Input bloccato su questo Mac; il passaggio è disattivato"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input on another machine"
+msgstr "Input su un altro computer"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "About Beamer"
+msgstr "Informazioni su Beamer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hide Beamer"
+msgstr "Nascondi Beamer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hide Others"
+msgstr "Nascondi altre"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Quit Beamer"
+msgstr "Esci da Beamer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Edit"
+msgstr "Modifica"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Undo"
+msgstr "Annulla"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Redo"
+msgstr "Ripeti"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Cut"
+msgstr "Taglia"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Copy"
+msgstr "Copia"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Paste"
+msgstr "Incolla"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Select All"
+msgstr "Seleziona tutto"
+
+#: mac_app/kvm_bridge_app.py
+msgid "View"
+msgstr "Vista"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Window"
+msgstr "Finestra"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Close"
+msgstr "Chiudi"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Minimise"
+msgstr "Contrai"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Shortcut: {style} {key} ·"
+msgstr "Scorciatoia: {style} {key} ·"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Idle"
+msgstr "Inattivo"
+
+#: mac_app/kvm_bridge_app.py mac_app/machines.py mac_app/machines_panel.py mac_app/widgets.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Mac"
+msgstr "Mac"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Everything"
+msgstr "Tutto"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shares every group and can replace local values on this machine."
+msgstr "Condivide ogni gruppo e può sostituire i valori locali su questo computer."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Older Beamer versions share known Crossing and Design settings without group choices."
+msgstr "Le versioni precedenti di Beamer condividono le impostazioni note di Passaggio e Aspetto senza scegliere i gruppi."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Revert"
+msgstr "Ripristina"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Start Beamer when you log in"
+msgstr "Apri Beamer al login"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Open Login Items settings"
+msgstr "Apri le impostazioni Elementi login"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Show in Dock"
+msgstr "Mostra nel Dock"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Show in menu bar"
+msgstr "Mostra nella barra dei menu"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Check for updates"
+msgstr "Controlla aggiornamenti"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Download"
+msgstr "Scarica"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Reverse other machines' scrolling"
+msgstr "Inverti lo scorrimento degli altri computer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Delay"
+msgstr "Ritardo"
+
+#: mac_app/kvm_bridge_app.py mac_app/ledger.py win_app/crossing_ledger.py win_app/kvm_bridge_win.py
+msgid "Machine"
+msgstr "Computer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Send input"
+msgstr "Invia input"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Pause crossing"
+msgstr "Sospendi il passaggio"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hold this Mac's edges while an app on it is full screen"
+msgstr "Blocca i bordi di questo Mac mentre un'app è a schermo intero"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This screen decides, including when another machine drives it. On, a full-screen app here holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer can go home or onward through the configured ways."
+msgstr "Decide questo schermo, anche quando lo controlla un altro computer. Se attivo, un'app a schermo intero qui blocca il passaggio del puntatore; scorciatoie e tasti di salto funzionano comunque. Se disattivo, il puntatore di un altro computer può tornare a casa o proseguire attraverso le vie configurate."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This screen's setting applies to every pointer on it."
+msgstr "L'impostazione di questo schermo vale per ogni puntatore che vi si trova."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hide the pointer on the machine not in use"
+msgstr "Nascondi il puntatore sul computer non in uso"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same ways on every machine"
+msgstr "Stesse vie su tutti i computer"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Set every machine's ways from this screen. Turning it on changes nothing until you do; each machine's own ways are kept."
+msgstr "Imposta le vie di tutti i computer da questa schermata. Attivarlo non cambia nulla finché non le modifichi; ciascun computer conserva le proprie vie."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"
+msgstr "Opzione-clic su uno schermo per dividerlo o raggrupparlo · trascina per spostare · fai clic su un terzo di un bordo illuminato per escluderlo · trascina un angolo per ridimensionare"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Switching moves every machine to this profile's places and ways."
+msgstr "Passare a questo profilo applica a tutti i computer le sue posizioni e vie."
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/machines_win.py
+msgid "Machines"
+msgstr "Computer"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Keep this machine's own ways"
+msgstr "Usa le vie di questo computer"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Use the desk's ways"
+msgstr "Usa le vie della scrivania"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Share mine with the desk"
+msgstr "Condividi le mie con la scrivania"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac keeps its own ways"
+msgstr "Questo Mac mantiene le proprie vie"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Don't cross while dragging with this Mac's pointer"
+msgstr "Non passare mentre trascini con il puntatore di questo Mac"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shake to come home"
+msgstr "Scuoti per tornare a casa"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Delete…"
+msgstr "Elimina…"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Profile name"
+msgstr "Nome del profilo"
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Cancel"
+msgstr "Annulla"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Earlier ways ▾"
+msgstr "Vie precedenti ▾"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Earlier ways ▴"
+msgstr "Vie precedenti ▴"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "hold"
+msgstr "tieni premuto"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "double-tap"
+msgstr "doppio tocco"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Time between taps"
+msgstr "Tempo tra i tocchi"
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "With Hold, input goes to the last machine."
+msgstr "Con Tieni premuto, l'input va all'ultimo computer."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Nothing yet. Every key and button goes to the machine that has input."
+msgstr "Ancora nulla. Ogni tasto e pulsante va al computer che ha l'input."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Animate crossings on this Mac"
+msgstr "Anima i passaggi su questo Mac"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Show where the pointer lands"
+msgstr "Mostra dove arriva il puntatore"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hover to preview"
+msgstr "Passa sopra per l'anteprima"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Length"
+msgstr "Durata"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Sets the effect's playback time."
+msgstr "Imposta il tempo di riproduzione dell'effetto."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Size"
+msgstr "Dimensione"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Sets effect depth relative to the shorter screen edge."
+msgstr "Imposta la profondità dell'effetto rispetto al lato più corto dello schermo."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Tick as the push builds"
+msgstr "Vibra mentre la spinta cresce"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Ticks at"
+msgstr "Vibra a"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Try it"
+msgstr "Prova"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Modifier keys"
+msgstr "Tasti modificatori"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hide addresses"
+msgstr "Nascondi indirizzi"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Beamer changes language when it next opens."
+msgstr "Beamer cambierà lingua alla prossima apertura."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Relaunch Beamer"
+msgstr "Riavvia Beamer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "First paired machine's port"
+msgstr "Porta del primo computer abbinato"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Accessibility"
+msgstr "Accessibilità"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Lets Beamer move this Mac's pointer and type on it when another machine drives."
+msgstr "Consente a Beamer di muovere il puntatore di questo Mac e di scrivere quando lo controlla un altro computer."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input Monitoring"
+msgstr "Monitoraggio input"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Lets Beamer read this keyboard and trackpad, to send them to another machine."
+msgstr "Consente a Beamer di leggere questa tastiera e questo trackpad, per inviarli a un altro computer."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Required"
+msgstr "Obbligatorio"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Grant"
+msgstr "Concedi"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Saved. Connecting…"
+msgstr "Salvato. Connessione…"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Current chain: Idle"
+msgstr "Catena attuale: inattiva"
+
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac drives other machines"
+msgstr "Questo Mac controlla gli altri computer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Other machines drive this Mac"
+msgstr "Gli altri computer controllano questo Mac"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Profile"
+msgstr "Profilo"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Configuration reloaded"
+msgstr "Configurazione ricaricata"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Beamer is using the config on disk."
+msgstr "Beamer usa la configurazione salvata sul disco."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Open Beamer's website, kalkmancode.co.uk/beamer"
+msgstr "Apri il sito di Beamer, kalkmancode.co.uk/beamer"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Click a machine on the map to set its ways. The ledger says how it reaches each other machine."
+msgstr "Fai clic su un computer sulla mappa per impostarne le vie. L'elenco indica come raggiunge ogni altro computer."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Off: the trackpad stays still while you push."
+msgstr "Disattivato: il trackpad resta fermo mentre spingi."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Switches the moment this Mac's pointer touches the edge. Each screen supplies its own zones."
+msgstr "Passa nell'istante in cui il puntatore di questo Mac tocca il bordo. Ogni schermo fornisce le proprie zone."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Custom: the key map in settings.json is kept as it is."
+msgstr "Personalizzata: la mappa dei tasti in settings.json resta com'è."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Refused: that position is already occupied."
+msgstr "Rifiutato: quella posizione è già occupata."
+
+#: mac_app/kvm_bridge_app.py mac_app/link_state.py
+msgid "Not paired"
+msgstr "Non abbinato"
+
+#: mac_app/kvm_bridge_app.py mac_app/machines.py win_app/peers_view.py
+msgid "No address"
+msgstr "Nessun indirizzo"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Settings"
+msgstr "Impostazioni"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same on all machines"
+msgstr "Uguale su tutti i computer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "At login"
+msgstr "Al login"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Updates"
+msgstr "Aggiornamenti"
+
+#: mac_app/kvm_bridge_app.py mac_app/widgets.py win_app/kvm_bridge_win.py
+msgid "Match design with"
+msgstr "Segui l'aspetto di"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "None"
+msgstr "Nessuno"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Appearance"
+msgstr "Aspetto della finestra"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Another machine's pointer here"
+msgstr "Il puntatore di un altro computer qui"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Pointer speed"
+msgstr "Velocità del puntatore"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Scrolling"
+msgstr "Scorrimento"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Scroll speed"
+msgstr "Velocità di scorrimento"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Keyboard and pointer"
+msgstr "Tastiera e puntatore"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "New profile…"
+msgstr "Nuovo profilo…"
+
+#: mac_app/kvm_bridge_app.py mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Rename"
+msgstr "Rinomina"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This machine kept the ways set while it ran an older Beamer."
+msgstr "Questo computer ha mantenuto le vie impostate quando usava una versione precedente di Beamer."
+
+#: mac_app/kvm_bridge_app.py
+msgid "● Crosses"
+msgstr "● Passa"
+
+#: mac_app/kvm_bridge_app.py
+msgid "● Offline, ways kept"
+msgstr "● Non in linea, vie mantenute"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "Back to This Mac"
+msgstr "Torna a questo Mac"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "The desk is full. Remove an unused profile before adding more ways."
+msgstr "La scrivania è piena. Rimuovi un profilo inutilizzato prima di aggiungere altre vie."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shake sensitivity"
+msgstr "Sensibilità dello scuotimento"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same → Shortcut"
+msgstr "Uguale su tutti → Scorciatoia"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "Rename profile"
+msgstr "Rinomina profilo"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "New profile"
+msgstr "Nuovo profilo"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Save"
+msgstr "Salva"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "Add"
+msgstr "Aggiungi"
+
+#: mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py
+msgid "Drag a machine on the map to where it sits. The ledger says how each one is reached; click a row to pick it on the map."
+msgstr "Trascina un computer sulla mappa dove si trova. L'elenco indica come si raggiunge ciascuno; fai clic su una riga per selezionarlo sulla mappa."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Click a machine to set its ways · Tab and Return pick one from the keyboard"
+msgstr "Fai clic su un computer per impostarne le vie · Usa Tab e Invio per sceglierne uno dalla tastiera"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "Before Beamer 1.5.5"
+msgstr "Prima di Beamer 1.5.5"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "From an older Beamer"
+msgstr "Da una versione precedente di Beamer"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "When Same ways went off"
+msgstr "Quando Stesse vie è stato disattivato"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "When Same ways went on"
+msgstr "Quando Stesse vie è stato attivato"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "Before you changed it"
+msgstr "Prima della tua modifica"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "Before a restore"
+msgstr "Prima di un ripristino"
+
+#: mac_app/kvm_bridge_app.py
+msgid "With Hold, input goes to the first ready machine in order. Choose which machines join the cycle with the tick boxes on their tiles."
+msgstr "Con Tieni premuto, l'input va al primo computer pronto, in ordine. Scegli quali computer entrano nel ciclo con le caselle sui loro riquadri."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Stays on this Mac"
+msgstr "Resta su questo Mac"
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Remove"
+msgstr "Rimuovi"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "That key is the shortcut; it always stays with Beamer."
+msgstr "Quel tasto è la scorciatoia; resta sempre a Beamer."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "On screen"
+msgstr "Sullo schermo"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Notch style"
+msgstr "Stile del notch"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Style"
+msgstr "Stile"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Style for"
+msgstr "Stile per"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Show at"
+msgstr "Mostra su"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Frame rate"
+msgstr "Frequenza fotogrammi"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Colour"
+msgstr "Colore"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Trackpad"
+msgstr "Trackpad"
+
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/machines_win.py
+msgid "Address"
+msgstr "Indirizzo"
+
+#: mac_app/kvm_bridge_app.py
+msgctxt "list"
+msgid " or "
+msgstr " o "
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Hold {key}, or push through {ways}"
+msgstr "Tieni premuto {key}, oppure spingi attraverso {ways}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Double-tap {key}, or push through {ways}"
+msgstr "Tocca due volte {key}, oppure spingi attraverso {ways}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Saved. Changes apply as you make them."
+msgstr "Salvato. Le modifiche si applicano subito."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Quit Beamer and start it again."
+msgstr "Esci da Beamer e aprilo di nuovo."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Grant both Mac permissions first."
+msgstr "Concedi prima entrambi i permessi del Mac."
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Current chain: {route}"
+msgstr "Catena attuale: {route}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Granted"
+msgstr "Concesso"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Both granted. Relaunch Beamer so macOS passes it the keyboard."
+msgstr "Entrambi concessi. Riavvia Beamer perché macOS gli passi la tastiera."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Resume crossing"
+msgstr "Riprendi il passaggio"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Return input to Mac"
+msgstr "Riporta l'input al Mac"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Not yet learned"
+msgstr "Non ancora rilevato"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Read from the network the first time this Mac connects; nothing to type."
+msgstr "Viene letto dalla rete la prima volta che questo Mac si connette; non c'è nulla da digitare."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Beamer • Local"
+msgstr "Beamer • Locale"
+
+#: mac_app/kvm_bridge_app.py
+msgid " macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr " macOS le riproduce solo mentre un dito è sul trackpad, quindi tieni premuto Prova."
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Once the pointer is through to another machine the notch keeps playing for {seconds} seconds. Outline and Island apply to Glow and Beam; other styles draw their own notch."
+msgstr "Quando il puntatore è passato a un altro computer, il notch continua per {seconds} secondi. Contorno e Isola valgono per Bagliore e Raggio; gli altri stili disegnano un proprio notch."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Input is on another machine for as long as the key is held. If you jump while holding the shortcut, releasing it brings input home."
+msgstr "L'input resta su un altro computer finché tieni premuto il tasto. Se salti mentre tieni premuta la scorciatoia, rilasciandola l'input torna a casa."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Tap twice to switch; tap twice again to come back."
+msgstr "Tocca due volte per passare; tocca di nuovo due volte per tornare."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones."
+msgstr "Segue il mouse o il trackpad di questo Mac su ogni schermo; ogni schermo fornisce le proprie zone."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Crossing shares resistance and drag protection. Design shares effects, colour, length, size and arrival animation. Shortcut shares shortcut on/off, trigger key and style, and destination. Names shares this machine's name and paired-machine labels."
+msgstr "Passaggio condivide resistenza e protezione durante il trascinamento. Aspetto condivide effetti, colore, durata, dimensione e animazione di arrivo. Scorciatoia condivide attivazione della scorciatoia, tasto e modo di attivazione, e destinazione. Nomi condivide il nome di questo computer e le etichette dei computer abbinati."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Ways: set on the Crossing page · {state}"
+msgstr "Vie: si impostano nella pagina Passaggio · {state}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "With the Dock icon off, Beamer stays in the menu bar and appears in the Dock while its window is open. The Dock and the menu bar are never both off: the one still showing cannot be switched off."
+msgstr "Con l'icona del Dock disattivata, Beamer resta nella barra dei menu e appare nel Dock mentre la sua finestra è aperta. Il Dock e la barra dei menu non sono mai disattivati entrambi: quello ancora visibile non può essere disattivato."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."
+msgstr "Chiede a GitHub una volta al giorno se c'è una versione più recente di Beamer. Non viene inviato nulla oltre alla richiesta stessa."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "System"
+msgstr "Sistema"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgctxt "appearance"
+msgid "Light"
+msgstr "Chiaro"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Dark"
+msgstr "Scuro"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This window"
+msgstr "Questa finestra"
+
+#: mac_app/kvm_bridge_app.py
+msgid "System follows your Mac's light or dark setting."
+msgstr "Sistema segue l'impostazione chiara o scura del Mac."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Pointer speed for another machine's mouse or trackpad while it drives this Mac."
+msgstr "Velocità del puntatore per il mouse o il trackpad di un altro computer mentre controlla questo Mac."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Link"
+msgstr "Collegamento"
+
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac's pointer always hides while it drives another machine. On, it also hides after another machine stops driving it, until its own mouse or trackpad moves."
+msgstr "Il puntatore di questo Mac si nasconde sempre mentre controlla un altro computer. Se attivo, si nasconde anche dopo che un altro computer smette di controllarlo, finché il suo mouse o trackpad non si muove."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Each chip is a side of this screen; click one to add or remove it. The side a machine touches crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. A corner is a diagonal push, shown as a square on the map. The notch is this Mac only."
+msgstr "Ogni etichetta è un lato di questo schermo; fai clic per aggiungerlo o toglierlo. Il lato toccato da un computer fa passare sui suoi terzi illuminati; ogni altro lato libero rimanda a esso, arrivando sul lato opposto. Un angolo è una spinta in diagonale, mostrata come un quadrato sulla mappa. Il notch vale solo per questo Mac."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "This machine's pointer"
+msgstr "Il puntatore di questo computer"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Applies when this physical pointer pushes through this screen's ways; visiting pointers are not protected by this switch."
+msgstr "Vale quando questo puntatore fisico spinge attraverso le vie di questo schermo; i puntatori in visita non sono protetti da questo interruttore."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Way home"
+msgstr "Via di casa"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shake the mouse or trackpad left and right a few times while you drive another machine, and input comes straight back to the machine you are using."
+msgstr "Scuoti il mouse o il trackpad a destra e a sinistra alcune volte mentre controlli un altro computer, e l'input torna subito al computer che stai usando."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py
+msgid "Push back the way you came: where an edge leads back to This Mac"
+msgstr "Spingi indietro per la stessa via: dove un bordo riporta a questo Mac"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "+"
+msgstr "+"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Double-tap"
+msgstr "Doppio tocco"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Hold"
+msgstr "Tieni premuto"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "How you press it"
+msgstr "Come lo premi"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Last machine"
+msgstr "Ultimo computer"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Next in order"
+msgstr "Prossimo in ordine"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Next among ticked"
+msgstr "Prossimo spuntato"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shortcut goes to"
+msgstr "La scorciatoia va a"
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+msgid "With Hold, input goes to the first ready machine in order."
+msgstr "Con Tieni premuto, l'input va al primo computer pronto, in ordine."
+
+#: mac_app/kvm_bridge_app.py
+msgid "These keys and buttons keep working on this Mac while its input is on another machine: a mouse's back button for this Mac's browser, say, or a volume key for its speakers."
+msgstr "Questi tasti e pulsanti continuano a funzionare su questo Mac mentre il suo input è su un altro computer: per esempio il tasto Indietro del mouse per il browser di questo Mac, o un tasto del volume per i suoi altoparlanti."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Turns crossing and landing animations on or off on this screen. Saved style choices stay in place."
+msgstr "Attiva o disattiva le animazioni di passaggio e di arrivo su questo schermo. Gli stili scelti restano salvati."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "For shortcut, menu and jump arrivals; requires Animate crossings on this screen."
+msgstr "Per gli arrivi da scorciatoia, menu e salto; richiede Anima i passaggi su questo schermo."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Outline"
+msgstr "Contorno"
+
+#: mac_app/kvm_bridge_app.py
+msgid "A line of colour runs round the notch, faster the harder you push."
+msgstr "Una linea di colore corre attorno al notch, tanto più veloce quanto più spingi."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Island"
+msgstr "Isola"
+
+#: mac_app/kvm_bridge_app.py
+msgid "The notch grows as you push, with a meter inside, and flashes as you go through."
+msgstr "Il notch si allarga mentre spingi, con un indicatore all'interno, e lampeggia quando passi."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Keep animating"
+msgstr "Continua l'animazione"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Shortcut and menu"
+msgstr "Scorciatoia e menu"
+
+#: mac_app/kvm_bridge_app.py
+msgid "What plays around the pointer for shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style."
+msgstr "Cosa appare attorno al puntatore negli arrivi da scorciatoia, menu e salto. Come il passaggio usa lo stile di passaggio di questo schermo."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Any colour works with any style. The notch's Outline uses it too; Island keeps Beamer's own cyan."
+msgstr "Qualsiasi colore funziona con qualsiasi stile. Anche il Contorno del notch lo usa; Isola mantiene il ciano di Beamer."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Every quarter"
+msgstr "A ogni quarto"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Halfway"
+msgstr "A metà"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Only when through"
+msgstr "Solo al passaggio"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Feel it"
+msgstr "Prova la vibrazione"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same shortcuts"
+msgstr "Stesse scorciatoie"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Same positions"
+msgstr "Stesse posizioni"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Hides every IP and hardware address in this window and its menu."
+msgstr "Nasconde ogni indirizzo IP e hardware in questa finestra e nel suo menu."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Automatic"
+msgstr "Automatica"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Language"
+msgstr "Lingua"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Wake-on-LAN"
+msgstr "Wake-on-LAN"
+
+#: mac_app/kvm_bridge_app.py
+msgid "A new address or port takes effect when you connect."
+msgstr "Un nuovo indirizzo o una nuova porta hanno effetto quando ti connetti."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Connect"
+msgstr "Connetti"
+
+#: mac_app/kvm_bridge_app.py
+msgid "On Overview, turn on Start Beamer when you log in. If macOS needs approval, that page shows the status and opens Login Items settings."
+msgstr "In Panoramica, attiva Apri Beamer al login. Se macOS richiede un'approvazione, quella pagina mostra lo stato e apre le impostazioni Elementi login."
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Push through {ways}"
+msgstr "Spingi attraverso {ways}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Input capture ready."
+msgstr "Acquisizione dell'input pronta."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Nothing is paired yet. Pairing fills the address and port in."
+msgstr "Ancora nulla di abbinato. L'abbinamento compila indirizzo e porta."
+
+#: mac_app/kvm_bridge_app.py
+msgid "This Mac drives every machine"
+msgstr "Questo Mac controlla tutti i computer"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Every machine drives this Mac"
+msgstr "Tutti i computer controllano questo Mac"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Configuration not reloaded"
+msgstr "Configurazione non ricaricata"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Driving {name}"
+msgstr "Controlla {name}"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Driven by {name}"
+msgstr "Controllato da {name}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid ""
+"Beamer {version}\n"
+"Beamer's website"
+msgstr ""
+"Beamer {version}\n"
+"Sito di Beamer"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Plays {name}"
+msgstr "Riproduce {name}"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{key}, to where input last went"
+msgstr "{key}, dove è andato l'input l'ultima volta"
+
+#: mac_app/kvm_bridge_app.py
+msgid "On a PC, Command arrives as Control, so Command-C copies there too, and Control arrives as the Windows key. Between two Macs every key arrives as itself."
+msgstr "Su un PC, Comando arriva come Ctrl, quindi Comando-C copia anche lì, e Ctrl arriva come tasto Windows. Tra due Mac ogni tasto arriva com'è."
+
+#: mac_app/kvm_bridge_app.py
+msgid "On a PC, each key arrives as the key in its place, so Command arrives as the Windows key. Between two Macs every key arrives as itself."
+msgstr "Su un PC, ogni tasto arriva come il tasto nella stessa posizione, quindi Comando arriva come tasto Windows. Tra due Mac ogni tasto arriva com'è."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "On"
+msgstr "Attivato"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Off"
+msgstr "Disattivato"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Download Beamer {version}"
+msgstr "Scarica Beamer {version}"
+
+#. {reason} is the system's reason for refusing the login item.
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "macOS refused: {reason}"
+msgstr "macOS ha rifiutato: {reason}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Requires approval. Allow Beamer in System Settings, General, Login Items."
+msgstr "Stato dell'elemento login: richiede approvazione. Consenti Beamer in Impostazioni di Sistema, Generali, Elementi login."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Requires approval. Move Beamer to Applications and reopen it before allowing it in Login Items."
+msgstr "Stato dell'elemento login: richiede approvazione. Sposta Beamer in Applicazioni e riaprilo prima di consentirlo in Elementi login."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{name}'s ways"
+msgstr "Vie di {name}"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Editing {name}'s ways ·"
+msgstr "Modifica delle vie di {name} ·"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Jump keys and permissions are set on {name}."
+msgstr "I tasti di salto e i permessi si impostano su {name}."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Changes go to {name} at once."
+msgstr "Le modifiche arrivano subito a {name}."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Restore"
+msgstr "Ripristina"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Delete"
+msgstr "Elimina"
+
+#: mac_app/kvm_bridge_app.py
+msgid "The order follows the tiles from top to bottom, then left to right. This Mac is always in the cycle. Choose which machines join the cycle with the tick boxes on their tiles."
+msgstr "L'ordine segue i riquadri dall'alto in basso, poi da sinistra a destra. Questo Mac è sempre nel ciclo. Scegli quali computer entrano nel ciclo con le caselle sui loro riquadri."
+
+#: mac_app/kvm_bridge_app.py
+msgid "The order follows the tiles from top to bottom, then left to right. This Mac is always in the cycle."
+msgstr "L'ordine segue i riquadri dall'alto in basso, poi da sinistra a destra. Questo Mac è sempre nel ciclo."
+
+#. {name} is the machine name.
+#: mac_app/kvm_bridge_app.py mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "Remove {name}"
+msgstr "Rimuovi {name}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "the {side} edge"
+msgstr "il bordo {side}"
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "Hold {key}"
+msgstr "Tieni premuto {key}"
+
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "Double-tap {key}"
+msgstr "Tocca due volte {key}"
+
+#: mac_app/kvm_bridge_app.py mac_app/link_state.py
+#, python-brace-format
+msgid "Waking {name}. It connects on its own once it is up."
+msgstr "Risveglio di {name}. Si connette da solo appena è acceso."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Beamer needs both, granted separately. macOS only delivers keyboard events to a process started after the grant, so relaunch Beamer once you have given them."
+msgstr "Beamer ha bisogno di entrambi, concessi separatamente. macOS invia gli eventi della tastiera solo a un processo avviato dopo la concessione, quindi riavvia Beamer dopo averli concessi."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Settings…"
+msgstr "Impostazioni…"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Reload configuration"
+msgstr "Ricarica la configurazione"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Open log folder"
+msgstr "Apri la cartella dei registri"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer {version} is available…"
+msgstr "Beamer {version} è disponibile…"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer {version}"
+msgstr "Beamer {version}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "This Mac drives {name}"
+msgstr "Questo Mac controlla {name}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "{name} drives this Mac"
+msgstr "{name} controlla questo Mac"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Same as crossing: {name}"
+msgstr "Come il passaggio: {name}"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{name}, {intensity}"
+msgstr "{name}, {intensity}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "A tick at a quarter, half and three quarters of the push, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr "Una vibrazione a un quarto, a metà e a tre quarti della spinta, poi una doppia quando il puntatore passa. macOS le riproduce solo mentre un dito è sul trackpad, quindi tieni premuto Prova."
+
+#: mac_app/kvm_bridge_app.py
+msgid "One tick halfway through the push, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr "Una vibrazione a metà della spinta, poi una doppia quando il puntatore passa. macOS le riproduce solo mentre un dito è sul trackpad, quindi tieni premuto Prova."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Nothing on the way in, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."
+msgstr "Nulla durante la spinta, poi una doppia vibrazione quando il puntatore passa. macOS le riproduce solo mentre un dito è sul trackpad, quindi tieni premuto Prova."
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones. This screen's {side} edge lights to show the resistance."
+msgstr "Segue il mouse o il trackpad di questo Mac su ogni schermo; ogni schermo fornisce le proprie zone. Il bordo {side} di questo schermo si illumina per mostrare la resistenza."
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Could not save this Mac's name: {error}"
+msgstr "Impossibile salvare il nome di questo Mac: {error}"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Could not save the machine's name: {error}"
+msgstr "Impossibile salvare il nome del computer: {error}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Not found. Check Beamer is installed in Applications, then turn it on again."
+msgstr "Stato dell'elemento login: non trovato. Controlla che Beamer sia installato in Applicazioni, poi riattivalo."
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Could not open Login Items settings: {reason}"
+msgstr "Impossibile aprire le impostazioni Elementi login: {reason}"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{name} has no way back to {machine} except the shortcut and a shake."
+msgstr "{name} non ha una via di ritorno verso {machine}, se non la scorciatoia e lo scuotimento."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "Before {name} changed it"
+msgstr "Prima che {name} le modificasse"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: mac_app/kvm_bridge_app.py win_app/pages_win.py
+#, python-brace-format
+msgid "{date} · {reason}"
+msgstr "{date} · {reason}"
+
+#. {detail} is a diagnostic reason supplied by macOS.
+#: mac_app/kvm_bridge_app.py
+msgid "Retrying input capture…"
+msgstr "Nuovo tentativo di acquisizione dell'input…"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "The address and port of {name}, the first machine paired. Another machine is changed by pairing it again."
+msgstr "Indirizzo e porta di {name}, il primo computer abbinato. Per cambiare un altro computer, abbinalo di nuovo."
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Crossing to {name} while it sleeps sends a wake-up packet and waits for it."
+msgstr "Passare a {name} mentre è in stop invia un pacchetto di risveglio e attende che si riattivi."
+
+#. {error} is the system error message.
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Could not save the change: {error}"
+msgstr "Impossibile salvare la modifica: {error}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "{error}"
+msgstr "{error}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Login item status: {status}. Move Beamer to Applications and open it there to start at login."
+msgstr "Stato dell'elemento login: {status}. Sposta Beamer in Applicazioni e aprilo da lì per avviarlo al login."
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Enabled. Beamer will start when you log in."
+msgstr "Stato dell'elemento login: attivo. Beamer si aprirà al login."
+
+#: mac_app/kvm_bridge_app.py mac_app/wake.py win_app/peers_view.py win_app/sender.py
+#, python-brace-format
+msgid "Waking {name}…"
+msgstr "Risveglio di {name}…"
+
+#: mac_app/kvm_bridge_app.py mac_app/pages.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Send input to {name}"
+msgstr "Invia input a {name}"
+
+#: mac_app/kvm_bridge_app.py
+msgid "Login item status: Not registered. Turn on Start Beamer when you log in."
+msgstr "Stato dell'elemento login: non registrato. Attiva Apri Beamer al login."
+
+#. {detail} is a diagnostic reason supplied by macOS.
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Retrying input capture… {detail}"
+msgstr "Nuovo tentativo di acquisizione dell'input… {detail}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Wake {name}"
+msgstr "Risveglia {name}"
+
+#: mac_app/kvm_bridge_app.py
+#, python-brace-format
+msgid "Login item status: {status}."
+msgstr "Stato dell'elemento login: {status}."
+
+#: mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/machines_win.py
+msgid "Leave out"
+msgstr "Escludi"
+
+#: mac_app/ledger.py
+msgid "Return saves, Escape cancels"
+msgstr "Invio salva, Esc annulla"
+
+#: mac_app/ledger.py mac_app/machines_panel.py
+msgid "Only on this Mac"
+msgstr "Solo su questo Mac"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Place it on the map"
+msgstr "Posizionalo sulla mappa"
+
+#: mac_app/ledger.py
+msgid "No notch"
+msgstr "Nessun notch"
+
+#: mac_app/ledger.py
+msgid "Return through the notch"
+msgstr "Ritorna attraverso il notch"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Jump"
+msgstr "Salto"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Clear"
+msgstr "Cancella"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Left out"
+msgstr "Escluso"
+
+#: mac_app/ledger.py mac_app/machines_panel.py win_app/crossing_ledger.py win_app/machines_win.py
+msgid "Put back"
+msgstr "Reinserisci"
+
+#: mac_app/ledger.py
+msgid "Machines and crossing ways"
+msgstr "Computer e vie di passaggio"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Edges"
+msgstr "Bordi"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Corners"
+msgstr "Angoli"
+
+#: mac_app/ledger.py mac_app/previews.py win_app/crossing_ledger.py
+msgid "Notch"
+msgstr "Notch"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Keys"
+msgstr "Tasti"
+
+#: mac_app/ledger.py mac_app/widgets.py win_app/widgets.py
+msgid "Press a key combination…"
+msgstr "Premi una combinazione di tasti…"
+
+#: mac_app/ledger.py mac_app/widgets.py win_app/kvm_bridge_win.py win_app/widgets.py
+msgid "Click again to cancel"
+msgstr "Fai di nuovo clic per annullare"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py win_app/kvm_bridge_win.py
+msgid "Offline, ways kept"
+msgstr "Non in linea, vie mantenute"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Left out machines stay paired and linked. The shortcut, menu and clipboard still reach them."
+msgstr "I computer esclusi restano abbinati e collegati. La scorciatoia, il menu e gli appunti li raggiungono comunque."
+
+#: mac_app/ledger.py
+msgid "Leave this machine out of pointer crossings"
+msgstr "Escludi questo computer dal passaggio del puntatore"
+
+#: mac_app/ledger.py
+msgid "Notch, no notch"
+msgstr "Notch, nessun notch"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Return through the notch, on"
+msgstr "Ritorna attraverso il notch, attivo"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Return through the notch, off"
+msgstr "Ritorna attraverso il notch, disattivo"
+
+#: mac_app/ledger.py
+msgctxt "switch state"
+msgid "on"
+msgstr "attivo"
+
+#: mac_app/ledger.py
+msgctxt "switch state"
+msgid "off"
+msgstr "disattivo"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Notch, on"
+msgstr "Notch, attivo"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Notch, off"
+msgstr "Notch, disattivo"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Push into the notch to reach {name}"
+msgstr "Spingi nel notch per raggiungere {name}"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Coming back from {name}, arrive just below the notch"
+msgstr "Tornando da {name}, arriva appena sotto il notch"
+
+#. {key} is the recorded key combination; {name} is the machine name.
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Press {key} to send input to {name}; press again to bring it home."
+msgstr "Premi {key} per inviare l'input a {name}; premi di nuovo per riportarlo a casa."
+
+#: mac_app/ledger.py mac_app/machines_panel.py
+#, python-brace-format
+msgid "Rename {name}"
+msgstr "Rinomina {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{side} edge"
+msgstr "Bordo {side}"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "Left out: Put back to change its ways"
+msgstr "Escluso: reinseriscilo per cambiarne le vie"
+
+#: mac_app/ledger.py
+msgid "unavailable"
+msgstr "non disponibile"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+msgid "macOS"
+msgstr "macOS"
+
+#: mac_app/ledger.py mac_app/machines.py mac_app/widgets.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Windows"
+msgstr "Windows"
+
+#: mac_app/ledger.py mac_app/machines.py win_app/crossing_ledger.py win_app/peers_view.py
+msgid "Linux"
+msgstr "Linux"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "Put back {name}"
+msgstr "Reinserisci {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "Leave out {name}"
+msgstr "Escludi {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: touches {name}; click to turn it {state}"
+msgstr "{edge}: tocca {name}; fai clic per impostarlo su {state}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, touches {name}, {state}"
+msgstr "{edge}, tocca {name}, {state}"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner, {state}"
+msgstr "Angolo {corner}, {state}"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side}, wraps"
+msgstr "{side}, rimanda"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge} wraps round to {name}; click to remove"
+msgstr "{edge} rimanda a {name}; fai clic per toglierlo"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, wraps round, {state}"
+msgstr "{edge}, rimanda, {state}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{corner} corner: click to turn it off"
+msgstr "Angolo {corner}: fai clic per disattivarlo"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{corner} corner: click to turn it on"
+msgstr "Angolo {corner}: fai clic per attivarlo"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{name}'s corner"
+msgstr "Angolo di {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "Place {name} beside this Mac first"
+msgstr "Posiziona prima {name} accanto a questo Mac"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "held by {name}"
+msgstr "occupato da {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, wraps round, kept"
+msgstr "{edge}, rimanda, mantenuto"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, {third} third, {state}"
+msgstr "{edge}, terzo {third}, {state}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge} wraps round to {name} once Edge is on; click to turn Edge on"
+msgstr "{edge} rimanda a {name} quando Bordo è attivo; fai clic per attivare Bordo"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: none of it is free just now; click to remove"
+msgstr "{edge}: al momento nessuna parte è libera; fai clic per toglierlo"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: click to wrap round to {name}"
+msgstr "{edge}: fai clic per rimandare a {name}"
+
+#: mac_app/ledger.py win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side}, {name}"
+msgstr "{side}, {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}: {name}'s"
+msgstr "{edge}: di {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{edge}, held by {name}"
+msgstr "{edge}, occupato da {name}"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{third} third: click to leave it out"
+msgstr "Terzo {third}: fai clic per escluderlo"
+
+#: mac_app/ledger.py
+#, python-brace-format
+msgid "{third} third: click to turn it on"
+msgstr "Terzo {third}: fai clic per attivarlo"
+
+#: mac_app/link_state.py
+msgid "Beamer keeps trying to reconnect."
+msgstr "Beamer continua a provare a riconnettersi."
+
+#: mac_app/link_state.py
+msgid "Disconnected"
+msgstr "Disconnesso"
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+msgid "Dropped"
+msgstr "Interrotto"
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Live"
+msgstr "Attivo"
+
+#: mac_app/link_state.py
+msgid "Waking"
+msgstr "Risveglio"
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Tunnel"
+msgstr "Tunnel"
+
+#: mac_app/link_state.py
+msgid "On Mac"
+msgstr "Sul Mac"
+
+#: mac_app/link_state.py
+msgid "Setup"
+msgstr "Configurazione"
+
+#: mac_app/link_state.py
+msgid "Pair a machine on Overview and Beamer connects on its own."
+msgstr "Abbina un computer in Panoramica e Beamer si connette da solo."
+
+#. a machine's address and port, as in "192.0.2.20 port 24820".
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{host} port {port}"
+msgstr "{host} porta {port}"
+
+#: mac_app/link_state.py
+msgid "Pairing removed"
+msgstr "Abbinamento rimosso"
+
+#: mac_app/link_state.py mac_app/machines.py win_app/pages_win.py win_app/peers_view.py
+msgid "Refused"
+msgstr "Rifiutato"
+
+#: mac_app/link_state.py
+msgid "Token mismatch"
+msgstr "Token non corrispondente"
+
+#: mac_app/link_state.py
+msgid "Version mismatch"
+msgstr "Versione non corrispondente"
+
+#: mac_app/link_state.py
+msgid "Did not wake"
+msgstr "Non si è riattivato"
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "No reply"
+msgstr "Nessuna risposta"
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Blocked"
+msgstr "Bloccato"
+
+#: mac_app/link_state.py
+msgid "macOS 27 blocked direct LAN access. Open Beamer Tunnel from Applications."
+msgstr "macOS 27 ha bloccato l'accesso diretto alla rete locale. Apri Beamer Tunnel da Applicazioni."
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+msgid "Unreachable"
+msgstr "Non raggiungibile"
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+msgid "Not listening"
+msgstr "Non in ascolto"
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "No receiver"
+msgstr "Nessun ricevitore"
+
+#: mac_app/link_state.py mac_app/machines.py win_app/kvm_bridge_win.py win_app/peers_view.py
+msgid "Waiting"
+msgstr "In attesa"
+
+#: mac_app/link_state.py mac_app/machines.py
+msgid "Looking"
+msgstr "Ricerca"
+
+#: mac_app/link_state.py
+msgid "Unlocking"
+msgstr "Sblocco"
+
+#: mac_app/link_state.py
+msgid "Paused"
+msgstr "In pausa"
+
+#: mac_app/link_state.py
+msgid "Held"
+msgstr "Bloccato"
+
+#: mac_app/link_state.py mac_app/pages.py win_app/pages_win.py
+msgid "Held: an app is full screen."
+msgstr "Bloccato: un'app è a schermo intero."
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "{status}. Beamer keeps trying to reconnect."
+msgstr "{status}. Beamer continua a provare a riconnettersi."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "From {name}"
+msgstr "Da {name}"
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name}'s keyboard and pointer are on this Mac. Push its pointer back through the edge it arrived by to send them home."
+msgstr "La tastiera e il puntatore di {name} sono su questo Mac. Riporta il suo puntatore attraverso il bordo da cui è arrivato per rimandarli a casa."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "Connected to {name} through the macOS 27 tunnel."
+msgstr "Connesso a {name} attraverso il tunnel di macOS 27."
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "Connected to {name}."
+msgstr "Connesso a {name}."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} no longer has this pairing: remove {name} here and pair the two again."
+msgstr "{name} non ha più questo abbinamento: rimuovi {name} qui e abbina di nuovo i due computer."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} refused this Mac's token. Remove it, then pair again to write a fresh one."
+msgstr "{name} ha rifiutato il token di questo Mac. Rimuovilo, poi abbinalo di nuovo per scriverne uno nuovo."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} runs a different Beamer from this Mac. Update both to the same version."
+msgstr "{name} usa una versione di Beamer diversa da questo Mac. Aggiorna entrambi alla stessa versione."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} did not answer within a minute of the wake-up packet."
+msgstr "{name} non ha risposto entro un minuto dal pacchetto di risveglio."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{address} is not answering. {name} may be asleep or off this network."
+msgstr "{address} non risponde. {name} potrebbe essere in stop o fuori da questa rete."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} answers, but Beamer is not listening on port {port}. Open Beamer on {name}."
+msgstr "{name} risponde, ma Beamer non è in ascolto sulla porta {port}. Apri Beamer su {name}."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} stopped responding. Beamer keeps trying to reconnect."
+msgstr "{name} ha smesso di rispondere. Beamer continua a provare a riconnettersi."
+
+#: mac_app/link_state.py mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "Looking for {name}. It connects on its own once Beamer is open there."
+msgstr "Ricerca di {name}. Si connette da solo appena Beamer è aperto lì."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "{name} is at its lock screen and is unlocking itself; input follows once the desktop is back."
+msgstr "{name} è alla schermata di blocco e si sta sbloccando; l'input segue appena torna la scrivania."
+
+#: mac_app/link_state.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "On {name}"
+msgstr "Su {name}"
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "Keyboard and pointer are on {name}. Do the same again to bring them home."
+msgstr "Tastiera e puntatore sono su {name}. Ripeti la stessa azione per riportarli a casa."
+
+#: mac_app/link_state.py
+#, python-brace-format
+msgid "Connected to {name}. Crossing is held, so you can lean on an edge."
+msgstr "Connesso a {name}. Il passaggio è bloccato, quindi puoi appoggiarti a un bordo."
+
+#: mac_app/login_item.py
+msgid "Not registered"
+msgstr "Non registrato"
+
+#: mac_app/login_item.py
+msgid "Enabled"
+msgstr "Attivo"
+
+#: mac_app/login_item.py
+msgid "Requires approval"
+msgstr "Richiede approvazione"
+
+#: mac_app/login_item.py
+msgid "Not found"
+msgstr "Non trovato"
+
+#: mac_app/login_item.py win_app/kvm_bridge_win.py
+msgid "Unknown"
+msgstr "Sconosciuto"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "iPhone"
+msgstr "iPhone"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Android"
+msgstr "Android"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Other"
+msgstr "Altro"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Needs re-pair"
+msgstr "Da riabbinare"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "NOT IN USE"
+msgstr "NON IN USO"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Pair again"
+msgstr "Abbina di nuovo"
+
+#: mac_app/machines.py
+msgid "Driving this Mac"
+msgstr "Controlla questo Mac"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Input here"
+msgstr "Input qui"
+
+#: mac_app/machines.py win_app/peers_view.py
+msgid "Version"
+msgstr "Versione"
+
+#: mac_app/machines.py mac_app/machines_panel.py win_app/peers_view.py
+#, python-brace-format
+msgid "{address} · port {port}"
+msgstr "{address} · porta {port}"
+
+#: mac_app/machines.py
+#, python-brace-format
+msgid "{name} is not in use on this Mac."
+msgstr "{name} non è in uso su questo Mac."
+
+#: mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "{name} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0."
+msgstr "{name} è stato abbinato con Beamer 1.4. Abbina di nuovo i due computer per collegarli con la 1.5.0."
+
+#: mac_app/machines.py
+#, python-brace-format
+msgid "{name}'s keyboard and pointer are on this Mac. Push the pointer back through the edge it arrived by to send them home."
+msgstr "La tastiera e il puntatore di {name} sono su questo Mac. Riporta il puntatore attraverso il bordo da cui è arrivato per rimandarli a casa."
+
+#: mac_app/machines.py
+#, python-brace-format
+msgid "This Mac's keyboard and pointer are on {name}. Do the same again to bring them home."
+msgstr "La tastiera e il puntatore di questo Mac sono su {name}. Ripeti la stessa azione per riportarli a casa."
+
+#: mac_app/machines.py win_app/peers_view.py
+#, python-brace-format
+msgid "Waiting for {name} to connect."
+msgstr "In attesa che {name} si connetta."
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "Expires in {n} s"
+msgstr "Scade tra {n} s"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair nearby"
+msgstr "Abbina nelle vicinanze"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair a phone"
+msgstr "Abbina un telefono"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair a machine"
+msgstr "Abbina un computer"
+
+#: mac_app/machines_panel.py
+msgid "No machines paired yet."
+msgstr "Ancora nessun computer abbinato."
+
+#: mac_app/machines_panel.py
+msgid "Beamer connects to each machine on its own whenever both are running."
+msgstr "Beamer si connette da solo a ogni computer quando entrambi sono in funzione."
+
+#: mac_app/machines_panel.py
+msgid "Rename this Mac"
+msgstr "Rinomina questo Mac"
+
+#: mac_app/machines_panel.py
+msgid "Name for this Mac"
+msgstr "Nome di questo Mac"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Show a code"
+msgstr "Mostra un codice"
+
+#: mac_app/machines_panel.py
+msgid "The pairing code as a QR code"
+msgstr "Il codice di abbinamento come codice QR"
+
+#: mac_app/machines_panel.py
+msgid "Cancel code"
+msgstr "Annulla codice"
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing digits"
+msgstr "Cifre dell'abbinamento nelle vicinanze"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Confirm"
+msgstr "Conferma"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pair"
+msgstr "Abbina"
+
+#: mac_app/machines_panel.py
+msgid "Choose a machine, or type its address, then type the code it shows."
+msgstr "Scegli un computer, o digita il suo indirizzo, poi digita il codice che mostra."
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "In use"
+msgstr "In uso"
+
+#: mac_app/machines_panel.py
+msgid "This Mac drives it"
+msgstr "Questo Mac lo controlla"
+
+#: mac_app/machines_panel.py
+msgid "It drives this Mac"
+msgstr "Controlla questo Mac"
+
+#: mac_app/machines_panel.py
+msgid "Press Pair nearby on the other machine within 60 seconds."
+msgstr "Premi Abbina nelle vicinanze sull'altro computer entro 60 secondi."
+
+#: mac_app/machines_panel.py
+msgid "Choose a machine to pair nearby."
+msgstr "Scegli un computer da abbinare nelle vicinanze."
+
+#: mac_app/machines_panel.py
+msgid "Compare all six digits on both machines, then confirm on each."
+msgstr "Confronta tutte e sei le cifre su entrambi i computer, poi conferma su ciascuno."
+
+#: mac_app/machines_panel.py
+msgid "Waiting for confirmation on the other machine."
+msgstr "In attesa di conferma sull'altro computer."
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing complete."
+msgstr "Abbinamento nelle vicinanze completato."
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing expired. Press Pair nearby to try again."
+msgstr "L'abbinamento nelle vicinanze è scaduto. Premi Abbina nelle vicinanze per riprovare."
+
+#: mac_app/machines_panel.py
+msgid "Nearby pairing refused. Use a new window to try again."
+msgstr "Abbinamento nelle vicinanze rifiutato. Usa una nuova finestra per riprovare."
+
+#: mac_app/machines_panel.py
+msgid "The new peer could not be saved."
+msgstr "Impossibile salvare il nuovo computer."
+
+#. {name} and {address} come from the other machine.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {address}, older Beamer"
+msgstr "{name}, {address}, Beamer precedente"
+
+#: mac_app/machines_panel.py
+msgid "That machine"
+msgstr "Quel computer"
+
+#: mac_app/machines_panel.py
+msgid "Show a code on this Mac"
+msgstr "Mostra un codice su questo Mac"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Enter a code from another machine"
+msgstr "Inserisci un codice da un altro computer"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "On this network"
+msgstr "In questa rete"
+
+#: mac_app/machines_panel.py
+msgid "Address of a machine that is not listed"
+msgstr "Indirizzo di un computer non in elenco"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Not listed? Type its address."
+msgstr "Non in elenco? Digita il suo indirizzo."
+
+#: mac_app/machines_panel.py
+msgid "Code shown on the other machine"
+msgstr "Codice mostrato sull'altro computer"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Re-pair"
+msgstr "Riabbina"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Hide directions"
+msgstr "Nascondi direzioni"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Directions"
+msgstr "Direzioni"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Keep"
+msgstr "Mantieni"
+
+#: mac_app/machines_panel.py
+msgid "Pairing is not available on this Mac."
+msgstr "L'abbinamento non è disponibile su questo Mac."
+
+#: mac_app/machines_panel.py
+msgid "Connecting to the selected machine…"
+msgstr "Connessione al computer selezionato…"
+
+#: mac_app/machines_panel.py win_app/crossing_ledger.py win_app/sender.py
+msgid "Another machine"
+msgstr "Un altro computer"
+
+#: mac_app/machines_panel.py
+msgid "Looking for machines running Beamer. Open it on the other machine and it appears here; across a VPN or on guest Wi-Fi it may not, so type its address below."
+msgstr "Ricerca dei computer con Beamer in funzione. Apri Beamer sull'altro computer e comparirà qui; attraverso una VPN o su una rete Wi-Fi ospite potrebbe non comparire, quindi digita il suo indirizzo qui sotto."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {address}, showing a code"
+msgstr "{name}, {address}, sta mostrando un codice"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {address}"
+msgstr "{name}, {address}"
+
+#: mac_app/machines_panel.py
+msgid "On the other machine, open Beamer, choose this Mac in its list and type the code."
+msgstr "Sull'altro computer, apri Beamer, scegli questo Mac nel suo elenco e digita il codice."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name}, {state}"
+msgstr "{name}, {state}"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Name for {name}"
+msgstr "Nome per {name}"
+
+#. {name} is the other machine's chosen name.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Off: no input or settings link to {name}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect."
+msgstr "Disattivato: nessun collegamento di input o di impostazioni con {name}. Abbinamento, direzioni, vie e tasto di salto restano. Riattivalo qui per riconnetterti."
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "{action} {name}"
+msgstr "{action} {name}"
+
+#. {name} is the other machine's chosen name.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Input moves only when this Mac enables this switch and {name} enables It drives this Mac."
+msgstr "L'input passa solo quando questo Mac attiva questo interruttore e {name} attiva Controlla questo Mac."
+
+#. {name} is the other machine's chosen name.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Input moves only when {name} enables This machine drives it and this Mac enables this switch."
+msgstr "L'input passa solo quando {name} attiva Questo computer lo controlla e questo Mac attiva questo interruttore."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{action} directions for {name}"
+msgstr "{action} le direzioni per {name}"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Remove {name}? It stays paired on that machine until you remove this one there too."
+msgstr "Rimuovere {name}? Resta abbinato su quel computer finché non rimuovi anche questo lì."
+
+#: mac_app/machines_panel.py
+msgid "The QR is hidden while addresses are hidden."
+msgstr "Il QR è nascosto mentre gli indirizzi sono nascosti."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Pairing with {name}…"
+msgstr "Abbinamento con {name}…"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Paired with {name}. Connecting…"
+msgstr "Abbinato a {name}. Connessione…"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+#, python-brace-format
+msgid "Re-pair {name}"
+msgstr "Riabbina {name}"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Left out of the layout. The shortcut and the menu still reach it."
+msgstr "Escluso dalla disposizione. La scorciatoia e il menu lo raggiungono comunque."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Off: {name} cannot connect or drive this Mac. Turn it back on here to reconnect."
+msgstr "Disattivato: {name} non può connettersi né controllare questo Mac. Riattivalo qui per riconnetterti."
+
+#: mac_app/machines_panel.py
+msgid "Hide"
+msgstr "Nascondi"
+
+#: mac_app/machines_panel.py
+msgid "Show"
+msgstr "Mostra"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Confirm removing {name}"
+msgstr "Conferma la rimozione di {name}"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Keep {name}"
+msgstr "Mantieni {name}"
+
+#: mac_app/machines_panel.py
+msgid "this machine"
+msgstr "questo computer"
+
+#: mac_app/machines_panel.py
+msgid "The same code as a QR, for a phone to scan."
+msgstr "Lo stesso codice come QR, da scansionare con un telefono."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Beamer cannot look for machines: {reason}"
+msgstr "Beamer non può cercare computer: {reason}"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Code shown on {name}"
+msgstr "Codice mostrato su {name}"
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "The code is {n} digits."
+msgstr "Il codice ha {n} cifre."
+
+#. {error} is the system error message.
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Could not remove it: {error}"
+msgstr "Impossibile rimuoverlo: {error}"
+
+#. {error} is the system error message.
+#: mac_app/machines_panel.py win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Nearby pairing is not available: {error}"
+msgstr "L'abbinamento nelle vicinanze non è disponibile: {error}"
+
+#: mac_app/machines_panel.py
+msgid "Not selected"
+msgstr "Non selezionato"
+
+#: mac_app/machines_panel.py
+msgid "No network address found"
+msgstr "Nessun indirizzo di rete trovato"
+
+#: mac_app/machines_panel.py
+msgid "No QR while this Mac has no address."
+msgstr "Nessun QR finché questo Mac non ha un indirizzo."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "{name} is not showing a code yet. Show one in Beamer on it first."
+msgstr "{name} non mostra ancora un codice. Mostrane prima uno in Beamer su quel computer."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "Six digits, as shown on {name}."
+msgstr "Sei cifre, come mostrate su {name}."
+
+#: mac_app/machines_panel.py
+#, python-brace-format
+msgid "No QR: {reason}"
+msgstr "Nessun QR: {reason}"
+
+#: mac_app/pages.py
+msgid "This Mac only."
+msgstr "Solo questo Mac."
+
+#: mac_app/pages.py
+msgid "The notch is this Mac only."
+msgstr "Il notch vale solo per questo Mac."
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Changes apply as you make them."
+msgstr "Le modifiche si applicano subito."
+
+#: mac_app/pages.py
+msgid "Closing this window keeps Beamer running in the menu bar."
+msgstr "Chiudendo questa finestra Beamer resta attivo nella barra dei menu."
+
+#: mac_app/pages.py
+msgid "Simple"
+msgstr "Semplice"
+
+#: mac_app/pages.py
+msgid "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this Mac's input for every destination."
+msgstr "Le vie qui sotto portano al computer selezionato. Il suo lato è condiviso con quel computer. Resistenza, protezione durante il trascinamento e Scorciatoia valgono per l'input di questo Mac verso ogni destinazione."
+
+#: mac_app/pages.py
+msgid "Used on this screen. Shared animation settings may follow another machine; Animate, window appearance, notch and trackpad controls stay on this Mac."
+msgstr "Usato su questo schermo. Le impostazioni dell'animazione condivise possono seguire un altro computer; Anima i passaggi, aspetto della finestra e controlli del notch e del trackpad restano su questo Mac."
+
+#: mac_app/pages.py
+msgid "Modifier keys and Stays here belong to this Mac's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own."
+msgstr "Tasti modificatori e Resta qui riguardano l'input di questo Mac. Velocità del puntatore e scorrimento riguardano questo schermo quando lo controlla un altro computer. Ogni computer mantiene i propri."
+
+#: mac_app/pages.py
+msgid "Classic"
+msgstr "Classico"
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Signal"
+msgstr "Segnale"
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Colourful"
+msgstr "Colorato"
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Ocean"
+msgstr "Oceano"
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Sunset"
+msgstr "Tramonto"
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Aurora"
+msgstr "Aurora"
+
+#: mac_app/pages.py
+msgid "to the left of"
+msgstr "a sinistra di"
+
+#: mac_app/pages.py
+msgid "to the right of"
+msgstr "a destra di"
+
+#: mac_app/pages.py
+msgid "This corner crosses its left or right edge."
+msgstr "Questo angolo passa dal suo bordo sinistro o destro."
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "On. Pause it to lean on an edge without switching."
+msgstr "Attivo. Sospendilo per appoggiarti a un bordo senza passare."
+
+#: mac_app/pages.py
+msgid "the edge"
+msgstr "il bordo"
+
+#: mac_app/pages.py
+msgid "a corner"
+msgstr "un angolo"
+
+#: mac_app/pages.py
+msgid "With only the notch or a corner on, input arrives by the notch's or corner's own side, so this choice does nothing on this Mac; the other machine's own push still follows it."
+msgstr "Con solo il notch o un angolo attivo, l'input arriva dal lato del notch o dell'angolo, quindi questa scelta non ha effetto su questo Mac; la spinta dell'altro computer la segue comunque."
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Overview"
+msgstr "Panoramica"
+
+#: mac_app/pages.py
+msgid "Where input is, whether each link is up, and the controls you reach for every day. Pair your machines here first."
+msgstr "Dove si trova l'input, se ogni collegamento è attivo, e i controlli che usi ogni giorno. Abbina prima qui i tuoi computer."
+
+#: mac_app/pages.py
+msgid "Permissions"
+msgstr "Permessi"
+
+#: mac_app/pages.py
+msgid "macOS must allow Beamer to read this Mac's input and to move its pointer and type when another machine drives it."
+msgstr "macOS deve consentire a Beamer di leggere l'input di questo Mac e di muoverne il puntatore e scrivere quando lo controlla un altro computer."
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Keyboard"
+msgstr "Tastiera"
+
+#: mac_app/pages.py
+msgid "How this Mac's modifier keys arrive on other machines, which keys and buttons stay on this Mac, and how fast another machine's pointer moves here. The switch key is on the Crossing page."
+msgstr "Come arrivano i tasti modificatori di questo Mac sugli altri computer, quali tasti e pulsanti restano su questo Mac, e quanto velocemente si muove qui il puntatore di un altro computer. Il tasto per passare è nella pagina Passaggio."
+
+#: mac_app/pages.py
+msgid "How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad."
+msgstr "Come appare e si sente il passaggio su questo Mac: il bordo, l'angolo, il notch e il trackpad."
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Connection"
+msgstr "Connessione"
+
+#: mac_app/pages.py
+msgid "Local connection details for the first machine you paired. Pair again to change another machine's entry."
+msgstr "Dettagli della connessione locale per il primo computer abbinato. Abbina di nuovo per cambiare la voce di un altro computer."
+
+#: mac_app/pages.py
+msgid "Changes apply as you make them. Closing this window keeps Beamer running in the menu bar."
+msgstr "Le modifiche si applicano subito. Chiudendo questa finestra Beamer resta attivo nella barra dei menu."
+
+#: mac_app/pages.py
+msgid "Where the other machine is"
+msgstr "Dove si trova l'altro computer"
+
+#: mac_app/pages.py
+msgid "Not paired yet, so no edge or shortcut moves input until you pair a machine on Overview."
+msgstr "Non ancora abbinato, quindi nessun bordo o scorciatoia sposta l'input finché non abbini un computer in Panoramica."
+
+#: mac_app/pages.py
+msgid "No machine is driven by this Mac, so edges and the shortcut do nothing."
+msgstr "Nessun computer è controllato da questo Mac, quindi i bordi e la scorciatoia non fanno nulla."
+
+#: mac_app/pages.py
+msgid "Not connected to any machine, so edges and the shortcut do nothing yet."
+msgstr "Non connesso a nessun computer, quindi i bordi e la scorciatoia non fanno ancora nulla."
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Only the shortcut is switched on; there is nothing to pause."
+msgstr "È attiva solo la scorciatoia; non c'è nulla da sospendere."
+
+#: mac_app/pages.py win_app/pages_win.py
+msgid "Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts."
+msgstr "Sospende il passaggio del puntatore attraverso questo schermo, compreso il puntatore di un altro computer. Scorciatoie e tasti di salto funzionano comunque. Si azzera al riavvio di Beamer."
+
+#: mac_app/pages.py
+msgid "This Mac has no notch, so this only shows how it would look."
+msgstr "Questo Mac non ha il notch, quindi qui vedi solo come apparirebbe."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{names} already cross from the {side} edge of this Mac. The thirds you pick go to {name}; the rest stay where they are."
+msgstr "{names} passano già dal bordo {side} di questo Mac. I terzi che scegli vanno a {name}; gli altri restano dove sono."
+
+#: mac_app/pages.py
+msgid "At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it."
+msgstr "Nel notch, Bagliore e Raggio non disegnano: al loro posto appare lo stile del notch che scegli qui, e i loro riquadri lo mostrano."
+
+#: mac_app/pages.py
+msgid "Plays Glow"
+msgstr "Riproduce Bagliore"
+
+#: mac_app/pages.py
+msgid "Closes onto the pointer"
+msgstr "Si stringe sul puntatore"
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{names} already crosses from the {side} edge of this Mac. The thirds you pick go to {name}; the rest stay with {holder}."
+msgstr "{names} passa già dal bordo {side} di questo Mac. I terzi che scegli vanno a {name}; gli altri restano a {holder}."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "Not placed yet: {names}"
+msgstr "Ancora da posizionare: {names}"
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "Where {name} is"
+msgstr "Dove si trova {name}"
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing. {name} draws its own form round the notch."
+msgstr "{place} non è una delle tue vie d'ingresso, quindi qui vedi solo come apparirebbe. Attivalo in Passaggio. {name} disegna la propria forma attorno al notch."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} draws its own form round the notch."
+msgstr "{name} disegna la propria forma attorno al notch."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "With only the notch or a corner on, input arrives by the notch's or corner's own side, so this choice does nothing on this Mac; {name}'s own push still follows it."
+msgstr "Con solo il notch o un angolo attivo, l'input arriva dal lato del notch o dell'angolo, quindi questa scelta non ha effetto su questo Mac; la spinta di {name} la segue comunque."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} is {position} this Mac."
+msgstr "{name} è {position} questo Mac."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} is not placed yet."
+msgstr "{name} non è ancora posizionato."
+
+#: mac_app/pages.py
+msgid "No way in is on."
+msgstr "Nessuna via d'ingresso è attiva."
+
+#: mac_app/pages.py
+msgid "Bring input back"
+msgstr "Riporta qui l'input"
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing."
+msgstr "{place} non è una delle tue vie d'ingresso, quindi qui vedi solo come apparirebbe. Attivalo in Passaggio."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing. At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it."
+msgstr "{place} non è una delle tue vie d'ingresso, quindi qui vedi solo come apparirebbe. Attivalo in Passaggio. Nel notch, Bagliore e Raggio non disegnano: al loro posto appare lo stile del notch che scegli qui, e i loro riquadri lo mostrano."
+
+#: mac_app/pages.py
+#, python-brace-format
+msgid "{name} is unavailable"
+msgstr "{name} non è disponibile"
+
+#: mac_app/previews.py win_app/kvm_bridge_win.py
+msgid "Edge"
+msgstr "Bordo"
+
+#: mac_app/previews.py win_app/kvm_bridge_win.py
+msgid "Corner"
+msgstr "Angolo"
+
+#: mac_app/wake.py win_app/sender.py
+#, python-brace-format
+msgid "{name} did not wake"
+msgstr "{name} non si è riattivato"
+
+#: mac_app/wake.py win_app/sender.py
+msgid "Could not send the wake-up packet"
+msgstr "Impossibile inviare il pacchetto di risveglio"
+
+#: mac_app/wake.py win_app/sender.py
+#, python-brace-format
+msgid "{name} is awake — switch again to send input"
+msgstr "{name} è attivo: passa di nuovo per inviare l'input"
+
+#: mac_app/widgets.py
+msgid "Press a key…"
+msgstr "Premi un tasto…"
+
+#: mac_app/widgets.py win_app/kvm_bridge_win.py
+msgid "Click, then press the key"
+msgstr "Fai clic, poi premi il tasto"
+
+#: mac_app/widgets.py win_app/widgets.py
+msgid "Click, then press a key combination"
+msgstr "Fai clic, poi premi una combinazione di tasti"
+
+#: mac_app/widgets.py win_app/kvm_bridge_win.py
+msgid "Add a key or button"
+msgstr "Aggiungi un tasto o un pulsante"
+
+#: mac_app/widgets.py win_app/widgets.py
+msgid "Press a key or button…"
+msgstr "Premi un tasto o un pulsante…"
+
+#: mac_app/widgets.py win_app/kvm_bridge_win.py win_app/widgets.py
+msgid "Click, then press it"
+msgstr "Fai clic, poi premilo"
+
+#: mac_app/widgets.py win_app/widgets.py
+msgid "Choose a key combination"
+msgstr "Scegli una combinazione di tasti"
+
+#: mac_app/widgets.py
+msgid "Add a key or button that stays on this Mac"
+msgstr "Aggiungi un tasto o un pulsante che resta su questo Mac"
+
+#. {key} is the key combination recorded by the person.
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "Shortcut key, {key}"
+msgstr "Tasto della scorciatoia, {key}"
+
+#. {key} is the key combination recorded by the person.
+#. {key} is the key combination recorded for a machine.
+#: mac_app/widgets.py win_app/widgets.py
+#, python-brace-format
+msgid "Jump straight here key, {key}"
+msgstr "Tasto per saltare qui direttamente, {key}"
+
+#: mac_app/widgets.py win_app/crossing_ledger.py
+msgid "Set a key"
+msgstr "Imposta un tasto"
+
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "Digit {n}"
+msgstr "Cifra {n}"
+
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "{name} ⌘{key}"
+msgstr "{name} ⌘{key}"
+
+#. {name} is a settings page name.
+#: mac_app/widgets.py
+#, python-brace-format
+msgid "{name}, needs attention"
+msgstr "{name}, richiede attenzione"
+
+#: win_app/crossing_ledger.py
+msgid "Return saves, Escape cancels · Only on this PC"
+msgstr "Invio salva, Esc annulla · Solo su questo PC"
+
+#: win_app/crossing_ledger.py
+msgid "Clear jump key"
+msgstr "Cancella il tasto di salto"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/crossing_ledger.py
+msgid "Return here"
+msgstr "Ritorna qui"
+
+#: win_app/crossing_ledger.py
+msgid "Leave this machine out of crossings"
+msgstr "Escludi questo computer dai passaggi"
+
+#: win_app/crossing_ledger.py
+msgid "How each machine is reached"
+msgstr "Come si raggiunge ogni computer"
+
+#: win_app/crossing_ledger.py
+msgid "turn it off"
+msgstr "disattivarlo"
+
+#: win_app/crossing_ledger.py
+msgid "turn it on"
+msgstr "attivarlo"
+
+#: win_app/crossing_ledger.py
+msgid "PC"
+msgstr "PC"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, {third} third, {state}"
+msgstr "Bordo {side}, terzo {third}, {state}"
+
+#: win_app/crossing_ledger.py
+msgid "on"
+msgstr "attivo"
+
+#: win_app/crossing_ledger.py
+msgid "off"
+msgstr "disattivo"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{third} third: click to {action}"
+msgstr "Terzo {third}: fai clic per {action}"
+
+#: win_app/crossing_ledger.py
+msgid "leave it out"
+msgstr "escluderlo"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Choose a key combination to jump to {name} and back."
+msgstr "Scegli una combinazione di tasti per saltare a {name} e tornare."
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, touches {name}, {state}"
+msgstr "Bordo {side}, tocca {name}, {state}"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner, held by {name}"
+msgstr "Angolo {corner}, occupato da {name}"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: touches {name}; click to {action}"
+msgstr "Bordo {side}: tocca {name}; fai clic per {action}"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, wraps round, on"
+msgstr "Bordo {side}, rimanda, attivo"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner, unavailable"
+msgstr "Angolo {corner}, non disponibile"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge wraps round to {name}; click to remove"
+msgstr "Il bordo {side} rimanda a {name}; fai clic per toglierlo"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, wraps round, kept"
+msgstr "Bordo {side}, rimanda, mantenuto"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "Place {name} beside this {platform} first"
+msgstr "Posiziona prima {name} accanto a questo {platform}"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{corner} corner: click to turn it {state}"
+msgstr "Angolo {corner}: fai clic per impostarlo su {state}"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge wraps round to {name} once Edge is on; click to turn Edge on"
+msgstr "Il bordo {side} rimanda a {name} quando Bordo è attivo; fai clic per attivare Bordo"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: none of it is free just now; click to remove"
+msgstr "Bordo {side}: al momento nessuna parte è libera; fai clic per toglierlo"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: {name}'s"
+msgstr "Bordo {side}: di {name}"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, held by {name}"
+msgstr "Bordo {side}, occupato da {name}"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge, wraps round, off"
+msgstr "Bordo {side}, rimanda, disattivo"
+
+#: win_app/crossing_ledger.py
+#, python-brace-format
+msgid "{side} edge: click to wrap round to {name}"
+msgstr "Bordo {side}: fai clic per rimandare a {name}"
+
+#: win_app/diagram.py win_app/kvm_bridge_win.py
+msgid "This PC"
+msgstr "Questo PC"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/diagram.py
+msgid "Tile size can be changed by dragging a corner or pressing Alt+arrow."
+msgstr "Le dimensioni del riquadro si cambiano trascinando un angolo o premendo Alt+freccia."
+
+#: win_app/diagram.py
+msgid "Arrangement"
+msgstr "Disposizione"
+
+#: win_app/diagram.py
+msgid "Crossing layout"
+msgstr "Disposizione del passaggio"
+
+#: win_app/diagram.py
+msgid "at a corner of This PC"
+msgstr "in un angolo di questo PC"
+
+#: win_app/diagram.py
+msgid "Crosses."
+msgstr "Passa."
+
+#: win_app/diagram.py
+msgid "THIS PC"
+msgstr "QUESTO PC"
+
+#. {name} is a machine name; {position} is relative to this PC; {detail} optionally names the third crossed.
+#: win_app/diagram.py
+#, python-brace-format
+msgid "{name}, {position}{detail}. {result}"
+msgstr "{name}, {position}{detail}. {result}"
+
+#: win_app/diagram.py
+msgctxt "list"
+msgid "; "
+msgstr "; "
+
+#: win_app/diagram.py
+msgid "Rename this computer on Overview."
+msgstr "Rinomina questo computer in Panoramica."
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid "{side} of This PC"
+msgstr "lato {side} di questo PC"
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid ", {part} third"
+msgstr ", terzo {part}"
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid "Current pressure {pressure} of {threshold} pointer units at the {edge} edge."
+msgstr "Pressione attuale {pressure} su {threshold} unità del puntatore sul bordo {edge}."
+
+#: win_app/diagram.py
+#, python-brace-format
+msgid "No push. Current pressure is 0 of {threshold} pointer units."
+msgstr "Nessuna spinta. La pressione attuale è 0 su {threshold} unità del puntatore."
+
+#: win_app/firewall_win.py win_app/linux_stand_ins.py
+msgid "Check again"
+msgstr "Controlla di nuovo"
+
+#: win_app/firewall_win.py
+msgid "Fix the firewall"
+msgstr "Correggi il firewall"
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Beamer could not read the Windows Firewall: {error}"
+msgstr "Beamer non è riuscito a leggere Windows Firewall: {error}"
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rule for private networks."
+msgstr "Windows Firewall blocca Beamer sulla porta {port}. Succede quando si preme Annulla nella richiesta di Windows \"consenti questa app\", e una regola di blocco prevale su qualsiasi regola di consenso, quindi reinstallare non la elimina. La correzione rimuove il blocco e aggiunge la regola giusta per le reti private."
+
+#: win_app/firewall_win.py
+msgid "Trust this network"
+msgstr "Considera attendibile questa rete"
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "{sentence} Beamer is not running as administrator, so it cannot make this change itself: quit Beamer and open it again from the Start menu."
+msgstr "{sentence} Beamer non è in esecuzione come amministratore, quindi non può fare questa modifica da solo: esci da Beamer e aprilo di nuovo dal menu Start."
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will say this PC is unreachable. This happens when the installer was run without administrator rights. Fixing it adds the rule for private networks."
+msgstr "Windows Firewall non ha una regola che consenta agli altri tuoi computer di raggiungere Beamer sulla porta {port}, quindi diranno che questo PC non è raggiungibile. Succede quando il programma di installazione è stato eseguito senza diritti di amministratore. La correzione aggiunge la regola per le reti private."
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."
+msgstr "Windows considera {names} una rete pubblica, quindi la regola del firewall di Beamer non vale lì e gli altri tuoi computer non possono entrare. Considerarla attendibile la contrassegna come privata, e li lascia entrare senza aprire la porta su ogni altra rete a cui si collega questo PC."
+
+#: win_app/firewall_win.py
+msgid "this private network"
+msgstr "questa rete privata"
+
+#: win_app/firewall_win.py
+msgid "this network"
+msgstr "questa rete"
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Beamer's firewall rule does not apply on this network (Windows calls it {names}). Fixing it rewrites the rule to cover it."
+msgstr "La regola del firewall di Beamer non vale su questa rete (Windows la chiama {names}). La correzione riscrive la regola per includerla."
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for {rules}, so {effects}. Installs made before these rules existed are missing them. Fixing it adds what is missing and leaves the working rules alone."
+msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer sulla porta {port}, ma non c'è una regola per {rules}, quindi {effects}. Le installazioni precedenti a queste regole ne sono prive. La correzione aggiunge ciò che manca e lascia invariate le regole funzionanti."
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine discover this PC."
+msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer sulla porta {port} su {where}, e consente a un nuovo computer di trovare questo PC."
+
+#: win_app/global_shortcut_portal.py
+msgid "Send input to another machine"
+msgstr "Invia input a un altro computer"
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer's website"
+msgstr "Sito di Beamer"
+
+#: win_app/kvm_bridge_win.py
+msgid "Receiver stopped"
+msgstr "Ricevitore fermo"
+
+#: win_app/kvm_bridge_win.py
+msgid "Waiting for a machine"
+msgstr "In attesa di un computer"
+
+#: win_app/kvm_bridge_win.py
+msgid "Machine connected"
+msgstr "Computer connesso"
+
+#: win_app/kvm_bridge_win.py
+msgid "Receiver needs attention"
+msgstr "Il ricevitore richiede attenzione"
+
+#: win_app/kvm_bridge_win.py
+msgid "Stopped"
+msgstr "Fermo"
+
+#: win_app/kvm_bridge_win.py
+msgid "Connected"
+msgstr "Connesso"
+
+#: win_app/kvm_bridge_win.py
+msgid "Error"
+msgstr "Errore"
+
+#: win_app/kvm_bridge_win.py
+msgid "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."
+msgstr "Su un Mac, Ctrl arriva come Comando e il tasto Windows come Control, quindi Ctrl+C copia anche lì. Tra due PC ogni tasto arriva com'è."
+
+#: win_app/kvm_bridge_win.py
+msgid "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."
+msgstr "Su un Mac, ogni tasto arriva come il tasto Mac nella stessa posizione: Ctrl come Control, il tasto Windows come Comando. Tra due PC ogni tasto arriva com'è."
+
+#: win_app/kvm_bridge_win.py
+msgid "To a Mac: Alt becomes Command and Win becomes Option; Ctrl stays Control."
+msgstr "Verso un Mac: Alt diventa Comando e Win diventa Opzione; Ctrl resta Control."
+
+#: win_app/kvm_bridge_win.py
+msgid "These keep working on this PC while its input is on another machine: a mouse's back button for this PC's browser, say, or a volume key for its speakers."
+msgstr "Questi continuano a funzionare su questo PC mentre il suo input è su un altro computer: per esempio il tasto Indietro del mouse per il browser di questo PC, o un tasto del volume per i suoi altoparlanti."
+
+#: win_app/kvm_bridge_win.py
+msgid "Nothing yet. Every key and button goes to the machine that has input. Add one to keep it here: a mouse's back button for this PC's browser, say, or a volume key for its speakers."
+msgstr "Ancora nulla. Ogni tasto e pulsante va al computer che ha l'input. Aggiungine uno per tenerlo qui: per esempio il tasto Indietro del mouse per il browser di questo PC, o un tasto del volume per i suoi altoparlanti."
+
+#: win_app/kvm_bridge_win.py
+msgid "Top-left"
+msgstr "In alto a sinistra"
+
+#: win_app/kvm_bridge_win.py
+msgid "Top-right"
+msgstr "In alto a destra"
+
+#: win_app/kvm_bridge_win.py
+msgid "Bottom-left"
+msgstr "In basso a sinistra"
+
+#: win_app/kvm_bridge_win.py
+msgid "Bottom-right"
+msgstr "In basso a destra"
+
+#: win_app/kvm_bridge_win.py
+msgid "Mac keyboard layout"
+msgstr "Layout tastiera Mac"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Sets the effect's playback time. Current value: {value}."
+msgstr "Imposta il tempo di riproduzione dell'effetto. Valore attuale: {value}."
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Sets effect depth relative to the shorter screen edge. Current value: {value}."
+msgstr "Imposta la profondità dell'effetto rispetto al lato più corto dello schermo. Valore attuale: {value}."
+
+#: win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Only on this computer"
+msgstr "Solo su questo computer"
+
+#: win_app/kvm_bridge_win.py win_app/machines_win.py
+msgid "Only on this PC"
+msgstr "Solo su questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "Linux permissions"
+msgstr "Permessi Linux"
+
+#: win_app/kvm_bridge_win.py
+msgid "Send input — Input Capture"
+msgstr "Invia input: Acquisizione input"
+
+#: win_app/kvm_bridge_win.py
+msgid "Receive input — Remote Desktop"
+msgstr "Ricevi input: Desktop remoto"
+
+#: win_app/kvm_bridge_win.py
+msgid "Tray"
+msgstr "Area di notifica"
+
+#: win_app/kvm_bridge_win.py
+msgid "Show in tray"
+msgstr "Mostra nell'area di notifica"
+
+#: win_app/kvm_bridge_win.py
+msgid "Keyboard and mouse"
+msgstr "Tastiera e mouse"
+
+#: win_app/kvm_bridge_win.py
+msgid "Send input across"
+msgstr "Invia input"
+
+#: win_app/kvm_bridge_win.py
+msgid "Switch on This PC drives it for a machine above to send input from here."
+msgstr "Attiva Questo PC lo controlla per un computer qui sopra per inviare l'input da qui."
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland the desktop lets input go to another machine only when the pointer pushes through an edge, so this button cannot send it."
+msgstr "Su Wayland il desktop lascia passare l'input a un altro computer solo quando il puntatore spinge attraverso un bordo, quindi questo pulsante non può inviarlo."
+
+#: win_app/kvm_bridge_win.py
+msgid "Hold this PC's edges while an app on it is full screen"
+msgstr "Blocca i bordi di questo PC mentre un'app è a schermo intero"
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC's pointer hides while it drives another machine, and after another machine stops driving it, until its own mouse moves."
+msgstr "Il puntatore di questo PC si nasconde mentre controlla un altro computer, e dopo che un altro computer smette di controllarlo, finché il suo mouse non si muove."
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an edge, so the edges are never held for one and a drag can cross."
+msgstr "Su Wayland Beamer non vede un'app a schermo intero, né un pulsante del mouse tenuto premuto prima che il puntatore raggiunga un bordo, quindi i bordi non vengono mai bloccati per un'app e un trascinamento può passare."
+
+#: win_app/kvm_bridge_win.py
+msgid "At sign-in"
+msgstr "All'accesso"
+
+#: win_app/kvm_bridge_win.py
+msgid "Start Beamer when you sign in"
+msgstr "Apri Beamer all'accesso"
+
+#: win_app/kvm_bridge_win.py
+msgid "Windows could not identify the signed-in account, so start at sign-in is unavailable."
+msgstr "Windows non è riuscito a identificare l'account connesso, quindi l'avvio all'accesso non è disponibile."
+
+#: win_app/kvm_bridge_win.py
+msgid "In the tray, with no window."
+msgstr "Nell'area di notifica, senza finestra."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"
+msgstr "Alt-clic su uno schermo per dividerlo o raggrupparlo · trascina per spostare · fai clic su un terzo di un bordo illuminato per escluderlo · trascina un angolo per ridimensionare"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "Back to This PC"
+msgstr "Torna a questo PC"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Earlier ways"
+msgstr "Vie precedenti"
+
+#: win_app/kvm_bridge_win.py win_app/pages_win.py
+#, python-brace-format
+msgid "hold {key}"
+msgstr "tieni premuto {key}"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "double-tap {key}"
+msgstr "tocca due volte {key}"
+
+#: win_app/kvm_bridge_win.py
+msgid "Don't cross while dragging with this PC's pointer"
+msgstr "Non passare mentre trascini con il puntatore di questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "Switches the moment this PC's pointer touches the edge. Each screen supplies its own zones."
+msgstr "Passa nell'istante in cui il puntatore di questo PC tocca il bordo. Ogni schermo fornisce le proprie zone."
+
+#: win_app/kvm_bridge_win.py
+msgid "Reverse scrolling from other machines"
+msgstr "Inverti lo scorrimento degli altri computer"
+
+#: win_app/kvm_bridge_win.py
+msgid "Stays on this PC"
+msgstr "Resta su questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland the shortcut only brings input back: the desktop lets input go to another machine only when the pointer pushes through an edge, and keys on the Stays on this PC list cannot stay here while input is away."
+msgstr "Su Wayland la scorciatoia riporta solo indietro l'input: il desktop lascia passare l'input a un altro computer solo quando il puntatore spinge attraverso un bordo, e i tasti nell'elenco Resta su questo PC non possono restare qui mentre l'input è altrove."
+
+#: win_app/kvm_bridge_win.py
+msgid "Send input out with Super+Shift+B"
+msgstr "Invia input altrove con Super+Maiusc+B"
+
+#: win_app/kvm_bridge_win.py
+msgid "From here, where the double-tap cannot be seen, the key combination pushes the pointer through the edge to the machine the shortcut goes to. The desktop asks once to allow it, and its keyboard settings can change the keys."
+msgstr "Da qui, dove il doppio tocco non è visibile, la combinazione di tasti spinge il puntatore attraverso il bordo verso il computer a cui va la scorciatoia. Il desktop chiede una volta di consentirlo, e le sue impostazioni della tastiera possono cambiare i tasti."
+
+#: win_app/kvm_bridge_win.py
+msgid "None: this PC keeps its own Design."
+msgstr "Nessuno: questo PC mantiene il proprio Aspetto."
+
+#: win_app/kvm_bridge_win.py
+msgid "System follows your Linux desktop's light or dark setting."
+msgstr "Sistema segue l'impostazione chiara o scura del desktop Linux."
+
+#: win_app/kvm_bridge_win.py
+msgid "System follows Windows' light or dark setting."
+msgstr "Sistema segue l'impostazione chiara o scura di Windows."
+
+#: win_app/kvm_bridge_win.py
+msgid "Animate crossings on this PC"
+msgstr "Anima i passaggi su questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "Jump arrivals use this screen's landing animation too."
+msgstr "Anche gli arrivi da salto usano l'animazione di arrivo di questo schermo."
+
+#: win_app/kvm_bridge_win.py
+msgid "For shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style."
+msgstr "Per gli arrivi da scorciatoia, menu e salto. Come il passaggio usa lo stile di passaggio di questo schermo."
+
+#: win_app/kvm_bridge_win.py
+msgid "For the crossing and the shortcut alike"
+msgstr "Sia per il passaggio sia per la scorciatoia"
+
+#: win_app/kvm_bridge_win.py
+msgid "Addresses"
+msgstr "Indirizzi"
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC's address"
+msgstr "Indirizzo di questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC's listening port"
+msgstr "Porta di ascolto di questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "Save and reconnect"
+msgstr "Salva e riconnetti"
+
+#: win_app/kvm_bridge_win.py
+msgid "Saved."
+msgstr "Salvato."
+
+#: win_app/kvm_bridge_win.py
+msgid "Linux firewall"
+msgstr "Firewall Linux"
+
+#: win_app/kvm_bridge_win.py win_app/linux_stand_ins.py
+msgid "Beamer's firewall check is not yet on Linux."
+msgstr "Il controllo del firewall di Beamer non è ancora disponibile su Linux."
+
+#: win_app/kvm_bridge_win.py
+msgid "Windows Firewall"
+msgstr "Windows Firewall"
+
+#: win_app/kvm_bridge_win.py
+msgid "Checking Windows Firewall…"
+msgstr "Verifica di Windows Firewall…"
+
+#: win_app/kvm_bridge_win.py
+msgid "Checking…"
+msgstr "Verifica…"
+
+#: win_app/kvm_bridge_win.py
+msgid "Fixing…"
+msgstr "Correzione…"
+
+#: win_app/kvm_bridge_win.py
+msgid "This PC drives machines"
+msgstr "Questo PC controlla gli altri computer"
+
+#: win_app/kvm_bridge_win.py
+msgid "Machines drive this PC"
+msgstr "Gli altri computer controllano questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "On this PC"
+msgstr "Su questo PC"
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer requests keyboard and pointer access when each Wayland session starts."
+msgstr "Beamer chiede l'accesso a tastiera e puntatore all'inizio di ogni sessione Wayland."
+
+#: win_app/kvm_bridge_win.py win_app/pages_win.py
+msgid "Not requested"
+msgstr "Non richiesto"
+
+#: win_app/kvm_bridge_win.py
+msgid "Ask again"
+msgstr "Chiedi di nuovo"
+
+#: win_app/kvm_bridge_win.py
+msgid "Input:"
+msgstr "Input:"
+
+#: win_app/kvm_bridge_win.py
+msgid "Delay:"
+msgstr "Ritardo:"
+
+#: win_app/kvm_bridge_win.py
+msgid "Start at sign-in needs the same administrator account that runs Beamer."
+msgstr "L'avvio all'accesso richiede lo stesso account amministratore che esegue Beamer."
+
+#: win_app/kvm_bridge_win.py
+msgid "Each chip is a side of this screen; click one to add or remove it. The side a machine touches crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. A corner is a diagonal push, shown as a square on the map."
+msgstr "Ogni etichetta è un lato di questo schermo; fai clic per aggiungerlo o toglierlo. Il lato toccato da un computer fa passare sui suoi terzi illuminati; ogni altro lato libero rimanda a esso, arrivando sul lato opposto. Un angolo è una spinta in diagonale, mostrata come un quadrato sulla mappa."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "Push back the way you came: where an edge leads back to This PC"
+msgstr "Spingi indietro per la stessa via: dove un bordo riporta a questo PC"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "This PC keeps its own ways"
+msgstr "Questo PC mantiene le proprie vie"
+
+#: win_app/kvm_bridge_win.py
+msgid "Follows this PC's mouse or trackpad on every screen; each screen supplies its own zones."
+msgstr "Segue il mouse o il trackpad di questo PC su ogni schermo; ogni schermo fornisce le proprie zone."
+
+#: win_app/kvm_bridge_win.py
+msgid "For the trackpad or mouse of whichever machine drives this PC."
+msgstr "Per il trackpad o il mouse del computer che controlla questo PC."
+
+#: win_app/kvm_bridge_win.py
+msgid "That could not be saved, so the list is unchanged."
+msgstr "Impossibile salvarlo, quindi l'elenco è invariato."
+
+#: win_app/kvm_bridge_win.py
+msgid "Shortcut key"
+msgstr "Tasto della scorciatoia"
+
+#: win_app/kvm_bridge_win.py
+msgid "That key cannot be the shortcut. Choose a modifier such as Right Ctrl, a function key, or a key like Insert or Scroll Lock."
+msgstr "Quel tasto non può essere la scorciatoia. Scegli un modificatore come Ctrl destro, un tasto funzione, o un tasto come Ins o Bloc Scorr."
+
+#: win_app/kvm_bridge_win.py
+msgid "Sets depth relative to the shorter screen edge."
+msgstr "Imposta la profondità rispetto al lato più corto dello schermo."
+
+#: win_app/kvm_bridge_win.py
+msgid "On Wayland the desktop does not let Beamer draw at the edges of the screen, so crossings show no effect on this machine. The other machines still show theirs."
+msgstr "Su Wayland il desktop non consente a Beamer di disegnare ai bordi dello schermo, quindi i passaggi non mostrano effetti su questo computer. Gli altri computer mostrano comunque i loro."
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Current chain: {names}"
+msgstr "Catena attuale: {names}"
+
+#: win_app/kvm_bridge_win.py
+msgid "Pairing is not available: this PC's settings could not be read."
+msgstr "L'abbinamento non è disponibile: impossibile leggere le impostazioni di questo PC."
+
+#: win_app/kvm_bridge_win.py
+msgid "The QR holds this PC's address, so it is not shown while Hide addresses is on."
+msgstr "Il QR contiene l'indirizzo di questo PC, quindi non viene mostrato mentre Nascondi indirizzi è attivo."
+
+#: win_app/kvm_bridge_win.py
+msgid "Hides every IP and hardware address in this window and the tray."
+msgstr "Nasconde ogni indirizzo IP e hardware in questa finestra e nell'area di notifica."
+
+#: win_app/kvm_bridge_win.py
+msgid "Not known yet"
+msgstr "Non ancora noto"
+
+#: win_app/kvm_bridge_win.py
+msgid "With it off, closing the window quits Beamer. Open Beamer again to bring the window back."
+msgstr "Se disattivato, chiudere la finestra chiude Beamer. Apri di nuovo Beamer per riavere la finestra."
+
+#: win_app/kvm_bridge_win.py
+msgid "This desktop has no system tray, so Beamer's window is all there is: closing it quits Beamer."
+msgstr "Questo desktop non ha un'area di notifica, quindi la finestra di Beamer è tutto ciò che c'è: chiuderla chiude Beamer."
+
+#: win_app/kvm_bridge_win.py
+msgid "Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps."
+msgstr "Si avvia con privilegi elevati all'accesso senza richiesta UAC, così Beamer può inviare input alle app amministratore."
+
+#: win_app/kvm_bridge_win.py
+msgid "Seam crossings need X11 on Linux."
+msgstr "Il passaggio tra le giunture richiede X11 su Linux."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "These ways could not be saved. Try again."
+msgstr "Impossibile salvare queste vie. Riprova."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Shortcut: {shortcut} (set in {link})"
+msgstr "Scorciatoia: {shortcut} (si imposta in {link})"
+
+#: win_app/kvm_bridge_win.py
+msgid "That position cannot connect this machine."
+msgstr "Quella posizione non può collegare questo computer."
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{value} px"
+msgstr "{value} px"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{value} ms"
+msgstr "{value} ms"
+
+#: win_app/kvm_bridge_win.py
+msgid "The effects stopped working and are off until Beamer restarts, so crossings show Glow in the same colours. The log says why."
+msgstr "Gli effetti hanno smesso di funzionare e restano disattivati fino al riavvio di Beamer, quindi i passaggi mostrano Bagliore con gli stessi colori. Il registro spiega perché."
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer could not save the removal. Try again in a moment."
+msgstr "Beamer non è riuscito a salvare la rimozione. Riprova tra un momento."
+
+#: win_app/kvm_bridge_win.py
+msgid "port must be an integer from 1 to 65535"
+msgstr "la porta deve essere un numero intero da 1 a 65535"
+
+#: win_app/kvm_bridge_win.py
+msgid "Save failed"
+msgstr "Salvataggio non riuscito"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "<b>Beamer {version}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br><a href=\"{url}\" style=\"color: {colour};\">{link}</a>"
+msgstr "<b>Beamer {version}</b><br>Una sola tastiera e un solo mouse per tutti i tuoi Mac e PC.<br><br><a href=\"{url}\" style=\"color: {colour};\">{link}</a>"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Ready on TCP port {port}"
+msgstr "Pronto sulla porta TCP {port}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid ""
+"Beamer {version}\n"
+"{link}"
+msgstr ""
+"Beamer {version}\n"
+"{link}"
+
+#: win_app/kvm_bridge_win.py
+msgid "When enabled, a logon task starts Beamer elevated without a UAC prompt, so it can send input to administrator apps."
+msgstr "Se attivo, un'attività all'accesso avvia Beamer con privilegi elevati senza richiesta UAC, così può inviare input alle app amministratore."
+
+#: win_app/kvm_bridge_win.py
+msgid "Only the installed app can start at sign-in."
+msgstr "Solo l'app installata può avviarsi all'accesso."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "These ways could not be changed."
+msgstr "Impossibile modificare queste vie."
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "This desk is full. Remove an unused profile before adding more ways."
+msgstr "Questa scrivania è piena. Rimuovi un profilo inutilizzato prima di aggiungere altre vie."
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{version} · only sees which side"
+msgstr "{version} · vede solo il lato"
+
+#. {side} is the direction of this screen's edge.
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Follows this PC's mouse or trackpad on every screen; each screen supplies its own zones. This screen's {side} edge lights to show the resistance."
+msgstr "Segue il mouse o il trackpad di questo PC su ogni schermo; ogni schermo fornisce le proprie zone. Il bordo {side} di questo schermo si illumina per mostrare la resistenza."
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Remove {key}"
+msgstr "Rimuovi {key}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Pairing is not available: {error}"
+msgstr "L'abbinamento non è disponibile: {error}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "This PC's address: {address} · port {port}"
+msgstr "Indirizzo di questo PC: {address} · porta {port}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Beamer — {status}: {detail}"
+msgstr "Beamer — {status}: {detail}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Could not save this PC's name: {error}"
+msgstr "Impossibile salvare il nome di questo PC: {error}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Windows refused: {error}"
+msgstr "Windows ha rifiutato: {error}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Nearby pairing could not continue: {error}"
+msgstr "L'abbinamento nelle vicinanze non è potuto proseguire: {error}"
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "Could not reload the configuration: {error}"
+msgstr "Impossibile ricaricare la configurazione: {error}"
+
+# New in 1.5.5: awaiting Lorenzo's check
+#: win_app/kvm_bridge_win.py
+msgid "Give the profile a name of 1 to 32 characters."
+msgstr "Dai al profilo un nome da 1 a 32 caratteri."
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "{blurb} It plays around the pointer when the shortcut or a menu brings input to this PC."
+msgstr "{blurb} Appare attorno al puntatore quando la scorciatoia o un menu porta l'input su questo PC."
+
+#: win_app/kvm_bridge_win.py
+#, python-brace-format
+msgid "the change failed: {error}"
+msgstr "la modifica non è riuscita: {error}"
+
+#: win_app/machines_win.py
+msgid "Pairing code"
+msgstr "Codice di abbinamento"
+
+#: win_app/machines_win.py
+msgid "Off on this PC: no input or settings link to this machine. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect."
+msgstr "Disattivato su questo PC: nessun collegamento di input o di impostazioni con questo computer. Abbinamento, direzioni, vie e tasto di salto restano. Riattivalo qui per riconnetterti."
+
+#: win_app/machines_win.py
+msgid "This PC drives it"
+msgstr "Questo PC lo controlla"
+
+#: win_app/machines_win.py
+msgid "Input moves only when this PC enables this switch and the other machine enables It drives this PC."
+msgstr "L'input passa solo quando questo PC attiva questo interruttore e l'altro computer attiva Controlla questo PC."
+
+#: win_app/machines_win.py
+msgid "It drives this PC"
+msgstr "Controlla questo PC"
+
+#: win_app/machines_win.py
+msgid "Input moves only when the other machine enables This machine drives it and this PC enables this switch."
+msgstr "L'input passa solo quando l'altro computer attiva Questo computer lo controlla e questo PC attiva questo interruttore."
+
+#: win_app/machines_win.py
+msgid "QR code for the pairing code"
+msgstr "Codice QR del codice di abbinamento"
+
+#: win_app/machines_win.py
+msgid "Time left"
+msgstr "Tempo rimanente"
+
+#: win_app/machines_win.py
+msgid "Nearby pairing status"
+msgstr "Stato dell'abbinamento nelle vicinanze"
+
+#: win_app/machines_win.py
+msgid "Nearby pairing time left"
+msgstr "Tempo rimanente per l'abbinamento nelle vicinanze"
+
+#: win_app/machines_win.py
+msgid "No other machine is showing a code yet."
+msgstr "Nessun altro computer sta ancora mostrando un codice."
+
+#: win_app/machines_win.py
+msgid "Address of the other machine"
+msgstr "Indirizzo dell'altro computer"
+
+#: win_app/machines_win.py
+msgid "Code"
+msgstr "Codice"
+
+#: win_app/machines_win.py
+msgid "Show a code on this PC"
+msgstr "Mostra un codice su questo PC"
+
+#: win_app/machines_win.py
+msgid "Pairing digits"
+msgstr "Cifre di abbinamento"
+
+#: win_app/machines_win.py
+msgid "Pairing…"
+msgstr "Abbinamento…"
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "{name}: {status}"
+msgstr "{name}: {status}"
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Off on this PC: no input or settings link to {name}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect."
+msgstr "Disattivato su questo PC: nessun collegamento di input o di impostazioni con {name}. Abbinamento, direzioni, vie e tasto di salto restano. Riattivalo qui per riconnetterti."
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Input moves only when this PC enables this switch and {name} enables It drives this PC."
+msgstr "L'input passa solo quando questo PC attiva questo interruttore e {name} attiva Controlla questo PC."
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Input moves only when {name} enables This PC drives it and this PC enables this switch."
+msgstr "L'input passa solo quando {name} attiva Questo PC lo controlla e questo PC attiva questo interruttore."
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Selected: {name} · {platform}"
+msgstr "Selezionato: {name} · {platform}"
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Remove {name}? {note}"
+msgstr "Rimuovere {name}? {note}"
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Off on this PC: {name} cannot connect or drive it. Turn it back on here to reconnect."
+msgstr "Disattivato su questo PC: {name} non può connettersi né controllarlo. Riattivalo qui per riconnetterti."
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Pairing digits {digits}"
+msgstr "Cifre di abbinamento {digits}"
+
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Pairing code {digits}"
+msgstr "Codice di abbinamento {digits}"
+
+#: win_app/pages_win.py
+msgid "This PC only."
+msgstr "Solo questo PC."
+
+#: win_app/pages_win.py
+msgid "Closing this window keeps Beamer running in the tray."
+msgstr "Chiudendo questa finestra Beamer resta attivo nell'area di notifica."
+
+#: win_app/pages_win.py
+msgid "Changes apply as you make them. Closing this window keeps Beamer running in the tray."
+msgstr "Le modifiche si applicano subito. Chiudendo questa finestra Beamer resta attivo nell'area di notifica."
+
+#: win_app/pages_win.py
+msgid "The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."
+msgstr "La scorciatoia riporta a casa o all'ultimo computer disponibile; se non è disponibile, un altro computer disponibile può ricevere l'input."
+
+#: win_app/pages_win.py
+msgid "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this PC's input for every destination."
+msgstr "Le vie qui sotto portano al computer selezionato. Il suo lato è condiviso con quel computer. Resistenza, protezione durante il trascinamento e Scorciatoia valgono per l'input di questo PC verso ogni destinazione."
+
+#: win_app/pages_win.py
+msgid "Used on this screen. Shared animation settings may follow another machine; Animate and window appearance stay on this PC."
+msgstr "Usato su questo schermo. Le impostazioni dell'animazione condivise possono seguire un altro computer; Anima i passaggi e aspetto della finestra restano su questo PC."
+
+#: win_app/pages_win.py
+msgid "Modifier keys and Stays here belong to this PC's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own."
+msgstr "Tasti modificatori e Resta qui riguardano l'input di questo PC. Velocità del puntatore e scorrimento riguardano questo schermo quando lo controlla un altro computer. Ogni computer mantiene i propri."
+
+#: win_app/pages_win.py
+msgid "Ready"
+msgstr "Pronto"
+
+#: win_app/pages_win.py
+msgid "Unavailable"
+msgstr "Non disponibile"
+
+#: win_app/pages_win.py
+msgid "top-left"
+msgstr "in alto a sinistra"
+
+#: win_app/pages_win.py
+msgid "top-right"
+msgstr "in alto a destra"
+
+#: win_app/pages_win.py
+msgid "bottom-left"
+msgstr "in basso a sinistra"
+
+#: win_app/pages_win.py
+msgid "bottom-right"
+msgstr "in basso a destra"
+
+#: win_app/pages_win.py
+msgid "This PC is always in the shortcut's cycle."
+msgstr "Questo PC è sempre nel ciclo della scorciatoia."
+
+#: win_app/pages_win.py
+msgid "to the right of this PC"
+msgstr "a destra di questo PC"
+
+#: win_app/pages_win.py
+msgid "to the left of this PC"
+msgstr "a sinistra di questo PC"
+
+#: win_app/pages_win.py
+msgid "above this PC"
+msgstr "sopra questo PC"
+
+#: win_app/pages_win.py
+msgid "below this PC"
+msgstr "sotto questo PC"
+
+#: win_app/pages_win.py
+msgid "The machines paired with this PC, where input is right now, and the controls you reach for every day. Pair a machine here first."
+msgstr "I computer abbinati a questo PC, dove si trova ora l'input, e i controlli che usi ogni giorno. Abbina prima qui un computer."
+
+#: win_app/pages_win.py
+msgid "Choose how the pointer or a key moves input to each machine, and how hard the edge pushes back first."
+msgstr "Scegli come il puntatore o un tasto sposta l'input verso ogni computer, e quanto resiste prima il bordo."
+
+#: win_app/pages_win.py
+msgid "How this PC's Ctrl and Windows keys arrive on another machine, the keys and buttons that stay here, and how fast another machine's pointer moves here."
+msgstr "Come arrivano i tasti Ctrl e Windows di questo PC su un altro computer, i tasti e pulsanti che restano qui, e quanto velocemente si muove qui il puntatore di un altro computer."
+
+#: win_app/pages_win.py
+msgid "How crossing looks on this PC: the light as you push toward another machine, and where the pointer lands."
+msgstr "Come appare il passaggio su questo PC: la luce mentre spingi verso un altro computer, e dove arriva il puntatore."
+
+#: win_app/pages_win.py
+msgid "This PC's network access, address and listening port; hide addresses in this window and tray."
+msgstr "Accesso alla rete, indirizzo e porta di ascolto di questo PC; nascondi gli indirizzi in questa finestra e nell'area di notifica."
+
+#: win_app/pages_win.py
+msgid "Not paired yet, so no edge or shortcut moves input until you pair a machine above."
+msgstr "Non ancora abbinato, quindi nessun bordo o scorciatoia sposta l'input finché non abbini un computer qui sopra."
+
+#: win_app/pages_win.py
+msgid "Above"
+msgstr "Sopra"
+
+#: win_app/pages_win.py
+msgid "Below"
+msgstr "Sotto"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{place} is not one of this PC's ways in, so this only shows how it would look. Turn it on under Crossing."
+msgstr "{place} non è una delle vie d'ingresso di questo PC, quindi qui vedi solo come apparirebbe. Attivalo in Passaggio."
+
+#. {side} is the direction of the screen edge.
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{names} already cross from the {side} edge of this PC. The thirds you pick go to {name}; the rest stay where they are."
+msgstr "{names} passano già dal bordo {side} di questo PC. I terzi che scegli vanno a {name}; gli altri restano dove sono."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Not learned yet: choose a side here or on {name}."
+msgstr "Non ancora rilevato: scegli un lato qui o su {name}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{key}, twice"
+msgstr "{key}, due volte"
+
+#. Several ways to move input, offered as alternatives.
+#: win_app/pages_win.py
+#, python-brace-format
+msgctxt "ways list"
+msgid "{head} or {last}"
+msgstr "{head} o {last}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you {ways}."
+msgstr "L'input passa a {name} quando {ways}."
+
+#: win_app/pages_win.py
+msgid "The order follows the tiles from top to bottom, then left to right. This PC is always in the cycle."
+msgstr "L'ordine segue i riquadri dall'alto in basso, poi da sinistra a destra. Questo PC è sempre nel ciclo."
+
+#: win_app/pages_win.py
+msgid "Choose which machines join the cycle with the tick boxes on their tiles."
+msgstr "Scegli quali computer entrano nel ciclo con le caselle sui loro riquadri."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{first} {second} {third}"
+msgstr "{first} {second} {third}"
+
+#. {side} is the direction of the screen edge.
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{names} already crosses from the {side} edge of this PC. The thirds you pick go to {name}; the rest stay with {holder}."
+msgstr "{names} passa già dal bordo {side} di questo PC. I terzi che scegli vanno a {name}; gli altri restano a {holder}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Waiting to hear from {name}. This PC cannot push into it until it has connected once."
+msgstr "In attesa di notizie da {name}. Questo PC non può spingere verso di esso finché non si è connesso almeno una volta."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "This PC does not drive {name}, so edges and the shortcut do nothing."
+msgstr "Questo PC non controlla {name}, quindi i bordi e la scorciatoia non fanno nulla."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Not connected to {name}, so edges and the shortcut do nothing yet. Check that it is switched on and lets this PC drive it."
+msgstr "Non connesso a {name}, quindi i bordi e la scorciatoia non fanno ancora nulla. Controlla che sia acceso e che si lasci controllare da questo PC."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{key}, held"
+msgstr "{key}, tenuto premuto"
+
+#. Two ways to move input, offered as alternatives.
+#: win_app/pages_win.py
+#, python-brace-format
+msgctxt "ways list"
+msgid "{first} or {last}"
+msgstr "{first} o {last}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Nothing moves input to {name} until this PC knows which side it is on."
+msgstr "Nulla sposta l'input verso {name} finché questo PC non sa da che lato si trova."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Nothing moves input to {name}: choose at least one way below."
+msgstr "Nulla sposta l'input verso {name}: scegli almeno una via qui sotto."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you {ways}. The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."
+msgstr "L'input passa a {name} quando {ways}. La scorciatoia riporta a casa o all'ultimo computer disponibile; se non è disponibile, un altro computer disponibile può ricevere l'input."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through {ways}"
+msgstr "spingi attraverso {ways}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{action}."
+msgstr "{action}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{shortcut}."
+msgstr "{shortcut}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Not placed yet: {machines}"
+msgstr "Ancora da posizionare: {machines}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{name} is {position}"
+msgstr "{name} è {position}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{first} {second}"
+msgstr "{first} {second}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you press {key} twice. Its edges and corner wait until this PC knows which side {name} is on."
+msgstr "L'input passa a {name} quando premi due volte {key}. I suoi bordi e il suo angolo attendono finché questo PC non sa da che lato si trova {name}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through the whole {edge} edge"
+msgstr "spingi attraverso l'intero bordo {edge}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through {parts}"
+msgstr "spingi attraverso {parts}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push diagonally into the {corner} corner"
+msgstr "spingi in diagonale nell'angolo {corner}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "No edge or corner leads to {name} yet: choose one below. The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."
+msgstr "Nessun bordo o angolo porta ancora a {name}: scegline uno qui sotto. La scorciatoia riporta a casa o all'ultimo computer disponibile; se non è disponibile, un altro computer disponibile può ricevere l'input."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "No edge or corner leads to {name} yet: choose one below."
+msgstr "Nessun bordo o angolo porta ancora a {name}: scegline uno qui sotto."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "push through {ways} to reach {name}"
+msgstr "spingi attraverso {ways} per raggiungere {name}"
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{shortcut}, or {action}."
+msgstr "{shortcut}, oppure {action}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{machines}."
+msgstr "{machines}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "{line}."
+msgstr "{line}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "Input moves to {name} when you hold {key}. Its edges and corner wait until this PC knows which side {name} is on."
+msgstr "L'input passa a {name} quando tieni premuto {key}. I suoi bordi e il suo angolo attendono finché questo PC non sa da che lato si trova {name}."
+
+#: win_app/pages_win.py
+#, python-brace-format
+msgid "press {key} twice"
+msgstr "premi due volte {key}"
+
+#: win_app/peers_view.py
+msgid "Driving this PC"
+msgstr "Controlla questo PC"
+
+#: win_app/peers_view.py
+#, python-brace-format
+msgid "{name} is not in use on this PC."
+msgstr "{name} non è in uso su questo PC."
+
+#: win_app/peers_view.py
+#, python-brace-format
+msgid "{name}'s keyboard and pointer are on this PC. Push the pointer back through the edge it arrived by to send them home."
+msgstr "La tastiera e il puntatore di {name} sono su questo PC. Riporta il puntatore attraverso il bordo da cui è arrivato per rimandarli a casa."
+
+#: win_app/peers_view.py
+#, python-brace-format
+msgid "This PC's keyboard and pointer are on {name}. Do the same again to bring them home."
+msgstr "La tastiera e il puntatore di questo PC sono su {name}. Ripeti la stessa azione per riportarli a casa."
+
+#: win_app/sender.py
+msgid "Not connected"
+msgstr "Non connesso"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} does not accept input from this one"
+msgstr "{name} non accetta input da questo computer"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} sent the input back"
+msgstr "{name} ha rimandato indietro l'input"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} would not take the input"
+msgstr "{name} non ha accettato l'input"
+
+#: win_app/sender.py
+msgid "Cannot switch — on this desktop input goes to another machine only by pushing the pointer through an edge"
+msgstr "Impossibile passare: su questo desktop l'input va a un altro computer solo spingendo il puntatore attraverso un bordo"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {name} could not be reached"
+msgstr "Impossibile passare: impossibile raggiungere {name}"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {name} could not be reached while this PC is being driven"
+msgstr "Impossibile passare: impossibile raggiungere {name} mentre questo PC è controllato"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — {reason}"
+msgstr "Impossibile passare: {reason}"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{other} took over {name}"
+msgstr "{other} ha preso il controllo di {name}"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "{name} returned the input"
+msgstr "{name} ha restituito l'input"
+
+#: win_app/sender.py
+#, python-brace-format
+msgid "Cannot switch — the desktop did not let Beamer send input to {name}"
+msgstr "Impossibile passare: il desktop non ha consentito a Beamer di inviare input a {name}"
+
+#: win_app/widgets.py
+msgid "Response time: no fresh measurement"
+msgstr "Tempo di risposta: nessuna misura recente"
+
+#: win_app/widgets.py
+msgid "Response time: disconnected"
+msgstr "Tempo di risposta: disconnesso"
+
+#: win_app/widgets.py
+#, python-brace-format
+msgid "{name}, {key}"
+msgstr "{name}, {key}"
+
+#: win_app/widgets.py
+#, python-brace-format
+msgid "{name}, {choice}"
+msgstr "{name}, {choice}"
+
+#: win_app/widgets.py
+#, python-brace-format
+msgid "{name}, selected"
+msgstr "{name}, selezionato"
diff --git a/mac_app/bridge.py b/mac_app/bridge.py
index f568e3d..42cfc85 100644
--- a/mac_app/bridge.py
+++ b/mac_app/bridge.py
@@ -1,6 +1,7 @@
import collections
import copy
import errno
+import inspect
import logging
import platform
import queue
@@ -26,6 +27,8 @@ import gestures
from core import idle_pointer
from core import ignored
from core import crossing_state
+from core import profiles
+from core import shake
from core import effects
import frame_clock
import keyboard_layout
@@ -39,6 +42,7 @@ from core import special_keys
from core import receiver
from core import settings_sync
from core import ways
+from core.i18n import N_, tr
from pointer_hide import PointerHider
from key_codes import (
KEY_NAME_TO_CODE,
@@ -66,22 +70,25 @@ SSH_FALLBACK_PORT = 24822
DESKTOP_BOUNDS_MAX_AGE_SECONDS = 1.0
CROSSING_RETRY_SECONDS = 30.0
TAP_HID_STALL_SECONDS = 2.0
+# The HID event time is rebuilt from an age read a moment before this process's own clock, so an
+# event the tap has had can come out a few milliseconds newer than the tap's stamp for it.
+TAP_HID_CLOCK_SLACK_SECONDS = 0.25
ROUND_TRIP_SAMPLES = 8
ROUND_TRIP_MAX_AGE_SECONDS = 5.0
# A driven Mac that is asked to drive waits this long for its owner to let go (the responder ends
# the ownership by force after one second), then goes ahead.
LET_GO_WAIT_SECONDS = 1.3
OWN_PLATFORM = "macos"
-CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "displays", "ping_rtt")
+CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "ping_rtt")
MEDIA_KEY_NAMES = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause", "brightness_up", "brightness_down"})
# Why input came home, in words, for the alert. A why that is not here comes home quietly.
WHY_TEXT = {
- "not_allowed": "{name} does not accept input from this Mac",
- "malformed": "{name} could not read the request to take it",
- "refused": "{name} refused the input",
- "no_answer": "{name} did not answer",
- "link_lost": "Lost the link to {name}",
+ "not_allowed": N_("{name} does not accept input from this Mac"),
+ "malformed": N_("{name} could not read the request to take it"),
+ "refused": N_("{name} refused the input"),
+ "no_answer": N_("{name} did not answer"),
+ "link_lost": N_("Lost the link to {name}"),
}
@@ -101,6 +108,7 @@ NX_DEVICE_MODIFIER_BITS = {
0x3E: 0x2000,
}
CAPS_LOCK_KEY_CODE = 0x39
+INPUT_METHOD_KEY_CODES = frozenset({0x66, 0x68}) # Hanja and Han/Yeong, sent as taps
# Command, Option and Control, left and right. Shift and caps lock are
# excluded on purpose -- see _unicode_character.
CHORD_MODIFIER_KEY_CODES = frozenset({0x36, 0x37, 0x3A, 0x3B, 0x3D, 0x3E})
@@ -177,6 +185,11 @@ class QuartzEventTranslator:
)
if is_trigger:
return KeyResult(True, is_down, is_repeat, [])
+ name = SPECIAL_KEY_NAMES.get(keycode)
+ if name in ("hangul", "hanja"):
+ # Only the keyboard's own key: an input-source switch may post these keycodes itself.
+ physical = quartz.CGEventGetIntegerValueField(event, quartz.kCGEventSourceStateID) == quartz.kCGEventSourceStateHIDSystemState
+ return KeyResult(False, is_down, is_repeat, keytable.tap_messages(name, physical and is_down and not is_repeat))
special_messages = self._special_key_messages(keycode, is_down, key_map)
if special_messages:
return KeyResult(False, is_down, is_repeat, special_messages)
@@ -201,11 +214,14 @@ class QuartzEventTranslator:
data["us"] = PRINTABLE_KEY_FALLBACKS[keycode]
return KeyResult(False, is_down, is_repeat, [{"type": message_type, "data": data}])
- def mouse_messages(self, event_type, event):
+ def mouse_messages(self, event_type, event, motion=None):
quartz = self.quartz
if event_type in self.movement_event_types:
dx = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaX)
dy = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaY)
+ if motion is not None and motion(dx, dy):
+ self.reset_mouse_accumulators()
+ return []
self._move_accum_x += dx
self._move_accum_y += dy
int_x = int(self._move_accum_x) # truncates toward zero
@@ -507,6 +523,14 @@ class KVMController:
self._redirecting = bool(value)
if old != self._redirecting:
self.logger.info("redirecting %s -> %s (thread %s)", old, self._redirecting, threading.current_thread().name)
+ if self._redirecting:
+ self._refresh_shake()
+ if self._shake_enabled:
+ self.shake.arm(self.clock())
+ with self._shake_presses_lock:
+ self.shake.held(self.clock(), bool(self._shake_presses))
+ else:
+ self.shake.disarm()
if not self._redirecting:
self.pointer.show()
@@ -563,6 +587,14 @@ class KVMController:
self._cursor_assoc_status_logged = False
self._cursor_warp_error_logged = False
self._redirecting = False
+ self.shake = shake.ShakeDetector(shake.STROKE_MAC)
+ self.home_hold = shake.HomeHold()
+ self._shake_enabled = True
+ self._shake_presses = {}
+ self._shake_press_seq = 0
+ self._shake_presses_lock = threading.Lock()
+ self.desk_last_heard = {}
+ self.desk_link_times = {}
self._repair_lock = threading.Lock()
self._repair_running = False
self._repair_again = False
@@ -594,7 +626,7 @@ class KVMController:
self.capture_lock = threading.Lock()
self.capture_thread = None
self.input_error = None
- self._connection_status = "Waiting to connect"
+ self._connection_status = tr("Waiting to connect")
self.tap_ready = threading.Event()
self.event_tap = None
self.tap_source = None
@@ -609,6 +641,7 @@ class KVMController:
self.trigger_suppressed = False
self.redirect_started_at = 0.0
self._last_tap_event_at = self.clock()
+ self._hid_unseen_since = None
self._move_reason = None
self.ignore_gate = ignored.Gate(cfg.ignored_inputs)
# Crossing: the engine is pure and runs on the event-tap thread; the
@@ -709,6 +742,18 @@ class KVMController:
def zones_changed(self):
"""A machine's side or zones changed in the settings: the engine is built again from them."""
self.crossing = self._crossing_engine()
+ self._refresh_shake()
+
+ def publish_desk(self):
+ """Send every desk register changed since the last publish, whatever changed it: a crossing
+ event, a pairing, a peer removed, a load that reconciled. Receivers ignore one they hold."""
+ with self.book.lock:
+ desk = profiles.desk_message(self.book._load())
+ # The first publish sends the whole desk: it is what any linked peer was last told.
+ held, self._desk_published = getattr(self, "_desk_published", {}), desk
+ paths = profiles.changed_paths(held, desk)
+ if paths:
+ self._send_desk(profiles.desk_message({"crossing_desk": desk}, paths))
def crossing_capable(self):
known = getattr(self, "_crossing_known_caps", {})
@@ -747,7 +792,10 @@ class KVMController:
def crossing_event(self, handler, *args, arrived=None, **kwargs):
"""Compute and save atomically, releasing the book before taking responder locks."""
- capable = kwargs.setdefault("capable", self.crossing_capable())
+ capable = self.crossing_capable()
+ parameters = inspect.signature(handler).parameters
+ if "capable" in parameters or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in parameters.values()):
+ capable = kwargs.setdefault("capable", capable)
with self.book.lock:
outcome = handler(self.book._load(), *args, **kwargs)
self._save_crossing(outcome, capable)
@@ -755,7 +803,8 @@ class KVMController:
def carry_crossing(self, outcome, source=None, arrived=None, saved=False):
"""Save, rebuild and re-arm before publishing a crossing event's messages."""
- if not (outcome["changed"] or outcome["tell"] or outcome["send_picture"] or outcome["forward_picture"]):
+ if not (outcome["changed"] or outcome["tell"] or outcome["send_picture"] or outcome["forward_picture"]
+ or outcome.get("send_desk") or outcome.get("forward") or outcome.get("answer")):
return outcome
if outcome["changed"] and not saved:
capable = self.crossing_capable()
@@ -784,6 +833,76 @@ class KVMController:
self._send_crossing_picture(message["data"])
if outcome["forward_picture"] and arrived is not None:
self._send_crossing_picture(arrived, source=source)
+ self.publish_desk()
+ if outcome.get("forward"):
+ self._send_desk(outcome["forward"], source=source)
+ if outcome.get("answer") and source is not None:
+ self._send_desk(outcome["answer"], target=source)
+ return outcome
+
+ def profiles_capable(self):
+ known = getattr(self, "_profiles_known_caps", {})
+ known.update({peer: frozenset(link.caps) for peer, link in list(self._peers_up.items())})
+ if self.responder is not None:
+ known.update({protocol.id_text(peer): self.responder.caps_of(peer) or frozenset()
+ for peer in self.responder.links()})
+ peers = {entry.get("id") for entry in self.book.peers()}
+ self._profiles_known_caps = {peer: caps for peer, caps in known.items() if peer in peers}
+ return {peer for peer, caps in self._profiles_known_caps.items() if "profiles" in caps}
+
+ def _desk_envelope(self):
+ for message in self.announce():
+ if message.get("type") == protocol.MSG_SETTINGS:
+ return message["data"]
+ cfg = self.cfg
+ return settings_sync.message_data(cfg.same_on_both, cfg.same_set_at,
+ by=cfg.same_by or protocol.id_text(self.identity()["id"]), groups=cfg.same_groups)
+
+ def _send_desk(self, desk, source=None, target=None):
+ frames = profiles.frames(desk)
+ if not frames:
+ return
+ envelope = self._desk_envelope()
+ outbound = set()
+ for peer, link in list(self._peers_up.items()):
+ if peer == source or (target is not None and peer != target) or "profiles" not in link.caps or not link.live():
+ continue
+ for frame in frames:
+ data = settings_sync.desk_message_data(envelope, frame)
+ link.post(protocol.settings_msg(settings_sync.for_capabilities(data, link.caps)))
+ outbound.add(peer)
+ if self.responder is not None:
+ for ident in self.responder.links():
+ peer = protocol.id_text(ident)
+ caps = self.responder.caps_of(ident) or ()
+ if peer == source or peer in outbound or (target is not None and peer != target) or "profiles" not in caps:
+ continue
+ for frame in frames:
+ data = settings_sync.desk_message_data(envelope, frame)
+ self.responder.send(ident, protocol.settings_msg(settings_sync.for_capabilities(data, caps)))
+
+ def send_desk_to(self, peer):
+ with self.book.lock:
+ desk = profiles.desk_message(self.book._load())
+ self._send_desk(desk, target=peer)
+
+ def reset_desk_peer(self, peer):
+ self.desk_last_heard.pop(peer, None)
+ self.desk_link_times[peer] = time.time()
+
+ def receive_desk(self, data, source, *, linked=None, live=None, gone=None, now=None):
+ now = time.time() if now is None else now
+ state = profiles.read_desk_state(data, now=now)
+ if state is None:
+ return None
+ if linked is None:
+ link = self._peers_up.get(source)
+ linked = bool(link is not None and link.live()) or bool(self.responder is not None
+ and protocol.read_id(source) in self.responder.links())
+ outcome = self.crossing_event(crossing_state.desk_arrived, state, source=source,
+ linked=linked, platform="mac", live=live, gone=gone, now=now)
+ if linked and outcome["accepted"]:
+ self.desk_last_heard[source] = True
return outcome
def _send_crossing_picture(self, data, source=None):
@@ -896,7 +1015,7 @@ class KVMController:
def _announce_shortcut_skips(self, skipped):
for ident in skipped:
- self._alert("Beamer", f"Skipped {self._name_of(ident)}: not connected.")
+ self._alert("Beamer", tr("Skipped {name}: not connected.").format(name=self._name_of(ident)))
def _link_of(self, peer):
"""The link to `peer`, up or not; None when this Mac has none to it."""
@@ -1127,6 +1246,7 @@ class KVMController:
if self._memory is not None:
self._memory.follow(cfg)
self.crossing = self._crossing_engine()
+ self._refresh_shake()
self._crossing_failed = False
self._drain_outbound()
self._sync_links()
@@ -1134,9 +1254,9 @@ class KVMController:
for link in list(self.links.values()):
entry = link.entry()
if link.live() and entry is not None and link.dialled != (entry.get("host"), entry.get("port")):
- link.drop("Settings saved; reconnecting")
+ link.drop(tr("Settings saved; reconnecting"))
link.refresh()
- self.connection_status = "Settings saved; reconnecting"
+ self.connection_status = tr("Settings saved; reconnecting")
self.logger.info("settings updated; redirect mode returned to local")
def apply_settings(self, cfg):
@@ -1158,8 +1278,93 @@ class KVMController:
if self._memory is not None:
self._memory.follow(cfg)
self.crossing = self._crossing_engine()
+ self._refresh_shake()
self._crossing_failed = False
+ def _refresh_shake(self):
+ with self.book.lock:
+ settings = self.book._load() or {}
+ enabled = profiles.shake_on(settings) if "crossing_own" in settings else True
+ sensitivity = profiles.shake_sensitivity(settings) if "crossing_own" in settings else 100
+ self.shake.set_stroke(shake.stroke_at_sensitivity(shake.STROKE_MAC, sensitivity))
+ if enabled != self._shake_enabled:
+ self._shake_enabled = enabled
+ if enabled and self.redirecting:
+ self.shake.arm(self.clock())
+ with self._shake_presses_lock:
+ self.shake.held(self.clock(), bool(self._shake_presses))
+ else:
+ self.shake.disarm()
+
+ def _shake_input_event(self, event_type, event):
+ quartz = self.quartz
+ if event_type in (quartz.kCGEventKeyDown, quartz.kCGEventKeyUp, quartz.kCGEventFlagsChanged):
+ code = quartz.CGEventGetIntegerValueField(event, quartz.kCGKeyboardEventKeycode)
+ down = event_type == quartz.kCGEventKeyDown
+ if event_type == quartz.kCGEventFlagsChanged:
+ down = False if code == CAPS_LOCK_KEY_CODE else self.translator._modifier_transition(code, event)
+ press = ("key", code)
+ else:
+ button = self.translator.button_of(event_type, event)
+ if button is None:
+ if event_type == quartz.kCGEventScrollWheel:
+ self.shake.scroll(self.clock())
+ return
+ press, down = ("button", button[0]), button[1]
+ with self._shake_presses_lock:
+ if down:
+ self._shake_press_seq += 1
+ self._shake_presses[press] = self._shake_press_seq
+ else:
+ self._shake_presses.pop(press, None)
+ self.shake.held(self.clock(), bool(self._shake_presses))
+
+ def _shake_reconcile_input_state(self):
+ """Keep only the presses still physically down: their releases while a peer drove this Mac
+ never reached the tap."""
+ quartz, source = self.quartz, self.quartz.kCGEventSourceStateHIDSystemState
+ numbers = {"left": 0, "right": 1, **{name: number for number, name in WIRE_OTHER_BUTTONS.items()}}
+
+ def down(kind, value):
+ if kind == "key":
+ return quartz.CGEventSourceKeyState(source, value)
+ return quartz.CGEventSourceButtonState(source, numbers[value] if value in numbers else int(value) - 1)
+
+ with self._shake_presses_lock:
+ presses = self._shake_presses.copy()
+ released = {press: seq for press, seq in presses.items() if not down(*press)}
+ with self._shake_presses_lock:
+ # HID polling must not erase a fresh down delivered meanwhile by the tap.
+ for press, seq in released.items():
+ if self._shake_presses.get(press) == seq:
+ del self._shake_presses[press]
+ self.shake.held(self.clock(), bool(self._shake_presses))
+
+ def _shake_motion(self, dx, dy):
+ if not self.redirecting or not self._shake_enabled or not self.shake.motion(self.clock(), dx, dy):
+ return False
+ peer = self.owner.on
+ name = self._name_of(peer)
+ self.set_redirecting(False, came_home=True)
+ self.home_hold.motion(self.clock())
+ self._shook = True
+ # Off the event tap: a settings write in its callback could outlast the tap's timeout.
+ threading.Thread(target=self._shake_notice, args=(name,), name="Beamer-shake-notice", daemon=True).start()
+ return True
+
+ def _shake_notice(self, name):
+ """The first three shakes say what happened and where to turn it off."""
+ with self.book.lock:
+ settings = copy.deepcopy(self.book._load())
+ count = settings.get("shake_notices", 0)
+ count = count if type(count) is int and count >= 0 else 0
+ if count < 3:
+ settings["shake_notices"] = count + 1
+ self.book._save(settings)
+ if count < 3:
+ self._alert(tr("Beamer"), tr("Shook home from {name}. Turn this off in Crossing → Way home.").format(name=name))
+ self.logger.info("shook home from %s", name)
+
def set_redirecting(self, value, edge=None, offset=None, came_home=True, peer=None, reason=None,
display=None, side=None):
"""`edge` and `offset` are the edge of the other machine and fraction along it a
@@ -1195,7 +1400,7 @@ class KVMController:
if link is None or link is self._primary_link:
status = self.connection_status
else:
- status = link.status or "Waiting to connect"
+ status = link.status or tr("Waiting to connect")
name = self._name_of(peer) if peer else None
return status if not name or name in status else f"{name}: {status}"
@@ -1204,7 +1409,7 @@ class KVMController:
link = self._peers_up.get(peer) if peer else None
if link is None or not link.live():
self.logger.warning("cannot redirect: %s is not connected", self._name_of(peer) if peer else "the other machine")
- self._alert("Beamer", f"Cannot switch — {self._cannot_reach(peer)}")
+ self._alert("Beamer", tr("Cannot switch — {status}").format(status=self._cannot_reach(peer)))
return False
if self.receiving:
# Driven, so this Mac sends its owner home first and drives once the owner has let go
@@ -1309,8 +1514,10 @@ class KVMController:
self.crossing.reset()
if value:
self.idle_pointer.cancel()
- elif not self.stop_event.is_set() and self.cfg.hide_idle_pointer:
- self.idle_pointer.driver_left()
+ else:
+ self._shake_reconcile_input_state()
+ if not self.stop_event.is_set() and self.cfg.hide_idle_pointer:
+ self.idle_pointer.driver_left()
def _pointer_location(self):
x, y = self.quartz.CGEventGetLocation(self.quartz.CGEventCreate(None))
@@ -1492,6 +1699,8 @@ class KVMController:
if self.event_tap is not None:
self.quartz.CGEventTapEnable(self.event_tap, True)
return event
+ if not self.receiving and not self._was_injected(event):
+ self._shake_input_event(event_type, event)
if not self._was_injected(event) and self._handle_jump_key(event_type, event):
return None
if self.receiving:
@@ -1563,13 +1772,16 @@ class KVMController:
if self.redirecting and not self.owner.away:
self._repair_redirecting_disagreement()
return event
+ keycode = self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode)
+ if keycode in INPUT_METHOD_KEY_CODES and not (self.redirecting and result.is_down):
+ # A tap goes whole on the press. Its release, and the key at home, stay here.
+ return event
had = len(result.messages)
result.messages = self._after_home_presses(result.messages)
- keycode = self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode)
if self.redirecting:
entry = ignored.key(keycode)
kept = self.ignore_gate.keeps(entry, result.is_down)
- if keycode == CAPS_LOCK_KEY_CODE:
+ if keycode == CAPS_LOCK_KEY_CODE or keycode in INPUT_METHOD_KEY_CODES:
# One event per toggle, always read as down and sent as a press and its
# release, so it is a whole press to the gate too: a lone down would pin
# its route until input came home, whatever the list said by then.
@@ -1604,7 +1816,12 @@ class KVMController:
self._home_presses.discard(("button", button[0]))
if button is not None and self.ignore_gate.keeps(ignored.button(button[0]), button[1]):
return event
- messages = self.translator.mouse_messages(event_type, event)
+ messages = self.translator.mouse_messages(event_type, event, motion=self._shake_motion)
+ if getattr(self, "_shook", False):
+ # The motion that fired the shake belongs to neither machine: input is home now
+ # and the pointer stays where it was captured.
+ self._shook = False
+ return None
if button is not None and not messages:
# A button the wire has no name for stays on this Mac, as one does on the PC,
# rather than being swallowed and reaching neither.
@@ -1685,6 +1902,11 @@ class KVMController:
CROSSING_RETRY_SECONDS or until the next settings save, so one broken
geometry call cannot log an exception per mouse move -- and a passing
one cannot leave the edge dead until someone thinks to save a setting."""
+ if self.home_hold.blocks(self.clock()):
+ if event_type in self.translator.movement_event_types:
+ self.home_hold.motion(self.clock())
+ self.crossing.reset()
+ return event
if self._crossing_failed and self.clock() - self._crossing_failed_at < CROSSING_RETRY_SECONDS:
return event
self._crossing_failed = False
@@ -2087,6 +2309,7 @@ class KVMController:
and tell every peer we can send to who else this machine has (`paired`)."""
self._sync_links()
self.zones_changed()
+ self.publish_desk()
for link in list(self.links.values()):
link.refresh()
if link.live():
@@ -2101,6 +2324,7 @@ class KVMController:
peer = link.peer_id
if peer and self._peers_up.get(peer) is link:
self._peers_up.pop(peer, None)
+ self.reset_desk_peer(peer)
self._forget_held(peer)
self._step(lambda owner: owner.link_down(peer))
@@ -2137,7 +2361,7 @@ class KVMController:
) from exc
def _name_of(self, peer):
- return self._label(lambda entry: entry.get("id") == peer) or self._up_names.get(peer) or "the other machine"
+ return self._label(lambda entry: entry.get("id") == peer) or self._up_names.get(peer) or tr("the other machine")
# Link callbacks: each on a link's own thread
@@ -2202,7 +2426,11 @@ class KVMController:
# `paired` goes before the shared picture: the receiver admits third-party tiles only from
# the paired list it holds, and a picture is applied once per stamp.
self._announce_paired(link)
+ self.profiles_capable()
+ self.reset_desk_peer(link.peer_id)
self.crossing_link_up(link.peer_id)
+ if "profiles" in link.caps:
+ self.send_desk_to(link.peer_id)
if "settings" in link.caps and "layout" not in link.caps:
for message in self.announce():
if message.get("type") == protocol.MSG_SETTINGS:
@@ -2555,9 +2783,10 @@ class KVMController:
name = self._name_of(moved.left)
text = peerlist.refusal_text(moved.why, name, other)
if moved.why == "taken_over":
- text = f"{other or 'Another machine'} took over {name}"
+ text = (tr("{machine} took over {name}").format(machine=other, name=name) if other else
+ tr("Another machine took over {name}").format(name=name))
if text is None and moved.why in WHY_TEXT:
- text = WHY_TEXT[moved.why].format(name=name)
+ text = tr(WHY_TEXT[moved.why]).format(name=name)
if text is not None:
self.logger.warning("%s; input returned to this Mac", text)
self._alert("Beamer", text)
@@ -2602,7 +2831,7 @@ class KVMController:
other = peerlist.label_for(self.book.peers(), peer_id=protocol.id_text(unreachable.other))
text = peerlist.refusal_text(why, name, other)
if text is None:
- text = WHY_TEXT.get(why, "{name} could not be reached").format(name=name)
+ text = tr(WHY_TEXT.get(why, N_("{name} could not be reached"))).format(name=name)
self.logger.warning("%s", text)
self._alert("Beamer", text)
@@ -2693,6 +2922,7 @@ class KVMController:
def _check_tap_watchdog(self):
if not self.redirecting:
+ self._hid_unseen_since = None
return
try:
seconds_ago = float(self.quartz.CGEventSourceSecondsSinceLastEventType(
@@ -2702,9 +2932,20 @@ class KVMController:
except Exception:
self.logger.debug("could not read the last HID event time", exc_info=True)
return
- latest_hid_event = self.clock() - seconds_ago
- if latest_hid_event - self._last_tap_event_at <= TAP_HID_STALL_SECONDS:
+ now = self.clock()
+ latest_hid_event = now - seconds_ago
+ if latest_hid_event <= self._last_tap_event_at + TAP_HID_CLOCK_SLACK_SECONDS:
+ self._hid_unseen_since = None
+ return
+ # The HID system stamps an event before the tap is called with it, so the first input after
+ # a pause is always newer than the tap's last event for a few milliseconds. Comparing the two
+ # times alone sent input home on 14-10-2026 18 ms after a touch that ended a 14 s pause; the
+ # tap is dead only when input it has not seen stays unseen for the whole stall time.
+ if self._hid_unseen_since is None or self._hid_unseen_since <= self._last_tap_event_at:
+ self._hid_unseen_since = latest_hid_event
+ if now - self._hid_unseen_since <= TAP_HID_STALL_SECONDS:
return
+ self._hid_unseen_since = None
self.logger.warning("the event tap is not receiving input while redirected")
self._return_local()
if self.event_tap is not None:
@@ -2793,7 +3034,7 @@ class KVMController:
link.drop(reason)
self.logger.error("%s; connection dropped and input forced local", reason)
if was_redirecting:
- self._alert("Beamer", "Input returned to this Mac")
+ self._alert("Beamer", tr("Input returned to this Mac"))
def _drain_outbound(self):
while True:
diff --git a/mac_app/build_dmg.sh b/mac_app/build_dmg.sh
index 04503c0..12a9cf6 100755
--- a/mac_app/build_dmg.sh
+++ b/mac_app/build_dmg.sh
@@ -159,18 +159,28 @@ if [ "$RELEASE" -eq 1 ]; then TIMESTAMP="--timestamp"; else TIMESTAMP="--timesta
# whose signature seals the lot. --identifier pins the bundle id, which must never change - the
# privacy grants are keyed to it.
sign_app() {
- local identity="$1" binary
- find "$APP/Contents" -type f ! -path "$APP/Contents/MacOS/Beamer" -print0 \
+ local identity="$1" app="${2:-$APP}" bundle_id="${3:-uk.co.kalkman.beamer}" binary
+ local entitlements="$SCRIPT_DIR/entitlements.plist"
+ # Library validation admits only code with the process's own Team ID, and ad-hoc code has none,
+ # so an ad-hoc python under the hardened runtime cannot load its own Python.framework. A local
+ # ad-hoc build turns it off; a Developer ID build, and so every release, keeps it on.
+ if [ "$identity" = - ]; then
+ entitlements="$STAGING_DIR/entitlements-adhoc.plist"
+ cp "$SCRIPT_DIR/entitlements.plist" "$entitlements"
+ /usr/libexec/PlistBuddy -c "Add :com.apple.security.cs.disable-library-validation bool true" "$entitlements"
+ echo "ad-hoc signature: library validation is off in this build, which has no Team ID"
+ fi
+ find "$app/Contents" -type f ! -path "$app/Contents/MacOS/Beamer" -print0 \
| xargs -0 file | grep 'Mach-O' | grep -v '(for architecture' | cut -d: -f1 > "$STAGING_DIR/nested.txt"
while IFS= read -r binary; do
local entitle=()
- [ "$binary" = "$APP/Contents/MacOS/python" ] && entitle=(--entitlements "$SCRIPT_DIR/entitlements.plist")
+ [ "$binary" = "$app/Contents/MacOS/python" ] && entitle=(--entitlements "$entitlements")
codesign --force --sign "$identity" --options runtime $TIMESTAMP ${entitle[@]+"${entitle[@]}"} "$binary" || return 1
done < "$STAGING_DIR/nested.txt"
codesign --force --sign "$identity" --options runtime $TIMESTAMP \
- "$APP/Contents/Frameworks/Python.framework/Versions/"[0-9]* || return 1
+ "$app/Contents/Frameworks/Python.framework/Versions/"[0-9]* || return 1
codesign --force --sign "$identity" --options runtime $TIMESTAMP \
- --entitlements "$SCRIPT_DIR/entitlements.plist" --identifier uk.co.kalkman.beamer "$APP" || return 1
+ --entitlements "$entitlements" --identifier "$bundle_id" "$app" || return 1
}
# A real identity is stable across rebuilds, so macOS keeps the Accessibility and Input Monitoring
@@ -184,11 +194,15 @@ if ! security find-identity -v -p codesigning 2>/dev/null | grep -F "$IDENTITY"
[ "$RELEASE" -eq 1 ] && { echo "$IDENTITY is not in the keychain" >&2; exit 1; }
echo "$IDENTITY is not in the keychain - signing ad-hoc instead"
TIMESTAMP="--timestamp=none"
+ SIGNED_WITH=-
sign_app -
-elif ! sign_app "$IDENTITY" 2>"$STAGING_DIR/sign.log"; then
+elif sign_app "$IDENTITY" 2>"$STAGING_DIR/sign.log"; then
+ SIGNED_WITH="$IDENTITY"
+else
[ "$RELEASE" -eq 1 ] && { cat "$STAGING_DIR/sign.log" >&2; exit 1; }
echo "the login keychain would not release $IDENTITY - signing ad-hoc instead"
TIMESTAMP="--timestamp=none"
+ SIGNED_WITH=-
sign_app -
fi
codesign --verify --deep --strict --verbose=2 "$APP"
@@ -198,15 +212,55 @@ codesign -dvv "$APP" 2>&1 | grep -E '^(Identifier|Signature|Authority|Timestamp|
# entitlement fails here rather than at a user's first launch. The probe lives with the project's
# own tools, which the public source does not carry; a build from that source says so and goes on.
PROBE="$PROJECT_DIR/tools/runtime_probe.py"
+
+# dyld aborts a python whose Python.framework library validation refuses before Python starts,
+# which leaves a crash report and its dialog on the desktop of whoever is at this Mac (two on
+# 14-10-2026). Validation passes when python carries disable-library-validation or both carry the
+# same Team ID, so the probe is only run when one of those holds.
+probe_loads() {
+ local python="$1/Contents/MacOS/python" framework team_python team_framework
+ framework=("$1/Contents/Frameworks/Python.framework/Versions/"[0-9]*)
+ if codesign -d --entitlements - --xml "$python" 2>/dev/null | grep -F disable-library-validation >/dev/null; then
+ return 0
+ fi
+ team_python="$(codesign -dv "$python" 2>&1 | sed -n 's/^TeamIdentifier=//p')"
+ team_framework="$(codesign -dv "${framework[0]}" 2>&1 | sed -n 's/^TeamIdentifier=//p')"
+ [ -n "$team_python" ] && [ "$team_python" != "not set" ] && [ "$team_python" = "$team_framework" ]
+}
+
+# run_probe <app> [launcher...]: the probe imports the app's modules and never makes an
+# NSApplication, so nothing registers with the window server.
+run_probe() {
+ local app="$1"
+ shift
+ if ! probe_loads "$app"; then
+ echo "The runtime probe was not run: library validation would refuse the Python.framework in $app" >&2
+ return 1
+ fi
+ env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$app/Contents/Resources" \
+ "$@" "$app/Contents/MacOS/python" "$PROBE"
+}
+
if [ ! -f "$PROBE" ]; then
echo "No runtime probe in this source tree: the hardened-runtime probe was not run" >&2
else
- env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \
- "$APP/Contents/MacOS/python" "$PROBE"
- # The same probe as an Intel Mac would run it, where Rosetta is here to run it.
+ run_probe "$APP"
+ # The same probe as an Intel Mac would run it, where Rosetta is here to run it. macOS records a
+ # bundle run under Rosetta as an Intel app, and on macOS 27 that put "App Update Required ...
+ # will not open in macOS 28" on this Mac's own Beamer, so the x86_64 run is a throwaway copy
+ # under its own identifier, signed as the app was.
if /usr/bin/arch -x86_64 /usr/bin/true 2>/dev/null; then
- env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \
- /usr/bin/arch -x86_64 "$APP/Contents/MacOS/python" "$PROBE"
+ PROBE_APP="$STAGING_DIR/Beamer Rosetta Probe.app"
+ PROBE_ID=uk.co.kalkman.beamer.rosetta-probe
+ ditto "$APP" "$PROBE_APP"
+ /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier $PROBE_ID" "$PROBE_APP/Contents/Info.plist"
+ TIMESTAMP="--timestamp=none" sign_app "$SIGNED_WITH" "$PROBE_APP" "$PROBE_ID"
+ PROBE_FAILED=0
+ run_probe "$PROBE_APP" /usr/bin/arch -x86_64 || PROBE_FAILED=1
+ /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister \
+ -u "$PROBE_APP" 2>/dev/null || true
+ rm -rf "$PROBE_APP"
+ [ "$PROBE_FAILED" -eq 0 ] || exit 1
else
echo "Rosetta is not installed here: the x86_64 half of the bundle was not run" >&2
fi
diff --git a/mac_app/config.py b/mac_app/config.py
index 9fc655e..bab5634 100644
--- a/mac_app/config.py
+++ b/mac_app/config.py
@@ -77,6 +77,7 @@ class Config:
check_updates: bool = True
# Every address the window shows is hidden; see pages.redact.
hide_addresses: bool = False
+ language: str = "auto"
# Only the machine in use shows a pointer: this Mac's after a driver lets go of it, until it
# moves (core/idle_pointer). Its pointer always hides while it drives. This Mac's own choice.
hide_idle_pointer: bool = True
@@ -219,5 +220,6 @@ def parse_config(raw: dict) -> Config:
scroll_speed=raw.get("scroll_speed", 1.0),
reverse_scroll=raw.get("reverse_scroll", False),
appearance=raw.get("appearance") if raw.get("appearance") in APPEARANCES else "system",
+ language=raw.get("language") if raw.get("language") in ("auto", "en", "it") else "auto",
ignored_inputs=raw.get("ignored_inputs", []),
)
diff --git a/mac_app/diagram.py b/mac_app/diagram.py
index c735a6f..eb3bdf1 100644
--- a/mac_app/diagram.py
+++ b/mac_app/diagram.py
@@ -16,6 +16,11 @@ import pages
import theme
from core.resistance_strip import MAX_RESISTANCE, resistance_x
from core import ways as core_ways
+from core.i18n import N_, tr
+
+POSITION_WORDS = {"right of": N_("right of"), "left of": N_("left of"),
+ "below": N_("below"), "above": N_("above")}
+THIRD_WORDS = {"start": N_("start"), "middle": N_("middle"), "end": N_("end")}
def _rect(frame):
@@ -85,6 +90,7 @@ def _collapsed(frame, side):
# The clear space centred on each third boundary of the selected machine's seam and tracks.
THIRD_GAP = 2.0
CYCLE_BOX = 16.0
+RESIZE_GRIP = 12.0
def _at_break(value, breaks):
@@ -219,7 +225,7 @@ class ArrangementDiagram(AppKit.NSView):
self.this.setFrame_(_rect(this))
line = theme.TYPE["small"] + 4
x, y, w, h = this
- _fit_text(self.this_label, "This Mac", (x + 6, y + (4 if has_notch else 0), w - 12, h))
+ _fit_text(self.this_label, tr("This Mac"), (x + 6, y + (4 if has_notch else 0), w - 12, h))
keys = {machine["key"] for machine in machines}
for key in [key for key in self.screens if key not in keys]:
for layer in self.screens.pop(key):
@@ -317,12 +323,12 @@ def outcome_for_tile(state, crosses, is_own=False):
if is_own:
return ""
if state == "overlap":
- return "Overlaps"
+ return tr("Overlaps")
if state in ("gap", "between", "set-elsewhere", "set_elsewhere"):
- return "Drag to connect"
+ return tr("Drag to connect")
if not crosses:
- return "Edge off"
- return "Crosses"
+ return tr("Edge off")
+ return tr("Crosses")
class AtlasAccessibleElement(AppKit.NSObject):
@@ -338,15 +344,23 @@ class AtlasAccessibleElement(AppKit.NSObject):
def accessibilityLabel(self):
if self.kind == "recentre":
- name = self.canvas.labels.get(self.canvas.selected, "machine")
- return f"Recentre {name}"
- name = self.canvas.labels.get(self.key, f"Machine · {self.key[-6:]}")
- return f"{name}, In the shortcut's cycle" if self.kind == "cycle" else name
+ name = self.canvas.labels.get(self.canvas.selected, tr("machine"))
+ return tr("Recentre {name}").format(name=name)
+ name = self.canvas.labels.get(self.key, tr("Machine · {id}").format(id=self.key[-6:]))
+ if self.kind == "cycle":
+ return tr("{name}, In the shortcut's cycle").format(name=name)
+ word = self.canvas.tile_words.get(self.key)
+ return tr("{name}, {status}").format(name=name, status=word) if word else name
def accessibilityValue(self):
if self.kind == "cycle":
return self.canvas.cycle.get(self.key, True) is True
- return "Selected" if self.canvas.selected == self.key else ""
+ return tr("Selected") if self.canvas.selected == self.key else ""
+
+ def accessibilityHelp(self):
+ if self.kind == "tile" and self.canvas._can_resize(self.key):
+ return tr("Drag a corner to resize, or use Option and the arrow keys.")
+ return ""
def accessibilityParent(self):
return self.canvas
@@ -401,6 +415,10 @@ class AtlasCanvas(AppKit.NSView):
self.tiles = {}
self.states = {}
self.labels = {}
+ self.tile_words = {}
+ self.machine_picker = False
+ self.read_only = False
+ self.fixed_machine_id = ""
self.older = set()
self.selected = None
self.own_id = ""
@@ -419,6 +437,7 @@ class AtlasCanvas(AppKit.NSView):
self.outcome_for_tile = {}
self.dot_for_tile = {}
self.cycle_for_tile = {}
+ self.resize_layers = {}
self.accessible_elements = {}
self.contact_layers = {}
self.seam_segments = []
@@ -464,7 +483,7 @@ class AtlasCanvas(AppKit.NSView):
self.last_announcement = ""
self.setAccessibilityElement_(True)
self.setAccessibilityRole_(AppKit.NSAccessibilityGroupRole)
- self.setAccessibilityLabel_("Whole desk layout")
+ self.setAccessibilityLabel_(tr("Whole desk layout"))
return self
def acceptsFirstResponder(self):
@@ -484,13 +503,19 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def show_layout(self, tiles, states, labels, own_id, selected, cycle=None, cycle_enabled=False,
- older=(), animate=False):
+ older=(), animate=False, tile_words=None, machine_picker=False, read_only=False,
+ fixed_machine_id=None):
+ """`own_id` anchors the viewed machine's seams; picker mode includes it in selection."""
cycle = dict(cycle or {})
older = set(older)
+ tile_words = dict(tile_words or {})
+ fixed_machine_id = own_id if fixed_machine_id is None else fixed_machine_id
if (tiles == self.tiles and states == self.states and labels == self.labels
and own_id == self.own_id and selected == self.selected
and cycle == self.cycle and bool(cycle_enabled) == self.cycle_enabled
- and older == self.older):
+ and older == self.older and tile_words == self.tile_words
+ and bool(machine_picker) == self.machine_picker and bool(read_only) == self.read_only
+ and fixed_machine_id == self.fixed_machine_id):
return
self.tiles = copy.deepcopy(tiles)
self.states = copy.deepcopy(states)
@@ -500,13 +525,20 @@ class AtlasCanvas(AppKit.NSView):
self.cycle = cycle
self.cycle_enabled = bool(cycle_enabled)
self.older = older
+ self.tile_words = tile_words
+ self.machine_picker = bool(machine_picker)
+ self.read_only = bool(read_only)
+ self.fixed_machine_id = fixed_machine_id
+ if self.read_only:
+ self.dragging = self.third_pressed = None
for key in list(self.layer_for_tile):
if key not in self.tiles:
for layer in self.display_layers.pop(key, []):
layer.removeFromSuperlayer()
for layer in (self.layer_for_tile.pop(key), self.label_for_tile.pop(key),
self.state_for_tile.pop(key), self.outcome_for_tile.pop(key),
- self.dot_for_tile.pop(key), self.cycle_for_tile.pop(key)):
+ self.dot_for_tile.pop(key), self.cycle_for_tile.pop(key),
+ self.resize_layers.pop(key)):
layer.removeFromSuperlayer()
self.setAccessibilityLabel_(self.last_announcement or self._description())
self.setNeedsLayout_(True)
@@ -519,24 +551,33 @@ class AtlasCanvas(AppKit.NSView):
def _description(self):
parts = []
for key, tile in self.tiles.items():
- label = self.labels.get(key, f"Machine · {key[-6:]}")
+ label = self.labels.get(key, tr("Machine · {id}").format(id=key[-6:]))
state = self.states.get(key, {}).get("state")
sentence = self.states.get(key, {}).get("sentence", "")
if sentence:
parts.append(sentence)
+ elif self.machine_picker and key == self.own_id:
+ parts.append(label)
elif key == self.own_id:
name = self.states.get(key, {}).get("machine_name")
- parts.append(f"{label}, {name}, this Mac." if name else f"{label}, this Mac.")
+ parts.append(tr("{label}, {name}, this Mac.").format(label=label, name=name) if name else
+ tr("{label}, this Mac.").format(label=label))
else:
status = self.states.get(key, {})
- outcome = ("Offline" if not status.get("linked") else
- "Crosses" if status.get("crosses") else
- "Edge off" if status.get("edge_off") else
+ outcome = (tr("Offline") if not status.get("linked") else
+ tr("Crosses") if status.get("crosses") else
+ tr("Edge off") if status.get("edge_off") else
outcome_for_tile(state, False))
- parts.append(f"{label}, {outcome}.")
+ parts.append(tr("{label}, {outcome}.").format(label=label, outcome=outcome))
+ if self.tile_words.get(key):
+ parts.append(self.tile_words[key])
+ if self._can_resize(key):
+ parts.append(tr("{name}: drag a corner to resize, or use Option and the arrow keys.").format(name=label))
if self.cycle_enabled and key != self.own_id:
- parts.append(f"{label} is {'in' if self.cycle.get(key, True) else 'out of'} the shortcut's cycle.")
- return " ".join(parts) or "No machines paired."
+ sentence = (tr("{name} is in the shortcut's cycle.") if self.cycle.get(key, True) else
+ tr("{name} is out of the shortcut's cycle."))
+ parts.append(sentence.format(name=label))
+ return " ".join(parts) or tr("No machines paired.")
def accessibilityChildren(self):
children = []
@@ -553,7 +594,7 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def select_tile(self, key):
- if key not in self.tiles or key == self.own_id:
+ if key not in self.tiles or (key == self.own_id and not self.machine_picker):
return
self.selected = key
if self.on_select:
@@ -563,7 +604,8 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def reading_order(self):
placed = sorted(((tile["y"] + tile["h"] / 2, tile["x"] + tile["w"] / 2,
- tile["h"], key) for key, tile in self.tiles.items() if key != self.own_id))
+ tile["h"], key) for key, tile in self.tiles.items()
+ if self.machine_picker or key != self.own_id))
rows = []
for item in placed:
if not rows or item[0] - rows[-1][0][0] > min(item[2], rows[-1][0][2]) / 2:
@@ -589,12 +631,32 @@ class AtlasCanvas(AppKit.NSView):
"left of" if tile["x"] + tile["w"] <= own.get("x", 0) else \
"below" if tile["y"] >= own.get("y", 0) + own.get("h", 0) else "above"
thirds = state.get("thirds", [])
- third = f", {thirds[0]} third" if len(thirds) == 1 else ""
map_state = state.get("state")
if not state.get("crosses") and core_ways._rect_contact(own, tile) is None:
map_state = "gap"
- crosses = outcome_for_tile(map_state, state.get("crosses")) + "."
- self.announce(f"{name}, {side} This Mac{third}. {crosses}")
+ outcome = outcome_for_tile(map_state, state.get("crosses"))
+ if len(thirds) == 1:
+ # Translators: {third} is one of the three sections along an edge.
+ sentence = tr("{name}, {side} This Mac, {third} third. {outcome}.")
+ position = tr(POSITION_WORDS[side])
+ third = tr(THIRD_WORDS[thirds[0]])
+ self.announce(sentence.format(name=name, side=position, third=third, outcome=outcome))
+ else:
+ sentence = tr("{name}, {side} This Mac. {outcome}.")
+ position = tr(POSITION_WORDS[side])
+ self.announce(sentence.format(name=name, side=position, outcome=outcome))
+
+ @objc.python_method
+ def announce_resize(self, key):
+ name = self.labels.get(key, tr("Machine · {id}").format(id=key[-6:]))
+ self.announce(tr("{name} resized.").format(name=name))
+
+ @objc.python_method
+ def _commit_resize(self, key):
+ if self.on_layout_change:
+ self.on_layout_change(self.tiles, key, snap=False)
+ else:
+ self.announce_resize(key)
@objc.python_method
def _layer(self, key):
@@ -621,18 +683,26 @@ class AtlasCanvas(AppKit.NSView):
check.setFrame_(((0, 0), (CYCLE_BOX, CYCLE_BOX)))
check.setHidden_(True)
cycle.addSublayer_(check)
+ grip = Quartz.CAShapeLayer.layer()
+ grip.setFillColor_(AppKit.NSColor.clearColor().CGColor())
+ grip.setLineWidth_(1.5)
+ grip.setLineCap_(Quartz.kCALineCapRound)
+ grip.setZPosition_(23)
+ grip.setHidden_(True)
self.layer().addSublayer_(tile)
self.layer().addSublayer_(title)
self.layer().addSublayer_(state)
self.layer().addSublayer_(outcome)
self.layer().addSublayer_(dot)
self.layer().addSublayer_(cycle)
+ self.layer().addSublayer_(grip)
self.layer_for_tile[key] = tile
self.label_for_tile[key] = title
self.state_for_tile[key] = state
self.outcome_for_tile[key] = outcome
self.dot_for_tile[key] = dot
self.cycle_for_tile[key] = cycle
+ self.resize_layers[key] = grip
return (self.layer_for_tile[key], self.label_for_tile[key], self.state_for_tile[key],
self.outcome_for_tile[key], self.dot_for_tile[key], self.cycle_for_tile[key])
@@ -674,6 +744,42 @@ class AtlasCanvas(AppKit.NSView):
x, y, width, height = AtlasCanvas._cycle_box(frame)
return x - 4, y - 4, width + 8, height + 8
+ @objc.python_method
+ def _can_resize(self, key):
+ tile = self.tiles.get(key)
+ state = self.states.get(key, {})
+ return (tile is not None and not self.read_only
+ and not any(tile.get(flag) or state.get(flag) for flag in ("left_out", "shelved", "dormant"))
+ and tile.get("in_use") is not False and state.get("in_use") is not False
+ and (key == self.fixed_machine_id or not tile.get("display_offsets")))
+
+ @staticmethod
+ def _resize_rect(frame):
+ x, y, width, height = frame
+ size = min(RESIZE_GRIP, width, height)
+ return x + width - size, y + height - size, size, size
+
+ @objc.python_method
+ def _resize_hit(self, point):
+ # An edge third's 5 px band wins over a grip it overlaps, as on the PC map.
+ if self._third_hit(point):
+ return None
+ frames, _scale = self._map()
+ for key, frame in reversed(list(frames.items())):
+ if not self._can_resize(key):
+ continue
+ x, y, width, height = self._resize_rect(frame)
+ # A tile drawn smaller than the grip has its whole grip inside the band of the side it
+ # shares; the hit area keeps the full grip size, reaching out past the corner.
+ if x <= point.x <= x + max(width, RESIZE_GRIP) and y <= point.y <= y + max(height, RESIZE_GRIP):
+ return key
+ return None
+
+ @staticmethod
+ def _resize_cursor():
+ cursor = getattr(AppKit.NSCursor, "resizeNorthWestSouthEastCursor", None)
+ return cursor() if cursor is not None else AppKit.NSCursor.crosshairCursor()
+
@objc.python_method
def _map(self):
width, height = self.bounds().size.width, self.bounds().size.height
@@ -721,12 +827,14 @@ class AtlasCanvas(AppKit.NSView):
is_own = key == self.own_id
inactive = self.states.get(key, {}).get("in_use") is False
selected = key == self.selected
- gap = state in ("gap", "set-elsewhere", "between", "overlap")
+ elsewhere = (self.machine_picker and self.own_id != self.fixed_machine_id
+ and state in ("gap", "between", "set-elsewhere", "set_elsewhere"))
+ gap = not elsewhere and state in ("gap", "set-elsewhere", "set_elsewhere", "between", "overlap")
hover = key == self.hovered and not self.keyboard_focus
_set_layer_frame_if_changed(tile, _rect(frame))
- tile.setBorderWidth_(1 if is_own else 2 if selected or gap else 1)
+ tile.setBorderWidth_(2 if selected and self.machine_picker else 1 if is_own else 2 if selected or gap else 1)
theme.tint(tile, background="well" if is_own else "panel",
- border="edge" if is_own else "ink_2" if selected else
+ border="ink_2" if selected and self.machine_picker else "edge" if is_own else "ink_2" if selected else
"ink_3" if hover else "amber" if gap else "edge")
tile.setOpacity_(0.42 if inactive else 1.0)
screens = core_ways._display_frames(self.tiles[key]) if self.tiles[key].get("displays") else []
@@ -752,16 +860,20 @@ class AtlasCanvas(AppKit.NSView):
(screen["w"] * scale_x, screen["h"] * scale_y)))
layer.setHidden_(False)
theme.tint(layer, background="well", border="edge")
- title.setString_(self.labels.get(key, f"Machine · {key[-6:]}"))
+ title.setString_(self.labels.get(key, tr("Machine · {id}").format(id=key[-6:])))
+ title.setWrapped_(False)
+ title.setTruncationMode_(Quartz.kCATruncationEnd)
_set_layer_frame_if_changed(title, _rect(self._title_rect(key, frame)))
status_info = self.states.get(key, {})
- status = (f"{status_info.get('machine_name') or platform.node().split('.')[0] or 'This Mac'} · macOS"
+ status = (tr("{name} · macOS").format(name=status_info.get('machine_name') or platform.node().split('.')[0] or tr("This Mac"))
if is_own else
- f"{status_info.get('platform', 'Computer')} · {'Linked' if status_info.get('linked') else 'Offline'}")
+ tr("{platform} · {status}").format(platform=status_info.get('platform', tr("Computer")),
+ status=tr("Linked") if status_info.get('linked') else tr("Offline")))
if key in self.older:
- status = f"Beamer {status_info.get('version') or '1.5.2'} · only sees which side"
+ status = tr("Beamer {version} · only sees which side").format(version=status_info.get('version') or '1.5.2')
if inactive:
- status = "Not in use"
+ status = tr("Not in use")
+ status = self.tile_words.get(key) or status
state_layer.setString_(status)
state_layer.setAlignmentMode_(Quartz.kCAAlignmentLeft)
_set_layer_frame_if_changed(state_layer, ((frame[0] + 24, frame[1] + 35),
@@ -769,25 +881,28 @@ class AtlasCanvas(AppKit.NSView):
state_layer.setHidden_(frame[3] < 72)
theme.tint(state_layer, foreground="amber" if gap else "ink_3")
crosses = status_info.get("crosses", is_own)
- outcome = ("Offline" if not is_own and not status_info.get("linked") else
- "Crosses" if crosses and (status_info.get("corner_ways") or status_info.get("wrap_sides")
- or status_info.get("notch_way")) else
- "Edge off" if status_info.get("edge_off") or status_info.get("unpicked") else
- outcome_for_tile(state, crosses, is_own))
+ outcome_kind = ("offline" if not is_own and not status_info.get("linked") else
+ "crosses" if crosses and (status_info.get("corner_ways") or status_info.get("wrap_sides")
+ or status_info.get("notch_way")) else
+ "edge_off" if status_info.get("edge_off") or status_info.get("unpicked") else
+ "tile")
+ outcome = {"offline": tr("Offline"), "crosses": tr("Crosses"), "edge_off": tr("Edge off")}.get(
+ outcome_kind, outcome_for_tile(state, crosses, is_own))
if is_own:
outcome = ""
- outcome_layer.setString_(outcome)
+ outcome_layer.setString_(tr("Set elsewhere") if elsewhere and not is_own else outcome)
_set_layer_frame_if_changed(
outcome_layer, ((frame[0] + 8, frame[1] + frame[3] - 22),
(max(1, frame[2] - 16), 14)))
outcome_layer.setHidden_(frame[3] < 56)
- theme.tint(outcome_layer, foreground="signal" if outcome == "Crosses" else
- "amber" if outcome in ("Drag to connect", "Overlaps") else "ink_3")
+ theme.tint(outcome_layer, foreground="ink_3" if elsewhere else "signal" if outcome_kind == "crosses" else
+ "amber" if state in ("gap", "between", "set-elsewhere", "set_elsewhere", "overlap") else "ink_3")
_set_layer_frame_if_changed(dot, ((frame[0] + 12, frame[1] + 40), (6, 6)))
dot.setCornerRadius_(3)
dot.setHidden_(frame[3] < 72)
- theme.tint(dot, background="amber" if key in self.older else
- "signal" if status_info.get("linked") else "ink_3")
+ word = self.tile_words.get(key)
+ theme.tint(dot, background=("signal" if word in (tr("Desk"), tr("Own")) else "ink_3") if word else
+ "ink_3" if key in self.older else "signal" if status_info.get("linked") else "ink_3")
cycle_layer.setHidden_(not self._shows_cycle(key))
_set_layer_frame_if_changed(cycle_layer, _rect(self._cycle_box(frame)))
ticked = self.cycle.get(key, True) is True
@@ -798,6 +913,15 @@ class AtlasCanvas(AppKit.NSView):
z_position = max(layer.zPosition() for layer in self.display_layers[key]) + 1.0
for layer in (title, state_layer, outcome_layer, dot, cycle_layer):
layer.setZPosition_(z_position)
+ grip = self.resize_layers[key]
+ grip.setHidden_(not (self._can_resize(key) and (selected or key == self.hovered)))
+ gx, gy, gw, gh = self._resize_rect(frame)
+ path = Quartz.CGPathCreateMutable()
+ for inset in (4, 8):
+ Quartz.CGPathMoveToPoint(path, None, gx + gw - inset, gy + gh - 3)
+ Quartz.CGPathAddLineToPoint(path, None, gx + gw - 3, gy + gh - inset)
+ grip.setPath_(path)
+ theme.tint(grip, stroke="ink_2" if selected else "ink_3")
focus = frames.get(self.selected) if self.keyboard_focus else None
self.focus_layer.setHidden_(focus is None)
if focus is not None:
@@ -815,17 +939,23 @@ class AtlasCanvas(AppKit.NSView):
self.recentre_layer.setBorderWidth_(1 if self.keyboard_focus or self.recentre_hovered else 0)
theme.tint(self.recentre_layer, background="panel",
border="ink_2" if self.keyboard_focus or self.recentre_hovered else "rule")
- self.recentre_label.setString_("Recentre")
+ self.recentre_label.setString_(tr("Recentre"))
self.recentre_label.setAlignmentMode_(Quartz.kCAAlignmentCenter)
_set_layer_frame_if_changed(self.recentre_label, ((4, 2), (button[2] - 8, button[3] - 4)))
theme.tint(self.recentre_label, foreground="ink_2" if self.recentre_hovered or self.keyboard_focus else "ink_3")
self.removeAllToolTips()
for _peer, _third, _side, start, end in self._third_segments(frames):
+ if self.read_only:
+ continue
rect = (AppKit.NSMakeRect(start[0] - 5, start[1], 10, end[1] - start[1])
if start[0] == end[0] else
AppKit.NSMakeRect(start[0], start[1] - 5, end[0] - start[0], 10))
self.addToolTipRect_owner_userData_(rect, self, 1)
for key, frame in frames.items():
+ title_rect = self._title_rect(key, frame)
+ name = self.labels.get(key, tr("Machine · {id}").format(id=key[-6:]))
+ if _text_width(name, self.label_for_tile[key].font()) > title_rect[2]:
+ self.addToolTipRect_owner_userData_(AppKit.NSMakeRect(*title_rect), self, 2)
if self._shows_cycle(key):
self.addToolTipRect_owner_userData_(AppKit.NSMakeRect(*self._cycle_hit_rect(frame)), self, 0)
Quartz.CATransaction.commit()
@@ -839,7 +969,7 @@ class AtlasCanvas(AppKit.NSView):
if (peer != own and own in frames and peer in frames
and state.get("state") in ("edge", "part", "corner") and state.get("crosses")
and state.get("picked_thirds", ["start"])):
- found = [(screen, stretch, self._third_breaks(contact, screen) if peer == self.selected else set())
+ found = [(screen, stretch, self._third_breaks(contact, screen) if self.machine_picker or peer == self.selected else set())
for screen, contact in self._side_contacts(peer)
for stretch in core_ways.crossing_stretches(contact, screen, state.get("lit_thirds", []))]
if found:
@@ -924,7 +1054,7 @@ class AtlasCanvas(AppKit.NSView):
for peer, state in self.states.items():
if peer == self.own_id or peer not in frames or state.get("in_use") is False:
continue
- opacity = (1.0 if state.get("linked", True) else 0.55) * (1.0 if peer == self.selected else 0.7)
+ opacity = (1.0 if state.get("linked", True) else 0.55) * (1.0 if self.machine_picker or peer == self.selected else 0.7)
for kept, sides in ((False, state.get("wrap_sides", [])), (True, state.get("kept_sides", []))):
for side in sides:
wanted[(peer, side)] = (kept, opacity)
@@ -1101,8 +1231,11 @@ class AtlasCanvas(AppKit.NSView):
return (max(start[0], low), start[1]), (min(end[0], high), end[1])
@objc.python_method
- def _third_segments(self, frames):
- peer, own = self.selected, self.own_id
+ def _third_segments(self, frames, peer=None):
+ if peer is None and self.machine_picker:
+ return [segment for key in self.tiles if key != self.own_id
+ for segment in self._third_segments(frames, key)]
+ peer, own = self.selected if peer is None else peer, self.own_id
state = self.states.get(peer, {})
if (peer == own or peer not in frames or own not in frames
or state.get("in_use") is False):
@@ -1125,9 +1258,10 @@ class AtlasCanvas(AppKit.NSView):
def _draw_thirds(self, frames):
marks = {}
segments = self._third_segments(frames)
- peer = segments[0][0] if segments else None
- state = self.states.get(peer, {})
- if segments and not state.get("edge_off") and state.get("picked_thirds"):
+ for peer in dict.fromkeys(segment[0] for segment in segments):
+ state = self.states.get(peer, {})
+ if state.get("edge_off") or not state.get("picked_thirds"):
+ continue
contacts = self._side_contacts(peer)
for index, (screen, contact) in enumerate(contacts):
breaks = self._third_breaks(contact, screen)
@@ -1173,6 +1307,8 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def _third_hit(self, point):
+ if self.read_only:
+ return None
hit = self._third_hit_segment(point)
return hit[:2] if hit else None
@@ -1181,8 +1317,9 @@ class AtlasCanvas(AppKit.NSView):
side = side or core_ways._rect_contact(self.tiles[self.own_id], self.tiles[peer])[0]
name = core_ways.part_names(side)[third]
picked = self.states.get(peer, {}).get("picked_thirds", [])
- detail = f"click to turn it {'off' if third in picked else 'on'}"
- return f"{name} third: {detail}"
+ # Translators: third names are one of the three sections of a screen edge.
+ detail = tr("click to turn it off") if third in picked else tr("click to turn it on")
+ return tr("{name} third: {detail}").format(name=name, detail=detail)
@objc.python_method
def _draw_marks(self, frames):
@@ -1242,11 +1379,12 @@ class AtlasCanvas(AppKit.NSView):
dx = 1 if key[2].endswith("left") else -1
dy = 1 if key[2].startswith("top") else -1
chevron_path = Quartz.CGPathCreateMutable()
- Quartz.CGPathMoveToPoint(chevron_path, None, px - 4 * dx, py + 3 * dy)
- Quartz.CGPathAddLineToPoint(chevron_path, None, px - 4 * dx, py - 4 * dy)
- Quartz.CGPathAddLineToPoint(chevron_path, None, px + 3 * dx, py - 4 * dy)
+ # The 7 pt bracket centred on the vertex, as in the 16 pt pad around it.
+ Quartz.CGPathMoveToPoint(chevron_path, None, px - 3.5 * dx, py + 3.5 * dy)
+ Quartz.CGPathAddLineToPoint(chevron_path, None, px - 3.5 * dx, py - 3.5 * dy)
+ Quartz.CGPathAddLineToPoint(chevron_path, None, px + 3.5 * dx, py - 3.5 * dy)
chevron.setPath_(chevron_path)
- selected = key[0] == self.selected
+ selected = self.machine_picker or key[0] == self.selected
layer.setOpacity_(1.0 if selected else 0.55)
layer.setZPosition_(21 if selected else 20)
if vertex is not None:
@@ -1272,7 +1410,7 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def snap_preview(self):
- if self.dragging is None or self.dragging.get("display") is not None:
+ if self.dragging is None or self.dragging.get("display") is not None or self.dragging.get("resize"):
return None
key = self.dragging.get("key")
if key in (None, self.own_id) or key not in self.tiles or self.own_id not in self.tiles:
@@ -1415,12 +1553,12 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def _show_recentre(self):
- return (self.selected not in (None, self.own_id) and self.selected in self.tiles
+ return (not self.read_only and self.selected not in (None, self.own_id, self.fixed_machine_id) and self.selected in self.tiles
and self.own_id in self.tiles and not self._is_centred(self.selected))
@objc.python_method
def recentre_selected(self):
- if self.dragging is not None:
+ if self.read_only or self.selected == self.fixed_machine_id or self.dragging is not None:
return False
peer = self.selected
side = self._recentre_side(peer) if peer not in (None, self.own_id) else None
@@ -1472,7 +1610,8 @@ class AtlasCanvas(AppKit.NSView):
def _stop_tile_animations(self, key):
layers = [self.layer_for_tile.get(key), self.label_for_tile.get(key),
self.state_for_tile.get(key), self.outcome_for_tile.get(key),
- self.dot_for_tile.get(key), self.cycle_for_tile.get(key), self.focus_layer]
+ self.dot_for_tile.get(key), self.cycle_for_tile.get(key),
+ self.resize_layers.get(key), self.focus_layer]
layers.extend(self.display_layers.get(key, ()))
for layer in layers:
if layer is not None:
@@ -1480,7 +1619,7 @@ class AtlasCanvas(AppKit.NSView):
@objc.python_method
def toggle_cycle(self, key):
- if not self.cycle_enabled or key == self.own_id or key not in self.tiles:
+ if self.read_only or not self.cycle_enabled or key == self.own_id or key not in self.tiles:
return
self.cycle[key] = not self.cycle.get(key, True)
if self.on_cycle_change:
@@ -1504,9 +1643,13 @@ class AtlasCanvas(AppKit.NSView):
point = self.convertPoint_fromView_(event.locationInWindow(), None)
recentre_hovered = self._recentre_hit(point)
hovered = self.tile_at(point)
- if self._third_hit(point):
+ if self._resize_hit(point) is not None:
+ self._resize_cursor().set()
+ elif self._third_hit(point):
+ AppKit.NSCursor.pointingHandCursor().set()
+ elif hovered is not None and self.machine_picker:
AppKit.NSCursor.pointingHandCursor().set()
- elif hovered is not None and hovered != self.own_id:
+ elif hovered is not None and hovered != self.fixed_machine_id and not self.read_only:
AppKit.NSCursor.openHandCursor().set()
else:
AppKit.NSCursor.arrowCursor().set()
@@ -1523,12 +1666,18 @@ class AtlasCanvas(AppKit.NSView):
self._draw(False)
def view_stringForToolTip_point_userData_(self, _view, _tag, point, _data):
+ if _data == 2:
+ key = self.tile_at(point)
+ return self.labels.get(key, tr("Machine · {id}").format(id=(key or "")[-6:]))
hit = self._third_hit_segment(point)
if hit:
return self._third_tooltip(*hit)
- return "In the shortcut's cycle"
+ return tr("In the shortcut's cycle")
def accessibilityPerformPress(self):
+ if self.machine_picker and self.selected in self.tiles:
+ self.select_tile(self.selected)
+ return True
if self.selected in self.tiles and self.selected != self.own_id:
self.toggle_cycle(self.selected)
return True
@@ -1537,7 +1686,30 @@ class AtlasCanvas(AppKit.NSView):
def mouseDown_(self, event):
self.window().makeFirstResponder_(self)
point = self.convertPoint_fromView_(event.locationInWindow(), None)
- self.third_pressed = self._third_hit(point)
+ resize_key = self._resize_hit(point)
+ if resize_key is not None:
+ frames, scale = self._map()
+ original = copy.deepcopy(self.tiles[resize_key])
+ frame = frames[resize_key]
+ self._stop_tile_animations(resize_key)
+ self.keyboard_focus = False
+ self.selected = resize_key
+ self.last_announcement = ""
+ self.third_pressed = None
+ self.dragging = {"key": resize_key, "resize": True, "original": original,
+ "pointer_x": point.x, "pointer_y": point.y, "scale": scale,
+ "map_x": frame[0] - original["x"] * scale,
+ "map_y": frame[1] - original["y"] * scale, "moved": False}
+ # Picking a machine in profiles mode switches the viewed layout. A grip edits the
+ # current picture instead; This Mac's move-selection handler also resets selection.
+ if self.on_select and not self.machine_picker and resize_key != self.fixed_machine_id:
+ self.on_select(resize_key)
+ self._resize_cursor().set()
+ self._draw(False)
+ return
+ hit_key = self.tile_at(point)
+ picking = self.machine_picker and hit_key is not None and hit_key != self.own_id
+ self.third_pressed = None if self.read_only or picking else self._third_hit(point)
if self.third_pressed:
return
if self._recentre_hit(point):
@@ -1548,20 +1720,19 @@ class AtlasCanvas(AppKit.NSView):
key = self.tile_at(point)
if key is None:
return
- if event.clickCount() > 1 and key != self.own_id and self.on_rename:
+ if event.clickCount() > 1 and not self.machine_picker and not self.read_only and key != self.own_id and self.on_rename:
self.selected = key
self.on_rename(key)
return
- if event.clickCount() > 1 and key == self.own_id:
- self.announce("Rename this Mac on Overview.")
+ if event.clickCount() > 1 and not self.machine_picker and key == self.own_id:
+ self.announce(tr("Rename this Mac on Overview."))
return
if self._cycle_hit(key, point):
- self.cycle[key] = not self.cycle.get(key, True)
- if self.on_cycle_change:
- self.on_cycle_change(key, self.cycle[key])
- self._draw(False)
+ self.toggle_cycle(key)
return
- if key == self.own_id:
+ if key == self.fixed_machine_id:
+ if self.machine_picker:
+ self.select_tile(key)
return
self._stop_tile_animations(key)
self.keyboard_focus = False
@@ -1574,6 +1745,9 @@ class AtlasCanvas(AppKit.NSView):
map_y = frames[origin_id][1] - origin["y"] * scale
if self.on_select:
self.on_select(key)
+ if self.read_only:
+ self._draw(False)
+ return
offsets = self.tiles[key].get("display_offsets", {})
split = display is not None and display in offsets
option = bool(event.modifierFlags() & AppKit.NSEventModifierFlagOption)
@@ -1600,6 +1774,14 @@ class AtlasCanvas(AppKit.NSView):
point = self.convertPoint_fromView_(event.locationInWindow(), None)
scale = self.dragging["scale"]
key = self.dragging["key"]
+ if self.dragging.get("resize"):
+ original = self.dragging["original"]
+ self.tiles[key] = core_ways.resize_from_drag(
+ original, (point.x - self.dragging["pointer_x"]) / scale,
+ (point.y - self.dragging["pointer_y"]) / scale)
+ self.dragging["moved"] = self.tiles[key] != original
+ self._draw(False)
+ return
if self.dragging.get("display") is not None:
display = self.dragging["display"]
dx = round((point.x - self.dragging["pointer_x"]) / scale)
@@ -1630,6 +1812,13 @@ class AtlasCanvas(AppKit.NSView):
if self.dragging is None:
return
key, moved = self.dragging["key"], self.dragging["moved"]
+ if self.dragging.get("resize"):
+ self.dragging = None
+ AppKit.NSCursor.arrowCursor().set()
+ self._draw(False)
+ if moved:
+ self._commit_resize(key)
+ return
display = self.dragging.get("display")
split_toggle = self.dragging.get("split_toggle", False)
group_toggle = self.dragging.get("group_toggle", False)
@@ -1640,7 +1829,7 @@ class AtlasCanvas(AppKit.NSView):
if preview is not None:
self._draw(True)
AppKit.NSCursor.arrowCursor().set()
- if key != self.own_id and self.on_layout_change and (moved or (display is not None and (split_toggle or group_toggle))):
+ if key != self.fixed_machine_id and self.on_layout_change and (moved or (display is not None and (split_toggle or group_toggle))):
point = self.convertPoint_fromView_(event.locationInWindow(), None)
if display is not None and not moved and (split_toggle or group_toggle):
tile = dict(self.tiles[key])
@@ -1664,12 +1853,16 @@ class AtlasCanvas(AppKit.NSView):
def keyDown_(self, event):
self.keyboard_focus = True
+ if self.machine_picker and event.keyCode() in (36, 49):
+ self.select_tile(self.selected)
+ return
if event.keyCode() == 8 and self._show_recentre():
self.recentre_selected()
return
vectors = {123: (-1, 0), 124: (1, 0), 125: (0, 1), 126: (0, -1)}
vector = vectors.get(event.keyCode())
- if event.keyCode() in (36, 120) and self.selected not in (None, self.own_id) and self.on_rename:
+ if (not self.read_only and not self.machine_picker and event.keyCode() in (36, 120)
+ and self.selected not in (None, self.own_id) and self.on_rename):
self.on_rename(self.selected)
return
if event.keyCode() == 49 and self.cycle_enabled and self.selected not in (None, self.own_id):
@@ -1680,13 +1873,30 @@ class AtlasCanvas(AppKit.NSView):
backwards = bool(event.modifierFlags() & AppKit.NSEventModifierFlagShift)
next_index = ordered.index(self.selected) + (-1 if backwards else 1) if self.selected in ordered else 0
if 0 <= next_index < len(ordered):
- self.select_tile(ordered[next_index])
+ if self.machine_picker:
+ self.selected = ordered[next_index]
+ self._draw(False)
+ else:
+ self.select_tile(ordered[next_index])
return
self.keyboard_focus = False
self._draw(False)
if vector is not None and self.selected not in self.tiles:
return
- if vector is None or self.selected is None or self.selected == self.own_id:
+ if self.read_only and vector is not None:
+ return
+ if vector is not None and event.modifierFlags() & AppKit.NSEventModifierFlagOption:
+ if not self._can_resize(self.selected):
+ return
+ tile = self.tiles[self.selected]
+ long_side = max(tile["w"], tile["h"])
+ resized = core_ways.resize_tile(tile, long_side + (vector[0] + vector[1]) * long_side / 8)
+ if resized != tile:
+ self.tiles[self.selected] = resized
+ self._draw(True)
+ self._commit_resize(self.selected)
+ return
+ if vector is None or self.selected is None or self.selected == self.fixed_machine_id:
objc.super(AtlasCanvas, self).keyDown_(event)
return
tile = dict(self.tiles[self.selected])
@@ -1731,10 +1941,10 @@ class PushStrip(AppKit.NSView):
self._crossing = False
self._flash_timer = None
self.on_change = None
- self.other_name = "Other machine"
+ self.other_name = tr("Other machine")
self.setAccessibilityElement_(True)
self.setAccessibilityRole_(AppKit.NSAccessibilitySliderRole)
- self.setAccessibilityLabel_("Resistance")
+ self.setAccessibilityLabel_(tr("Resistance"))
self.setAccessibilityValue_(self._value)
self._update_accessibility_description()
return self
@@ -1771,7 +1981,7 @@ class PushStrip(AppKit.NSView):
@objc.python_method
def set_other_name(self, name):
- name = name or "Other machine"
+ name = name or tr("Other machine")
if name != self.other_name:
self.other_name = name
self.setNeedsDisplay_(True)
@@ -1791,7 +2001,8 @@ class PushStrip(AppKit.NSView):
return value + "…" if value != self.other_name.upper() else self.other_name.upper()
@objc.python_method
- def show(self, fraction, other_name="Other machine"):
+ def show(self, fraction, other_name=None):
+ other_name = other_name or tr("Other machine")
self.set_value(float(fraction) * self.MAXIMUM)
self.set_other_name(other_name)
@@ -1834,10 +2045,13 @@ class PushStrip(AppKit.NSView):
@objc.python_method
def _update_accessibility_description(self):
pressure = int(round(self._pressure))
- self._accessibility_description = (
- f"Current pressure {pressure} of {self._value} pointer units at the {self._active_edge} edge."
- if pressure > 0 else f"No push. Current pressure is 0 of {self._value} pointer units."
- )
+ if pressure > 0:
+ sentence = tr("Current pressure {pressure} of {value} pointer units at the {edge} edge.")
+ self._accessibility_description = sentence.format(
+ pressure=pressure, value=self._value, edge=tr(core_ways.EDGE_NAMES[self._active_edge]))
+ else:
+ self._accessibility_description = tr("No push. Current pressure is 0 of {value} pointer units.").format(
+ value=self._value)
self.setAccessibilityHelp_(self._accessibility_description)
@objc.python_method
@@ -1948,7 +2162,7 @@ class PushStrip(AppKit.NSView):
path.stroke()
top_font = theme.font(theme.TYPE["eyebrow"], 600)
- local_label = "THIS MAC"
+ local_label = tr("This Mac").upper()
peer_label = self.peer_label_text(width)
text(local_label, 8, 2, width / 2 - 8, 15, top_font, "ink_3", align="left", kern=1.45)
text(peer_label, width / 2, 2, width / 2 - 8, 15, top_font, "ink_3", align="right", kern=1.45)
diff --git a/mac_app/key_codes.py b/mac_app/key_codes.py
index 0351218..2ade983 100644
--- a/mac_app/key_codes.py
+++ b/mac_app/key_codes.py
@@ -25,6 +25,8 @@ SPECIAL_KEY_NAMES = {
0x64: "f8",
0x65: "f9",
0x67: "f11",
+ 0x68: "hangul",
+ 0x66: "hanja",
0x69: "f13",
0x6A: "f16",
0x6B: "f14",
@@ -126,6 +128,8 @@ KEY_TITLES = {
"shift": "Left Shift",
"shift_r": "Right Shift",
"caps_lock": "Caps Lock",
+ "hangul": "Han/Yeong",
+ "hanja": "Hanja",
"esc": "Escape",
"page_up": "Page Up",
"page_down": "Page Down",
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index 6514450..bb2e03f 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -34,6 +34,7 @@ import dock_visibility
from core import crash_log
from core import effects
from core.locale import americanise
+from core.i18n import matches_translation, LANGUAGES, N_, tr, trc, install
import effects_overlay
import gestures
import hardware_mac
@@ -61,6 +62,7 @@ from core import peerlist
from core import settings_sync
from core import ways as core_ways
from core import crossing_state
+from core import profiles
from settings_store import (
SettingsError,
SettingsStore,
@@ -88,9 +90,13 @@ WIDE_WIDTH = 600.0
# Accessibility description per menu-bar state. "held" is input on this Mac with the pointer ways
# in off, by a pause or a full-screen app.
MENU_BAR_STATES = {
- "local": "Input on this Mac",
- "held": "Input held on this Mac; crossing is off",
- "windows": "Input on another machine",
+ "local": N_("Input on this Mac"),
+ "held": N_("Input held on this Mac; crossing is off"),
+ "windows": N_("Input on another machine"),
+}
+CORNER_NAMES = {
+ "top_left": N_("top left"), "top_right": N_("top right"),
+ "bottom_left": N_("bottom left"), "bottom_right": N_("bottom right"),
}
# The menu's one Send input item, by the key rumps files it under, its first title.
TOGGLE_ITEM = "Send input"
@@ -126,7 +132,7 @@ def menu_bar_glyph(state):
image = AppKit.NSImage.imageWithSize_flipped_drawingHandler_((22, 16), True, draw)
image.setTemplate_(True)
- image.setAccessibilityDescription_(MENU_BAR_STATES[state])
+ image.setAccessibilityDescription_(tr(MENU_BAR_STATES[state]))
return image
@@ -898,50 +904,51 @@ def install_main_menu(control_window):
application_item = main_menu.addItemWithTitle_action_keyEquivalent_("Beamer", None, "")
application_menu = AppKit.NSMenu.alloc().initWithTitle_("Beamer")
- item(application_menu, "About Beamer", "showAbout:", "", target=control_window)
+ item(application_menu, tr("About Beamer"), "showAbout:", "", target=control_window)
application_menu.addItem_(AppKit.NSMenuItem.separatorItem())
- item(application_menu, "Hide Beamer", "hide:", "h")
+ item(application_menu, tr("Hide Beamer"), "hide:", "h")
item(
application_menu,
- "Hide Others",
+ tr("Hide Others"),
"hideOtherApplications:",
"h",
AppKit.NSEventModifierFlagCommand | AppKit.NSEventModifierFlagOption,
)
application_menu.addItem_(AppKit.NSMenuItem.separatorItem())
- item(application_menu, "Quit Beamer", "quitApp:", "q", target=control_window)
+ item(application_menu, tr("Quit Beamer"), "quitApp:", "q", target=control_window)
main_menu.setSubmenu_forItem_(application_menu, application_item)
- edit_item = main_menu.addItemWithTitle_action_keyEquivalent_("Edit", None, "")
- edit_menu = AppKit.NSMenu.alloc().initWithTitle_("Edit")
- item(edit_menu, "Undo", "undo:", "z")
+ edit_item = main_menu.addItemWithTitle_action_keyEquivalent_(tr("Edit"), None, "")
+ edit_menu = AppKit.NSMenu.alloc().initWithTitle_(tr("Edit"))
+ item(edit_menu, tr("Undo"), "undo:", "z")
item(
edit_menu,
- "Redo",
+ tr("Redo"),
"redo:",
"z",
AppKit.NSEventModifierFlagCommand | AppKit.NSEventModifierFlagShift,
)
edit_menu.addItem_(AppKit.NSMenuItem.separatorItem())
- item(edit_menu, "Cut", "cut:", "x")
- item(edit_menu, "Copy", "copy:", "c")
- item(edit_menu, "Paste", "paste:", "v")
- item(edit_menu, "Select All", "selectAll:", "a")
+ item(edit_menu, tr("Cut"), "cut:", "x")
+ item(edit_menu, tr("Copy"), "copy:", "c")
+ item(edit_menu, tr("Paste"), "paste:", "v")
+ item(edit_menu, tr("Select All"), "selectAll:", "a")
main_menu.setSubmenu_forItem_(edit_menu, edit_item)
- view_item = main_menu.addItemWithTitle_action_keyEquivalent_("View", None, "")
- view_menu = AppKit.NSMenu.alloc().initWithTitle_("View")
+ view_item = main_menu.addItemWithTitle_action_keyEquivalent_(tr("View"), None, "")
+ view_menu = AppKit.NSMenu.alloc().initWithTitle_(tr("View"))
for index, page in enumerate(pages.PAGES):
- item(view_menu, page[1], "showPage:", str(index + 1), target=control_window).setTag_(index)
+ title = tr(page[1])
+ item(view_menu, title, "showPage:", str(index + 1), target=control_window).setTag_(index)
main_menu.setSubmenu_forItem_(view_menu, view_item)
- window_item = main_menu.addItemWithTitle_action_keyEquivalent_("Window", None, "")
- window_menu = AppKit.NSMenu.alloc().initWithTitle_("Window")
+ window_item = main_menu.addItemWithTitle_action_keyEquivalent_(tr("Window"), None, "")
+ window_menu = AppKit.NSMenu.alloc().initWithTitle_(tr("Window"))
# No target, so these travel the responder chain to whichever window is key rather than
# being bound to one. Closing is safe to offer because the control window is created with
# setReleasedWhenClosed_(False) and the menu-bar item reopens it.
- item(window_menu, "Close", "performClose:", "w")
- item(window_menu, "Minimise", "performMiniaturize:", "m")
+ item(window_menu, tr("Close"), "performClose:", "w")
+ item(window_menu, tr("Minimise"), "performMiniaturize:", "m")
main_menu.setSubmenu_forItem_(window_menu, window_item)
AppKit.NSApp.setWindowsMenu_(window_menu)
@@ -1274,8 +1281,8 @@ class ControlWindow(AppKit.NSObject):
self._select_page,
# Words rather than the address, which wraps mid-path at the sidebar's narrowest; the
# address is in the tooltip.
- footer_text=f"Beamer {VERSION}\nBeamer's website",
- footer_label="Open Beamer's website, kalkmancode.co.uk/beamer",
+ footer_text=tr("Beamer {version}\nBeamer's website").format(version=VERSION),
+ footer_label=tr("Open Beamer's website, kalkmancode.co.uk/beamer"),
on_footer=self._open_beamer_site,
)
self.sidebar.footer_icon.setImage_(menu_bar_glyph("local"))
@@ -1338,7 +1345,12 @@ class ControlWindow(AppKit.NSObject):
"permissions": self._permissions_page,
}
for key, name, _symbol, purpose in pages.PAGES:
- scroll, body = self._page(name, purpose, pages.SCOPE.get(key) if key != "crossing" else None, key)
+ title = tr(name)
+ page_purpose = (tr("Click a machine on the map to set its ways. The ledger says how it reaches each other machine.")
+ if key == "crossing" and profiles.same_ways_on(self.settings_store.current())
+ else tr(purpose))
+ scope = tr(pages.SCOPE[key]) if key in pages.SCOPE and key != "crossing" else None
+ scroll, body = self._page(title, page_purpose, scope, key)
host.addArrangedSubview_(scroll)
scroll.setHidden_(True)
self.pages[key] = scroll
@@ -1526,6 +1538,7 @@ class ControlWindow(AppKit.NSObject):
self.scroll_numeral.set(str(self.scroll_ruler.value))
self.reverse_scroll_box.value = raw["reverse_scroll"]
self.appearance_select.value = raw["appearance"]
+ self.language_select.value = raw["language"]
self._apply_appearance(raw["appearance"])
self.updates_switch.value = raw["check_updates"]
self.pointer_box.value = raw["hide_idle_pointer"]
@@ -1628,18 +1641,18 @@ class ControlWindow(AppKit.NSObject):
if mode == "switch":
choice = self.switch_style_select.value or "match"
fx = effects.switch_effect(choice, style or "glow")
- prefix = "Same as crossing: " if choice == "match" else ""
- self.effect_name.set(f"{prefix}{fx.name}")
+ self.effect_name.set(tr("Same as crossing: {name}").format(name=tr(fx.name)) if choice == "match" else tr(fx.name))
else:
fx = effects.preview_effect(style) if self.effects_ready else effects.CLASSIC.get(style)
if fx is not None:
- self.effect_name.set(f"{fx.name}, {pages.INTENSITIES.get(fx.intensity, fx.intensity).lower()}")
+ self.effect_name.set(tr("{name}, {intensity}").format(
+ name=tr(fx.name), intensity=tr(pages.INTENSITIES.get(fx.intensity, fx.intensity.capitalize())).lower()))
crossing_fx = effects.preview_effect(style) if self.effects_ready else effects.CLASSIC.get(style)
if crossing_fx is not None:
- self.switch_style_select.set_detail("match", f"Plays {crossing_fx.name}")
+ self.switch_style_select.set_detail("match", tr("Plays {name}").format(name=tr(crossing_fx.name)))
motion.set_hidden(self.chosen_box, fx is None)
if fx is not None:
- self.effect_blurb.set(fx.blurb)
+ self.effect_blurb.set(tr(fx.blurb))
# Drawing every still is tens of milliseconds, so only what they show redraws them: the
# 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,
@@ -1650,18 +1663,16 @@ class ControlWindow(AppKit.NSObject):
still.setNeedsDisplay_(True)
self.previews.repaint()
self.tick_note.set(
- {
- "quarters": "A tick at a quarter, half and three quarters of the push, then a double tick as the pointer goes through.",
- "halves": "One tick halfway through the push, then a double tick as the pointer goes through.",
- "breakthrough": "Nothing on the way in, then a double tick as the pointer goes through.",
- }.get(self.tick_steps_select.value, "")
- + " macOS plays them only while a finger is on the trackpad, so press and hold Try it."
- if haptics
- else "Off: the trackpad stays still while you push."
+ ({
+ "quarters": tr("A tick at a quarter, half and three quarters of the push, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."),
+ "halves": tr("One tick halfway through the push, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."),
+ "breakthrough": tr("Nothing on the way in, then a double tick as the pointer goes through. macOS plays them only while a finger is on the trackpad, so press and hold Try it."),
+ }.get(self.tick_steps_select.value, tr(" macOS plays them only while a finger is on the trackpad, so press and hold Try it.")))
+ if haptics else tr("Off: the trackpad stays still while you push.")
)
after = (self.notch_after_select.value or 1200) / 1000
self.notch_note.set(
- f"Once the pointer is through to another machine the notch keeps playing for {after:g} seconds. Outline and Island apply to Glow and Beam; other styles draw their own notch."
+ tr("Once the pointer is through to another machine the notch keeps playing for {seconds} seconds. Outline and Island apply to Glow and Beam; other styles draw their own notch.").format(seconds=f"{after:g}")
)
self._run_previews()
notch_range = self.controller.notch_range
@@ -1675,14 +1686,15 @@ class ControlWindow(AppKit.NSObject):
# this Mac's, and goes where input last went.
several = len(self.settings_store.current()["peers"]) > 1
self.method_boxes["shortcut"].set_detail(
- widgets.key_title(self.key_recorder.value) + (", to where input last went" if several else ""))
+ tr("{key}, to where input last went").format(key=widgets.key_title(self.key_recorder.value))
+ if several else widgets.key_title(self.key_recorder.value))
self.ignored_recorder.set_trigger_code(KEY_NAME_TO_CODE.get(self.key_recorder.value))
hold = self.style_select.value == "hold"
motion.set_hidden(self.double_tap_head, hold)
self.style_hint.set(
- getattr(self, "_trigger_conflict", "") or ("Input is on another machine for as long as the key is held. If you jump while holding the shortcut, releasing it brings input home."
+ getattr(self, "_trigger_conflict", "") or (tr("Input is on another machine for as long as the key is held. If you jump while holding the shortcut, releasing it brings input home.")
if hold
- else "Tap twice to switch; tap twice again to come back."),
+ else tr("Tap twice to switch; tap twice again to come back.")),
ink="amber" if getattr(self, "_trigger_conflict", "") else "ink_2",
)
resistance = self.resistance_ruler.value
@@ -1690,24 +1702,21 @@ class ControlWindow(AppKit.NSObject):
self.push_strip.set_other_name(self._chosen_label())
side = self._selected_ways()["side"]
self.resistance_hint.set(
- "Switches the moment this Mac's pointer touches the edge. Each screen supplies its own zones."
+ tr("Switches the moment this Mac's pointer touches the edge. Each screen supplies its own zones.")
if resistance == 0
- else "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones. "
- f"This screen's {side} edge lights to show the resistance."
+ else tr("Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones. This screen's {side} edge lights to show the resistance.").format(side=tr(core_ways.EDGE_NAMES[side]))
if side
- else "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones."
+ else tr("Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones.")
)
self.modifier_note.set({
- "semantic": "On a PC, Command arrives as Control, so Command-C copies there too, and Control arrives as the Windows key. "
- "Between two Macs every key arrives as itself.",
- "positional": "On a PC, each key arrives as the key in its place, so Command arrives as the Windows key. "
- "Between two Macs every key arrives as itself.",
- }.get(self.modifier_select.value, "Custom: the key map in settings.json is kept as it is."))
+ "semantic": tr("On a PC, Command arrives as Control, so Command-C copies there too, and Control arrives as the Windows key. Between two Macs every key arrives as itself."),
+ "positional": tr("On a PC, each key arrives as the key in its place, so Command arrives as the Windows key. Between two Macs every key arrives as itself."),
+ }.get(self.modifier_select.value, tr("Custom: the key map in settings.json is kept as it is.")))
@objc.python_method
def _selected_ways(self):
if self.chosen_peer is not None:
- return core_ways.ways(self.settings_store.current(), self.chosen_peer)
+ return core_ways.ways(self._view_settings(), self.chosen_peer)
flat = self.controller.cfg.crossing
return dict(side=flat["edge"], methods=flat["methods"], parts=flat["edge_parts"], corner=flat["corner"])
@@ -1720,14 +1729,20 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _load_ways(self, flat=None):
- peers = peerlist.desktops(self.settings_store.current()["peers"])
+ peers = peerlist.desktops(self._view_settings()["peers"])
if self.chosen_peer not in {entry["id"] for entry in peers}:
self.chosen_peer = peers[0]["id"] if peers else None
self._show_machines()
@objc.python_method
def _show_machines(self):
if hasattr(self, "crossing_ledger"):
- self.crossing_ledger.refresh(self.settings_store.current(), self.chosen_peer)
+ remote = self._editing_other()
+ viewed = self._view_settings()
+ self.crossing_ledger.refresh(viewed, self.chosen_peer, remote=remote,
+ read_only=remote and "profiles" not in self._profile_caps().get(self.viewed_machine, ()),
+ has_notch=(self.settings_store.current()["crossing_desk"].get("status", {}).get(
+ self.viewed_machine, {}).get("value", {}).get("platform") == "mac"
+ if remote else self.has_notch))
@objc.python_method
def _machine_picked(self, peer):
# A change still waiting out the pause belongs to the machine being left.
@@ -1753,7 +1768,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _show_arrangement(self, methods=None):
- settings = self.settings_store.current()
+ settings = self._view_settings()
own = settings.get("machine_id", "")
entries = {entry["id"]: entry for entry in peerlist.desktops(settings["peers"])}
stored = self._atlas_layout_for(settings)
@@ -1762,11 +1777,16 @@ class ControlWindow(AppKit.NSObject):
tiles = {key: dict(tile) for key, tile in stored.items() if key not in excluded}
caps = self._design_peer_caps()
capable = self._crossing_args()["capable"]
- result = core_ways.compile_layout(settings, tiles, capable=capable)
+ if self._editing_other():
+ capable = set(tiles)
+ result = core_ways.compile_layout(settings, tiles, capable=capable,
+ platform=profiles.view_platform(self.settings_store.current(), own) if self._editing_other() else "mac")
states = result.get("tiles", {})
names = {peer: self._shown(peerlist.label_for(settings["peers"], peer_id=peer) or peerlist.UNNAMED)
for peer in entries}
- names[own] = "This Mac"
+ names[self.own_id()] = tr("This Mac")
+ if self._editing_other():
+ names[own] = settings["name"]
older = {peer for peer, values in caps.items() if "layout" not in values}
for peer, entry in entries.items():
held = core_ways.ways(settings, peer)
@@ -1787,20 +1807,33 @@ class ControlWindow(AppKit.NSObject):
if peer not in excluded and held["edges"]:
sides = self._reach(peer, settings)["sides"]
state["kept_sides"] = [side for side in core_ways.EDGES if sides[side]["state"] == "kept"]
- state["notch_way"] = bool(peer not in excluded and self.has_notch and "notch" in held["methods"])
+ has_notch = (profiles.view_platform(self.settings_store.current(), own) == "mac"
+ if self._editing_other() else self.has_notch)
+ state["notch_way"] = bool(peer not in excluded and has_notch and "notch" in held["methods"])
states[peer] = state
try:
notch = diagram.notch_span(self.controller.notch_range, self.controller.crossing_display_map())
except Exception:
notch = None
+ if self._editing_other():
+ notch = None
self.atlas_canvas.show_layout(
- tiles, {own: {"state": "this", "platform": "macOS", "notch_span": notch,
+ tiles, {own: {"state": "this", "platform": ("macOS" if not self._editing_other()
+ or profiles.view_platform(self.settings_store.current(), own) == "mac" else "PC"), "notch_span": notch,
"machine_name": settings.get("name", "") or socket.gethostname().split(".")[0]}, **states},
- names, own, self.chosen_peer or own,
+ names, own, own if profiles.same_ways_on(self.settings_store.current()) else self.chosen_peer or own,
cycle={peer: entry.get("shortcut_cycle") is not False for peer, entry in entries.items()},
- cycle_enabled=(self.shortcut_goes_to.value or "last") == "ticked", older=older,
- animate=motion.live(self.atlas_canvas))
+ cycle_enabled=not self._editing_other() and (self.shortcut_goes_to.value or "last") == "ticked", older=older,
+ animate=motion.live(self.atlas_canvas),
+ tile_words={machine: profiles.tile_word(self.settings_store.current(), machine,
+ linked=machine == self.own_id() or self._live(machine),
+ caps=("profiles",) if machine == self.own_id() else self._profile_caps().get(machine, ()))
+ for machine in tiles},
+ machine_picker=profiles.same_ways_on(self.settings_store.current()),
+ fixed_machine_id=self.own_id(),
+ read_only=self._editing_other() and "profiles" not in self._profile_caps().get(own, ()))
self._show_machines()
+ self._show_profiles()
@objc.python_method
def _atlas_default_layout(self, settings):
return core_ways.derive_layout(settings, gap=0)
@@ -1811,6 +1844,13 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _atlas_selected(self, peer):
+ if profiles.same_ways_on(self.settings_store.current()):
+ self._flush()
+ self.viewed_machine = peer
+ self.chosen_peer = None
+ self._load_ways()
+ self._show_arrangement()
+ return
if peer == self.own_id():
self.atlas_canvas.selected = self.chosen_peer or self.own_id()
self.atlas_canvas._draw(False)
@@ -1854,21 +1894,28 @@ class ControlWindow(AppKit.NSObject):
self.atlas_canvas.show_layout(previous, {}, {}, held.get("machine_id", ""), self.chosen_peer, animate=False)
return
if not outcome["accepted"]:
- labels = {entry.get("id"): peerlist.label_for(held["peers"], peer_id=entry.get("id")) or "Machine"
+ labels = {entry.get("id"): peerlist.label_for(held["peers"], peer_id=entry.get("id")) or tr("Machine")
for entry in peerlist.desktops(held["peers"])}
self.atlas_canvas.show_layout(previous, {}, labels,
held.get("machine_id", ""), self.chosen_peer, animate=True)
- self._say("Refused: that position is already occupied.", "fault")
+ self._say(tr("Refused: that position is already occupied."), "fault")
return
self._load_ways()
self._reflect()
if moved in outcome["settings"]["layout"]:
tile_state = dict(outcome["tiles"].get(moved, {}))
tile_state["crosses"] = core_ways.crosses_on_map(self.settings_store.current(), moved)
- self.atlas_canvas.announce_move(moved, outcome["settings"]["layout"][moved], tile_state)
+ before = previous.get(moved, {})
+ after = outcome["settings"]["layout"][moved]
+ if (before.get("w"), before.get("h")) != (after["w"], after["h"]):
+ self.atlas_canvas.announce_resize(moved)
+ else:
+ self.atlas_canvas.announce_move(moved, after, tile_state)
@objc.python_method
def _begin_atlas_rename(self, peer):
+ if self._editing_other():
+ return
if peer in self.crossing_ledger.rows:
self.crossing_ledger.rows[peer].begin_rename()
def control_textView_doCommandBySelector_(self, control, _text_view, selector):
@@ -1893,6 +1940,8 @@ class ControlWindow(AppKit.NSObject):
row.finish_rename(False)
@objc.python_method
def _set_atlas_left_out(self, peer, enabled):
+ if self._editing_other():
+ return
self._flush()
settings = self.settings_store.current()
entry = next((item for item in settings["peers"] if item.get("id") == peer), None)
@@ -1914,6 +1963,8 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _set_shortcut_cycle(self, peer, enabled):
+ if hasattr(self, "viewed_machine") and self._editing_other():
+ return
self._flush()
try:
with self.settings_store.lock:
@@ -1947,19 +1998,19 @@ class ControlWindow(AppKit.NSObject):
entry = self._focus_entry()
if entry is None:
self.peer.value.set("—")
- self.peer_footer.set("Not paired")
+ self.peer_footer.set(tr("Not paired"))
return
self.peer.value.set(self._shown(self._machine_label()))
host, port = entry.get("host"), entry.get("port")
if not host:
- self.peer_footer.set("No address")
+ self.peer_footer.set(tr("No address"))
else:
# The port does not fit a third of the status module at the narrow grid.
self.peer_footer.set(self._shown(f"{host}:{port}" if self.wide else host))
@objc.python_method
def _first_label(self):
- return self.controller.peer_label or "the other machine"
+ return self.controller.peer_label or tr("the other machine")
@objc.python_method
def _focus_entry(self):
@@ -2012,6 +2063,8 @@ class ControlWindow(AppKit.NSObject):
def _live(self, peer):
"""Whether `peer` has a link up now, either way. One that has none gives way on the Crossing
page and to an arrangement (core/ways.py give_way)."""
+ if peer == self.own_id():
+ return True
link = self.controller._peers_up.get(peer)
return (link is not None and link.live()) or peer in self.inbound_ids()
@@ -2265,6 +2318,8 @@ class ControlWindow(AppKit.NSObject):
self.page_titles[key] = heading
widgets.add(header, heading.view)
purpose_label = widgets.Label(purpose, theme.TYPE["body"], ink="ink_2", wrap=True)
+ if key == "crossing":
+ self.crossing_intro = purpose_label
purpose_label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)
widgets.add(header, purpose_label.view)
if scope is not None:
@@ -2302,11 +2357,11 @@ class ControlWindow(AppKit.NSObject):
saved = self.settings_store.save_settings(raw)
except (SettingsError, TypeError, ValueError) as exc:
self.logger.exception("This Mac's name could not be saved")
- self._say(f"Could not save this Mac's name: {exc}", "fault")
+ self._say(tr("Could not save this Mac's name: {error}").format(error=exc), "fault")
return
cfg = self.settings_store._config(saved)
self.controller.apply_settings(cfg)
- display = saved.get("name", "") or socket.gethostname().split(".")[0] or "Mac"
+ display = saved.get("name", "") or socket.gethostname().split(".")[0] or tr("Mac")
self.panel._own_rename_views[0].setStringValue_(display)
if settings_sync.group_on(cfg, "names"):
self._send_same()
@@ -2322,7 +2377,7 @@ class ControlWindow(AppKit.NSObject):
saved = self.settings_store.save_settings(raw)
except (SettingsError, TypeError, ValueError) as exc:
self.logger.exception("A machine's name could not be saved")
- self._say(f"Could not save the machine's name: {exc}", "fault")
+ self._say(tr("Could not save the machine's name: {error}").format(error=exc), "fault")
return
self.controller.apply_settings(self.settings_store._config(saved))
self.panel.refresh()
@@ -2346,42 +2401,45 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _same_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Settings"))
- module.add(widgets.label("Same on all machines", theme.TYPE["body"]))
+ module.add(widgets.eyebrow(tr("Settings")))
+ module.add(widgets.label(tr("Same on all machines"), theme.TYPE["body"]))
self.same_checks = {}
- for key, title in (("crossing", "Crossing"), ("design", "Design"), ("shortcut", "Shortcut"), ("names", "Names")):
+ for key, title in (("crossing", N_("Crossing")), ("design", N_("Design")),
+ ("shortcut", N_("Shortcut")), ("names", N_("Names"))):
button = AppKit.NSButton.alloc().initWithFrame_(((0, 0), (0, 0)))
button.setTranslatesAutoresizingMaskIntoConstraints_(False)
button.setFont_(theme.font(theme.TYPE["body"]))
button.setButtonType_(AppKit.NSButtonTypeSwitch)
- button.setTitle_(title)
+ button.setTitle_(tr(title))
button.setTarget_(self)
button.setAction_("sameGroupsChanged:")
button.setTag_(("crossing", "design", "shortcut", "names", "everything").index(key))
module.add(button, full_width=False)
self.same_checks[key] = button
- module.add(widgets.note(
+ module.add(widgets.note(tr(
"Crossing shares resistance and drag protection. Design shares effects, colour, length, size and arrival animation. "
"Shortcut shares shortcut on/off, trigger key and style, and destination. Names shares this machine's name and paired-machine labels."
- ).view)
+ )).view)
button = AppKit.NSButton.alloc().initWithFrame_(((0, 0), (0, 0)))
button.setTranslatesAutoresizingMaskIntoConstraints_(False)
button.setFont_(theme.font(theme.TYPE["body"]))
button.setButtonType_(AppKit.NSButtonTypeSwitch)
- button.setTitle_("Everything")
+ button.setTitle_(tr("Everything"))
button.setTarget_(self)
button.setAction_("sameGroupsChanged:")
button.setTag_(4)
module.add(button, full_width=False)
self.same_checks["everything"] = button
- self.same_everything_note = widgets.note("Shares every group and can replace local values on this machine.")
+ self.same_everything_note = widgets.note(tr("Shares every group and can replace local values on this machine."))
module.add(self.same_everything_note.view)
- self.same_old_note = widgets.note("Older Beamer versions share known Crossing and Design settings without group choices.")
+ self.same_old_note = widgets.note(tr("Older Beamer versions share known Crossing and Design settings without group choices."))
module.add(self.same_old_note.view)
- self.same_revert = widgets.Button("Revert", self, "revertSame:", scale="small")
+ self.same_revert = widgets.Button(tr("Revert"), self, "revertSame:", scale="small")
module.add(self.same_revert.view)
self.same_note = widgets.note()
module.add(self.same_note.view)
+ self.same_ways_note = widgets.note()
+ module.add(self.same_ways_note.view)
return module
def sameGroupsChanged_(self, sender):
@@ -2393,9 +2451,9 @@ class ControlWindow(AppKit.NSObject):
self._set_same_groups(selected)
@objc.python_method
- def _own_note(self, text=pages.OWN_ROW):
+ def _own_note(self):
"""A note on a row this Mac keeps to itself, shown only while the pages are kept in step."""
- note = widgets.note(text)
+ note = widgets.note(tr(pages.OWN_ROW))
note.view.setHidden_(True)
self.own_notes.append(note)
return note.view
@@ -2424,6 +2482,8 @@ class ControlWindow(AppKit.NSObject):
on = cfg.same_on_both
self.same_note.set(settings_sync.group_note(groups, on), ink="ink_2")
self.same_note.view.setToolTip_(settings_sync.switch_detail("mac"))
+ self.same_ways_note.set(tr("Ways: set on the Crossing page · {state}").format(
+ state=tr("On") if profiles.same_ways_on(self.settings_store.current()) else tr("Off")))
for key, label in self.scope_labels.items():
text = settings_sync.scope(key, who, on, pages.SCOPE.get(key), "mac", groups=groups)
if label.text != text:
@@ -2622,6 +2682,9 @@ class ControlWindow(AppKit.NSObject):
peer_id = protocol.id_text(peer) if isinstance(peer, bytes) else peer
if peer_id is not None and peer_id not in {entry.get("id") for entry in peerlist.desktops(self.controller.book.peers())}:
return
+ if "desk" in data:
+ self._receive_desk(data, peer_id)
+ return
settings = copy.deepcopy(self.settings_store.current())
cfg = self.controller.cfg
taken = settings_sync.arrived(data, cfg.same_set_at, KEY_NAME_TO_CODE, by_here=cfg.same_by,
@@ -2652,7 +2715,7 @@ class ControlWindow(AppKit.NSObject):
self.controller.apply_settings(self.settings_store._config(saved))
self.panel.refresh()
if own_name is not None and hasattr(self.panel, "_own_rename_views"):
- display = own_name or socket.gethostname().split(".")[0] or "Mac"
+ display = own_name or socket.gethostname().split(".")[0] or tr("Mac")
self.panel._own_rename_views[0].setStringValue_(display)
cfg = self.controller.cfg
layout_applied = self._receive_layout(data, peer_id)
@@ -2747,16 +2810,29 @@ class ControlWindow(AppKit.NSObject):
self.refresh()
return True
+ @objc.python_method
+ def _receive_desk(self, data, peer):
+ if peer is None or "profiles" not in self._design_peer_caps().get(peer, ()):
+ return False
+ outcome = self.controller.receive_desk(data, peer, linked=self._live(peer),
+ live=self._live, gone=self._gone, now=time.time())
+ if outcome is None:
+ return False
+ self._load_ways()
+ self._show_arrangement()
+ self.refresh()
+ return outcome["changed"]
+
@objc.python_method
def _login_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("At login"))
- self.login_switch = widgets.Switch("Start Beamer when you log in", on_change=self._set_login)
+ module.add(widgets.eyebrow(tr("At login")))
+ self.login_switch = widgets.Switch(tr("Start Beamer when you log in"), on_change=self._set_login)
module.add(self.login_switch.view)
self.login_note = widgets.note()
module.add(self.login_note.view)
self.login_approval_button = widgets.Button(
- "Open Login Items settings", self, "openLoginItemsSettings:", full_width=True
+ tr("Open Login Items settings"), self, "openLoginItemsSettings:", full_width=True
)
self.login_approval_button.view.setHidden_(True)
module.add(self.login_approval_button.view)
@@ -2767,15 +2843,15 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _dock_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Window"))
- self.dock_switch = widgets.Switch("Show in Dock", on_change=self._set_show_in_dock)
- self.tray_switch = widgets.Switch("Show in menu bar", on_change=self._set_show_in_tray)
+ module.add(widgets.eyebrow(tr("Window")))
+ self.dock_switch = widgets.Switch(tr("Show in Dock"), on_change=self._set_show_in_dock)
+ self.tray_switch = widgets.Switch(tr("Show in menu bar"), on_change=self._set_show_in_tray)
module.add(self.dock_switch.view)
module.add(self.tray_switch.view)
- module.add(widgets.note(
+ module.add(widgets.note(tr(
"With the Dock icon off, Beamer stays in the menu bar and appears in the Dock while its window is open. "
"The Dock and the menu bar are never both off: the one still showing cannot be switched off."
- ).view)
+ )).view)
self._reflect_visibility()
return module
@@ -2822,14 +2898,14 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _updates_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Updates"))
- self.updates_switch = widgets.Switch("Check for updates", on_change=self._set_check_updates)
+ module.add(widgets.eyebrow(tr("Updates")))
+ self.updates_switch = widgets.Switch(tr("Check for updates"), on_change=self._set_check_updates)
self.updates_switch.value = self.controller.cfg.check_updates
module.add(self.updates_switch.view)
- module.add(widgets.note(
+ module.add(widgets.note(tr(
"Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."
- ).view)
- self.update_button = widgets.Button("Download", self, "downloadUpdate:", style="primary", full_width=True)
+ )).view)
+ self.update_button = widgets.Button(tr("Download"), self, "downloadUpdate:", style="primary", full_width=True)
self.update_button.view.setHidden_(True)
module.add(self.update_button.view)
self.update_url = None
@@ -2854,7 +2930,7 @@ class ControlWindow(AppKit.NSObject):
"""`found` is (version, url) for a newer release, or None."""
self.update_url = found[1] if found else None
if found:
- self.update_button.set_title(f"Download Beamer {found[0]}")
+ self.update_button.set_title(tr("Download Beamer {version}").format(version=found[0]))
motion.set_hidden(self.update_button.view, found is None)
def downloadUpdate_(self, _sender):
@@ -2872,32 +2948,33 @@ class ControlWindow(AppKit.NSObject):
in_applications = login_item.installed_in_applications(self.login_bundle_path)
self.login_switch.set_enabled(login_item.can_toggle(state, self.login_bundle_path))
if refused:
- self.login_note.set(f"macOS refused: {refused}")
+ # Translators: {reason} is the system's reason for refusing the login item.
+ self.login_note.set(tr("macOS refused: {reason}").format(reason=refused))
elif state == login_item.REQUIRES_APPROVAL:
if in_applications:
self.login_note.set(
- "Login item status: Requires approval. Allow Beamer in System Settings, General, Login Items."
+ tr("Login item status: Requires approval. Allow Beamer in System Settings, General, Login Items.")
)
else:
self.login_note.set(
- "Login item status: Requires approval. Move Beamer to Applications and reopen it before allowing it in Login Items."
+ tr("Login item status: Requires approval. Move Beamer to Applications and reopen it before allowing it in Login Items.")
)
elif not in_applications:
self.login_note.set(
- f"Login item status: {login_item.status_text(state)}. Move Beamer to Applications and open it there to start at login."
+ tr("Login item status: {status}. Move Beamer to Applications and open it there to start at login.").format(status=login_item.status_text(state))
)
elif state == login_item.NOT_FOUND:
self.login_note.set(
- "Login item status: Not found. Check Beamer is installed in Applications, then turn it on again."
+ tr("Login item status: Not found. Check Beamer is installed in Applications, then turn it on again.")
)
elif state == login_item.ENABLED:
- self.login_note.set("Login item status: Enabled. Beamer will start when you log in.")
+ self.login_note.set(tr("Login item status: Enabled. Beamer will start when you log in."))
elif state == login_item.NOT_REGISTERED:
self.login_note.set(
- "Login item status: Not registered. Turn on Start Beamer when you log in."
+ tr("Login item status: Not registered. Turn on Start Beamer when you log in.")
)
else:
- self.login_note.set(f"Login item status: {login_item.status_text(state)}.")
+ self.login_note.set(tr("Login item status: {status}.").format(status=login_item.status_text(state)))
self.login_approval_button.view.setHidden_(state != login_item.REQUIRES_APPROVAL)
def openLoginItemsSettings_(self, _sender):
@@ -2905,7 +2982,7 @@ class ControlWindow(AppKit.NSObject):
login_item.open_system_settings()
except Exception as exc:
self.logger.warning("could not open Login Items settings: %s", exc)
- self.login_note.set(f"Could not open Login Items settings: {exc}")
+ self.login_note.set(tr("Could not open Login Items settings: {reason}").format(reason=exc))
@objc.python_method
def _set_login(self, enabled):
@@ -2925,9 +3002,15 @@ class ControlWindow(AppKit.NSObject):
# The ledger's Keys cells use the global shortcut's recorder.
self.shortcut_module = self._shortcut_module()
self.resistance_module = self._resistance_module()
+ self.viewed_machine = self.own_id()
machines = self._ways_module()
- for module in (machines, self._pointer_module(), self.resistance_module, self.shortcut_module):
+ self.pointer_module = self._pointer_module()
+ for module in (machines, self.own_ways_module, self.ways_ledger_module, self._home_module(), self.pointer_module,
+ self.resistance_module, self.shortcut_module):
widgets.add(body, module.view)
+ own_width = self.own_ways_module.view.widthAnchor().constraintEqualToAnchor_(self.ways_ledger_module.view.widthAnchor())
+ own_width.setPriority_(999)
+ own_width.setActive_(True)
# The table must fill the page before its notes' preferred reading width is solved.
for constraint in body.constraints():
if constraint.firstItem() == machines.view and constraint.firstAttribute() == AppKit.NSLayoutAttributeWidth:
@@ -2951,7 +3034,7 @@ class ControlWindow(AppKit.NSObject):
self._trackpad_module(), self._appearance_module()):
widgets.add(body, module.view)
self.follow_module = widgets.Module()
- self.follow_module.add(widgets.eyebrow("Match design with"))
+ self.follow_module.add(widgets.eyebrow(tr("Match design with")))
self.follow_host = widgets.stack(spacing=0)
self.follow_module.add(self.follow_host)
self.follow_note = widgets.note()
@@ -2979,12 +3062,12 @@ class ControlWindow(AppKit.NSObject):
return
peers = peerlist.desktops(self.settings_store.current()["peers"])
labels = peerlist.labels(peers)
- choices = [("", "None")]
+ choices = [("", tr("None"))]
caps = self._design_peer_caps()
rows = settings_sync.follow_rows(peers, caps, self._design_states, self.controller.cfg.design_follow_peer)
unsupported = {entry["id"]: why_not for entry, why_not in rows if why_not is not None}
for entry, why_not in rows:
- title = labels.get(entry.get("token", "")) or "Machine"
+ title = labels.get(entry.get("token", "")) or tr("Machine")
if why_not == settings_sync.NEEDS_DESIGN_SYNC:
title += f" — {why_not}"
choices.append((entry["id"], title))
@@ -3041,13 +3124,13 @@ class ControlWindow(AppKit.NSObject):
"""The settings window's own palette. Last on the page: it is chosen once, and the modules
above are what the page is for."""
module = widgets.Module()
- module.add(widgets.eyebrow("Appearance"))
+ module.add(widgets.eyebrow(tr("Appearance")))
module.add(self._own_note())
self.appearance_select = widgets.Segmented(
- [("system", "System"), ("light", "Light"), ("dark", "Dark")], on_change=self._appearance_chosen
+ [("system", tr("System")), ("light", trc("appearance", "Light")), ("dark", tr("Dark"))], on_change=self._appearance_chosen
)
- module.add(widgets.field_row("This window", self.appearance_select.view)[0])
- module.add(widgets.note("System follows your Mac's light or dark setting.").view)
+ module.add(widgets.field_row(tr("This window"), self.appearance_select.view)[0])
+ module.add(widgets.note(tr("System follows your Mac's light or dark setting.")).view)
return module
@objc.python_method
@@ -3095,21 +3178,21 @@ class ControlWindow(AppKit.NSObject):
hand's movement, and this Mac's settings decide the rest."""
module = widgets.Module()
figure, self.pointer_numeral = self._numeral("%")
- module.add(self._head("Another machine's pointer here", figure))
+ module.add(self._head(tr("Another machine's pointer here"), figure))
self.pointer_ruler = widgets.Ruler(
25, 400, (25, 100, 200, 300, 400), step=5, minor=25, on_change=self._speed_moved,
- title="Pointer speed", arrow_step=25,
+ title=tr("Pointer speed"), arrow_step=25,
)
module.add(self.pointer_ruler.view)
- module.add(widgets.note("Pointer speed for another machine's mouse or trackpad while it drives this Mac.").view)
+ module.add(widgets.note(tr("Pointer speed for another machine's mouse or trackpad while it drives this Mac.")).view)
figure, self.scroll_numeral = self._numeral("%")
- module.add(self._head("Scrolling", figure))
+ module.add(self._head(tr("Scrolling"), figure))
self.scroll_ruler = widgets.Ruler(
25, 400, (25, 100, 200, 300, 400), step=5, minor=25, on_change=self._speed_moved,
- title="Scroll speed", arrow_step=25,
+ title=tr("Scroll speed"), arrow_step=25,
)
module.add(self.scroll_ruler.view)
- self.reverse_scroll_box = widgets.Switch("Reverse other machines' scrolling", on_change=self._changed)
+ self.reverse_scroll_box = widgets.Switch(tr("Reverse other machines' scrolling"), on_change=self._changed)
module.add(self.reverse_scroll_box.view)
return module
@@ -3131,7 +3214,7 @@ class ControlWindow(AppKit.NSObject):
def _status_module(self):
module = widgets.Module()
head = widgets.stack(vertical=False, spacing=7)
- head.addArrangedSubview_(widgets.hug(widgets.eyebrow("Link"), AppKit.NSLayoutPriorityDefaultLow))
+ head.addArrangedSubview_(widgets.hug(widgets.eyebrow(tr("Link")), AppKit.NSLayoutPriorityDefaultLow))
self.link_led = widgets.LED()
head.addArrangedSubview_(self.link_led.view)
self.link_tag = widgets.Label("", theme.TYPE["eyebrow"], 700, "ink_3", tracking=theme.TRACKING["eyebrow"], upper=True)
@@ -3146,10 +3229,10 @@ class ControlWindow(AppKit.NSObject):
module.add(self.state_detail.view)
self.spark = widgets.size(widgets.flipped(widgets.Spark), height=14)
# The time a move takes to reach the PC and be answered, while input is there.
- self.round_trip = widgets.Readout("Delay", "ms", self.spark)
+ self.round_trip = widgets.Readout(tr("Delay"), "ms", self.spark)
self.peer_footer = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")
widgets.squeeze(self.peer_footer.view)
- self.peer = widgets.Readout("Machine", "", self.peer_footer.view, sizes=(theme.PEER_SIZE, theme.PEER_SIZE_NARROW))
+ self.peer = widgets.Readout(tr("Machine"), "", self.peer_footer.view, sizes=(theme.PEER_SIZE, theme.PEER_SIZE_NARROW))
module.add(widgets.grid([self.round_trip.view, self.peer.view], 2))
return module
@@ -3158,33 +3241,33 @@ class ControlWindow(AppKit.NSObject):
"""Sending input by hand and pausing the edge, together as on the PC. Where input is now is
the status word above; a MAC / WINDOWS indicator here only said it twice."""
module = widgets.Module(spacing=12)
- module.add(widgets.eyebrow("Keyboard and pointer"))
+ module.add(widgets.eyebrow(tr("Keyboard and pointer")))
self.toggle_button = widgets.Button(
- "Send input", self, "toggleRedirect:", style="primary", scale="big", full_width=True
+ tr("Send input"), self, "toggleRedirect:", style="primary", scale="big", full_width=True
)
module.add(self.toggle_button.view)
self.pause_row = widgets.stack(spacing=8)
- self.pause_button = widgets.Button("Pause crossing", self, "togglePause:", full_width=True)
+ self.pause_button = widgets.Button(tr("Pause crossing"), self, "togglePause:", full_width=True)
widgets.add(self.pause_row, self.pause_button.view)
self.crossing_state = widgets.note()
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 this Mac's edges while an app on it is full screen", on_change=self._hold_changed)
+ self.hold_box = widgets.Switch(tr("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())
- self.hold_note = widgets.note(
+ self.hold_note = widgets.note(tr(
"This screen decides, including when another machine drives it. On, a full-screen app here holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer can go home or onward through the configured ways."
- )
+ ))
module.add(self.hold_note.view)
- self.hold_box.view.setToolTip_("This screen's setting applies to every pointer on it.")
- self.pointer_box = widgets.Switch("Hide the pointer on the machine not in use", on_change=self._set_hide_idle_pointer)
+ self.hold_box.view.setToolTip_(tr("This screen's setting applies to every pointer on it."))
+ self.pointer_box = widgets.Switch(tr("Hide the pointer on the machine not in use"), on_change=self._set_hide_idle_pointer)
self.pointer_box.value = self.controller.cfg.hide_idle_pointer
module.add(self.pointer_box.view)
- module.add(widgets.note(
+ module.add(widgets.note(tr(
"This Mac's pointer always hides while it drives another machine. On, it also hides after another "
"machine stops driving it, until its own mouse or trackpad moves."
- ).view)
+ )).view)
return module
@objc.python_method
@@ -3203,7 +3286,7 @@ class ControlWindow(AppKit.NSObject):
def _resistance_module(self):
module = widgets.Module()
figure, self.resistance_numeral = self._numeral("px")
- module.add(self._head("Resistance", figure))
+ module.add(self._head(tr("Resistance"), figure))
self.push_strip = diagram.PushStrip.alloc().init().setup()
self.push_strip.on_change = self._preview_resistance
self.resistance_ruler = self.push_strip
@@ -3215,7 +3298,36 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _ways_module(self):
module = widgets.Module()
- module.add(widgets.Label("Machines", theme.TYPE["body"], 600).view)
+ self.profile_tabs = widgets.stack(vertical=False, spacing=6)
+ self.profile_tabs.setDetachesHiddenViews_(True)
+ self.profile_buttons = {}
+ self._profile_tabs_key = None
+ self.ways_switch = widgets.Switch(tr("Same ways on every machine"),
+ on_change=lambda on: self._profile_event(crossing_state.set_same_ways, on))
+ widgets.hug(self.ways_switch.view)
+ widgets.hug(self.ways_switch.words.view)
+ widgets.hug(self.ways_switch.view.subviews()[0], AppKit.NSLayoutPriorityDefaultHigh)
+ widgets.hug(self.profile_tabs, AppKit.NSLayoutPriorityDefaultLow)
+ self.profile_top = widgets.SideBySide(self.profile_tabs, self.ways_switch.view, 120, 260, gap=16)
+ self.side_by_side.append(self.profile_top)
+ module.add(self.profile_top.view)
+ self.profile_actions = widgets.stack(vertical=False, spacing=12)
+ self.new_profile_button = widgets._autolayout(ledger.quiet_button(tr("New profile…"), lambda: self._profile_name()))
+ self.rename_profile_button = widgets._autolayout(ledger.quiet_button(tr("Rename"),
+ lambda: self._profile_name(self.settings_store.current()["crossing_desk"]["active"]["value"])))
+ # A click on a tab switches the whole desk, so a tab cannot be picked for an action: Rename
+ # names the active profile, and Delete offers the others (the active one never goes).
+ self.delete_profile_button = widgets._autolayout(ledger.quiet_button(tr("Delete…"),
+ self._show_delete_profile_menu))
+ for button in (self.new_profile_button, self.rename_profile_button, self.delete_profile_button):
+ self.profile_actions.addArrangedSubview_(widgets.hug(button))
+ module.add(self.profile_actions, full_width=False)
+ self.ways_off_note = widgets.note(tr("Set every machine's ways from this screen. Turning it on changes nothing until you do; each machine's own ways are kept."))
+ module.add(self.ways_off_note.view)
+ self.older_ways_notice = widgets.note()
+ if self.settings_store.take_profile_load_note("older_version"):
+ self.older_ways_notice.set(tr("This machine kept the ways set while it ran an older Beamer."))
+ self.older_ways_notice.view.setHidden_(not bool(self.older_ways_notice.text))
self.atlas_canvas = diagram.AtlasCanvas.alloc().init().setup()
self.arrangement_diagram = self.atlas_canvas
self.atlas_canvas.on_layout_change = self._atlas_layout_changed
@@ -3225,11 +3337,11 @@ class ControlWindow(AppKit.NSObject):
self.atlas_canvas.on_cycle_change = self._set_shortcut_cycle
self.atlas_canvas.on_leave_out = lambda peer: self._set_atlas_left_out(peer, True)
module.add(self.atlas_canvas)
- self.atlas_canvas_hint = widgets.note("Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out")
+ self.atlas_canvas_hint = widgets.note(tr("Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"))
module.add(self.atlas_canvas_hint.view)
module.body.setCustomSpacing_afterView_(8, self.atlas_canvas)
- crosses = widgets.Label("● Crosses", theme.TYPE["note"], 500, "signal").view
- offline = widgets.Label("● Offline, ways kept", theme.TYPE["note"], 500, "ink_3").view
+ crosses = widgets.Label(tr("● Crosses"), theme.TYPE["note"], 500, "signal").view
+ offline = widgets.Label(tr("● Offline, ways kept"), theme.TYPE["note"], 500, "ink_3").view
self.atlas_legend_pair = widgets.SideBySide(crosses, offline, 80, 125, gap=18)
for view, width in ((crosses, 80), (offline, 125)):
preferred = view.widthAnchor().constraintEqualToConstant_(width)
@@ -3238,19 +3350,381 @@ class ControlWindow(AppKit.NSObject):
self.side_by_side.append(self.atlas_legend_pair)
self.atlas_legend = self.atlas_legend_pair.view
module.add(self.atlas_legend)
+ self.profile_switch_note = widgets.note(tr("Switching moves every machine to this profile's places and ways."))
+ module.add(self.profile_switch_note.view)
+ self.ways_ledger_module = widgets.Module()
+ self.ledger_heading = widgets.Label(tr("Machines"), theme.TYPE["body"], 600)
+ self.ways_ledger_module.add(self.ledger_heading.view)
+ self.edit_header = widgets.stack(vertical=False, spacing=8)
+ self.edit_notice = widgets.note(reading=False)
+ widgets.hug(self.edit_notice.view, AppKit.NSLayoutPriorityDefaultLow)
+ self.back_ways_button = widgets._autolayout(ledger.quiet_button(tr("Back to This Mac"), lambda: self._atlas_selected(self.own_id())))
+ self.edit_header.addArrangedSubview_(self.edit_notice.view)
+ self.edit_header.addArrangedSubview_(widgets.hug(self.back_ways_button))
+ self.ways_ledger_module.add(self.edit_header, full_width=False)
+ self.profile_status = widgets.note()
+ self.ways_ledger_module.add(self.profile_status.view)
+ self.remote_changes_note = widgets.note()
+ self.ways_ledger_module.add(self.remote_changes_note.view)
+ self.remote_permissions_note = widgets.note()
+ self.ways_ledger_module.add(self.remote_permissions_note.view)
+ self.own_ways_module = widgets.Module()
+ self.own_ways_button = widgets.action_button(tr("Keep this machine's own ways"),
+ lambda: self._profile_event(crossing_state.set_own_ways, True), scale="small")
+ self.use_desk_button = widgets.action_button(tr("Use the desk's ways"),
+ lambda: self._profile_event(crossing_state.set_own_ways, False), scale="small")
+ self.share_ways_button = widgets.action_button(tr("Share mine with the desk"),
+ lambda: self._profile_event(crossing_state.share_mine), scale="small")
+ self.own_ways_title = widgets.stack(vertical=False, spacing=8)
+ self.own_ways_dot = widgets.box("amber", radius=3)
+ widgets.size(self.own_ways_dot, 6, 6)
+ self.own_ways_note = widgets.Label(tr("This Mac keeps its own ways"), theme.TYPE["body"], 600, wrap=True)
+ self.own_ways_title.addArrangedSubview_(self.own_ways_dot)
+ self.own_ways_title.addArrangedSubview_(self.own_ways_note.view)
+ self.own_ways_module.add(self.own_ways_title)
+ self.own_actions_pair = widgets.SideBySide(self.use_desk_button.view, self.share_ways_button.view,
+ 160, 190, gap=8)
+ self.side_by_side.append(self.own_actions_pair)
+ self.own_ways_module.add(self.own_actions_pair.view)
+ self.saved_toggle = widgets._autolayout(ledger.quiet_button(tr("Earlier ways ▾"), self._toggle_earlier))
+ self.own_toggle_row = widgets.SideBySide(self.own_ways_button.view, self.saved_toggle, 210, 100, gap=16)
+ widgets.hug(self.saved_toggle)
+ self.side_by_side.append(self.own_toggle_row)
+ self.own_ways_module.add(self.own_toggle_row.view)
+ self.earlier_host = widgets.stack(spacing=8)
+ self.earlier_host.setHidden_(True)
+ self.earlier_buttons = {}
+ self._earlier_pairs = []
+ self._earlier_key = None
+ self.own_ways_module.add(self.earlier_host)
+ self.own_ways_module.add(self.older_ways_notice.view)
self.crossing_ledger = ledger.Ledger.alloc().init().setup(self)
- module.add(self.crossing_ledger)
- module.add(widgets.note("Each chip is a side of this screen; click one to add or remove it. The side a machine touches crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. A corner is a diagonal push, shown as a square on the map. The notch is this Mac only.").view)
+ self.ways_ledger_module.add(self.crossing_ledger)
+ self.ways_ledger_module.add(widgets.note(tr("Each chip is a side of this screen; click one to add or remove it. The side a machine touches crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. A corner is a diagonal push, shown as a square on the map. The notch is this Mac only.")).view)
return module
@objc.python_method
def _pointer_module(self):
module = widgets.Module()
- module.add(widgets.Label("This machine's pointer", theme.TYPE["body"], 600).view)
- self.dragging_box = widgets.Switch("Don't cross while dragging with this Mac's pointer", on_change=self._changed)
+ module.add(widgets.Label(tr("This machine's pointer"), theme.TYPE["body"], 600).view)
+ self.dragging_box = widgets.Switch(tr("Don't cross while dragging with this Mac's pointer"), on_change=self._changed)
module.add(self.dragging_box.view)
- module.add(widgets.note("Applies when this physical pointer pushes through this screen's ways; visiting pointers are not protected by this switch.").view)
+ module.add(widgets.note(tr("Applies when this physical pointer pushes through this screen's ways; visiting pointers are not protected by this switch.")).view)
return module
+
+ @objc.python_method
+ def _editing_other(self):
+ return (profiles.same_ways_on(self.settings_store.current())
+ and getattr(self, "viewed_machine", self.own_id()) != self.own_id())
+
+ @objc.python_method
+ def _view_settings(self):
+ settings = self.settings_store.current()
+ machine = getattr(self, "viewed_machine", settings["machine_id"])
+ if not profiles.same_ways_on(settings) or machine not in profiles.machines_on_desk(settings):
+ machine = settings["machine_id"]
+ self.viewed_machine = machine
+ viewed = profiles.view_settings(settings, machine)
+ if machine != settings["machine_id"]:
+ for peer in viewed["peers"]:
+ if peer["id"] == settings["machine_id"]:
+ peer["name"] = tr("This Mac")
+ peer["platform"] = "macos"
+ else:
+ original = next((p for p in settings["peers"] if p["id"] == peer["id"]), {})
+ peer["platform"] = original.get("platform", "")
+ return viewed
+
+ @objc.python_method
+ def _profile_caps(self):
+ known = getattr(self, "_profile_known_caps", {})
+ for machine in self.settings_store.current().get("crossing_desk", {}).get("status", {}):
+ known.setdefault(machine, frozenset(("layout", "profiles")))
+ known.update(getattr(self.controller, "_profiles_known_caps", {}))
+ known.update(self._design_peer_caps())
+ self._profile_known_caps = known
+ return known
+
+ @objc.python_method
+ def _profile_event(self, event, *args, **changes):
+ self._flush()
+ keywords = dict(platform="mac", now=time.time(), **changes)
+ if event in (crossing_state.set_same_ways, crossing_state.set_own_ways,
+ crossing_state.switch_profile, crossing_state.restore_saved):
+ keywords.update(capable=self.controller.crossing_capable(), live=self._live, gone=self._gone)
+ try:
+ outcome = self.controller.crossing_event(event, *args, **keywords)
+ except (SettingsError, OSError, KeyError, TypeError, ValueError) as exc:
+ self._say(str(exc), "fault")
+ self._show_profiles()
+ return None
+ if outcome.get("reason") == "desk_full":
+ self._say(tr("The desk is full. Remove an unused profile before adding more ways."), "amber")
+ self._load_ways()
+ self._show_arrangement()
+ self._show_same()
+ return outcome
+
+ @objc.python_method
+ def _shake_sensitivity_changed(self, value):
+ self.shake_sensitivity_figure.set(text=str(value))
+ self._profile_event(crossing_state.set_shake_sensitivity, value)
+
+ @objc.python_method
+ def _home_module(self):
+ module = widgets.Module()
+ module.add(widgets.Label(tr("Way home"), theme.TYPE["body"], 600).view)
+ self.shake_switch = widgets.Switch(tr("Shake to come home"),
+ on_change=lambda on: self._profile_event(crossing_state.set_shake, on))
+ module.add(self.shake_switch.view)
+ sensitivity_head = widgets.stack(vertical=False, spacing=6)
+ sensitivity_head.addArrangedSubview_(
+ widgets.Label(tr("Shake sensitivity"), theme.TYPE["body"], wrap=True).view)
+ self.shake_sensitivity_figure = widgets.Figure("100", theme.TYPE["numeral"], "%")
+ self.shake_sensitivity_figure.view.setContentCompressionResistancePriority_forOrientation_(
+ AppKit.NSLayoutPriorityRequired, AppKit.NSLayoutConstraintOrientationHorizontal)
+ widgets.add(sensitivity_head, self.shake_sensitivity_figure.view, full_width=False)
+ module.add(sensitivity_head)
+ self.shake_sensitivity = widgets.Ruler(
+ 50, 200, (50, 100, 150, 200), step=1, arrow_step=10, minor=15,
+ on_change=self._shake_sensitivity_changed, title=tr("Shake sensitivity"),
+ )
+ module.add(self.shake_sensitivity.view)
+ module.add(widgets.note(tr("Shake the mouse or trackpad left and right a few times while you drive another machine, and input comes straight back to the machine you are using.")).view)
+ self.home_shortcut_row = widgets.stack(vertical=False, spacing=6)
+ self.home_shortcut_note = widgets.note(reading=False)
+ widgets.hug(self.home_shortcut_note.view, AppKit.NSLayoutPriorityDefaultLow)
+ self.home_shortcut_button = widgets._autolayout(ledger.quiet_button(tr("Same → Shortcut"), self._home_shortcut))
+ self.home_shortcut_row.addArrangedSubview_(self.home_shortcut_note.view)
+ self.home_shortcut_row.addArrangedSubview_(widgets.hug(self.home_shortcut_button))
+ module.add(self.home_shortcut_row, full_width=False)
+ module.add(widgets.note(tr("Push back the way you came: where an edge leads back to This Mac")).view)
+ self.home_warning = widgets.note(reading=False)
+ self.home_warning_box = widgets.box(stroke="rule")
+ self.home_warning_box.addSubview_(self.home_warning.view)
+ widgets.pin(self.home_warning.view, self.home_warning_box, (8, 12, 8, 12))
+ module.add(self.home_warning_box)
+ return module
+
+ @objc.python_method
+ def _home_shortcut(self):
+ self._select_page("overview")
+ shortcut = self.same_checks["shortcut"]
+ shortcut.scrollRectToVisible_(shortcut.bounds())
+ self.window.makeFirstResponder_(shortcut)
+
+ @objc.python_method
+ def _toggle_earlier(self):
+ self.earlier_host.setHidden_(not self.earlier_host.isHidden())
+ self._show_profiles()
+
+ @objc.python_method
+ def _delete_profile_menu(self):
+ """The profiles Delete… offers: every one but the active profile."""
+ settings = self.settings_store.current()
+ active = settings["crossing_desk"]["active"]["value"]
+ menu = AppKit.NSMenu.alloc().initWithTitle_(tr("Delete…"))
+ menu.setAutoenablesItems_(False)
+ self._delete_menu_targets = []
+ for choice in profiles.profile_list(settings):
+ if choice["id"] == active:
+ continue
+ target = widgets.callback_target(
+ lambda pid=choice["id"]: self._profile_event(crossing_state.remove_profile, pid))
+ self._delete_menu_targets.append(target)
+ item = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(choice["label"], "fire:", "")
+ item.setTarget_(target)
+ menu.addItem_(item)
+ return menu
+
+ @objc.python_method
+ def _show_delete_profile_menu(self):
+ view = self.delete_profile_button
+ self._delete_profile_menu().popUpMenuPositioningItem_atLocation_inView_(
+ None, AppKit.NSMakePoint(0, view.bounds().size.height + 4), view)
+
+ @objc.python_method
+ def _profile_name(self, profile_id=None):
+ settings = self.settings_store.current()
+ held = next((p for p in profiles.profile_list(settings) if p["id"] == profile_id), None)
+ alert = AppKit.NSAlert.alloc().init()
+ alert.setMessageText_(tr("Rename profile") if held else tr("New profile"))
+ field = AppKit.NSTextField.alloc().initWithFrame_(((0, 0), (260, 24)))
+ field.setStringValue_(held["name"] if held else "")
+ field.setAccessibilityLabel_(tr("Profile name"))
+ alert.setAccessoryView_(field)
+ alert.addButtonWithTitle_(tr("Save") if held else tr("Add"))
+ alert.addButtonWithTitle_(tr("Cancel"))
+ def finished(response):
+ if response == AppKit.NSAlertFirstButtonReturn:
+ name = field.stringValue().strip()
+ if name:
+ if held:
+ self._profile_event(crossing_state.rename_profile, profile_id, name)
+ else:
+ self._profile_event(crossing_state.new_profile, name)
+ alert.beginSheetModalForWindow_completionHandler_(self.window, finished)
+
+ @objc.python_method
+ def _show_profiles(self):
+ if not hasattr(self, "ways_switch"):
+ return
+ settings = self.settings_store.current()
+ on = profiles.same_ways_on(settings)
+ remote = self._editing_other()
+ machine = self.viewed_machine if remote else self.own_id()
+ name = tr("This Mac") if machine == self.own_id() else profiles.view_settings(settings, machine)["name"]
+ self.ways_switch.value = on
+ self.crossing_intro.set(
+ tr("Click a machine on the map to set its ways. The ledger says how it reaches each other machine.") if on else
+ tr("Drag a machine on the map to where it sits. The ledger says how each one is reached; click a row to pick it on the map."))
+ self.ways_off_note.view.setHidden_(on)
+ self.profile_tabs.setHidden_(not on)
+ self.profile_actions.setHidden_(not on)
+ self.atlas_canvas_hint.set(
+ tr("Click a machine to set its ways · Tab and Return pick one from the keyboard") if on else
+ tr("Option-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"))
+ self.atlas_canvas_hint.view.setHidden_(False)
+ self.ledger_heading.set(tr("{name}'s ways").format(name=name) if on else tr("Machines"))
+ self.edit_notice.set(tr("Editing {name}'s ways ·").format(name=name) if remote else "")
+ self.edit_header.setHidden_(not remote)
+ self.edit_notice.view.setHidden_(not remote)
+ self.back_ways_button.setHidden_(not remote)
+ self.remote_permissions_note.set(tr("Jump keys and permissions are set on {name}.").format(name=name) if remote else "")
+ self.remote_permissions_note.view.setHidden_(not remote)
+ caps = self._profile_caps().get(machine, ()) if remote else ("profiles",)
+ linked = self._live(machine) if remote else True
+ link_times = getattr(self.controller, "desk_link_times", {})
+ last_heard = None if getattr(self.controller, "desk_last_heard", {}).get(machine) else link_times.get(machine)
+ status = profiles.machine_line(settings, machine, linked=linked, caps=caps, last_heard=last_heard)
+ self.profile_status.set(status)
+ self.profile_status.view.setHidden_(not on)
+ self.remote_changes_note.set(tr("Changes go to {name} at once.").format(name=name) if remote else "")
+ self.remote_changes_note.view.setHidden_(not remote or not linked or "profiles" not in caps)
+ own = on and not remote and not profiles.in_force(settings)[1]
+ self.own_ways_title.setHidden_(not own)
+ self.own_ways_button.view.setHidden_(not on or remote or own)
+ self.use_desk_button.view.setHidden_(not own)
+ desk = settings["crossing_desk"]
+ desk_row = desk["profiles"].get(desk["active"]["value"], {}).get("rows", {}).get(self.own_id(), {}).get("value", {})
+ self.share_ways_button.view.setHidden_(not own or settings["crossing_own"]["row"] == desk_row)
+ self.own_actions_pair.view.setHidden_(not own)
+ self.own_ways_module.view.setHidden_(remote or not on and not bool(self.older_ways_notice.text))
+ saved = profiles.saved_list(settings)
+ self.saved_toggle.setHidden_(not on or remote or not saved)
+ self.own_toggle_row.view.setHidden_(not on or remote or own and not saved)
+ if not on or remote or not saved:
+ self.earlier_host.setHidden_(True)
+ earlier_title = tr("Earlier ways ▾") if self.earlier_host.isHidden() else tr("Earlier ways ▴")
+ self.saved_toggle.setTitle_(earlier_title)
+ self.saved_toggle.setAttributedTitle_(widgets.attributed(earlier_title, 12.5, 500, "ink_2"))
+ self.saved_toggle.setAccessibilityLabel_(earlier_title)
+ self.shake_switch.value = profiles.shake_on(settings)
+ self.shake_sensitivity.value = profiles.shake_sensitivity(settings)
+ self.shake_sensitivity_figure.set(text=str(self.shake_sensitivity.value))
+ warnings = profiles.no_way_back(settings, machine)
+ self.home_warning.set("\n".join(tr("{name} has no way back to {machine} except the shortcut and a shake.").format(
+ name=target, machine=name) for target in warnings))
+ self.home_warning.view.setHidden_(not warnings)
+ self.home_warning_box.setHidden_(not warnings)
+ style = tr("hold") if self.controller.cfg.trigger_style == "hold" else tr("double-tap")
+ key_title = widgets.key_title(self.controller.cfg.trigger_key)
+ shortcut_template = tr("Shortcut: {style} {key} ·")
+ shortcut_text = shortcut_template.format(style=style, key=key_title)
+ self.home_shortcut_note.set(shortcut_text)
+ before_key, _marker, after_key = shortcut_template.partition("{key}")
+ shortcut_ink = AppKit.NSMutableAttributedString.alloc().initWithAttributedString_(
+ widgets.attributed(before_key.format(style=style), theme.TYPE["note"], ink="ink_2", wrap=True))
+ shortcut_ink.appendAttributedString_(widgets.attributed(key_title, theme.TYPE["note"], ink="ink_2", mono=True))
+ shortcut_ink.appendAttributedString_(widgets.attributed(after_key.format(style=style), theme.TYPE["note"], ink="ink_2", wrap=True))
+ self.home_shortcut_note.view.setAttributedStringValue_(shortcut_ink)
+ rows = pages.crossing_rows(self._methods())
+ self.pointer_module.view.setHidden_(remote)
+ self.resistance_module.view.setHidden_(remote or not rows["resistance"])
+ self.shortcut_module.view.setHidden_(remote or not rows["shortcut"] and not bool(getattr(self, "_trigger_conflict", "")))
+ choices = profiles.profile_list(settings)
+ self.profile_switch_note.view.setHidden_(not on or len(choices) < 2)
+ self.delete_profile_button.setEnabled_(len(choices) > 1)
+ self.delete_profile_button.setAttributedTitle_(widgets.attributed(
+ tr("Delete…"), 12.5, 500, "ink_2" if len(choices) > 1 else "ink_3"))
+ wrap_tabs = len(choices) > 2
+ key = (tuple((p["id"], p["label"]) for p in choices), desk["active"]["value"], wrap_tabs)
+ if key != self._profile_tabs_key:
+ self._profile_tabs_key = key
+ for view in list(self.profile_tabs.arrangedSubviews()):
+ self.profile_tabs.removeArrangedSubview_(view)
+ view.removeFromSuperview()
+ self.profile_buttons = {}
+ self.profile_tabs.setOrientation_(AppKit.NSUserInterfaceLayoutOrientationVertical if wrap_tabs
+ else AppKit.NSUserInterfaceLayoutOrientationHorizontal)
+ tab_row = self.profile_tabs
+ for choice in choices:
+ pid = choice["id"]
+ button = widgets.action_button(choice["label"],
+ lambda pid=pid: self._profile_event(crossing_state.switch_profile, pid),
+ style="plain", scale="small")
+ if pid == desk["active"]["value"]:
+ widgets.paint(button.view, "panel", "ink_2")
+ menu = AppKit.NSMenu.alloc().initWithTitle_(tr("Profile"))
+ targets = []
+ for title, callback, enabled in (
+ (tr("Rename"), lambda pid=pid: self._profile_name(pid), True),
+ (tr("Remove"), lambda pid=pid: self._profile_event(crossing_state.remove_profile, pid),
+ len(choices) > 1 and pid != desk["active"]["value"])):
+ target = widgets.callback_target(callback)
+ targets.append(target)
+ item = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, "fire:", "")
+ item.setTarget_(target)
+ item.setEnabled_(enabled)
+ menu.addItem_(item)
+ menu.setAutoenablesItems_(False)
+ button.menu_targets = targets
+ button.view.setMenu_(menu)
+ if wrap_tabs:
+ tab_row = widgets.stack(vertical=False, spacing=6)
+ self.profile_tabs.addArrangedSubview_(tab_row)
+ tab_row.addArrangedSubview_(button.view)
+ self.profile_buttons[pid] = button
+ self.add_profile_button = widgets._autolayout(ledger.quiet_button(tr("+"), self._profile_name))
+ widgets.size(self.add_profile_button, 24, 24)
+ self.add_profile_button.setAccessibilityLabel_(tr("New profile"))
+ self.profile_tabs.addArrangedSubview_(self.add_profile_button)
+ if repr(saved) != self._earlier_key:
+ self._earlier_key = repr(saved)
+ self.side_by_side[:] = [pair for pair in self.side_by_side if pair not in self._earlier_pairs]
+ self._earlier_pairs = []
+ for view in list(self.earlier_host.arrangedSubviews()):
+ self.earlier_host.removeArrangedSubview_(view)
+ view.removeFromSuperview()
+ self.earlier_buttons = {}
+ reasons = {"upgrade": tr("Before Beamer 1.5.5"), "older_version": tr("From an older Beamer"),
+ "sync_off": tr("When Same ways went off"), "seeded": tr("When Same ways went on"),
+ "edited": tr("Before you changed it"), "restored": tr("Before a restore")}
+ for entry in saved:
+ sid = entry["id"]
+ why = reasons.get(entry["why"], tr("Before you changed it"))
+ if entry["why"] == "replaced_by":
+ changed_by = entry.get("by", "")
+ who = tr("This Mac") if changed_by == self.own_id() else peerlist.label_for(settings["peers"], peer_id=changed_by) or tr("another machine")
+ why = tr("Before {name} changed it").format(name=who)
+ caption = widgets.note(tr("{date} · {reason}").format(
+ date=time.strftime("%d-%m-%Y", time.localtime(entry["at"])), reason=why), reading=False)
+ widgets.hug(caption.view, AppKit.NSLayoutPriorityDefaultLow)
+ restore = widgets._autolayout(ledger.quiet_button(tr("Restore"), lambda sid=sid: self._profile_event(crossing_state.restore_saved, sid)))
+ delete = widgets._autolayout(ledger.quiet_button(tr("Delete"), lambda sid=sid: self._profile_event(crossing_state.delete_saved, sid)))
+ actions = widgets.stack(vertical=False, spacing=8)
+ widgets.hug(actions, AppKit.NSLayoutPriorityDefaultHigh)
+ for button in (restore, delete):
+ actions.addArrangedSubview_(button)
+ pair = widgets.SideBySide(caption.view, actions, 190, 150, gap=16)
+ # A stack has no intrinsic width to hug: give spare row width to the caption.
+ preferred = actions.widthAnchor().constraintEqualToConstant_(150)
+ preferred.setPriority_(489)
+ preferred.setActive_(True)
+ self.side_by_side.append(pair)
+ self._earlier_pairs.append(pair)
+ widgets.add(self.earlier_host, pair.view)
+ self.earlier_buttons[sid] = (restore, delete)
@objc.python_method
def _show_jump_key(self):
self._show_machines()
@@ -3282,7 +3756,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _ledger_edge(self, peer, part=None):
- settings = self.settings_store.current()
+ settings = self._view_settings() if hasattr(self, "viewed_machine") else self.settings_store.current()
entry = next((item for item in settings["peers"] if item["id"] == peer), None)
held = core_ways.ways(settings, peer)
own = settings.get("machine_id")
@@ -3301,8 +3775,11 @@ class ControlWindow(AppKit.NSObject):
def _reach(self, peer, settings=None):
"""`core.ways.reach` for one machine, kept until the settings or who is live change: the status
tick refreshes the ledger and the map every 0.4 s, and each answer is several compiles."""
- settings = settings or self.settings_store.current()
+ settings = settings or self._view_settings()
args = self._crossing_args()
+ if self._editing_other():
+ args["platform"] = profiles.view_platform(self.settings_store.current(), self.viewed_machine)
+ args["capable"] = set(settings.get("layout", {}))
ids = [entry.get("id") for entry in settings.get("peers", [])]
stamp = (repr(settings), args["platform"], frozenset(args["capable"] or ()),
tuple(bool(args["live"](ident)) for ident in ids), tuple(bool(args["gone"](ident)) for ident in ids))
@@ -3317,7 +3794,7 @@ class ControlWindow(AppKit.NSObject):
def _ledger_side(self, peer, side):
"""A side chip: the contact side toggles Edge as a whole; a free side is added (turning Edge on
if it was off), one that wraps is removed, and a kept one turns Edge back on or is removed."""
- settings = self.settings_store.current()
+ settings = self._view_settings()
entry = next((item for item in settings["peers"] if item["id"] == peer), None)
if entry is None or entry.get("left_out") or entry.get("in_use", True) is False:
return
@@ -3339,7 +3816,7 @@ class ControlWindow(AppKit.NSObject):
def _ledger_corner(self, peer, corner):
"""A corner button: several may be on; another machine's, or one with no side contact to leave
from, is refused without a write (a corner already on can always be taken off)."""
- settings = self.settings_store.current()
+ settings = self._view_settings() if hasattr(self, "viewed_machine") else self.settings_store.current()
entry = next((item for item in settings["peers"] if item["id"] == peer), None)
if entry is None or entry.get("left_out") or entry.get("in_use", True) is False:
return
@@ -3352,14 +3829,18 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _ledger_notch(self, peer, enabled):
- entry = next((item for item in self.settings_store.current()["peers"] if item["id"] == peer), None)
- if (self.has_notch and entry and not entry.get("left_out")
+ settings = self._view_settings() if hasattr(self, "viewed_machine") else self.settings_store.current()
+ entry = next((item for item in settings["peers"] if item["id"] == peer), None)
+ has_notch = (self.settings_store.current()["crossing_desk"].get("status", {}).get(
+ self.viewed_machine, {}).get("value", {}).get("platform") == "mac"
+ if hasattr(self, "viewed_machine") and self._editing_other() else self.has_notch)
+ if (has_notch and entry and not entry.get("left_out")
and entry.get("in_use", True) is not False):
self._write_ways(peer, notch=enabled)
self._reflect()
@objc.python_method
def _ledger_notch_return(self, peer, enabled):
- if self.has_notch:
+ if self.has_notch or self._editing_other():
self._write_ways(peer, notch_return=enabled)
@objc.python_method
@@ -3372,15 +3853,19 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _shortcut_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Shortcut"))
- self.method_boxes = {"shortcut": widgets.WayTile("Shortcut", on_change=lambda on: self._way_toggled("shortcut", on))}
+ module.add(widgets.eyebrow(tr("Shortcut")))
+ self.method_boxes = {"shortcut": widgets.WayTile(tr("Shortcut"), on_change=lambda on: self._way_toggled("shortcut", on))}
module.add(self.method_boxes["shortcut"].view)
- self.key_recorder = widgets.KeyRecorder("alt_r", on_change=self._trigger_chosen)
+ self.key_recorder = widgets.KeyRecorder(
+ "alt_r", on_change=self._trigger_chosen, hint=tr(widgets.KeyRecorder.HINT),
+ recording_title=tr(widgets.KeyRecorder.RECORDING_TITLE),
+ recording_hint=tr(widgets.KeyRecorder.RECORDING_HINT),
+ )
module.add(self.key_recorder.view)
- self.style_select = widgets.Segmented([("double_tap", "Double-tap"), ("hold", "Hold")], on_change=self._changed)
- module.add(widgets.field_row("How you press it", self.style_select.view)[0])
+ self.style_select = widgets.Segmented([("double_tap", tr("Double-tap")), ("hold", tr("Hold"))], on_change=self._changed)
+ module.add(widgets.field_row(tr("How you press it"), self.style_select.view)[0])
self.shortcut_goes_to = widgets.Segmented(
- [("last", "Last machine"), ("next", "Next in order"), ("ticked", "Next among ticked")],
+ [("last", tr("Last machine")), ("next", tr("Next in order")), ("ticked", tr("Next among ticked"))],
columns=3, on_change=self._shortcut_destination_changed,
)
self.shortcut_goes_to.cap = max(widgets.attributed(title, theme.TYPE["small"]).size().width + 24
@@ -3389,20 +3874,20 @@ class ControlWindow(AppKit.NSObject):
self.shortcut_goes_to.preference.setConstant_(self.shortcut_goes_to.cap)
for _value, _cell, words in self.shortcut_goes_to.cells:
words.view.setUsesSingleLineMode_(True)
- module.add(widgets.field_row("Shortcut goes to", self.shortcut_goes_to.view)[0])
+ module.add(widgets.field_row(tr("Shortcut goes to"), self.shortcut_goes_to.view)[0])
self.shortcut_cycle_note = widgets.note()
module.add(self.shortcut_cycle_note.view)
# The figure sits on the ruler's own line, so it reads as the ruler's value rather than as
# a heading for the whole module, and the two hide together under Hold.
self.double_tap_head = widgets.stack(spacing=6)
figure, self.double_tap_numeral = self._numeral("ms")
- caption, _ = widgets.field_row("Time between taps", figure)
+ caption, _ = widgets.field_row(tr("Time between taps"), figure)
widgets.add(self.double_tap_head, caption)
# The stored window runs 50 to 2000 ms, but only about 150 to 600 is useful, so the ruler
# shows 50 to 1000 on a square-root scale; a stored value past 1000 pins the thumb.
self.double_tap_ruler = widgets.Ruler(
50, 1000, (50, 150, 300, 600, 1000), step=10, scale="sqrt", minor=20, on_change=self._double_tap_moved,
- title="Time between taps",
+ title=tr("Time between taps"),
)
widgets.add(self.double_tap_head, self.double_tap_ruler.view)
module.add(self.double_tap_head)
@@ -3420,14 +3905,17 @@ class ControlWindow(AppKit.NSObject):
if not hasattr(self, "shortcut_cycle_note"):
return
mode = self.shortcut_goes_to.value or "last"
+ hold = self.style_select.value == "hold"
if mode == "last":
- note = "With Hold, input goes to the last machine."
- elif self.style_select.value == "hold":
- note = "With Hold, input goes to the first ready machine in order."
+ note = tr("With Hold, input goes to the last machine.")
+ elif hold and mode == "ticked":
+ note = tr("With Hold, input goes to the first ready machine in order. Choose which machines join the cycle with the tick boxes on their tiles.")
+ elif hold:
+ note = tr("With Hold, input goes to the first ready machine in order.")
+ elif mode == "ticked":
+ note = tr("The order follows the tiles from top to bottom, then left to right. This Mac is always in the cycle. Choose which machines join the cycle with the tick boxes on their tiles.")
else:
- note = "The order follows the tiles from top to bottom, then left to right. This Mac is always in the cycle."
- if mode == "ticked":
- note += " Choose which machines join the cycle with the tick boxes on their tiles."
+ note = tr("The order follows the tiles from top to bottom, then left to right. This Mac is always in the cycle.")
self.shortcut_cycle_note.set(note)
@objc.python_method
@@ -3450,18 +3938,22 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _ignored_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Stays on this Mac"))
- module.add(widgets.note(
+ module.add(widgets.eyebrow(tr("Stays on this Mac")))
+ module.add(widgets.note(tr(
"These keys and buttons keep working on this Mac while its input is on another machine: a "
"mouse's back button for this Mac's browser, say, or a volume key for its speakers."
- ).view)
+ )).view)
self.ignored_entries = []
self.ignored_list = widgets.stack(spacing=6)
module.add(self.ignored_list)
- self.ignored_empty = widgets.note("Nothing yet. Every key and button goes to the machine that has input.")
+ self.ignored_empty = widgets.note(tr("Nothing yet. Every key and button goes to the machine that has input."))
module.add(self.ignored_empty.view)
self.ignored_recorder = widgets.IgnoredRecorder(
- KEY_NAME_TO_CODE.get(self.key_recorder.value), on_recorded=self._add_ignored
+ KEY_NAME_TO_CODE.get(self.key_recorder.value), on_recorded=self._add_ignored,
+ title=tr(widgets.IgnoredRecorder.TITLE),
+ recording_title=tr(widgets.IgnoredRecorder.RECORDING_TITLE),
+ hint=tr(widgets.IgnoredRecorder.HINT),
+ recording_hint=tr(widgets.IgnoredRecorder.RECORDING_HINT),
)
module.add(self.ignored_recorder.view)
self.ignored_status = widgets.note()
@@ -3482,8 +3974,9 @@ class ControlWindow(AppKit.NSObject):
chip = widgets.box("well", "rule", theme.RADIUS["field"])
name = widgets.Label(title, theme.TYPE["small"], 600, mono=True)
remove = widgets.pressable(lambda entry=entry: self._remove_ignored(entry), radius=theme.RADIUS["field"])
- remove.setAccessibilityLabel_(f"Remove {title}")
- remove_word = widgets.Label("Remove", theme.TYPE["small"], ink="ink_2")
+ # Translators: {name} is the machine name.
+ remove.setAccessibilityLabel_(tr("Remove {name}").format(name=title))
+ remove_word = widgets.Label(tr("Remove"), theme.TYPE["small"], ink="ink_2")
remove.addSubview_(remove_word.view)
widgets.pin(remove_word.view, remove, (7, 10, 7, 10))
line = widgets.stack(vertical=False, spacing=10)
@@ -3503,7 +3996,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _add_ignored(self, entry):
if entry is None:
- self._ignored_said("That key is the shortcut; it always stays with Beamer.")
+ self._ignored_said(tr("That key is the shortcut; it always stays with Beamer."))
return
if entry in self.ignored_entries:
return
@@ -3522,19 +4015,19 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _on_screen_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("On screen"))
- self.glow_box = widgets.Switch("Animate crossings on this Mac", on_change=self._changed)
+ module.add(widgets.eyebrow(tr("On screen")))
+ self.glow_box = widgets.Switch(tr("Animate crossings on this Mac"), on_change=self._changed)
module.add(self.glow_box.view)
module.add(self._own_note())
- module.add(widgets.note(
+ module.add(widgets.note(tr(
"Turns crossing and landing animations on or off on this screen. Saved style choices stay in place."
- ).view)
- self.landing_box = widgets.Switch("Show where the pointer lands", on_change=self._changed)
+ )).view)
+ self.landing_box = widgets.Switch(tr("Show where the pointer lands"), on_change=self._changed)
self.landing_row = widgets.stack(spacing=8)
widgets.add(self.landing_row, self.landing_box.view)
- widgets.add(self.landing_row, widgets.note(
+ widgets.add(self.landing_row, widgets.note(tr(
"For shortcut, menu and jump arrivals; requires Animate crossings on this screen."
- ).view)
+ )).view)
module.add(self.landing_row)
return module
@@ -3567,12 +4060,12 @@ class ControlWindow(AppKit.NSObject):
"""The notch's own styles, which play at the notch in place of Glow and Beam: under Show at,
shown while it is at the notch. Named apart from Classic Beam, which is the edge's line."""
row = widgets.stack(spacing=12)
- widgets.add(row, widgets.label("Notch style", theme.TYPE["note"], 600, ink="ink_2"))
+ widgets.add(row, widgets.label(tr("Notch style"), theme.TYPE["note"], 600, ink="ink_2"))
notch = previews.notch_size()
self.notch_style_select = widgets.ChoiceTiles(
[
- self._preview_tile(NotchBeam, "beam", "Outline", "A line of colour runs round the notch, faster the harder you push.", notch),
- self._preview_tile(NotchIsland, "island", "Island", "The notch grows as you push, with a meter inside, and flashes as you go through.", notch),
+ self._preview_tile(NotchBeam, "beam", tr("Outline"), tr("A line of colour runs round the notch, faster the harder you push."), notch),
+ self._preview_tile(NotchIsland, "island", tr("Island"), tr("The notch grows as you push, with a meter inside, and flashes as you go through."), notch),
],
on_change=self._changed,
vertical=True,
@@ -3584,7 +4077,7 @@ class ControlWindow(AppKit.NSObject):
self.notch_after_select = widgets.Segmented(
[(600, "0.6 s"), (1200, "1.2 s"), (2000, "2 s"), (3000, "3 s")], on_change=self._changed
)
- widgets.add(row, widgets.field_row("Keep animating", self.notch_after_select.view)[0])
+ widgets.add(row, widgets.field_row(tr("Keep animating"), self.notch_after_select.view)[0])
widgets.add(row, self._own_note())
self.notch_note = widgets.note()
widgets.add(row, self.notch_note.view)
@@ -3626,21 +4119,21 @@ class ControlWindow(AppKit.NSObject):
stills like the rest, then each direction's quiet, medium and showpiece effect; every tile shows
its style at the place chosen above them, and plays while the pointer is over it."""
module = widgets.Module()
- module.add(widgets.eyebrow("Style"))
+ module.add(widgets.eyebrow(tr("Style")))
module.add(self._follow_banner())
- self.style_preview_hint = widgets.note("Hover to preview", ink="ink_2")
+ self.style_preview_hint = widgets.note(tr("Hover to preview"), ink="ink_2")
module.add(self.style_preview_hint.view)
self.style_for_select = widgets.Segmented(
- [("crossing", "Crossing"), ("switch", "Shortcut and menu")], on_change=self._changed
+ [("crossing", tr("Crossing")), ("switch", tr("Shortcut and menu"))], on_change=self._changed
)
self.style_for_select.value = "crossing"
- self.style_for_row = widgets.field_row("Style for", self.style_for_select.view)[0]
+ self.style_for_row = widgets.field_row(tr("Style for"), self.style_for_select.view)[0]
module.add(self.style_for_row)
# Where every tile below plays its style: never switched off by the style, and what differs
# there is said beneath it.
- self.effect_method_select = widgets.Segmented(previews.STAGE_METHODS, on_change=self._place_picked)
+ self.effect_method_select = widgets.Segmented([(key, tr(name)) for key, name in previews.STAGE_METHODS], on_change=self._place_picked)
self.effect_method_select.value = self.place = "edge"
- self.effect_method_view = widgets.field_row("Show at", self.effect_method_select.view)[0]
+ self.effect_method_view = widgets.field_row(tr("Show at"), self.effect_method_select.view)[0]
module.add(self.effect_method_view)
self.place_note = widgets.note()
module.body.setCustomSpacing_afterView_(6, self.effect_method_view)
@@ -3690,9 +4183,9 @@ class ControlWindow(AppKit.NSObject):
self.effect_stills.extend(tile[3] for tile in tiles)
rows.append(self._style_group(self.switch_styles_box, group, tiles))
self._style_grid(self.switch_styles_box)
- widgets.add(self.switch_styles_box, widgets.note(
+ widgets.add(self.switch_styles_box, widgets.note(tr(
"What plays around the pointer for shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style."
- ).view)
+ )).view)
self.switch_style_select = widgets.Linked(rows, on_change=self._changed, host=self.switch_styles_box)
module.add(tile_sets)
# The chosen style's name and what it does, under the tiles that chose it.
@@ -3704,12 +4197,12 @@ class ControlWindow(AppKit.NSObject):
module.add(self.chosen_box)
module.body.setCustomSpacing_afterView_(12, self.chosen_box)
# Every style and every switch plays at this length, so it follows the tiles either way.
- self.length_select = _DesignSliderChoice("Length", 25, 250, 5, 100, (0.5, 1.0, 2.0),
+ self.length_select = _DesignSliderChoice(tr("Length"), 25, 250, 5, 100, (0.5, 1.0, 2.0),
effects.LENGTHS, self._design_slider_changed,
- "Sets the effect's playback time.")
- self.size_select = _DesignSliderChoice("Size", 20, 80, 1, 1000, (0.03, 0.045, 0.06),
+ tr("Sets the effect's playback time."))
+ self.size_select = _DesignSliderChoice(tr("Size"), 20, 80, 1, 1000, (0.03, 0.045, 0.06),
effects.SIZES, self._design_slider_changed,
- "Sets effect depth relative to the shorter screen edge.")
+ tr("Sets effect depth relative to the shorter screen edge."))
self.length_readout = design_readout()
self.size_readout = design_readout()
length_control = widgets.stack(False, spacing=10)
@@ -3718,17 +4211,17 @@ class ControlWindow(AppKit.NSObject):
size_control = widgets.stack(False, spacing=10)
widgets.add(size_control, self.size_select.view)
widgets.add(size_control, self.size_readout.view, full_width=False)
- self.length_row = widgets.field_row("Length", length_control)[0]
- self.size_row = widgets.field_row("Size", size_control)[0]
+ self.length_row = widgets.field_row(tr("Length"), length_control)[0]
+ self.size_row = widgets.field_row(tr("Size"), size_control)[0]
self.frame_rate_select = widgets.Segmented(
- tuple((value, name) for value, name, _divisor in effects.FRAME_RATES),
+ tuple((value, tr(name)) for value, name, _divisor in effects.FRAME_RATES),
on_change=self._changed,
)
- self.frame_rate_row = widgets.field_row("Frame rate", self.frame_rate_select.view)[0]
+ self.frame_rate_row = widgets.field_row(tr("Frame rate"), self.frame_rate_select.view)[0]
module.add(self.length_row)
- module.add(widgets.note("Sets the effect's playback time.", ink="ink_2").view)
+ module.add(widgets.note(tr("Sets the effect's playback time."), ink="ink_2").view)
module.add(self.size_row)
- module.add(widgets.note("Sets effect depth relative to the shorter screen edge.", ink="ink_2").view)
+ module.add(widgets.note(tr("Sets effect depth relative to the shorter screen edge."), ink="ink_2").view)
module.add(self.frame_rate_row)
module.add(self.place_note.view)
module.add(self.notch_row)
@@ -3770,42 +4263,44 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _colour_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Colour"))
+ module.add(widgets.eyebrow(tr("Colour")))
rows = []
for group, choices in pages.colour_groups(crossing.GLOW_COLOURS, self.effects_ready):
if group != pages.TODAY:
- choices = [(value, title, effects_overlay.palette(value)) for value, title in choices]
- heading = module.add(widgets.label(group, theme.TYPE["note"], 600, ink="ink_2"))
+ choices = [(value, tr(title), effects_overlay.palette(value)) for value, title in choices]
+ else:
+ choices = [(value, tr(title)) for value, title in choices]
+ heading = module.add(widgets.label(tr(group), theme.TYPE["note"], 600, ink="ink_2"))
module.body.setCustomSpacing_afterView_(8, heading)
row = widgets.Swatches(choices, responsive=True)
module.add(row.view)
module.body.setCustomSpacing_afterView_(18, row.view)
rows.append(row)
self.glow_colour_select = widgets.Linked(rows, on_change=self._changed, host=module.body)
- module.add(widgets.note("Any colour works with any style. The notch's Outline uses it too; Island keeps Beamer's own cyan.").view)
+ module.add(widgets.note(tr("Any colour works with any style. The notch's Outline uses it too; Island keeps Beamer's own cyan.")).view)
return module
@objc.python_method
def _trackpad_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Trackpad"))
+ module.add(widgets.eyebrow(tr("Trackpad")))
module.add(self._own_note())
- self.haptics_box = widgets.Switch("Tick as the push builds", on_change=self._changed)
+ self.haptics_box = widgets.Switch(tr("Tick as the push builds"), on_change=self._changed)
module.add(self.haptics_box.view)
self.tick_steps_select = widgets.Segmented(
- [("quarters", "Every quarter"), ("halves", "Halfway"), ("breakthrough", "Only when through")],
+ [("quarters", tr("Every quarter")), ("halves", tr("Halfway")), ("breakthrough", tr("Only when through"))],
on_change=self._changed,
)
- ticks, _caption = widgets.field_row("Ticks at", self.tick_steps_select.view)
+ ticks, _caption = widgets.field_row(tr("Ticks at"), self.tick_steps_select.view)
self.tick_steps_pair = ticks
module.add(ticks)
# On the press, not the release: macOS plays nothing once the finger has left the trackpad.
- self.try_button = widgets.Button("Try it", self, "tryTick:", scale="small")
+ self.try_button = widgets.Button(tr("Try it"), self, "tryTick:", scale="small")
self.try_button.view.sendActionOn_(AppKit.NSEventMaskLeftMouseDown)
feel = widgets.stack(vertical=False, spacing=10)
feel.addArrangedSubview_(self.try_button.view)
feel.addArrangedSubview_(widgets.hug(widgets.box(), AppKit.NSLayoutPriorityDefaultLow))
- module.add(widgets.field_row("Feel it", feel)[0])
+ module.add(widgets.field_row(tr("Feel it"), feel)[0])
self.tick_note = widgets.note()
module.add(self.tick_note.view)
return module
@@ -3823,11 +4318,11 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _modifier_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Modifier keys"))
+ module.add(widgets.eyebrow(tr("Modifier keys")))
self.modifier_select = widgets.Segmented(
- [("semantic", "Same shortcuts"), ("positional", "Same positions")], on_change=self._changed
+ [("semantic", tr("Same shortcuts")), ("positional", tr("Same positions"))], on_change=self._changed
)
- self.modifier_select.view.setAccessibilityLabel_("Modifier keys")
+ self.modifier_select.view.setAccessibilityLabel_(tr("Modifier keys"))
module.add(self.modifier_select.view)
self.modifier_note = widgets.note()
module.add(self.modifier_note.view)
@@ -3839,11 +4334,22 @@ class ControlWindow(AppKit.NSObject):
# The page edits the first machine paired; any other is changed by pairing it again.
self.connection_note = widgets.note()
module.add(self.connection_note.view)
- self.hide_switch = widgets.Switch("Hide addresses", on_change=self._set_hide_addresses)
+ self.hide_switch = widgets.Switch(tr("Hide addresses"), on_change=self._set_hide_addresses)
module.add(self.hide_switch.view)
module.add(widgets.note(
- "Hides every IP and hardware address in this window and its menu."
+ tr("Hides every IP and hardware address in this window and its menu.")
).view)
+ self.language_select = widgets.MenuChoice(
+ [("auto", tr("Automatic")), *LANGUAGES.items()], on_change=self._set_language
+ )
+ module.add(widgets.field_row(tr("Language"), self.language_select.view)[0])
+ self.language_note = widgets.note(tr("Beamer changes language when it next opens."))
+ self.language_note.view.setHidden_(True)
+ module.add(self.language_note.view)
+ self.language_relaunch_button = widgets.Button(tr("Relaunch Beamer"), self, "relaunch:",
+ style="primary", full_width=True)
+ self.language_relaunch_button.view.setHidden_(True)
+ module.add(self.language_relaunch_button.view)
host_box, self.host_field = widgets.field()
secret_box, self.host_secret = widgets.field(secure=True)
secret_box.setHidden_(True)
@@ -3852,20 +4358,20 @@ class ControlWindow(AppKit.NSObject):
for box in self.host_boxes:
host_line.addArrangedSubview_(box)
widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow)
- module.add(widgets.field_row("Address", host_line)[0])
+ module.add(widgets.field_row(tr("Address"), host_line)[0])
for control in (self.host_field, self.host_secret):
- control.setAccessibilityLabel_("Address")
+ control.setAccessibilityLabel_(tr("Address"))
port_box, self.port_field = widgets.field()
- module.add(widgets.field_row("First paired machine's port", port_box)[0])
- self.port_field.setAccessibilityLabel_("First paired machine's port")
+ module.add(widgets.field_row(tr("First paired machine's port"), port_box)[0])
+ self.port_field.setAccessibilityLabel_(tr("First paired machine's port"))
self.wake_state = widgets.Label("", theme.TYPE["small"], mono=True)
- module.add(widgets.field_row("Wake-on-LAN", self.wake_state.view)[0])
+ module.add(widgets.field_row(tr("Wake-on-LAN"), self.wake_state.view)[0])
self.wake_hint = widgets.note()
module.add(self.wake_hint.view)
module.add(widgets.hairline())
line = widgets.stack(vertical=False, spacing=12)
- line.addArrangedSubview_(widgets.note("A new address or port takes effect when you connect.", reading=False).view)
- line.addArrangedSubview_(widgets.Button("Connect", self, "connect:", style="primary").view)
+ line.addArrangedSubview_(widgets.note(tr("A new address or port takes effect when you connect."), reading=False).view)
+ line.addArrangedSubview_(widgets.Button(tr("Connect"), self, "connect:", style="primary").view)
module.add(line)
return module
@@ -3873,22 +4379,22 @@ class ControlWindow(AppKit.NSObject):
def _access_module(self):
module = widgets.Module()
self.access_status, self.access_button = self._permission_row(
- module, "Accessibility", "Lets Beamer move this Mac's pointer and type on it when another machine drives.",
+ module, tr("Accessibility"), tr("Lets Beamer move this Mac's pointer and type on it when another machine drives."),
"requestAccessibility:",
)
module.add(widgets.hairline())
self.input_status, self.input_button = self._permission_row(
- module, "Input Monitoring", "Lets Beamer read this keyboard and trackpad, to send them to another machine.",
+ module, tr("Input Monitoring"), tr("Lets Beamer read this keyboard and trackpad, to send them to another machine."),
"requestInputMonitoring:",
)
module.add(widgets.hairline())
- module.add(widgets.eyebrow("At login"))
- module.add(widgets.note(
+ module.add(widgets.eyebrow(tr("At login")))
+ module.add(widgets.note(tr(
"On Overview, turn on Start Beamer when you log in. If macOS needs approval, that page shows the status and opens Login Items settings."
- ).view)
+ )).view)
self.capture_status = widgets.note()
module.add(self.capture_status.view)
- self.relaunch_button = widgets.Button("Relaunch Beamer", self, "relaunch:", style="primary", full_width=True)
+ self.relaunch_button = widgets.Button(tr("Relaunch Beamer"), self, "relaunch:", style="primary", full_width=True)
self.relaunch_button.view.setHidden_(True)
module.add(self.relaunch_button.view)
return module
@@ -3900,10 +4406,10 @@ class ControlWindow(AppKit.NSObject):
words = widgets.stack(spacing=4)
widgets.add(words, widgets.Label(name, theme.TYPE["body"], 600).view)
widgets.add(words, widgets.note(purpose).view)
- status = widgets.Label("Required", theme.TYPE["small"], mono=True, ink="amber", tracking=theme.STATE_TRACKING, upper=True)
+ status = widgets.Label(tr("Required"), theme.TYPE["small"], mono=True, ink="amber", tracking=theme.STATE_TRACKING, upper=True)
widgets.add(words, status.view)
line.addArrangedSubview_(widgets.hug(words, AppKit.NSLayoutPriorityDefaultLow))
- button = widgets.Button("Grant", self, action)
+ button = widgets.Button(tr("Grant"), self, action)
line.addArrangedSubview_(button.view)
module.add(line)
return status, button
@@ -3913,22 +4419,27 @@ class ControlWindow(AppKit.NSObject):
held = self._selected_ways()
methods = set(self._methods())
edge = held["side"]
- words = []
+ key = None
if "shortcut" in methods:
- words.append(f"{'Hold' if self.style_select.value == 'hold' else 'Double-tap'} {widgets.key_title(self.key_recorder.value)}")
+ key = widgets.key_title(self.key_recorder.value)
pushes = []
if edge and "edge" in methods:
- pushes.append(f"the {edge} edge")
+ pushes.append(tr("the {side} edge").format(side=tr(core_ways.EDGE_NAMES[edge])))
elif edge and "part" in methods:
pushes.append(pages.parts_phrase(edge, held["parts"]))
if "corner" in methods:
- pushes.append(f"the {held['corner'].replace('_', ' ')} corner")
+ corner = tr(CORNER_NAMES[held["corner"]])
+ pushes.append(tr("the {corner} corner").format(corner=corner))
if "notch" in methods:
- pushes.append("the notch")
- if pushes:
- words.append("push through " + " or ".join(pushes))
- sentence = ", or ".join(words)
- return sentence[:1].upper() + sentence[1:]
+ pushes.append(tr("the notch"))
+ ways = trc("list", " or ").join(pushes)
+ hold = self.style_select.value == "hold"
+ if key and pushes:
+ template = tr("Hold {key}, or push through {ways}") if hold else tr("Double-tap {key}, or push through {ways}")
+ return template.format(key=key, ways=ways)
+ if key:
+ return (tr("Hold {key}") if hold else tr("Double-tap {key}")).format(key=key)
+ return tr("Push through {ways}").format(ways=ways) if pushes else ""
@objc.python_method
def _commit(self):
bar = widgets.box("ground")
@@ -3972,6 +4483,17 @@ class ControlWindow(AppKit.NSObject):
self._pcs_key = None
self.refresh()
+ @objc.python_method
+ def _set_language(self, language):
+ try:
+ cfg = self.settings_store.save(config_to_raw(replace(self.controller.cfg, language=language)))
+ except SettingsError as exc:
+ self.logger.warning("language setting not saved: %s", exc)
+ return
+ self.controller.update_config(cfg)
+ self.language_note.view.setHidden_(False)
+ self.language_relaunch_button.view.setHidden_(False)
+
@objc.python_method
def _show_host_field(self):
"""The address fields as dots while addresses are hidden, still editable."""
@@ -3988,6 +4510,7 @@ class ControlWindow(AppKit.NSObject):
secret_box.setHidden_(not hide)
if self.hide_switch.value != hide:
self.hide_switch.value = hide
+ self.language_select.value = self.controller.cfg.language
@objc.python_method
def _host_text(self):
@@ -4008,7 +4531,7 @@ class ControlWindow(AppKit.NSObject):
except (SettingsError, TypeError, ValueError) as exc:
self._say(str(exc), "fault")
return
- self._say("Saved. Connecting…", "signal")
+ self._say(tr("Saved. Connecting…"), "signal")
self.controller.update_config(cfg)
@objc.python_method
@@ -4093,7 +4616,7 @@ class ControlWindow(AppKit.NSObject):
self._send_same()
self._refresh_design_follow()
if self._write_ways():
- self._say("Saved. Changes apply as you make them.", "ink_2")
+ self._say(tr("Saved. Changes apply as you make them."), "ink_2")
@objc.python_method
def _crossing_args(self):
@@ -4106,11 +4629,21 @@ class ControlWindow(AppKit.NSObject):
if not changes:
return True
peer = peer or self.chosen_peer
- current = self.settings_store.current()
+ current = self._view_settings()
if peer not in {entry["id"] for entry in current["peers"]}:
return True
try:
- self.controller.crossing_event(crossing_state.edit_ways, peer, **changes, **self._crossing_args())
+ if self._editing_other():
+ if "profiles" not in self._profile_caps().get(self.viewed_machine, ()):
+ return False
+ outcome = self.controller.crossing_event(crossing_state.edit_other, self.viewed_machine, peer,
+ **changes, platform="mac", now=time.time())
+ if not outcome.get("accepted", True):
+ if outcome.get("reason") == "desk_full":
+ self._say(tr("The desk is full. Remove an unused profile before adding more ways."), "amber")
+ return False
+ else:
+ self.controller.crossing_event(crossing_state.edit_ways, peer, **changes, **self._crossing_args())
except (SettingsError, OSError, KeyError, TypeError, ValueError) as exc:
self._say(str(exc), "fault")
self._load_ways()
@@ -4168,7 +4701,7 @@ class ControlWindow(AppKit.NSObject):
then quits. Run from source there is no bundle to reopen, so it only says what to do."""
bundle = AppKit.NSBundle.mainBundle().bundlePath()
if not bundle.endswith(".app"):
- self.capture_status.set("Quit Beamer and start it again.", ink="amber")
+ self.capture_status.set(tr("Quit Beamer and start it again."), ink="amber")
return
subprocess.Popen(
["/bin/sh", "-c", 'while kill -0 "$0" 2>/dev/null; do sleep 0.2; done; exec /usr/bin/open "$1"', str(os.getpid()), bundle],
@@ -4178,11 +4711,11 @@ class ControlWindow(AppKit.NSObject):
def toggleRedirect_(self, _sender):
if not self.controller.input_ready:
- self._say("Grant both Mac permissions first.", "fault")
+ self._say(tr("Grant both Mac permissions first."), "fault")
return
if not self.controller.redirecting and self.controller.can_wake:
self.controller.wake()
- self._say(f"Waking {self._first_label()}. It connects on its own once it is up.", "ink_2")
+ self._say(tr("Waking {name}. It connects on its own once it is up.").format(name=self._first_label()), "ink_2")
elif not self.controller.set_redirecting(not self.controller.redirecting, reason="menu"):
self._say(self.controller.connection_status, "fault")
self.refresh()
@@ -4231,18 +4764,18 @@ class ControlWindow(AppKit.NSObject):
driver = self.windows_input.server.owner if self.windows_input is not None else None
route = (protocol.id_text(driver), own_id) if driver is not None else ()
if not route:
- return "Current chain: Idle"
+ return tr("Current chain: Idle")
entries = controller.book.peers()
labels = peerlist.labels(entries)
names_by_id = {entry.get("id"): labels.get(entry.get("token", ""), "another machine")
for entry in entries if entry.get("id")}
names = [identity["name"] if ident == own_id else names_by_id.get(ident, "another machine")
for ident in route]
- return "Current chain: " + " → ".join(names)
+ return tr("Current chain: {route}").format(route=" → ".join(names))
@objc.python_method
def _permission(self, status, button, granted):
- status.set("Granted" if granted else "Required", ink="signal" if granted else "amber")
+ status.set(tr("Granted") if granted else tr("Required"), ink="signal" if granted else "amber")
# Granted, the state says so; a dead "Granted" button beside it only said it twice.
motion.set_hidden(button.view, granted)
@@ -4281,6 +4814,8 @@ class ControlWindow(AppKit.NSObject):
self.granted_at_launch, controller.redirecting, controller.waking,
controller.can_wake, controller.windows_locked, controller.round_trip_ms,
controller.notch_range, self._crossing_state_args(), self.chosen_peer,
+ self.viewed_machine, getattr(controller, "desk_last_heard", {}),
+ getattr(controller, "desk_link_times", {}),
self.wide, self._design_peer_caps(), self._design_states,
self._peer_too_old(), self.shortcut_goes_to.value,
frozenset(controller.crossing_capable()), controller.crossing_display_map())
@@ -4293,16 +4828,16 @@ class ControlWindow(AppKit.NSObject):
needs_relaunch = access and listening and not self.granted_at_launch
self.relaunch_button.view.setHidden_(not needs_relaunch)
if needs_relaunch:
- self.capture_status.set("Both granted. Relaunch Beamer so macOS passes it the keyboard.", ink="amber")
+ self.capture_status.set(tr("Both granted. Relaunch Beamer so macOS passes it the keyboard."), ink="amber")
elif controller.input_ready:
- self.capture_status.set("Input capture ready.", ink="signal")
+ self.capture_status.set(tr("Input capture ready."), ink="signal")
elif access and listening:
detail = controller.input_error
- self.capture_status.set(f"Retrying input capture… {detail}" if detail else "Retrying input capture…", ink="fault")
+ # Translators: {detail} is a diagnostic reason supplied by macOS.
+ self.capture_status.set(tr("Retrying input capture… {detail}").format(detail=detail) if detail else tr("Retrying input capture…"), ink="fault")
else:
self.capture_status.set(
- "Beamer needs both, granted separately. macOS only delivers keyboard events to a process "
- "started after the grant, so relaunch Beamer once you have given them.",
+ tr("Beamer needs both, granted separately. macOS only delivers keyboard events to a process started after the grant, so relaunch Beamer once you have given them."),
ink="ink_2",
)
@@ -4343,10 +4878,10 @@ class ControlWindow(AppKit.NSObject):
peers = peerlist.desktops(controller.book.peers())
first = peerlist.labels(peers)[peers[0]["token"]] if peers else None
self.connection_note.set(self._shown(
- f"The address and port of {first}, the first machine paired. Another machine is changed by pairing it again."
- if first else "Nothing is paired yet. Pairing fills the address and port in."))
+ tr("The address and port of {name}, the first machine paired. Another machine is changed by pairing it again.").format(name=first)
+ if first else tr("Nothing is paired yet. Pairing fills the address and port in.")))
- self.pause_button.set_title("Resume crossing" if controller.crossing_paused else "Pause crossing")
+ self.pause_button.set_title(tr("Resume crossing") if controller.crossing_paused else tr("Pause crossing"))
self.pause_button.set_style("primary" if controller.crossing_paused else "plain")
# With only the shortcut on there is no edge to pause, so there is no button either.
args = self._crossing_state_args()
@@ -4362,14 +4897,14 @@ class ControlWindow(AppKit.NSObject):
self.has_notch = has_notch
self._reflect()
if controller.redirecting:
- self.toggle_button.set_title("Return input to Mac")
+ self.toggle_button.set_title(tr("Return input to Mac"))
elif controller.waking:
- self.toggle_button.set_title(self._shown(f"Waking {self._first_label()}…"))
+ self.toggle_button.set_title(self._shown(tr("Waking {name}…").format(name=self._first_label())))
elif controller.can_wake:
- self.toggle_button.set_title(self._shown(f"Wake {self._first_label()}"))
+ self.toggle_button.set_title(self._shown(tr("Wake {name}").format(name=self._first_label())))
else:
self.toggle_button.set_title(
- self._shown(f"Send input to {self._first_label()}") if controller.peer_label else "Send input")
+ self._shown(tr("Send input to {name}").format(name=self._first_label())) if controller.peer_label else tr("Send input"))
self.toggle_button.set_style("live" if controller.redirecting or controller.windows_locked else "primary")
self.toggle_button.set_enabled(
controller.input_ready
@@ -4377,11 +4912,11 @@ class ControlWindow(AppKit.NSObject):
and (controller.connected or controller.can_wake)
)
mac = cfg.mac_address
- self.wake_state.set(self._shown(mac) if mac else "Not yet learned", ink="ink" if mac else "ink_3")
+ self.wake_state.set(self._shown(mac) if mac else tr("Not yet learned"), ink="ink" if mac else "ink_3")
self.wake_hint.set(
- self._shown(f"Crossing to {first or 'the other machine'} while it sleeps sends a wake-up packet and waits for it.")
+ self._shown(tr("Crossing to {name} while it sleeps sends a wake-up packet and waits for it.").format(name=first or tr("the other machine")))
if mac
- else "Read from the network the first time this Mac connects; nothing to type."
+ else tr("Read from the network the first time this Mac connects; nothing to type.")
)
@@ -4535,14 +5070,14 @@ class TrayApp(rumps.App):
self.toggle_item = _tray_item(TOGGLE_ITEM, callback=self.toggle_redirect)
# With several machines to send to, one item each after the one above, keyed by machine id.
self._send_keys = []
- self.pause_item = _tray_item("Pause crossing", callback=self.toggle_pause)
+ self.pause_item = _tray_item(tr("Pause crossing"), callback=self.toggle_pause)
# One tick per direction, so either can be switched off while the other keeps working.
- self.send_item = _tray_item("This Mac drives other machines", callback=self.toggle_send_to_windows)
- self.receive_item = _tray_item("Other machines drive this Mac", callback=self.toggle_windows_drives)
+ self.send_item = _tray_item(tr("This Mac drives other machines"), callback=self.toggle_send_to_windows)
+ self.receive_item = _tray_item(tr("Other machines drive this Mac"), callback=self.toggle_windows_drives)
self._symbol = None
super().__init__(
"Beamer",
- title="Beamer • Local",
+ title=tr("Beamer • Local"),
menu=[
self.status_item,
rumps.separator,
@@ -4554,12 +5089,12 @@ class TrayApp(rumps.App):
self.send_item,
self.receive_item,
rumps.separator,
- _tray_item("Settings…", callback=self.open_window),
- _tray_item("Reload configuration", callback=self.reload_config),
- _tray_item("Open log folder", callback=self.open_log_folder),
+ _tray_item(tr("Settings…"), callback=self.open_window),
+ _tray_item(tr("Reload configuration"), callback=self.reload_config),
+ _tray_item(tr("Open log folder"), callback=self.open_log_folder),
rumps.separator,
- _tray_item("About Beamer", callback=self.show_about),
- _tray_item("Quit Beamer", callback=self.quit_app),
+ _tray_item(tr("About Beamer"), callback=self.show_about),
+ _tray_item(tr("Quit Beamer"), callback=self.quit_app),
],
quit_button=None,
)
@@ -4577,10 +5112,10 @@ class TrayApp(rumps.App):
"""On the main thread. The version line in the menu becomes the way to the download."""
self.update_url = found[1] if found else None
if found:
- _set_tray_title(self.header_item, f"Beamer {found[0]} is available…")
+ _set_tray_title(self.header_item, tr("Beamer {version} is available…").format(version=found[0]))
self.header_item.set_callback(self.open_update)
else:
- _set_tray_title(self.header_item, f"Beamer {VERSION}")
+ _set_tray_title(self.header_item, tr("Beamer {version}").format(version=VERSION))
self.header_item.set_callback(None)
self.control_window.show_update(found)
@@ -4640,12 +5175,13 @@ class TrayApp(rumps.App):
)
hide = controller.cfg.hide_addresses
if controller.redirecting:
- _set_tray_title(self.toggle_item, "Return input to Mac")
+ _set_tray_title(self.toggle_item, tr("Return input to Mac"))
else:
_set_tray_title(self.toggle_item, pages.redact(
- f"Send input to {controller.peer_label}" if controller.peer_label else "Send input", hide))
- _set_tray_title(self.pause_item, "Resume crossing" if controller.crossing_paused else "Pause crossing")
+ tr("Send input to {name}").format(name=controller.peer_label) if controller.peer_label else tr("Send input"), hide))
+ _set_tray_title(self.pause_item, tr("Resume crossing") if controller.crossing_paused else tr("Pause crossing"))
self._machine_items()
+ self._profile_items()
self._direction_items()
self._refresh_tray_state()
@@ -4672,6 +5208,30 @@ class TrayApp(rumps.App):
item.set_callback((lambda _sender, ident=ident: self._send_to(ident)) if enabled else None)
self.toggle_item.hidden = bool(keys)
+ def _profile_items(self):
+ settings = self.settings_store.current()
+ choices = profiles.profile_list(settings)
+ active = settings["crossing_desk"]["active"]["value"]
+ key = (profiles.same_ways_on(settings), tuple((p["id"], p["label"]) for p in choices), active)
+ if key == getattr(self, "_profile_menu_key", None):
+ return
+ self._profile_menu_key = key
+ previous = getattr(self, "profile_item", None)
+ if previous is not None:
+ del self.menu[previous.title]
+ self.profile_item = None
+ if not key[0] or len(choices) < 2:
+ return
+ item = _tray_item(tr("Profile"), callback=None)
+ for choice in choices:
+ child = _tray_item(choice["id"], callback=lambda _sender, pid=choice["id"]:
+ self.control_window._profile_event(crossing_state.switch_profile, pid))
+ child.state = choice["id"] == active
+ item.add(child)
+ _set_tray_title(child, choice["label"])
+ self.menu.add(item)
+ self.profile_item = item
+
def _peer_live(self, entry):
link = self.controller.links.get(entry.get("token"))
return link is not None and link.live()
@@ -4681,7 +5241,7 @@ class TrayApp(rumps.App):
"Moving input"), or home when it is already there."""
controller = self.controller
if not controller.input_ready:
- self.notify_user("Beamer", "Grant both Mac permissions first.")
+ self.notify_user("Beamer", tr("Grant both Mac permissions first."))
return
if controller.redirecting and controller.owner.on == peer:
controller.set_redirecting(False)
@@ -4696,18 +5256,19 @@ class TrayApp(rumps.App):
hide = self.controller.cfg.hide_addresses
labels = [pages.redact(label, hide) for label in peerlist.labels(peers).values()]
if len(labels) == 1:
- send, receive = f"This Mac drives {labels[0]}", f"{labels[0]} drives this Mac"
+ send, receive = (tr("This Mac drives {name}").format(name=labels[0]),
+ tr("{name} drives this Mac").format(name=labels[0]))
elif labels:
- send, receive = "This Mac drives every machine", "Every machine drives this Mac"
+ send, receive = tr("This Mac drives every machine"), tr("Every machine drives this Mac")
else:
- send, receive = "This Mac drives other machines", "Other machines drive this Mac"
+ send, receive = tr("This Mac drives other machines"), tr("Other machines drive this Mac")
_set_tray_title(self.send_item, send)
_set_tray_title(self.receive_item, receive)
desktops = peerlist.desktops(peers)
send_labels = [pages.redact(label, hide) for label in peerlist.labels(desktops).values()]
_set_tray_title(self.send_item,
- f"This Mac drives {send_labels[0]}" if len(send_labels) == 1 else
- "This Mac drives every machine" if send_labels else "This Mac drives other machines")
+ tr("This Mac drives {name}").format(name=send_labels[0]) if len(send_labels) == 1 else
+ tr("This Mac drives every machine") if send_labels else tr("This Mac drives other machines"))
for item, name in ((self.send_item, "send"), (self.receive_item, "allow_drive")):
on = [peer.get(name) is True for peer in (desktops if name == "send" else peers)]
item.state = 1 if on and all(on) else -1 if any(on) else 0
@@ -4779,7 +5340,8 @@ class TrayApp(rumps.App):
entry["id"], **self.control_window._crossing_args())
except (SettingsError, OSError, KeyError) as exc:
self.logger.warning("layout state not saved: %s", exc)
- self.notify_user("Beamer", f"Could not save the change: {exc}")
+ # Translators: {error} is the system error message.
+ self.notify_user("Beamer", tr("Could not save the change: {error}").format(error=exc))
self.control_window.panel.invalidate()
self.control_window.peers_changed()
return
@@ -4795,7 +5357,8 @@ class TrayApp(rumps.App):
entries.append(entry)
except SettingsError as exc:
self.logger.warning("direction not saved: %s", exc)
- self.notify_user("Beamer", f"Could not save the change: {exc}")
+ # Translators: {error} is the system error message.
+ self.notify_user("Beamer", tr("Could not save the change: {error}").format(error=exc))
# Some machines may have been saved before this one failed, and a switch the person
# flipped shows a state that is not saved: read it all again.
self.control_window.panel.invalidate()
@@ -4823,12 +5386,12 @@ class TrayApp(rumps.App):
cfg = self.settings_store.load()
except SettingsError as exc:
self.logger.warning("configuration not reloaded: %s", exc)
- self.notify_user("Configuration not reloaded", str(exc))
+ self.notify_user(tr("Configuration not reloaded"), tr("{error}").format(error=exc))
return
# The controller first: the window's address fields read Hide addresses from it.
self.controller.update_config(cfg)
self.control_window._load(config_to_raw(cfg))
- self.notify_user("Configuration reloaded", "Beamer is using the config on disk.")
+ self.notify_user(tr("Configuration reloaded"), tr("Beamer is using the config on disk."))
def show_about(self, _sender):
show_about_panel()
@@ -5000,7 +5563,11 @@ class TrayApp(rumps.App):
AppHelper.callAfter(self._notify_user_main, title, message)
def _notify_user_main(self, title, message):
- if message.startswith("Can't cross to"):
+ if matches_translation(
+ message, "Can't cross to {name}: it is being driven from {other}.",
+ "Can't cross to {name}: another machine is driving it.",
+ "Can't cross to {name}: it is driving {other}.",
+ "Can't cross to {name}: it is driving another machine."):
self._last_refusal = message
refresh = getattr(self, "_refresh_tray_state", None)
if refresh is not None:
@@ -5019,10 +5586,10 @@ class TrayApp(rumps.App):
def _drive_status(self):
if self.controller.redirecting:
- return f"Driving {self.controller.on_label or 'another machine'}"
+ return tr("Driving {name}").format(name=self.controller.on_label or tr("another machine"))
if self.controller.driver is not None:
- return f"Driven by {self.controller.driver_label or 'another machine'}"
- return "Idle"
+ return tr("Driven by {name}").format(name=self.controller.driver_label or tr("another machine"))
+ return tr("Idle")
def _refresh_tray_state(self):
state = self._drive_status()
@@ -5096,6 +5663,7 @@ def main(argv=None):
else:
logger.info("first run: no settings yet, starting from the defaults")
cfg = editable_default_config()
+ install(cfg.language)
book, identity = bridge.links_from_store(settings_store, VERSION)
controller = WakingController(cfg, logger=logger, book=book, identity=identity, hardware=hardware_mac.hardware_address_towards)
app = TrayApp(controller, settings_store, logger, hidden=args.hidden)
diff --git a/mac_app/ledger.py b/mac_app/ledger.py
index 0fb9982..9138afa 100644
--- a/mac_app/ledger.py
+++ b/mac_app/ledger.py
@@ -9,6 +9,7 @@ import Quartz
import theme
import widgets
from core import peerlist, ways
+from core.i18n import N_, tr, trc
# The columns' narrowest widths sum to this plus the gaps; under it the table stacks.
CHIP_HEIGHT = 26
@@ -209,6 +210,8 @@ class Chip(_Control):
fill, border, alpha, dashed, text = [("well", 1)], "ink_2", 1.0, False, "ink"
if pressed:
fill, border, alpha, dashed, text = [("well", 1), ("signal", .35)], "signal", 1.0, False, "ink"
+ if not self.enabled:
+ fill, border, alpha, dashed, text, icon = None, "rule", 1.0, False, "ink_3", "ink_3"
self.paint_box(fill, border, alpha, dashed, 5, bounds)
_icon({"free": "plus", "on": "wrap", "kept": "wrap"}.get(self.kind, "touch"), icon, 9, 6)
bar_room = 28 if self.bar is not None else 0
@@ -221,7 +224,7 @@ class Chip(_Control):
path = AppKit.NSBezierPath.bezierPath()
path.moveToPoint_((self.bar_x() + 1 + index * 7.3, 13))
path.lineToPoint_((self.bar_x() + 6 + index * 7.3, 13))
- _stroke(path, "signal" if on else "edge", 1, 3 if on else 1.5)
+ _stroke(path, "ink_3" if not self.enabled else "signal" if on else "edge", 1, 3 if on else 1.5)
context.restoreGraphicsState()
@@ -262,9 +265,14 @@ class CornerButton(_Control):
fill, border, alpha, dashed = ([("well", 1)] if self.kind != "on" else fill), "ink_2", 1.0, False
if pressed:
fill, border, alpha, dashed = [("well", 1), ("signal", .35)], "signal", 1.0, False
+ if not self.enabled:
+ fill, border, alpha, dashed, bracket, bracket_alpha = None, "rule", 1.0, False, "ink_3", 1.0
self.paint_box(fill, border, alpha, dashed, 5, bounds)
vertical, horizontal = self.corner.split("_")
- sx, sy = (5 if horizontal == "left" else 13) + 5, (5 if vertical == "top" else 13) + 5
+ # The 7 pt bracket sits centred in the square, its corner towards the square's corner.
+ inset_x, inset_y = (bounds.size.width - 7) / 2, (bounds.size.height - 7) / 2
+ sx = inset_x if horizontal == "left" else bounds.size.width - inset_x
+ sy = inset_y if vertical == "top" else bounds.size.height - inset_y
dx, dy = (1 if horizontal == "left" else -1), (1 if vertical == "top" else -1)
path = AppKit.NSBezierPath.bezierPath()
path.moveToPoint_((sx, sy + dy * 7))
@@ -293,15 +301,15 @@ class Row(AppKit.NSView):
self.cells[key] = cell
self.name = widgets.Label("", theme.TYPE["body"], 600)
self.status = widgets.Label("", theme.TYPE["small"], ink="ink_3")
- self.rename = quiet_button("Rename", self.begin_rename)
- self.leave = quiet_button("Leave out", lambda: self.control._set_atlas_left_out(
+ self.rename = quiet_button(tr("Rename"), self.begin_rename)
+ self.leave = quiet_button(tr("Leave out"), lambda: self.control._set_atlas_left_out(
self.peer, not (self.entry.get("left_out") is True or self.entry.get("in_use", True) is False)))
self.name_field = AppKit.NSTextField.alloc().init()
self.name_field.setDelegate_(self.control)
self.name_field.setFont_(theme.font(theme.TYPE["body"]))
self.name_field.setHidden_(True)
- self.rename_hint = widgets.Label("Return saves, Escape cancels", theme.TYPE["small"], ink="ink_3", wrap=True)
- self.scope = widgets.Label("Only on this Mac", theme.TYPE["small"], ink="ink_3")
+ self.rename_hint = widgets.Label(tr("Return saves, Escape cancels"), theme.TYPE["small"], ink="ink_3", wrap=True)
+ self.scope = widgets.Label(tr("Only on this Mac"), theme.TYPE["small"], ink="ink_3")
for item in (self.name.view, self.status.view, self.rename, self.leave, self.name_field,
self.rename_hint.view, self.scope.view):
self._add("machine", item)
@@ -310,7 +318,7 @@ class Row(AppKit.NSView):
chip = self._chip(side)
self.chips[side] = chip
self._add("edge", chip)
- self.edge_note = widgets.Label("Place it on the map", theme.TYPE["small"], ink="ink_3")
+ self.edge_note = widgets.Label(tr("Place it on the map"), theme.TYPE["small"], ink="ink_3")
self._add("edge", self.edge_note.view)
self.corner_buttons = {}
for corner in ways.CORNERS:
@@ -320,18 +328,22 @@ class Row(AppKit.NSView):
self.corner_buttons[corner] = button
self._add("corner", button)
self.notch = self._check(lambda on: self.control._ledger_notch(self.peer, on))
- self.no_notch = widgets.Label("No notch", theme.TYPE["body"], ink="ink_3")
+ self.no_notch = widgets.Label(tr("No notch"), theme.TYPE["body"], ink="ink_3", wrap=True)
self.cycle = self._check(lambda on: self.control._set_shortcut_cycle(self.peer, on))
self.notch_return = self._check(lambda on: self.control._ledger_notch_return(self.peer, on))
- self.notch_return.setTitle_("Return through the notch")
+ self.notch_return.setTitle_(tr("Return through the notch"))
self._add("notch", self.notch)
self._add("notch", self.no_notch.view)
self._add("notch", self.notch_return)
self._add("keys", self.cycle)
- self.jump_caption = widgets.Label("Jump", theme.TYPE["small"], ink="ink_3")
+ self.jump_caption = widgets.Label(tr("Jump"), theme.TYPE["small"], ink="ink_3")
self.jump = widgets.JumpKeyRecorder(on_change=lambda value: self.control._save_jump_key(value, self.peer),
- on_arm=self._arm_jump, compact=True)
- self.clear = quiet_button("Clear", lambda: self.control._save_jump_key("", self.peer))
+ on_arm=self._arm_jump, compact=True,
+ hint=tr(widgets.JumpKeyRecorder.HINT),
+ recording_title=tr("Press a key combination…"),
+ recording_hint=tr("Click again to cancel"))
+ self.clear = quiet_button(tr("Clear"), lambda: self.control._save_jump_key("", self.peer))
+ self.leave_state = None
for item in (self.jump_caption.view, self.jump.view, self.clear):
self._add("keys", item)
return self
@@ -378,6 +390,8 @@ class Row(AppKit.NSView):
@objc.python_method
def begin_rename(self):
+ if self.ledger.remote or self.ledger.read_only:
+ return
if self.control.page != "crossing":
self.control._select_page("crossing")
self.renaming = True
@@ -410,49 +424,63 @@ class Row(AppKit.NSView):
name = self.control._shown(peerlist.label_for(settings["peers"], peer_id=self.peer) or peerlist.UNNAMED)
linked = self.control._live(self.peer)
out = entry.get("left_out") is True or entry.get("in_use", True) is False
+ inert = out or self.ledger.read_only
self.dimmed = out or not linked
- platform = {"macos": "macOS", "windows": "Windows", "linux": "Linux"}.get(entry.get("platform"), "Machine")
+ platform = tr({"macos": N_("macOS"), "windows": N_("Windows"), "linux": N_("Linux")}.get(entry.get("platform"), N_("Machine")))
caps = self.control._design_peer_caps()
- status = "Left out" if out else "Linked" if linked else "Offline, ways kept"
- self.status_text = f"{platform} · {status}"
+ status = tr("Left out") if out else tr("Linked") if linked else tr("Offline, ways kept")
+ self.status_text = tr("{platform} · {status}").format(platform=platform, status=status)
self.old_peer = self.peer in caps and "layout" not in caps[self.peer]
if self.old_peer:
- self.status_text = f"Beamer {entry.get('app') or '1.5.2'} · only sees which side"
+ self.status_text = tr("Beamer {version} · only sees which side").format(version=entry.get("app") or "1.5.2")
self.name.set(name, ink="ink_2" if self.dimmed else "ink")
self.name.view.setToolTip_(name)
self.name.view.setLineBreakMode_(AppKit.NSLineBreakByTruncatingTail)
self.status.set(self.status_text)
- leave_title = "Put back" if out else "Leave out"
- if self.leave.title() != leave_title:
+ leave_title = tr("Put back") if out else tr("Leave out")
+ if self.leave_state != out:
self.leave.setAttributedTitle_(widgets.attributed(leave_title, 12.5, 500, "ink_2"))
- self.leave.setAccessibilityLabel_("Put back" if out else "Leave out")
- self.leave.setToolTip_("Left out machines stay paired and linked. The shortcut, menu and clipboard still reach them." if out else "Leave this machine out of pointer crossings")
+ self.leave_state = out
+ self.leave.setAccessibilityLabel_(leave_title)
+ self.leave.setToolTip_(tr("Left out machines stay paired and linked. The shortcut, menu and clipboard still reach them.") if out else tr("Leave this machine out of pointer crossings"))
self.reach = self._reach(settings, out)
self._refresh_chips(name, out)
self._refresh_corners(name, out)
- self.notch.setTitle_("Notch" if self.control.has_notch else "")
- self.no_notch.view.setHidden_(self.control.has_notch)
- self.notch.setAccessibilityLabel_("Notch, no notch" if not self.control.has_notch else
- "Notch, on" if "notch" in self.held["methods"] else "Notch, off")
+ has_notch = self.ledger.has_notch
+ self.notch.setTitle_(tr("Notch") if has_notch else "")
+ self.no_notch.view.setHidden_(has_notch or self.ledger.remote)
+ self.notch.setAccessibilityLabel_(tr("Notch, no notch") if not has_notch else
+ tr("Notch, on") if "notch" in self.held["methods"] else tr("Notch, off"))
self.notch.setState_(int("notch" in self.held["methods"]))
- self.notch.setEnabled_(self.control.has_notch and not out)
- self.notch.setToolTip_(f"Push into the notch to reach {name}")
+ self.notch.setEnabled_(has_notch and not inert)
+ self.notch.setToolTip_(tr("Push into the notch to reach {name}").format(name=name))
notch_return = entry.get("notch_return") is True
- self.notch_return.setHidden_(not self.control.has_notch or "notch" not in self.held["methods"])
+ self.notch_return.setHidden_(not has_notch or "notch" not in self.held["methods"])
self.notch_return.setState_(int(notch_return))
- self.notch_return.setEnabled_(not out)
- self.notch_return.setAccessibilityLabel_(f"Return through the notch, {'on' if notch_return else 'off'}")
- self.notch_return.setToolTip_(f"Coming back from {name}, arrive just below the notch")
+ self.notch_return.setEnabled_(not inert)
+ self.notch_return.setAccessibilityLabel_(tr("Return through the notch, on") if notch_return else tr("Return through the notch, off"))
+ self.notch_return.setToolTip_(tr("Coming back from {name}, arrive just below the notch").format(name=name))
self.cycle.setTitle_(widgets.key_title(self.control.key_recorder.value))
self.cycle.setState_(int(entry.get("shortcut_cycle") is not False))
- self.cycle.setToolTip_("In the shortcut's cycle")
+ self.cycle.setToolTip_(tr("In the shortcut's cycle"))
if self.jump.monitor is None:
self.jump.set_value(entry.get("jump_key", ""))
self.jump.hint.view.setHidden_(self.jump.monitor is None)
- self.jump.view.setToolTip_(f"Press {self.jump._title()} to send input to {name}; press again to bring it home.")
+ # Translators: {key} is the recorded key combination; {name} is the machine name.
+ self.jump.view.setToolTip_(tr("Press {key} to send input to {name}; press again to bring it home.").format(key=self.jump._title(), name=name))
self.clear.setHidden_(not bool(self.jump.value))
- self.rename.setAccessibilityLabel_(f"Rename {name}")
- self.leave.setAccessibilityLabel_(f"{'Put back' if out else 'Leave out'} {name}")
+ self.rename.setAccessibilityLabel_(tr("Rename {name}").format(name=name))
+ self.leave.setAccessibilityLabel_(tr("Put back {name}").format(name=name) if out else tr("Leave out {name}").format(name=name))
+ self.cells["keys"].setHidden_(self.ledger.remote)
+ self.cells["notch"].setHidden_(self.ledger.remote and not has_notch)
+ self.rename.setHidden_(self.ledger.remote)
+ self.leave.setHidden_(self.ledger.remote)
+ self.rename.setEnabled_(not self.ledger.read_only)
+ self.leave.setEnabled_(not self.ledger.read_only)
+ self.cycle.setEnabled_(not self.ledger.read_only)
+ if self.ledger.remote:
+ self.renaming = False
+ self.jump.cancel()
self.setAccessibilityLabel_(name)
self.setNeedsDisplay_(True)
@@ -474,46 +502,54 @@ class Row(AppKit.NSView):
for side, chip in self.chips.items():
state = sides[side]
kind, bar = state["state"], None
- title = side.capitalize()
- lead = f"{title} edge"
+ side_title = tr({"left": N_("Left"), "right": N_("Right"),
+ "top": N_("Top"), "bottom": N_("Bottom")}[side])
+ title = side_title
+ lead = tr("{side} edge").format(side=side_title)
+ on_word, off_word = trc("switch state", "on"), trc("switch state", "off")
if kind == "contact":
kind, bar = "contact_on" if picked else "contact_off", picked
- tip = f"{lead}: touches {name}; click to turn it {'off' if picked else 'on'}"
- label = f"{lead}, touches {name}, {'on' if picked else 'off'}"
+ tip = tr("{edge}: touches {name}; click to turn it {state}").format(
+ edge=lead, name=name, state=off_word if picked else on_word)
+ label = tr("{edge}, touches {name}, {state}").format(
+ edge=lead, name=name, state=on_word if picked else off_word)
elif kind == "on":
- title += ", wraps"
- tip = f"{lead} wraps round to {name}; click to remove"
- label = f"{lead}, wraps round, on"
+ title = tr("{side}, wraps").format(side=side_title)
+ tip = tr("{edge} wraps round to {name}; click to remove").format(edge=lead, name=name)
+ label = tr("{edge}, wraps round, {state}").format(edge=lead, state=on_word)
elif kind == "kept":
- title += ", wraps"
- tip = (f"{lead} wraps round to {name} once Edge is on; click to turn Edge on" if not picked else
- f"{lead}: none of it is free just now; click to remove")
- label = f"{lead}, wraps round, kept"
+ title = tr("{side}, wraps").format(side=side_title)
+ tip = (tr("{edge} wraps round to {name} once Edge is on; click to turn Edge on").format(edge=lead, name=name) if not picked else
+ tr("{edge}: none of it is free just now; click to remove").format(edge=lead, name=name))
+ label = tr("{edge}, wraps round, kept").format(edge=lead)
elif kind == "free":
- tip = f"{lead}: click to wrap round to {name}"
- label = f"{lead}, wraps round, off"
+ tip = tr("{edge}: click to wrap round to {name}").format(edge=lead, name=name)
+ label = tr("{edge}, wraps round, {state}").format(edge=lead, state=off_word)
elif kind == "held":
other = self._holder(state)
- title += f", {other}"
- tip = f"{lead}: {other}'s"
- label = f"{lead}, held by {other}"
+ title = tr("{side}, {name}").format(side=side_title, name=other)
+ tip = tr("{edge}: {name}'s").format(edge=lead, name=other)
+ label = tr("{edge}, held by {name}").format(edge=lead, name=other)
else:
tip = label = ""
- chip.setToolTip_("Left out: Put back to change its ways" if out and kind != "unavailable" else tip)
+ chip.setToolTip_(tr("Left out: Put back to change its ways") if out and kind != "unavailable" else tip)
chip.setAccessibilityLabel_(label)
- chip.setAccessibilityValue_("on" if kind in ("contact_on", "on") else "off")
- chip.apply(kind, title, bar, kind not in ("held", "unavailable") and not out)
+ chip.setAccessibilityValue_(on_word if kind in ("contact_on", "on") else off_word)
+ chip.apply(kind, title, bar, kind not in ("held", "unavailable") and not out and not self.ledger.read_only)
# A left-out row shows only the ways it keeps.
chip.setHidden_(kind == "unavailable" or out and kind in ("free", "held"))
for part, segment in chip.segments.items():
segment.setHidden_(bar is None)
if bar is not None:
- third = ways.part_names(side)[part]
- segment.setEnabled_(not out)
- segment.setAccessibilityLabel_(f"{lead}, {third.lower()} third, {'on' if part in picked else 'off'}")
- segment.setAccessibilityValue_("on" if part in picked else "off")
- segment.setToolTip_("Left out: Put back to change its ways" if out else
- f"{third} third: click to {'leave it out' if part in picked else 'turn it on'}")
+ third = tr({"Top": N_("Top"), "Middle": N_("Middle"), "Bottom": N_("Bottom"),
+ "Left": N_("Left"), "Right": N_("Right")}[ways.part_names(side)[part]])
+ segment.setEnabled_(not out and not self.ledger.read_only)
+ segment.setAccessibilityLabel_(tr("{edge}, {third} third, {state}").format(
+ edge=lead, third=third.lower(), state=on_word if part in picked else off_word))
+ segment.setAccessibilityValue_(on_word if part in picked else off_word)
+ segment.setToolTip_(tr("Left out: Put back to change its ways") if out else
+ tr("{third} third: click to leave it out").format(third=third) if part in picked else
+ tr("{third} third: click to turn it on").format(third=third))
chip.place_segments()
self.edge_note.view.setHidden_(any(not chip.isHidden() for chip in self.chips.values()))
@@ -525,19 +561,23 @@ class Row(AppKit.NSView):
if kind == "unavailable" and corner in self.held["corners"]:
# A corner left on after its machine moved away must still be removable.
kind = "on"
- title = corner.replace("_", " ").capitalize()
- tip = {"on": f"{title} corner: click to turn it off",
- "free": f"{title} corner: click to turn it on",
- "held": f"{self._holder(state) if kind == 'held' else ''}'s corner",
- "unavailable": f"Place {name} beside this Mac first"}[kind]
- button.setToolTip_("Left out: Put back to change its ways" if out else tip)
- button.setAccessibilityLabel_(f"{title} corner, " + {"on": "on", "free": "off", "unavailable": "unavailable",
- "held": f"held by {self._holder(state) if kind == 'held' else ''}"}[kind])
- button.setAccessibilityValue_("on" if kind == "on" else "off")
- button.apply(kind, kind in ("on", "free") and not out)
+ title = tr({"top_left": N_("Top left"), "top_right": N_("Top right"),
+ "bottom_left": N_("Bottom left"), "bottom_right": N_("Bottom right")}[corner])
+ holder = self._holder(state) if kind == "held" else ""
+ tip = {"on": tr("{corner} corner: click to turn it off").format(corner=title),
+ "free": tr("{corner} corner: click to turn it on").format(corner=title),
+ "held": tr("{name}'s corner").format(name=holder),
+ "unavailable": tr("Place {name} beside this Mac first").format(name=name)}[kind]
+ button.setToolTip_(tr("Left out: Put back to change its ways") if out else tip)
+ on_word, off_word = trc("switch state", "on"), trc("switch state", "off")
+ state_word = {"on": on_word, "free": off_word, "unavailable": tr("unavailable"),
+ "held": tr("held by {name}").format(name=holder)}[kind]
+ button.setAccessibilityLabel_(tr("{corner} corner, {state}").format(corner=title, state=state_word))
+ button.setAccessibilityValue_(on_word if kind == "on" else off_word)
+ button.apply(kind, kind in ("on", "free") and not out and not self.ledger.read_only)
def mouseDown_(self, event):
- self.control._atlas_selected(self.peer)
+ self.control._machine_picked(self.peer)
def accessibilityRowHeaderUIElements(self):
return [self.name.view]
@@ -568,12 +608,18 @@ class Row(AppKit.NSView):
keys_x = 12 + CORNERS_COLUMN + 16 + NOTCH_COLUMN + 16
positions = [(0, width), (12, inner), (12, CORNERS_COLUMN), (12 + CORNERS_COLUMN + 16, NOTCH_COLUMN),
(keys_x, max(128, width - 12 - keys_x))]
+ if self.ledger.remote and not self.ledger.has_notch:
+ positions[3] = (width, 0)
positions[0] = (12, positions[0][1] - 12)
for key, (x, w) in zip(self.cells, positions):
self.cells[key].setFrame_(((x, 12), (w, 72)))
self.cells[key].setAlphaValue_(.5 if self.dimmed else 1)
cell_heights = {"machine": 72 + rename_space, "notch": 28,
"corner": 2 * CORNER_SIZE + CORNER_GAP}
+ if self.ledger.remote:
+ cell_heights["machine"] = 48
+ if not self.ledger.has_notch:
+ cell_heights["notch"] = 0
cell_heights["edge"] = self._flow(self.cells["edge"].bounds().size.width)
self.edge_note.view.setFrame_(((0, 2), (self.cells["edge"].bounds().size.width, 20)))
for index, corner in enumerate(ways.CORNERS):
@@ -593,6 +639,8 @@ class Row(AppKit.NSView):
self.clear.setHidden_(not self.jump.value or self.jump.monitor is not None)
cell_heights["keys"] = max(60, 32 + jump_h,
clear_y + 24 if not self.clear.isHidden() else 0)
+ if self.ledger.remote:
+ cell_heights["keys"] = 0
# Return through the notch runs on under the notch, corners and keys, from the notch's column to
# the row's end: no column is wide enough for it.
return_y = max(cell_heights["corner"], cell_heights["notch"], cell_heights["keys"]) + 8
@@ -610,12 +658,16 @@ class Row(AppKit.NSView):
places = [(12, height-24)] * 5
for key, (y, h) in zip(self.cells, places):
cell = self.cells[key]
+ if self.ledger.remote and (key == "keys" or key == "notch" and not self.ledger.has_notch):
+ h = 0
cell.setFrame_(((cell.frame().origin.x, y), (cell.bounds().size.width, h)))
machine = self.cells["machine"].bounds().size.width
self.name.view.setFrame_(((0, 0), (machine, 22)))
self.status.view.setFrame_(((12, 25), (machine-12, 19)))
- self.rename.setFrame_(((0, 48), (54, 24)))
- self.leave.setFrame_(((56, 48), (min(74, machine-56), 24)))
+ # Sized to the title, so a longer translation ("Rinomina") is not cut.
+ rename_w = max(54, math.ceil(self.rename.fittingSize().width))
+ self.rename.setFrame_(((0, 48), (rename_w, 24)))
+ self.leave.setFrame_(((rename_w + 2, 48), (min(74, machine - rename_w - 2), 24)))
self.name_field.setFrame_(((0, 0), (machine, 24)))
self.name_field.setHidden_(not self.renaming)
self.name.view.setHidden_(self.renaming)
@@ -623,8 +675,9 @@ class Row(AppKit.NSView):
label.view.setFrame_(((0, y), (machine, 32)))
label.view.setHidden_(not self.renaming or label is self.scope and self.control.controller.cfg.same_on_both)
w = self.cells["notch"].bounds().size.width
- self.notch.setFrame_(((0, 0), (w if self.control.has_notch else 22, 28)))
- self.no_notch.view.setFrame_(((0, 32), (w, 22)))
+ self.notch.setFrame_(((0, 0), (w if self.ledger.has_notch else 22, 28)))
+ # Wraps inside its column: the keys column sits beside it when rows stack, so it cannot grow sideways.
+ self.no_notch.view.setFrame_(((0, 32), (w, 40)))
self.notch_return.setFrame_(((0, return_y), (max(w, width - 12 - self.cells["notch"].frame().origin.x), 28)))
return height
@@ -647,15 +700,17 @@ class Ledger(AppKit.NSView):
@objc.python_method
def setup(self, control):
self.control, self.rows = control, {}
+ self.remote = self.read_only = False
+ self.has_notch = control.has_notch
self.order = []
self.setTranslatesAutoresizingMaskIntoConstraints_(False)
self.height = self.heightAnchor().constraintEqualToConstant_(0)
self.height.setActive_(True)
self.setAccessibilityElement_(True)
self.setAccessibilityRole_(AppKit.NSAccessibilityTableRole)
- self.setAccessibilityLabel_("Machines and crossing ways")
+ self.setAccessibilityLabel_(tr("Machines and crossing ways"))
self.headers = []
- for title in ("Machine", "Edges", "Corners", "Notch", "Keys"):
+ for title in (tr("Machine"), tr("Edges"), tr("Corners"), tr("Notch"), tr("Keys")):
label = widgets.Label(title, theme.TYPE["eyebrow"], 700, "ink_3",
tracking=theme.TRACKING["eyebrow"], upper=True)
label.view.setTranslatesAutoresizingMaskIntoConstraints_(True)
@@ -667,10 +722,22 @@ class Ledger(AppKit.NSView):
@objc.python_method
def narrow_below(self):
"""The narrowest table every column's least width fits: under it the rows stack."""
- return 132 + 220 + CORNERS_COLUMN + NOTCH_COLUMN + 132 + 4 * 16
+ if self.remote and not self.has_notch:
+ return 132 + 220 + CORNERS_COLUMN + 2 * 16
+ return 132 + 220 + CORNERS_COLUMN + NOTCH_COLUMN + (3 * 16 if self.remote else 132 + 4 * 16)
@objc.python_method
def columns(self, width):
+ if self.remote:
+ gaps = 48 if self.has_notch else 32
+ notch = NOTCH_COLUMN if self.has_notch else 0
+ remaining = max(352, width - gaps - CORNERS_COLUMN - notch)
+ machine = max(132, remaining - max(220, remaining * 2 / 3.3))
+ edge = remaining - machine
+ return [(0, machine), (machine + 16, edge),
+ (machine + edge + 32, CORNERS_COLUMN),
+ (machine + edge + CORNERS_COLUMN + 48, NOTCH_COLUMN) if self.has_notch else (width, 0),
+ (width, 0)]
weights = (1.3, 2, 0, 0, 1)
widths = [132, 220, CORNERS_COLUMN, NOTCH_COLUMN, 132]
remaining = max(480, width - 64 - CORNERS_COLUMN - NOTCH_COLUMN)
@@ -691,7 +758,9 @@ class Ledger(AppKit.NSView):
return result
@objc.python_method
- def refresh(self, settings, selected):
+ def refresh(self, settings, selected, *, remote=False, read_only=False, has_notch=None):
+ self.remote, self.read_only = bool(remote), bool(read_only)
+ self.has_notch = self.control.has_notch if has_notch is None else bool(has_notch)
entries = peerlist.desktops(settings["peers"])
tiles = ways.derive_layout(settings, gap=0)
entries.sort(key=lambda entry: (entry["id"] not in tiles,
@@ -716,8 +785,9 @@ class Ledger(AppKit.NSView):
width = self.bounds().size.width
narrow = width < self.narrow_below()
y = 0 if narrow or not self.rows else 34
- for label, (x, w) in zip(self.headers, self.columns(width)):
- label.view.setHidden_(narrow or not self.rows)
+ for index, (label, (x, w)) in enumerate(zip(self.headers, self.columns(width))):
+ label.view.setHidden_(narrow or not self.rows or self.remote and
+ (index == 4 or index == 3 and not self.has_notch))
label.view.setFrame_(((x, 0), (w, 24)))
for peer in self.order:
row = self.rows[peer]
@@ -736,7 +806,8 @@ class Ledger(AppKit.NSView):
return [self.rows[peer] for peer in self.order]
def accessibilityColumns(self):
- return [header.view for header in self.headers]
+ count = (4 if self.has_notch else 3) if self.remote else 5
+ return [header.view for header in self.headers[:count]]
def accessibilityColumnHeaderUIElements(self):
- return [header.view for header in self.headers]
+ return self.accessibilityColumns()
diff --git a/mac_app/link_state.py b/mac_app/link_state.py
index 597b816..9f95084 100644
--- a/mac_app/link_state.py
+++ b/mac_app/link_state.py
@@ -9,7 +9,7 @@ from __future__ import annotations
from dataclasses import dataclass
-from wake import NOT_WOKEN_SUFFIX
+from core.i18n import matches_translation, tr
SIGNAL = "signal"
AMBER = "amber"
@@ -28,7 +28,7 @@ class LinkState:
def peer_name(cfg) -> str:
- return cfg.pc_name or cfg.host or "the other machine"
+ return cfg.pc_name or cfg.host or tr("the other machine")
def describe(controller) -> LinkState:
@@ -44,58 +44,59 @@ def describe(controller) -> LinkState:
kind = getattr(controller, "status_kind", "none")
if getattr(controller, "receiving", False):
return LinkState(
- "receiving", SIGNAL, f"From {driver}", "Live",
- f"{driver}'s keyboard and pointer are on this Mac. Push its pointer back through the edge "
- "it arrived by to send them home.",
+ "receiving", SIGNAL, tr("From {name}").format(name=driver), tr("Live"),
+ tr("{name}'s keyboard and pointer are on this Mac. Push its pointer back through the edge it arrived by to send them home.").format(name=driver),
SIGNAL,
)
if controller.waking:
- return LinkState("waking", AMBER, "Waking", "Waking", f"Waking {peer}. It connects on its own once it is up.", AMBER, True)
+ return LinkState("waking", AMBER, tr("Waking"), tr("Waking"), tr("Waking {name}. It connects on its own once it is up.").format(name=peer), AMBER, True)
if controller.connected:
- linked = "Tunnel" if tunnel else "Linked"
+ linked = tr("Tunnel") if tunnel else tr("Linked")
if controller.windows_locked:
return LinkState(
- "unlocking", AMBER, "Unlocking", "Unlocking",
- f"{peer} is at its lock screen and is unlocking itself; input follows once the desktop is back.",
+ "unlocking", AMBER, tr("Unlocking"), tr("Unlocking"),
+ tr("{name} is at its lock screen and is unlocking itself; input follows once the desktop is back.").format(name=peer),
AMBER, True,
)
if controller.redirecting:
return LinkState(
- "windows", SIGNAL, f"On {on}", "Live",
- f"Keyboard and pointer are on {on}. Do the same again to bring them home.", SIGNAL,
+ "windows", SIGNAL, tr("On {name}").format(name=on), tr("Live"),
+ tr("Keyboard and pointer are on {name}. Do the same again to bring them home.").format(name=on), SIGNAL,
)
armed = controller.crossing.armed
if armed and controller.crossing_paused:
return LinkState(
- "paused", INK, "Paused", "Held",
- f"Connected to {peer}. Crossing is held, so you can lean on an edge.", SIGNAL,
+ "paused", INK, tr("Paused"), tr("Held"),
+ tr("Connected to {name}. Crossing is held, so you can lean on an edge.").format(name=peer), SIGNAL,
)
if armed and controller.full_screen_app is not None:
return LinkState(
- "full_screen", INK, "Held", "Held",
- "Held: an app is full screen.", SIGNAL,
+ "full_screen", INK, tr("Held"), tr("Held"),
+ tr("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)
+ detail = tr("Connected to {name} through the macOS 27 tunnel.").format(name=peer) if tunnel else tr("Connected to {name}.").format(name=peer)
+ return LinkState("mac", INK, tr("On Mac"), linked, detail, SIGNAL)
if not (cfg.host and cfg.auth_token):
- return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair a machine on Overview and Beamer connects on its own.", AMBER)
- address = f"{cfg.host} port {cfg.port}"
+ return LinkState("unpaired", AMBER, tr("Not paired"), tr("Setup"), tr("Pair a machine on Overview and Beamer connects on its own."), AMBER)
+ # Translators: a machine's address and port, as in "192.0.2.20 port 24820".
+ address = tr("{host} port {port}").format(host=cfg.host, port=cfg.port)
if kind == "forgotten":
- return LinkState("forgotten", FAULT, "Pairing removed", "Refused", f"{peer} no longer has this pairing: remove {peer} here and pair the two again.", FAULT)
+ return LinkState("forgotten", FAULT, tr("Pairing removed"), tr("Refused"), tr("{name} no longer has this pairing: remove {name} here and pair the two again.").format(name=peer), FAULT)
if kind in ("unauthenticated", "wrong_id", "different", "unreadable"):
- return LinkState("token", FAULT, "Token mismatch", "Refused", f"{peer} refused this Mac's token. Remove it, then pair again to write a fresh one.", FAULT)
+ return LinkState("token", FAULT, tr("Token mismatch"), tr("Refused"), tr("{name} refused this Mac's token. Remove it, then pair again to write a fresh one.").format(name=peer), FAULT)
if kind in ("older", "newer", "not_beamer"):
- return LinkState("version", FAULT, "Version mismatch", "Refused", f"{peer} runs a different Beamer from this Mac. Update both to the same version.", FAULT)
- if status.endswith(NOT_WOKEN_SUFFIX):
- return LinkState("not_woken", FAULT, "Did not wake", "No reply", f"{peer} did not answer within a minute of the wake-up packet.", FAULT)
+ return LinkState("version", FAULT, tr("Version mismatch"), tr("Refused"), tr("{name} runs a different Beamer from this Mac. Update both to the same version." ).format(name=peer), FAULT)
+ if matches_translation(status, "{name} did not wake"):
+ return LinkState("not_woken", FAULT, tr("Did not wake"), tr("No reply"), tr("{name} did not answer within a minute of the wake-up packet.").format(name=peer), FAULT)
if kind == "blocked":
- return LinkState("blocked", FAULT, "Blocked", "Tunnel", "macOS 27 blocked direct LAN access. Open Beamer Tunnel from Applications.", FAULT)
+ return LinkState("blocked", FAULT, tr("Blocked"), tr("Tunnel"), tr("macOS 27 blocked direct LAN access. Open Beamer Tunnel from Applications."), FAULT)
if kind in ("unreachable", "timeout"):
- return LinkState("unreachable", FAULT, "Unreachable", "No reply", f"{address} is not answering. {peer} may be asleep or off this network.", FAULT)
+ return LinkState("unreachable", FAULT, tr("Unreachable"), tr("No reply"), tr("{address} is not answering. {name} may be asleep or off this network.").format(address=address, name=peer), FAULT)
if kind == "refused":
- return LinkState("not_listening", FAULT, "Not listening", "No receiver", f"{peer} answers, but Beamer is not listening on port {cfg.port}. Open Beamer on {peer}.", FAULT)
+ return LinkState("not_listening", FAULT, tr("Not listening"), tr("No receiver"), tr("{name} answers, but Beamer is not listening on port {port}. Open Beamer on {name}.").format(name=peer, port=cfg.port), FAULT)
if kind in ("stopped", "closed"):
- return LinkState("stopped", FAULT, "No reply", "Dropped", f"{peer} stopped responding. Beamer keeps trying to reconnect.", FAULT)
- if status.startswith("Connecting to") or status in ("Waiting to connect", "Settings saved; reconnecting"):
- return LinkState("waiting", AMBER, "Waiting", "Looking", f"Looking for {peer}. It connects on its own once Beamer is open there.", AMBER, True)
- return LinkState("dropped", FAULT, "Disconnected", "Dropped", (status.rstrip(".") + ". Beamer keeps trying to reconnect.") if status else "Beamer keeps trying to reconnect.", FAULT)
+ return LinkState("stopped", FAULT, tr("No reply"), tr("Dropped"), tr("{name} stopped responding. Beamer keeps trying to reconnect.").format(name=peer), FAULT)
+ if matches_translation(status, "Connecting to {host}:{port}", "Waiting to connect", "Settings saved; reconnecting"):
+ return LinkState("waiting", AMBER, tr("Waiting"), tr("Looking"), tr("Looking for {name}. It connects on its own once Beamer is open there.").format(name=peer), AMBER, True)
+ detail = tr("{status}. Beamer keeps trying to reconnect.").format(status=status.rstrip(".")) if status else tr("Beamer keeps trying to reconnect.")
+ return LinkState("dropped", FAULT, tr("Disconnected"), tr("Dropped"), detail, FAULT)
diff --git a/mac_app/login_item.py b/mac_app/login_item.py
index 0f1c204..01bc6d0 100644
--- a/mac_app/login_item.py
+++ b/mac_app/login_item.py
@@ -8,6 +8,7 @@ pyobjc-framework-ServiceManagement, which would be a new dependency for four cal
from pathlib import Path
import objc
+from core.i18n import N_, tr
objc.loadBundle(
"ServiceManagement", {}, bundle_path="/System/Library/Frameworks/ServiceManagement.framework"
@@ -20,10 +21,10 @@ SMAppService = objc.lookUpClass("SMAppService")
NOT_REGISTERED, ENABLED, REQUIRES_APPROVAL, NOT_FOUND = 0, 1, 2, 3
STATUS_TEXT = {
- NOT_REGISTERED: "Not registered",
- ENABLED: "Enabled",
- REQUIRES_APPROVAL: "Requires approval",
- NOT_FOUND: "Not found",
+ NOT_REGISTERED: N_("Not registered"),
+ ENABLED: N_("Enabled"),
+ REQUIRES_APPROVAL: N_("Requires approval"),
+ NOT_FOUND: N_("Not found"),
}
@@ -32,7 +33,7 @@ def status():
def status_text(value):
- return STATUS_TEXT.get(value, "Unknown")
+ return tr(STATUS_TEXT.get(value, N_("Unknown")))
def installed_in_applications(bundle_path):
diff --git a/mac_app/machines.py b/mac_app/machines.py
index 33736c3..3e277e9 100644
--- a/mac_app/machines.py
+++ b/mac_app/machines.py
@@ -11,9 +11,10 @@ from dataclasses import dataclass
from core import protocol
from core import peerlist
+from core.i18n import N_, tr
from link_state import AMBER, FAULT, INK, SIGNAL, LinkState
-PLATFORMS = {"windows": "Windows", "macos": "Mac", "linux": "Linux", "ios": "iPhone", "android": "Android"}
+PLATFORMS = {"windows": N_("Windows"), "macos": N_("Mac"), "linux": N_("Linux"), "ios": N_("iPhone"), "android": N_("Android")}
TOKEN_KINDS = ("unauthenticated", "wrong_id", "different", "unreadable", "forgotten")
VERSION_KINDS = ("older", "newer", "not_beamer")
@@ -33,7 +34,7 @@ class Row:
def platform_name(platform: str) -> str:
- return PLATFORMS.get(platform, "Other")
+ return tr(PLATFORMS.get(platform, N_("Other")))
def row(entry: dict, label: str, live: bool, kind: str, status: str, here: bool, driving: bool, inbound: bool,
@@ -42,7 +43,7 @@ def row(entry: dict, label: str, live: bool, kind: str, status: str, here: bool,
the machine at all; `inbound` is whether the machine has a link up to this Mac; `here` and
`driving` are where input is."""
host, port = entry.get("host"), entry.get("port")
- address = f"{host} · port {port}" if host and port else "No address"
+ address = tr("{address} · port {port}").format(address=host, port=port) if host and port else tr("No address")
return Row(
entry["token"], label, platform_name(entry.get("platform", "")), address,
_state(entry, label, live, kind, status, here, driving, inbound, has_link), entry.get("in_use", True) is True,
@@ -54,39 +55,39 @@ def row(entry: dict, label: str, live: bool, kind: str, status: str, here: bool,
def _state(entry, label, live, kind, status, here, driving, inbound, has_link) -> LinkState:
reason = peerlist.dormant_reason(entry)
if reason:
- return LinkState("dormant", AMBER, "Needs re-pair", "Needs re-pair", reason, AMBER)
+ return LinkState("dormant", AMBER, N_("Needs re-pair"), N_("Needs re-pair"), reason, AMBER)
if entry.get("in_use", True) is not True:
- return LinkState("not_in_use", AMBER, "NOT IN USE", "NOT IN USE", f"{label} is not in use on this Mac.", AMBER)
+ return LinkState("not_in_use", AMBER, N_("NOT IN USE"), N_("NOT IN USE"), tr("{name} is not in use on this Mac.").format(name=label), AMBER)
if not protocol.linkable(entry):
return LinkState(
- "pair_again", AMBER, "Pair again", "Pair again",
- f"{label} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.", AMBER,
+ "pair_again", AMBER, N_("Pair again"), N_("Pair again"),
+ tr("{name} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.").format(name=label), AMBER,
)
if driving:
return LinkState(
- "driving", SIGNAL, "Driving this Mac", "Live",
- f"{label}'s keyboard and pointer are on this Mac. Push the pointer back through the edge it arrived by to send them home.",
+ "driving", SIGNAL, N_("Driving this Mac"), N_("Live"),
+ tr("{name}'s keyboard and pointer are on this Mac. Push the pointer back through the edge it arrived by to send them home.").format(name=label),
SIGNAL,
)
if here:
return LinkState(
- "here", SIGNAL, "Input here", "Live",
- f"This Mac's keyboard and pointer are on {label}. Do the same again to bring them home.", SIGNAL,
+ "here", SIGNAL, N_("Input here"), N_("Live"),
+ tr("This Mac's keyboard and pointer are on {name}. Do the same again to bring them home.").format(name=label), SIGNAL,
)
if live or inbound:
- return LinkState("linked", INK, "Linked", "Linked", f"Connected to {label}.", SIGNAL)
+ return LinkState("linked", INK, N_("Linked"), N_("Linked"), tr("Connected to {name}.").format(name=label), SIGNAL)
if not has_link:
- return LinkState("waiting", AMBER, "Waiting", "Waiting", f"Waiting for {label} to connect.", AMBER)
+ return LinkState("waiting", AMBER, N_("Waiting"), N_("Waiting"), tr("Waiting for {name} to connect.").format(name=label), AMBER)
if kind in TOKEN_KINDS:
- return LinkState("token", FAULT, "Refused", "Refused", status, FAULT)
+ return LinkState("token", FAULT, N_("Refused"), N_("Refused"), status, FAULT)
if kind in VERSION_KINDS or (kind == "closed" and not entry.get("linked")):
- return LinkState("version", FAULT, "Version", "Refused", status, FAULT)
+ return LinkState("version", FAULT, N_("Version"), N_("Refused"), status, FAULT)
if kind in ("unreachable", "timeout"):
- return LinkState("unreachable", FAULT, "Unreachable", "No reply", status, FAULT)
+ return LinkState("unreachable", FAULT, N_("Unreachable"), N_("No reply"), status, FAULT)
if kind == "refused":
- return LinkState("not_listening", FAULT, "Not listening", "No receiver", status, FAULT)
+ return LinkState("not_listening", FAULT, N_("Not listening"), N_("No receiver"), status, FAULT)
if kind == "blocked":
- return LinkState("blocked", FAULT, "Blocked", "Tunnel", status, FAULT)
+ return LinkState("blocked", FAULT, N_("Blocked"), N_("Tunnel"), status, FAULT)
if kind in ("stopped", "closed", "failed") and status:
- return LinkState("dropped", FAULT, "Dropped", "Dropped", f"{status.rstrip('.')}. Beamer keeps trying to reconnect.", FAULT)
- return LinkState("waiting", AMBER, "Waiting", "Looking", f"Looking for {label}. It connects on its own once Beamer is open there.", AMBER, True)
+ return LinkState("dropped", FAULT, N_("Dropped"), N_("Dropped"), tr("{status}. Beamer keeps trying to reconnect.").format(status=status.rstrip(".")), FAULT)
+ return LinkState("waiting", AMBER, N_("Waiting"), N_("Looking"), tr("Looking for {name}. It connects on its own once Beamer is open there.").format(name=label), AMBER, True)
diff --git a/mac_app/machines_panel.py b/mac_app/machines_panel.py
index 01dd6e1..d062354 100644
--- a/mac_app/machines_panel.py
+++ b/mac_app/machines_panel.py
@@ -24,6 +24,7 @@ import qr
import theme
import widgets
from core import feature_flags, pairing, peerlist, ways as core_ways
+from core.i18n import tr
QR_SIDE = 176
CODE_GROUP = 3
@@ -35,7 +36,7 @@ def grouped(code):
def seconds(count):
- return f"Expires in {count} s"
+ return tr("Expires in {n} s").format(n=count)
class _RenameDelegate(AppKit.NSObject):
@@ -86,41 +87,41 @@ class MachinesPanel:
def _machines_module(self):
module = widgets.Module()
header = widgets.stack(spacing=12)
- widgets.add(header, widgets.eyebrow("Machines"))
- self.nearby_button = widgets.action_button("Pair nearby", self.pair_nearby, style="primary")
- self.phone_button = widgets.action_button("Pair a phone", self.pair_phone)
+ widgets.add(header, widgets.eyebrow(tr("Machines")))
+ self.nearby_button = widgets.action_button(tr("Pair nearby"), self.pair_nearby, style="primary")
+ self.phone_button = widgets.action_button(tr("Pair a phone"), self.pair_phone)
self.phone_button.view.setHidden_(not feature_flags.PAIRING_QR_VISIBLE)
- self.pair_button = widgets.action_button("Pair a machine", self._toggle_sheet)
+ self.pair_button = widgets.action_button(tr("Pair a machine"), self._toggle_sheet)
for button in (self.nearby_button, self.phone_button, self.pair_button):
widgets.add(header, button.view, full_width=False)
module.add(header)
self.list = widgets.stack(spacing=8)
module.add(self.list)
- self.empty = widgets.note("No machines paired yet.")
+ self.empty = widgets.note(tr("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.", reading=False)
+ self.list_note = widgets.note(tr("Beamer connects to each machine on its own whenever both are running."), reading=False)
line.addArrangedSubview_(self.list_note.view)
module.add(line)
return module
def own_name_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow("This Mac"))
+ module.add(widgets.eyebrow(tr("This Mac")))
line = widgets.stack(vertical=False, spacing=9)
own_name = self.settings_store.current().get("name", "")
- name = widgets.Label(own_name or socket.gethostname().split(".")[0] or "Mac",
+ name = widgets.Label(own_name or socket.gethostname().split(".")[0] or tr("Mac"),
theme.TYPE["body"], 600)
widgets.squeeze(name.view)
line.addArrangedSubview_(name.view)
- rename = self._chip("Rename", lambda: self._begin_rename(None), "Rename this Mac")
+ rename = self._chip(tr("Rename"), lambda: self._begin_rename(None), tr("Rename this Mac"))
line.addArrangedSubview_(rename)
module.add(line)
box, edit = widgets.field(mono=False)
- edit.setAccessibilityLabel_("Name for this Mac")
+ edit.setAccessibilityLabel_(tr("Name for this Mac"))
edit.setStringValue_(own_name)
box.setHidden_(True)
- note = widgets.note("Only on this Mac", reading=False)
+ note = widgets.note(tr("Only on this Mac"), reading=False)
note.view.setHidden_(True)
delegate = _RenameDelegate.alloc().init()
delegate.panel, delegate.token = self, None
@@ -132,7 +133,7 @@ class MachinesPanel:
def _sheet(self):
module = widgets.Module()
- module.add(widgets.eyebrow("Pair a machine"))
+ module.add(widgets.eyebrow(tr("Pair a machine")))
self.pair_grid = widgets.stack(spacing=20)
self.pair_grid.setAlignment_(AppKit.NSLayoutAttributeTop)
show = self._show_half()
@@ -147,11 +148,11 @@ class MachinesPanel:
def _show_half(self):
half = widgets.stack(spacing=8)
- widgets.add(half, widgets.label("Show a code on this Mac", theme.TYPE["body"], 600))
+ widgets.add(half, widgets.label(tr("Show a code on this Mac"), theme.TYPE["body"], 600))
widgets.add(half, widgets.note(
- "On the other machine, open Beamer, choose this Mac in its list and type the code."
+ tr("On the other machine, open Beamer, choose this Mac in its list and type the code.")
).view)
- self.show_button = widgets.action_button("Show a code", self._show_code, style="primary")
+ self.show_button = widgets.action_button(tr("Show a code"), self._show_code, style="primary")
half.addArrangedSubview_(self.show_button.view)
self.shown_code_boxes = widgets.CodeBoxes(pairing.CODE_DIGITS, None, editable=False)
for control in self.shown_code_boxes.fields:
@@ -165,14 +166,14 @@ class MachinesPanel:
# Whole points to a module already: scaling would soften the edges.
self.qr_view.setImageScaling_(AppKit.NSImageScaleNone)
self.qr_view.setImageAlignment_(AppKit.NSImageAlignTopLeft)
- self.qr_view.setAccessibilityLabel_("The pairing code as a QR code")
+ self.qr_view.setAccessibilityLabel_(tr("The pairing code as a QR code"))
widgets.size(self.qr_view, QR_SIDE, QR_SIDE)
half.addArrangedSubview_(self.qr_view)
self.qr_caption = widgets.note("")
widgets.add(half, self.qr_caption.view)
self.hosted_status = widgets.note()
widgets.add(half, self.hosted_status.view)
- self.cancel_button = widgets.action_button("Cancel code", self._cancel_code, scale="small")
+ self.cancel_button = widgets.action_button(tr("Cancel code"), self._cancel_code, scale="small")
half.addArrangedSubview_(self.cancel_button.view)
self._show_code_widgets(False)
return half
@@ -187,22 +188,22 @@ class MachinesPanel:
self.nearby_choices = widgets.stack(spacing=2)
widgets.add(nearby, self.nearby_choices)
self.nearby_sas = widgets.Label("", theme.TYPE["readout"], 700, mono=True, ink="ink")
- self.nearby_sas.view.setAccessibilityLabel_("Nearby pairing digits")
+ self.nearby_sas.view.setAccessibilityLabel_(tr("Nearby pairing digits"))
widgets.add(nearby, self.nearby_sas.view)
self.nearby_peer_label = widgets.Label("", theme.TYPE["note"], ink="ink_2")
widgets.add(nearby, self.nearby_peer_label.view)
nearby_buttons = widgets.stack(vertical=False, spacing=8)
- self.nearby_confirm = widgets.action_button("Confirm", self._confirm_nearby, style="primary")
- self.nearby_cancel = widgets.action_button("Cancel", self._cancel_nearby, scale="small")
+ self.nearby_confirm = widgets.action_button(tr("Confirm"), self._confirm_nearby, style="primary")
+ self.nearby_cancel = widgets.action_button(tr("Cancel"), self._cancel_nearby, scale="small")
nearby_buttons.addArrangedSubview_(self.nearby_confirm.view)
nearby_buttons.addArrangedSubview_(self.nearby_cancel.view)
widgets.add(nearby, nearby_buttons)
self.nearby_view = nearby
self._nearby_widgets(False)
widgets.add(half, nearby)
- widgets.add(half, widgets.label("Enter a code from another machine", theme.TYPE["body"], 600))
+ widgets.add(half, widgets.label(tr("Enter a code from another machine"), theme.TYPE["body"], 600))
heard = widgets.stack(spacing=8)
- widgets.add(heard, widgets.label("On this network", theme.TYPE["note"], 600, ink="ink_2"))
+ widgets.add(heard, widgets.label(tr("On this network"), theme.TYPE["note"], 600, ink="ink_2"))
self.heard_list = widgets.stack(spacing=1)
self.heard_frame = widgets.box("rule")
self.heard_frame.addSubview_(self.heard_list)
@@ -215,29 +216,29 @@ class MachinesPanel:
find_secret_box.setHidden_(True)
self.find_boxes = (find_box, find_secret_box)
for control in (self.find_field, self.find_secret):
- control.setPlaceholderAttributedString_(widgets.attributed("Address", theme.TYPE["small"], ink="ink_3", mono=True))
- control.setAccessibilityLabel_("Address of a machine that is not listed")
+ control.setPlaceholderAttributedString_(widgets.attributed(tr("Address"), theme.TYPE["small"], ink="ink_3", mono=True))
+ control.setAccessibilityLabel_(tr("Address of a machine that is not listed"))
control.setTarget_(self._target(self._address_typed))
control.setAction_("fire:")
heard.setCustomSpacing_afterView_(14, self.heard_empty.view)
heard.setCustomSpacing_afterView_(14, self.heard_frame)
- widgets.add(heard, widgets.label("Not listed? Type its address.", theme.TYPE["note"], ink="ink_2"))
+ widgets.add(heard, widgets.label(tr("Not listed? Type its address."), theme.TYPE["note"], ink="ink_2"))
find_line = widgets.stack(vertical=False, spacing=8)
for box in self.find_boxes:
find_line.addArrangedSubview_(widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow))
widgets.add(heard, find_line)
widgets.add(half, heard)
- widgets.add(half, widgets.label("Code shown on the other machine", theme.TYPE["note"], 600, ink="ink_2"))
+ widgets.add(half, widgets.label(tr("Code shown on the other machine"), theme.TYPE["note"], 600, ink="ink_2"))
self.code_boxes = widgets.CodeBoxes(pairing.CODE_DIGITS, lambda _control: self._pair())
widgets.add(half, self.code_boxes.view)
line = widgets.stack(vertical=False, spacing=10)
line.setAlignment_(AppKit.NSLayoutAttributeTop)
self.pair_status = widgets.note()
line.addArrangedSubview_(self.pair_status.view)
- self.confirm_button = widgets.action_button("Pair", self._pair, style="primary")
+ self.confirm_button = widgets.action_button(tr("Pair"), self._pair, style="primary")
line.addArrangedSubview_(self.confirm_button.view)
widgets.add(half, line)
- self._say("Choose a machine, or type its address, then type the code it shows.")
+ self._say(tr("Choose a machine, or type its address, then type the code it shows."))
return half
def _target(self, callback):
@@ -295,7 +296,7 @@ class MachinesPanel:
self.list_note.view.setHidden_(not rows)
wanted = self.open or not rows
motion.set_hidden(self.sheet.view, not wanted)
- self.pair_button.set_title("Cancel" if self.open and rows else "Pair a machine")
+ self.pair_button.set_title(tr("Cancel") if self.open and rows else tr("Pair a machine"))
self.pair_button.view.setHidden_(False)
if wanted:
self._refresh_sheet(hide)
@@ -337,7 +338,8 @@ class MachinesPanel:
state = row.state
frame = widgets.box("ground", "rule", theme.RADIUS["field"])
label = self._shown(row.label)
- frame.setAccessibilityLabel_(f"{label}, {self._shown(state.word)}")
+ shown_word = self._shown(tr(state.word))
+ frame.setAccessibilityLabel_(tr("{name}, {state}").format(name=label, state=shown_word))
body = widgets.stack(spacing=6)
head = widgets.stack(vertical=False, spacing=9)
led = widgets.LED()
@@ -345,9 +347,9 @@ class MachinesPanel:
head.addArrangedSubview_(led.view)
name = widgets.Label(label, theme.TYPE["body"], 600, wrap=True)
head.addArrangedSubview_(widgets.hug(widgets.squeeze(name.view), AppKit.NSLayoutPriorityDefaultLow))
- rename = self._chip("Rename", lambda t=row.token: self._begin_rename(t), f"Rename {label}")
+ rename = self._chip(tr("Rename"), lambda t=row.token: self._begin_rename(t), tr("Rename {name}").format(name=label))
head.addArrangedSubview_(rename)
- tag = widgets.Label(self._shown(state.word), theme.TYPE["eyebrow"], 700, state.tone,
+ tag = widgets.Label(shown_word, theme.TYPE["eyebrow"], 700, state.tone,
tracking=theme.TRACKING["eyebrow"], upper=state.key != "dormant")
if self.wide:
head.addArrangedSubview_(tag.view)
@@ -355,16 +357,16 @@ class MachinesPanel:
if not self.wide:
widgets.add(body, tag.view)
remove = self._removal(row)
- repair = (self._chip("Re-pair", lambda t=row.token: self.re_pair(t), f"Re-pair {label}")
+ repair = (self._chip(tr("Re-pair"), lambda t=row.token: self.re_pair(t), tr("Re-pair {name}").format(name=label))
if state.key == "dormant" else None)
where = row.platform if row.phone else " ".join((row.platform, self._shown(row.address)))
widgets.add(body, widgets.Label(where, theme.TYPE["small"], ink="ink_3", wrap=True).view)
if row.left_out:
- widgets.add(body, widgets.note("Left out of the layout. The shortcut and the menu still reach it.").view)
+ widgets.add(body, widgets.note(tr("Left out of the layout. The shortcut and the menu still reach it.")).view)
widgets.add(body, widgets.note(self._shown(state.detail)).view)
entry = next((item for item in self.controller.book.peers() if item.get("token") == row.token), {})
if not row.phone and getattr(getattr(self.owner, "shortcut_goes_to", None), "value", "last") == "ticked":
- cycle = widgets.Switch("In the shortcut's cycle",
+ cycle = widgets.Switch(tr("In the shortcut's cycle"),
on_change=lambda on, peer=entry.get("id"): self.owner._set_shortcut_cycle(peer, on))
cycle.value = entry.get("shortcut_cycle") is not False
cycle.set_enabled(row.in_use)
@@ -372,37 +374,41 @@ class MachinesPanel:
self._cycle_controls[row.token] = cycle
widgets.add(body, cycle.view)
edit_box, edit = widgets.field(mono=False)
- edit.setAccessibilityLabel_(f"Name for {label}")
+ edit.setAccessibilityLabel_(tr("Name for {name}").format(name=label))
edit.setStringValue_(entry.get("label", "") or entry.get("name", ""))
edit_box.setHidden_(True)
delegate = _RenameDelegate.alloc().init()
delegate.panel, delegate.token = self, row.token
edit.setDelegate_(delegate)
- note = widgets.note("Only on this Mac", reading=False)
+ note = widgets.note(tr("Only on this Mac"), reading=False)
note.view.setHidden_(True)
self._rename_views[row.token] = (name.view, rename, edit_box, edit, note, delegate)
widgets.add(body, edit_box)
widgets.add(body, note.view)
- in_use = widgets.Switch("In use", on_change=lambda on, t=row.token: self._direction(t, in_use=on))
+ in_use = widgets.Switch(tr("In use"), on_change=lambda on, t=row.token: self._direction(t, in_use=on))
in_use.value = row.in_use
- in_use.view.setToolTip_(f"Off: no input or settings link to {label}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.")
+ # Translators: {name} is the other machine's chosen name.
+ in_use.view.setToolTip_(tr("Off: no input or settings link to {name}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.").format(name=label))
if row.phone:
- in_use.view.setToolTip_(f"Off: {label} cannot connect or drive this Mac. Turn it back on here to reconnect.")
+ in_use.view.setToolTip_(tr("Off: {name} cannot connect or drive this Mac. Turn it back on here to reconnect.").format(name=label))
in_use.view.focus_id = (row.token, "in_use")
- left_out = self._chip("Put back" if row.left_out else "Leave out",
+ action = tr("Put back") if row.left_out else tr("Leave out")
+ left_out = self._chip(action,
lambda out=not row.left_out, t=row.token: self._left_out(t, out),
- f"{'Put back' if row.left_out else 'Leave out'} {label}", (row.token, "left_out"))
- drives = widgets.Switch("This Mac drives it", on_change=lambda on, t=row.token: self._direction(t, send=on))
+ tr("{action} {name}").format(action=action, name=label), (row.token, "left_out"))
+ drives = widgets.Switch(tr("This Mac drives it"), on_change=lambda on, t=row.token: self._direction(t, send=on))
drives.value = row.drives
- drives.view.setToolTip_(f"Input moves only when this Mac enables this switch and {label} enables It drives this Mac.")
+ # Translators: {name} is the other machine's chosen name.
+ drives.view.setToolTip_(tr("Input moves only when this Mac enables this switch and {name} enables It drives this Mac.").format(name=label))
drives.view.focus_id = (row.token, "drives")
- driven = widgets.Switch("It drives this Mac", on_change=lambda on, t=row.token: self._direction(t, allow_drive=on))
+ driven = widgets.Switch(tr("It drives this Mac"), on_change=lambda on, t=row.token: self._direction(t, allow_drive=on))
driven.value = row.driven
- driven.view.setToolTip_(f"Input moves only when {label} enables This machine drives it and this Mac enables this switch.")
+ # Translators: {name} is the other machine's chosen name.
+ driven.view.setToolTip_(tr("Input moves only when {name} enables This machine drives it and this Mac enables this switch.").format(name=label))
driven.view.focus_id = (row.token, "driven")
opened = row.token in self.directions_open
- disclosure = self._chip("Hide directions" if opened else "Directions", lambda t=row.token: self._toggle_directions(t),
- f"{'Hide' if opened else 'Show'} directions for {label}",
+ disclosure = self._chip(tr("Hide directions") if opened else tr("Directions"), lambda t=row.token: self._toggle_directions(t),
+ tr("{action} directions for {name}").format(action=tr("Hide") if opened else tr("Show"), name=label),
(row.token, "directions"))
widgets.add(body, self._controls(row, in_use, left_out, disclosure, drives, driven, remove, repair))
frame.addSubview_(body)
@@ -488,12 +494,12 @@ class MachinesPanel:
def _removal(self, row):
label = self._shown(row.label)
if self.removing != row.token:
- return self._chip("Remove", lambda t=row.token: self._ask_to_remove(t), f"Remove {label}", (row.token, "remove"))
+ return self._chip(tr("Remove"), lambda t=row.token: self._ask_to_remove(t), tr("Remove {name}").format(name=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", reading=False)
+ words = widgets.note(tr("Remove {name}? It stays paired on that machine until you remove this one there too.").format(name=label), 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")))
+ line.addArrangedSubview_(self._chip(tr("Remove"), lambda t=row.token: self._remove(t), tr("Confirm removing {name}").format(name=label), (row.token, "confirm")))
+ line.addArrangedSubview_(self._chip(tr("Keep"), self._keep, tr("Keep {name}").format(name=label), (row.token, "keep")))
return line
def _ask_to_remove(self, token):
@@ -514,7 +520,8 @@ class MachinesPanel:
removed = self.settings_store.remove_peer(token)
except Exception as exc:
self.logger.warning("could not remove a machine: %s", exc)
- self.owner._say(f"Could not remove it: {exc}", "fault")
+ # Translators: {error} is the system error message.
+ self.owner._say(tr("Could not remove it: {error}").format(error=exc), "fault")
self.refresh()
return
if removed is not None:
@@ -559,12 +566,13 @@ class MachinesPanel:
self._cancel_code()
service = self.service
if service is None:
- self._say("Pairing is not available on this Mac.", "fault")
+ self._say(tr("Pairing is not available on this Mac."), "fault")
return
try:
service.begin_nearby()
except pairing.PairingError as exc:
- self._say(f"Nearby pairing is not available: {exc}", "fault")
+ # Translators: {error} is the system error message.
+ self._say(tr("Nearby pairing is not available: {error}").format(error=exc), "fault")
return
self._nearby_key = None
self._refresh_nearby()
@@ -591,20 +599,20 @@ class MachinesPanel:
return
messages = {
- "searching": "Press Pair nearby on the other machine within 60 seconds.",
- "choosing": "Choose a machine to pair nearby.",
- "confirm": "Compare all six digits on both machines, then confirm on each.",
- "waiting": "Waiting for confirmation on the other machine.",
- "paired": "Nearby pairing complete.",
- "expired": "Nearby pairing expired. Press Pair nearby to try again.",
- "refused": "Nearby pairing refused. Use a new window to try again.",
- "not_saved": "The new peer could not be saved.",
+ "searching": tr("Press Pair nearby on the other machine within 60 seconds."),
+ "choosing": tr("Choose a machine to pair nearby."),
+ "confirm": tr("Compare all six digits on both machines, then confirm on each."),
+ "waiting": tr("Waiting for confirmation on the other machine."),
+ "paired": tr("Nearby pairing complete."),
+ "expired": tr("Nearby pairing expired. Press Pair nearby to try again."),
+ "refused": tr("Nearby pairing refused. Use a new window to try again."),
+ "not_saved": tr("The new peer could not be saved."),
}
- message = messages.get(state, "Connecting to the selected machine…" if state == "exchanging" else "")
+ message = messages.get(state, tr("Connecting to the selected machine…") if state == "exchanging" else "")
tone = "fault" if state in {"refused", "expired", "not_saved"} else "ink_2"
self.nearby_status_label.set(message, ink=tone)
seconds_left = status.get("seconds_left", 0)
- self.nearby_expiry.set(f"Expires in {seconds_left} s" if state in {"searching", "choosing", "exchanging", "confirm", "waiting"} else "")
+ self.nearby_expiry.set(seconds(seconds_left) if state in {"searching", "choosing", "exchanging", "confirm", "waiting"} else "")
self.nearby_expiry.view.setHidden_(state not in {"searching", "choosing", "exchanging", "confirm", "waiting"})
peers = status.get("peers") or []
@@ -625,12 +633,12 @@ class MachinesPanel:
row = widgets.pressable(lambda item=candidate: self._choose_nearby(item),
"well" if picked else "ground", "rule", 5,
role=AppKit.NSAccessibilityRadioButtonRole)
- label = candidate.get("name") or "Another machine"
+ label = candidate.get("name") or tr("Another machine")
platform = machines.platform_name(candidate.get("platform") or "")
address = candidate.get("address")
detail = " · ".join(part for part in (label, platform, address) if part)
row.setAccessibilityLabel_(self._shown(detail))
- row.setAccessibilityValue_("Selected" if picked else "Not selected")
+ row.setAccessibilityValue_(tr("Selected") if picked else tr("Not selected"))
text = widgets.Label(self._shown(detail), theme.TYPE["note"], 600 if picked else 400)
row.addSubview_(text.view)
widgets.pin(text.view, row, (7, 10, 7, 10))
@@ -642,7 +650,7 @@ class MachinesPanel:
self.nearby_sas.set(shown_sas)
self.nearby_sas.view.setHidden_(not shown_sas)
if isinstance(peer, dict):
- peer_name = peer.get("name") or "Another machine"
+ peer_name = peer.get("name") or tr("Another machine")
peer_platform = machines.platform_name(peer.get("platform") or "")
selected = f"Selected: {peer_name} · {peer_platform}"
else:
@@ -716,7 +724,7 @@ class MachinesPanel:
self.code_boxes.clear()
self.chosen = None
self._heard_key = None
- self._say("Choose a machine, or type its address, then type the code it shows.")
+ self._say(tr("Choose a machine, or type its address, then type the code it shows."))
def _refresh_sheet(self, hide):
self._refresh_code(hide)
@@ -755,7 +763,7 @@ class MachinesPanel:
try:
service.begin_pairing()
except pairing.PairingError as exc:
- self.hosted_status.set(peerlist.pairing_error_text(exc, "this machine"), ink="fault")
+ self.hosted_status.set(peerlist.pairing_error_text(exc, tr("this machine")), ink="fault")
self.hosted_status.view.setHidden_(False)
return
self._hosted = None
@@ -784,14 +792,14 @@ class MachinesPanel:
address = pairing.pairing_address()
qr_text = service.qr_text(address)
if hide:
- self.code_address.set(self._shown(f"{address} · port {service.tcp_port}") if address else "")
- self._set_qr(None, "The QR is hidden while addresses are hidden.")
+ self.code_address.set(self._shown(tr("{address} · port {port}").format(address=address, port=service.tcp_port)) if address else "")
+ self._set_qr(None, tr("The QR is hidden while addresses are hidden."))
elif qr_text is None:
- self.code_address.set(f"{address} · port {service.tcp_port}" if address else "No network address found")
- self._set_qr(None, f"No QR: {service.tcp_error}" if service.tcp_error else "No QR while this Mac has no address.")
+ self.code_address.set(tr("{address} · port {port}").format(address=address, port=service.tcp_port) if address else tr("No network address found"))
+ self._set_qr(None, tr("No QR: {reason}").format(reason=service.tcp_error) if service.tcp_error else tr("No QR while this Mac has no address."))
else:
- self.code_address.set(f"{address} · port {service.tcp_port}")
- self._set_qr(qr_text, "The same code as a QR, for a phone to scan.")
+ self.code_address.set(tr("{address} · port {port}").format(address=address, port=service.tcp_port))
+ self._set_qr(qr_text, tr("The same code as a QR, for a phone to scan."))
self.hosted_status.view.setHidden_(not self.hosted_status.text)
return
if self._showing:
@@ -867,11 +875,10 @@ class MachinesPanel:
for index, (item, shared) in enumerate(zip(heard, peerlist.sharing_a_name(heard))):
self._heard_row(index, item, item["address"] == chosen, shared)
if service is not None and service.error:
- self.heard_empty.set(f"Beamer cannot look for machines: {service.error}", ink="fault")
+ self.heard_empty.set(tr("Beamer cannot look for machines: {reason}").format(reason=service.error), ink="fault")
else:
self.heard_empty.set(
- "Looking for machines running Beamer. Open it on the other machine and it appears here; "
- "across a VPN or on guest Wi-Fi it may not, so type its address below.", ink="ink_2")
+ tr("Looking for machines running Beamer. Open it on the other machine and it appears here; across a VPN or on guest Wi-Fi it may not, so type its address below."), ink="ink_2")
self.heard_frame.setHidden_(not heard)
self.heard_empty.view.setHidden_(bool(heard))
if chosen is not None and chosen not in {item["address"] for item in heard}:
@@ -885,8 +892,10 @@ class MachinesPanel:
role=AppKit.NSAccessibilityRadioButtonRole)
row.ring_inset = 1.0
platform = machines.platform_name(item.get("platform") or "")
- row.setAccessibilityLabel_(self._shown(f"{item['name']}, {item['address']}")
- + (", older Beamer" if older else ", showing a code" if showing else ""))
+ # Translators: {name} and {address} come from the other machine.
+ sentence = (tr("{name}, {address}, older Beamer") if older else
+ tr("{name}, {address}, showing a code") if showing else tr("{name}, {address}"))
+ row.setAccessibilityLabel_(self._shown(sentence.format(name=item["name"], address=item["address"])))
line = widgets.stack(vertical=False, spacing=9)
led = widgets.LED()
led.set("amber" if older else "signal" if showing else "off")
@@ -915,7 +924,7 @@ class MachinesPanel:
for box_field in (self.find_field, self.find_secret):
box_field.setStringValue_("")
self.code_boxes.clear()
- self.code_boxes.view.setAccessibilityLabel_(self._shown(f"Code shown on {self.chosen['name']}"))
+ self.code_boxes.view.setAccessibilityLabel_(self._shown(tr("Code shown on {name}").format(name=self.chosen["name"])))
self._say_choice()
self._heard_key = None
self._refresh_heard()
@@ -926,9 +935,9 @@ class MachinesPanel:
if chosen.get("pairing") != pairing.PAIRING_V3:
self._say(peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_VERSION), chosen["name"]), "fault")
elif chosen["pair_id"] is None:
- self._say(f"{chosen['name']} is not showing a code yet. Show one in Beamer on it first.")
+ self._say(tr("{name} is not showing a code yet. Show one in Beamer on it first.").format(name=chosen["name"]))
else:
- self._say(f"Six digits, as shown on {chosen['name']}.")
+ self._say(tr("Six digits, as shown on {name}.").format(name=chosen["name"]))
def _pair(self):
wanted = self._wanted()
@@ -937,7 +946,7 @@ class MachinesPanel:
return
code = re.sub(r"\D", "", self.code_boxes.value)
if len(code) != pairing.CODE_DIGITS:
- self._say(f"The code is {pairing.CODE_DIGITS} digits.", "fault")
+ self._say(tr("The code is {n} digits.").format(n=pairing.CODE_DIGITS), "fault")
return
kind, target = wanted
self._cancel_nearby()
@@ -954,11 +963,11 @@ class MachinesPanel:
return
run = lambda: service.pair(target, code)
else:
- name = "That machine"
+ name = tr("That machine")
run = lambda: service.pair_by_address(target, code)
self.pairing = True
self.confirm_button.set_enabled(False)
- self._say(self._shown(f"Pairing with {name}…" if kind == "machine" else f"Pairing with {target}…"))
+ self._say(tr("Pairing with {name}…").format(name=name if kind == "machine" else target))
def work():
try:
@@ -985,7 +994,7 @@ class MachinesPanel:
self.chosen = None
self._heard_key = None
self.open = False
- self._say("Choose a machine, or type its address, then type the code it shows.")
+ self._say(tr("Choose a machine, or type its address, then type the code it shows."))
self.owner.peers_changed()
- self.owner._say(f"Paired with {proved}. Connecting…", "signal")
+ self.owner._say(tr("Paired with {name}. Connecting…").format(name=proved), "signal")
self.logger.info("paired with %s", proved)
diff --git a/mac_app/pages.py b/mac_app/pages.py
index 3422a95..dcf02b8 100644
--- a/mac_app/pages.py
+++ b/mac_app/pages.py
@@ -9,46 +9,47 @@ from __future__ import annotations
import re
from core import effects
+from core.i18n import N_, joined, tr
from core import peerlist
from core.ways import DIAGRAM_GAP, DIAGRAM_THIS, diagram_layout, part_names, parts_phrase, toggle_part
# (key, name, SF Symbol, what the page is for), in sidebar order, which is the order a new Mac is
# set up in after the Overview; Cmd+1 is the first.
PAGES = (
- ("overview", "Overview", "gauge.with.needle",
- "Where input is, whether each link is up, and the controls you reach for every day. Pair your "
- "machines here first."),
- ("permissions", "Permissions", "lock.shield",
- "macOS must allow Beamer to read this Mac's input and to move its pointer and type when another machine drives it."),
- ("crossing", "Crossing", "cursorarrow.motionlines",
- "Drag a machine on the map to where it sits. The ledger says how each one is reached; click a row to pick it on the map."),
- ("keyboard", "Keyboard", "keyboard",
- "How this Mac's modifier keys arrive on other machines, which keys and buttons stay on this Mac, "
- "and how fast another machine's pointer moves here. The switch key is on the Crossing page."),
- ("design", "Design", "paintpalette",
- "How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad."),
- ("connection", "Connection", "network",
- "Local connection details for the first machine you paired. Pair again to change another machine's entry."),
+ ("overview", N_("Overview"), "gauge.with.needle",
+ N_("Where input is, whether each link is up, and the controls you reach for every day. Pair your "
+ "machines here first.")),
+ ("permissions", N_("Permissions"), "lock.shield",
+ N_("macOS must allow Beamer to read this Mac's input and to move its pointer and type when another machine drives it.")),
+ ("crossing", N_("Crossing"), "cursorarrow.motionlines",
+ N_("Drag a machine on the map to where it sits. The ledger says how each one is reached; click a row to pick it on the map.")),
+ ("keyboard", N_("Keyboard"), "keyboard",
+ N_("How this Mac's modifier keys arrive on other machines, which keys and buttons stay on this Mac, "
+ "and how fast another machine's pointer moves here. The switch key is on the Crossing page.")),
+ ("design", N_("Design"), "paintpalette",
+ N_("How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad.")),
+ ("connection", N_("Connection"), "network",
+ N_("Local connection details for the first machine you paired. Pair again to change another machine's entry.")),
)
KEYS = tuple(page[0] for page in PAGES)
# Under the purpose on the pages whose settings are this Mac's alone, so nobody looks for the other
# machine's on the Mac: each app sets only its own machine, and the other's are in Beamer there.
SCOPE = {
- "crossing": "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this Mac's input for every destination.",
- "design": "Used on this screen. Shared animation settings may follow another machine; Animate, window appearance, notch and trackpad controls stay on this Mac.",
- "keyboard": "Modifier keys and Stays here belong to this Mac's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own.",
+ "crossing": N_("Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this Mac's input for every destination."),
+ "design": N_("Used on this screen. Shared animation settings may follow another machine; Animate, window appearance, notch and trackpad controls stay on this Mac."),
+ "keyboard": N_("Modifier keys and Stays here belong to this Mac's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own."),
}
# With Same on all machines on, under each row of the shared pages that stays this Mac's own.
-OWN_ROW = "This Mac only."
-OWN_NOTCH = "The notch is this Mac only."
+OWN_ROW = N_("This Mac only.")
+OWN_NOTCH = N_("The notch is this Mac only.")
# The window's footer, and the pages where its first sentence would be untrue.
-FOOTER_APPLIES = "Changes apply as you make them."
-FOOTER_RUNNING = "Closing this window keeps Beamer running in the menu bar."
+FOOTER_APPLIES = N_("Changes apply as you make them.")
+FOOTER_RUNNING = N_("Closing this window keeps Beamer running in the menu bar.")
EXPLICIT_PAGES = ("connection",)
def footer(page):
- return FOOTER_RUNNING if page in EXPLICIT_PAGES else f"{FOOTER_APPLIES} {FOOTER_RUNNING}"
+ return tr(FOOTER_RUNNING) if page in EXPLICIT_PAGES else tr("Changes apply as you make them. Closing this window keeps Beamer running in the menu bar.")
def opening_page(last, accessibility, input_monitoring):
@@ -80,13 +81,13 @@ 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 = "Light"
+TODAY = N_("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."),
+ ("glow", N_("Glow"), N_("A band of light that deepens the harder you push.")),
+ ("beam", N_("Beam"), N_("A thin line with a comet of light running along it.")),
+ ("aperture", N_("Aperture"), N_("A fine lens of light opens under pressure and closes softly behind the arriving pointer.")),
)
-INTENSITIES = {"quiet": "Quiet", "medium": "Medium", "showpiece": "Showpiece", "classic": "Classic"}
+INTENSITIES = {"quiet": N_("Quiet"), "medium": N_("Medium"), "showpiece": N_("Showpiece"), "classic": N_("Classic")}
def effects_load_error():
@@ -105,33 +106,39 @@ def style_groups(with_effects=True):
# Glow and Beam's detail is their kind, as an effect's is its intensity; what they do is said
# under the preview.
classic_styles = TODAY_STYLES if with_effects else TODAY_STYLES[:2]
- groups = [(TODAY, [(value, name, effects.CLASSIC[value].intensity.capitalize())
+ groups = [(tr(TODAY), [(value, tr(name), tr(INTENSITIES[effects.CLASSIC[value].intensity]))
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:
fx = effects.effect(effect_id)
- row.append((effect_id, fx.name, INTENSITIES.get(fx.intensity, fx.intensity.capitalize())))
- groups.append((direction, row))
+ row.append((effect_id, tr(fx.name), tr(INTENSITIES[fx.intensity])))
+ groups.append((tr(direction), row))
return groups
-SIMPLE = "Simple"
+SIMPLE = N_("Simple")
def switch_style_groups(with_effects=True):
"""[(group, [(value, name, detail)])] for the style tiles in Switch mode: what a switch plays,
effects.SWITCH_STYLES, with the effects grouped as the crossing's are."""
- simple = [("match", "Same as crossing", "Plays Glow"), ("locator", "Ring", "Closes onto the pointer")]
+ simple = [("match", tr(N_("Same as crossing")), tr(N_("Plays Glow"))),
+ ("locator", tr(N_("Ring")), tr(N_("Closes onto the pointer")))]
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:]
+ aperture = [(tr(TODAY), [("aperture", tr(effects.CLASSIC["aperture"].name),
+ tr(INTENSITIES[effects.CLASSIC["aperture"].intensity]))])] if with_effects else []
+ return [(tr(SIMPLE), simple)] + aperture + style_groups(with_effects)[1:]
+
+
+COLOUR_NAMES = {"signal": N_("Signal"), "colourful": N_("Colourful"), "ocean": N_("Ocean"), "sunset": N_("Sunset"),
+ "mono": N_("Mono"), "aurora": N_("Aurora")}
def colour_groups(today_colours, with_effects=True):
"""[(group, [(colour id, name)])] for the swatches; `today_colours` is crossing.GLOW_COLOURS."""
- return effects.colour_groups([(name, name.capitalize()) for name in today_colours] + [('aurora', 'Aurora')], with_effects)
+ return effects.colour_groups([(name, COLOUR_NAMES.get(name, name.capitalize())) for name in today_colours]
+ + [("aurora", COLOUR_NAMES["aurora"])], with_effects)
def notch_style_applies(style):
@@ -141,12 +148,13 @@ def notch_style_applies(style):
def share_sentence(holders, side, name):
"""Name the machines already using the side the chosen machine wants."""
- names = holders[0] if len(holders) == 1 else ", ".join(holders[:-1]) + " and " + holders[-1]
- verb = "crosses" if len(holders) == 1 else "cross"
- # The sentence says what picking a third means: it goes to `name`.
- keep = f"stay with {holders[0]}" if len(holders) == 1 else "stay where they are"
- return (f"{names} already {verb} from the {side} edge of this Mac. The thirds you pick go to {name}; "
- f"the rest {keep}.")
+ names = joined(holders)
+ side_name = tr(SIDE_NAMES.get(side, side)).lower() if side in SIDE_NAMES else side
+ if len(holders) == 1:
+ return tr("{names} already crosses from the {side} edge of this Mac. The thirds you pick go to {name}; the rest stay with {holder}.").format(
+ names=names, side=side_name, name=name, holder=holders[0])
+ return tr("{names} already cross from the {side} edge of this Mac. The thirds you pick go to {name}; the rest stay where they are.").format(
+ names=names, side=side_name, name=name)
# The ways in, in the Crossing page's order.
@@ -168,6 +176,7 @@ CORNER_MARK = 12.0
SIDES = ("left", "right", "top", "bottom")
+SIDE_NAMES = {"left": N_("Left"), "right": N_("Right"), "top": N_("Top"), "bottom": N_("Bottom")}
PART_ORDER = ("start", "middle", "end")
@@ -217,7 +226,7 @@ def diagram_marks(this, machines):
return marks, ("chosen" if any(notch) else "other") if notch else None
-_WHERE = {"left": "to the left of", "right": "to the right of", "top": "above", "bottom": "below"}
+_WHERE = {"left": N_("to the left of"), "right": N_("to the right of"), "top": N_("above"), "bottom": N_("below")}
def _joined(names):
@@ -227,14 +236,14 @@ def _joined(names):
def not_placed(machines):
"""The line under the drawing naming the machines with no side yet; "" when every one has one."""
names = [machine["label"] for machine in machines if machine["side"] not in SIDES]
- return f"Not placed yet: {_joined(names)}" if names else ""
+ return tr("Not placed yet: {names}").format(names=joined(names)) if names else ""
def arrangement_description(machines, sentence):
"""What VoiceOver reads for the drawing: where every machine is, then the chosen one's ways in."""
- where = [f"{machine['label']} is {_WHERE[machine['side']]} this Mac." if machine["side"] in SIDES
- else f"{machine['label']} is not placed yet." for machine in machines]
- return " ".join(where + [sentence + "." if sentence else "No way in is on."])
+ where = [tr("{name} is {position} this Mac.").format(name=machine["label"], position=tr(_WHERE[machine["side"]])) if machine["side"] in SIDES
+ else tr("{name} is not placed yet.").format(name=machine["label"]) for machine in machines]
+ return " ".join(where + [sentence + "." if sentence else tr("No way in is on.")])
def send_items(peers, on, hide, live=lambda entry: True):
@@ -251,21 +260,21 @@ def send_items(peers, on, hide, live=lambda entry: True):
items = []
for entry in targets:
if entry["id"] == on:
- items.append((entry["id"], "Bring input back", True))
+ items.append((entry["id"], tr("Bring input back"), True))
elif live(entry):
- items.append((entry["id"], redact(f"Send input to {labels[entry['token']]}", hide), True))
+ items.append((entry["id"], redact(tr("Send input to {name}").format(name=labels[entry['token']]), hide), True))
else:
- items.append((entry["id"], redact(f"{labels[entry['token']]} is unavailable", hide), False))
+ items.append((entry["id"], redact(tr("{name} is unavailable").format(name=labels[entry['token']]), hide), False))
return items
def where_caption(label):
"""The caption of the side control: today's words with one machine, the chosen one's name with several."""
- return f"Where {label} is" if label else "Where the other machine is"
+ return tr("Where {name} is").format(name=label) if label else tr("Where the other machine is")
def corner_note():
- return "This corner crosses its left or right edge."
+ return tr("This corner crosses its left or right edge.")
def shown_side(side, machines):
@@ -313,18 +322,18 @@ def crossing_state_sentence(paired, sending, connected, armed, paused, full_scre
"""The Crossing page's line under Pause: why nothing can cross, first match wins, and only then
whether crossing is on, held or paused."""
if not paired:
- return "Not paired yet, so no edge or shortcut moves input until you pair a machine on Overview."
+ return tr("Not paired yet, so no edge or shortcut moves input until you pair a machine on Overview.")
if not sending:
- return "No machine is driven by this Mac, so edges and the shortcut do nothing."
+ return tr("No machine is driven by this Mac, so edges and the shortcut do nothing.")
if not connected:
- return "Not connected to any machine, so edges and the shortcut do nothing yet."
+ return tr("Not connected to any machine, so edges and the shortcut do nothing yet.")
if not armed:
- return "Only the shortcut is switched on; there is nothing to pause."
+ return tr("Only the shortcut is switched on; there is nothing to pause.")
if paused:
- return "Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts."
+ return tr("Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts.")
if full_screen_app is not None:
- return "Held: an app is full screen."
- return "On. Pause it to lean on an edge without switching."
+ return tr("Held: an app is full screen.")
+ return tr("On. Pause it to lean on an edge without switching.")
def crossing_state_blocked(paired, sending, connected):
@@ -332,7 +341,7 @@ def crossing_state_blocked(paired, sending, connected):
return not (paired and sending and connected)
-PLACES = {"edge": "the edge", "corner": "a corner", "notch": "the notch"}
+PLACES = {"edge": N_("the edge"), "corner": N_("a corner"), "notch": N_("the notch")}
def preview_place(methods):
@@ -349,20 +358,22 @@ def place_note(style, place, methods, has_notch):
"""The line under the preview's Edge / Corner / Notch switch: why nothing would cross there, or
how the chosen style plays there; empty when there is nothing to add."""
if place == "notch" and not has_notch:
- return "This Mac has no notch, so this only shows how it would look."
+ return tr("This Mac has no notch, so this only shows how it would look.")
ways = {"edge": {"edge", "part"}, "corner": {"corner"}, "notch": {"notch"}}[place]
off = not set(methods) & ways
if off:
- lead = f"{PLACES[place].capitalize()} is not one of your ways in, so this only shows how it would look. "
- lead += "Turn it on under Crossing."
+ place_name = tr(PLACES[place])
+ place_name = place_name[0].upper() + place_name[1:]
else:
- lead = ""
+ place_name = ""
if place != "notch":
- return lead
+ return tr("{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing.").format(place=place_name) if off else ""
if notch_style_applies(style):
- return (lead + " " if lead else "") + "At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it."
+ return (tr("{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing. At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it.").format(place=place_name)
+ if off else tr("At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it."))
name = effects.effect(style).name if effects.effect(style) is not None else "The effect"
- return (lead + " " if lead else "") + f"{name} draws its own form round the notch."
+ return (tr("{place} is not one of your ways in, so this only shows how it would look. Turn it on under Crossing. {name} draws its own form round the notch.").format(place=place_name, name=name)
+ if off else tr("{name} draws its own form round the notch.").format(name=name))
def notch_or_corner_only(methods):
@@ -375,8 +386,9 @@ def notch_or_corner_only(methods):
def notch_or_corner_note(label):
"""The note under the side control while only the notch or a corner leads there; `label` is the
chosen machine's with several paired, None with one."""
- return ("With only the notch or a corner on, input arrives by the notch's or corner's own side, so this "
- f"choice does nothing on this Mac; {label or 'the other machine'}'s own push still follows it.")
+ if label:
+ return tr("With only the notch or a corner on, input arrives by the notch's or corner's own side, so this choice does nothing on this Mac; {name}'s own push still follows it.").format(name=label)
+ return tr("With only the notch or a corner on, input arrives by the notch's or corner's own side, so this choice does nothing on this Mac; the other machine's own push still follows it.")
def crossing_rows(methods):
diff --git a/mac_app/previews.py b/mac_app/previews.py
index 70b8ca9..0af86eb 100644
--- a/mac_app/previews.py
+++ b/mac_app/previews.py
@@ -27,6 +27,7 @@ from frame_clock import PREVIEW_MAX_RATE, FrameClock
import motion
import notch_beam
import notch_island
+from core.i18n import N_
import theme
import tokens
@@ -711,7 +712,7 @@ def notch_update(renderer):
# The crossing effects' previews: effects.preview_scene drawn by effects_overlay.draw_scene, the same
# replay the overlay uses on screen. Every tile shows one still frame at the place the page's Show at
# chooses, and plays the full journey while TileHover says the pointer is over it.
-STAGE_METHODS = (("edge", "Edge"), ("corner", "Corner"), ("notch", "Notch"))
+STAGE_METHODS = (("edge", N_("Edge")), ("corner", N_("Corner")), ("notch", N_("Notch")))
def _played(view, still_at, switch=False):
diff --git a/mac_app/settings_store.py b/mac_app/settings_store.py
index e11a711..7a8e88b 100644
--- a/mac_app/settings_store.py
+++ b/mac_app/settings_store.py
@@ -14,6 +14,7 @@ import json
import logging
import os
import secrets
+import shutil
import tempfile
import threading
import time
@@ -28,6 +29,7 @@ from core import protocol
from core import receiver
from core import return_edge
from core import ways
+from core import profiles
from crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLES
import dock_visibility
@@ -37,6 +39,12 @@ from wake import parse_mac
LOGGER = logging.getLogger(__name__)
+try:
+ PROFILE_APP_VERSION = (Path(os.environ.get("RESOURCEPATH") or Path(__file__).resolve().parent.parent)
+ / "VERSION").read_text().strip()
+except OSError:
+ PROFILE_APP_VERSION = profiles.APP_VERSION
+
APP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "Beamer"
DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "settings.json"
LEGACY_FILE = "config.json"
@@ -109,6 +117,7 @@ def editable_default_config():
allow_windows_to_drive=True,
check_updates=True,
hide_addresses=False,
+ language="auto",
hide_idle_pointer=True,
same_on_both=False,
same_set_at=0,
@@ -147,6 +156,7 @@ def config_to_raw(cfg):
"allow_windows_to_drive": cfg.allow_windows_to_drive,
"check_updates": cfg.check_updates,
"hide_addresses": cfg.hide_addresses,
+ "language": cfg.language,
"hide_idle_pointer": cfg.hide_idle_pointer,
"same_on_both": cfg.same_on_both,
"same_set_at": cfg.same_set_at,
@@ -320,6 +330,8 @@ class SettingsStore:
# an id learnt on a link thread and a save from the window cannot cross.
self.lock = threading.RLock()
self._cache = None
+ self.profile_load_notes = set()
+ self._profile_load_notes_seen = set()
# The token of the first machine in the flat settings last handed out by load() or save(),
# which is what a window holds until it reads them again.
self._handed_token = ""
@@ -339,6 +351,14 @@ class SettingsStore:
def load(self):
return self._config(self.load_settings())
+ def take_profile_load_note(self, note):
+ with self.lock:
+ if note not in self.profile_load_notes:
+ return False
+ self.profile_load_notes.remove(note)
+ self._profile_load_notes_seen.add(note)
+ return True
+
def add_peer(self, entry, replaced=None):
"""Stores a pairing (`PairingService`'s `store`): `entry` joins the peers, taking the place
of `replaced` when there is one. Raises SettingsError, writing nothing, if it cannot be saved."""
@@ -543,6 +563,11 @@ class SettingsStore:
settings["zones"].extend(copy.deepcopy(zone) for zone in before["zones"] if zone.get("peer") == "")
settings = self._complete(settings)
self._ensure_zones(settings)
+ if settings.get("_crossing_profiles_upgrade_pending"):
+ settings, _ = profiles.after_load(
+ settings, platform="mac", capable=getattr(self, "_crossing_capable", ()), now=time.time(),
+ app=PROFILE_APP_VERSION
+ )
self._check(settings)
self._write(settings)
return settings
@@ -583,10 +608,19 @@ class SettingsStore:
if not isinstance(settings, dict) or settings.get("schema") != SCHEMA:
raise SettingsError(f"{self.path.name} is not a schema {SCHEMA} settings file")
original = copy.deepcopy(settings)
+ settings, notes = profiles.before_load(settings)
+ self.profile_load_notes.update(set(notes) - self._profile_load_notes_seen)
settings = self._complete(settings)
self._ensure_zones(settings)
+ settings, _ = profiles.after_load(
+ settings, platform="mac", capable=getattr(self, "_crossing_capable", ()), now=time.time(),
+ app=PROFILE_APP_VERSION
+ )
self._check(settings)
- self._read_migrated = settings != original
+ # Once the file holds profile state, a load's reconcile (its status, an older Beamer's edit
+ # folded in) is saved; only an upgrade waits for the first real save.
+ self._read_migrated = (_without_profile_state(settings) != _without_profile_state(original)
+ or "crossing_own" in original and settings != original)
return settings
def _complete(self, settings):
@@ -692,6 +726,7 @@ class SettingsStore:
raise SettingsError("a zone names a peer that is not in the list")
def _write(self, settings):
+ _backup_before_profile_upgrade(self.path)
self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
try:
os.chmod(self.path.parent, 0o700)
@@ -746,6 +781,7 @@ class SettingsStore:
settings = _merge_config(self._fresh(), cfg)
settings["migrated_token_sha256"] = _sha256(cfg.auth_token)
settings["port"] = cfg.port
+ settings, _ = profiles.before_load(settings)
return self.save_settings(settings)
def _reimport(self, settings):
@@ -852,3 +888,43 @@ class SettingsStore:
raise SettingsError(str(exc)) from exc
if cfg.mac_address and parse_mac(cfg.mac_address) is None:
raise SettingsError("mac_address must be six hex pairs, such as 02:1A:2B:3C:0D:4E")
+
+
+def _without_profile_state(settings):
+ result = copy.deepcopy(settings)
+ for name in ("crossing_own", "crossing_desk", "crossing_own_unreadable", "crossing_desk_unreadable",
+ "_crossing_profiles_upgrade_pending"):
+ result.pop(name, None)
+ return result
+
+
+def _backup_before_profile_upgrade(path):
+ """Keep the exact schema-6 source before the first save of a profile-migrated file."""
+ backup = path.with_name("settings.json.before-1.5.5")
+ if backup.exists():
+ return
+ try:
+ source = path.read_bytes()
+ except FileNotFoundError:
+ return
+ except OSError:
+ raise
+ raw = json.loads(source)
+ if not isinstance(raw, dict) or raw.get("schema") != SCHEMA:
+ return
+ own, desk = raw.get("crossing_own"), raw.get("crossing_desk")
+ if profiles._local_shape(own, desk):
+ return
+ temporary_path = None
+ try:
+ descriptor, temporary_name = tempfile.mkstemp(prefix=f".{backup.name}.", dir=path.parent)
+ os.close(descriptor)
+ temporary_path = Path(temporary_name)
+ shutil.copyfile(path, temporary_path)
+ try:
+ os.link(temporary_path, backup)
+ except FileExistsError:
+ pass
+ finally:
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
diff --git a/mac_app/setup.py b/mac_app/setup.py
index a29cd21..4282bb2 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -65,7 +65,7 @@ setup(
"../win_app/assets/B612Mono-Regular.ttf",
"../win_app/assets/B612Mono-Bold.ttf",
],
- ), ("", ["../VERSION"])],
+ ), ("", ["../VERSION"]), ("locales", [str(path) for path in Path(__file__).resolve().parent.parent.glob("locales/*.po")])],
options={
"py2app": {
"argv_emulation": False,
@@ -78,7 +78,7 @@ setup(
# the scan misses cannot drop out; naming the package whole would ship its tests too.
"includes": [
"objc", "AppKit", "ApplicationServices", "Quartz", "UserNotifications",
- "core.crash_log", "core.effects", "core.idle_pointer", "core.ignored", "core.keytable", "core.link", "core.owner", "core.pairing",
+ "core.crash_log", "core.effects", "core.i18n", "core.locale", "core.idle_pointer", "core.ignored", "core.keytable", "core.link", "core.owner", "core.pairing",
"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",
@@ -98,6 +98,8 @@ setup(
"ATSApplicationFontsPath": "Fonts",
"NSHumanReadableCopyright": "Copyright 2026 Toby Kalkman",
"NSLocalNetworkUsageDescription": "Beamer needs to reach your other computers on your local network to share keyboard and mouse input.",
+ "CFBundleLocalizations": ["en", "it"],
+ "CFBundleDevelopmentRegion": "en_GB",
},
}
},
diff --git a/mac_app/tests/bridge_fakes.py b/mac_app/tests/bridge_fakes.py
index 3706a68..df8c2f3 100644
--- a/mac_app/tests/bridge_fakes.py
+++ b/mac_app/tests/bridge_fakes.py
@@ -28,6 +28,7 @@ class FakeQuartz:
kCGEventTapDisabledByUserInput = 0xFFFFFFFF
kCGEventSourceUserData = 42
kCGEventSourceStateHIDSystemState = 1
+ kCGEventSourceStateID = 45
kCGAnyInputEventType = 0
kCGKeyboardEventKeycode = 9
kCGKeyboardEventAutorepeat = 8
@@ -116,6 +117,17 @@ class FakeQuartz:
def CGEventSourceSecondsSinceLastEventType(source, event_type):
return 3600.0
+ hid_keys = set()
+ hid_buttons = set()
+
+ @classmethod
+ def CGEventSourceKeyState(cls, source, keycode):
+ return keycode in cls.hid_keys
+
+ @classmethod
+ def CGEventSourceButtonState(cls, source, button):
+ return button in cls.hid_buttons
+
class FakeGestureEvent:
"""Stands in for bridge.py's `_GestureEventView` (the object a converted
diff --git a/mac_app/tests/test_atlas_canvas.py b/mac_app/tests/test_atlas_canvas.py
index d3ab9d1..059a3ca 100644
--- a/mac_app/tests/test_atlas_canvas.py
+++ b/mac_app/tests/test_atlas_canvas.py
@@ -286,7 +286,19 @@ class AtlasCanvas(Page):
arranged = list(window.atlas_legend.superview().arrangedSubviews())
self.assertLess(arranged.index(window.atlas_canvas), arranged.index(window.atlas_canvas_hint.view))
self.assertLess(arranged.index(window.atlas_canvas_hint.view), arranged.index(window.atlas_legend))
- self.assertLess(arranged.index(window.atlas_legend), arranged.index(window.crossing_ledger))
+ # The ledger has its own card below the map's (1.5.5, Map first): find each card in the page.
+ def card(view):
+ while view.superview() is not None and view.superview() is not page:
+ view = view.superview()
+ return view
+ page = window.atlas_canvas.superview()
+ while page is not None and not any(v is not None and v.isKindOfClass_(AppKit.NSStackView)
+ and window.crossing_ledger.isDescendantOf_(v) and v is not page
+ for v in [page.superview()]):
+ page = page.superview()
+ page = page.superview()
+ cards = list(page.arrangedSubviews())
+ self.assertLess(cards.index(card(window.atlas_legend)), cards.index(card(window.crossing_ledger)))
def test_left_out_ledger_row_has_status_and_named_put_back_action(self):
window = self.build([(BEE, token(100), "Bee", {"left_out": True})])
diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.py
index 510fb5f..f942b9f 100644
--- a/mac_app/tests/test_bridge.py
+++ b/mac_app/tests/test_bridge.py
@@ -423,7 +423,7 @@ class ControllerTests(unittest.TestCase):
self.assertEqual(link.dropped, [])
self.assertFalse(link.stopped)
- def test_hid_activity_missing_from_the_tap_returns_input_home(self):
+ def _redirected_after_a_pause(self):
class ActiveHIDQuartz(FakeQuartz):
kCGEventSourceStateHIDSystemState = 1
kCGAnyInputEventType = 0
@@ -441,16 +441,48 @@ class ControllerTests(unittest.TestCase):
controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, event, None)
self.assertTrue(controller.set_redirecting(True))
self.clock.value += 3.0
+ return controller, link, ActiveHIDQuartz, event
+ def test_hid_activity_missing_from_the_tap_returns_input_home(self):
+ controller, link, quartz, _event = self._redirected_after_a_pause()
+ with self.assertNoLogs(controller.logger, level="WARNING"):
+ controller._check_tap_watchdog()
+ self.assertTrue(controller.redirecting)
+
+ self.clock.value += 2.5
with self.assertLogs(controller.logger, level="WARNING") as said:
controller._check_tap_watchdog()
self.assertFalse(controller.redirecting)
self.assertFalse(controller.owner.away)
- self.assertIn(True, [enabled for _tap, enabled in ActiveHIDQuartz.tap_enable_calls])
+ self.assertIn(True, [enabled for _tap, enabled in quartz.tap_enable_calls])
self.assertTrue(any("event tap is not receiving input" in line for line in said.output), said.output)
self.assertTrue(link.live())
+ def test_first_input_after_a_pause_is_not_mistaken_for_a_dead_tap(self):
+ # 14-10-2026 09:08:07: the HID system had the touch that ended a 14 s pause 18 ms before
+ # the watchdog looked, and the tap had not been called with it yet.
+ controller, _link, quartz, event = self._redirected_after_a_pause()
+ with self.assertNoLogs(controller.logger, level="WARNING"):
+ controller._check_tap_watchdog()
+ self.clock.value += 0.02
+ controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, event, None)
+ self.clock.value += 2.5
+ quartz.hid_seconds_ago = 2.5
+ controller._check_tap_watchdog()
+ self.assertTrue(controller.redirecting)
+ self.assertTrue(controller.owner.away)
+
+ def test_an_event_the_tap_had_is_not_unseen_for_reading_the_clocks_apart(self):
+ # The age is read before the clock, so the event the tap last had comes out a little newer.
+ controller, _link, quartz, event = self._redirected_after_a_pause()
+ controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, event, None)
+ self.clock.value += 3.0
+ quartz.hid_seconds_ago = 2.998
+ with self.assertNoLogs(controller.logger, level="WARNING"):
+ controller._check_tap_watchdog()
+ self.assertTrue(controller.redirecting)
+
def test_move_logs_that_the_shortcut_double_tap_started_it(self):
bring_up(self.controller)
with self.assertLogs(self.controller.logger, level="INFO") as said:
diff --git a/mac_app/tests/test_caps_lock.py b/mac_app/tests/test_caps_lock.py
index 71dbf4f..9470003 100644
--- a/mac_app/tests/test_caps_lock.py
+++ b/mac_app/tests/test_caps_lock.py
@@ -40,6 +40,8 @@ from bridge_fakes import (
from fake_link import FakeLink
import keyboard_layout
+HID = FakeQuartz.kCGEventSourceStateHIDSystemState
+
class CapsLockEventTapTests(unittest.TestCase):
def setUp(self):
@@ -94,6 +96,40 @@ class CapsLockEventTapTests(unittest.TestCase):
self.assertIs(returned, event)
self.assertEqual(self.sent(), [])
+ def test_hangul_and_hanja_are_taps_without_a_release_message(self):
+ translator = QuartzEventTranslator(FakeQuartz)
+ for name, keycode in (("hangul", 0x68), ("hanja", 0x66)):
+ with self.subTest(name=name):
+ key = {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGEventSourceStateID: HID}
+ down = translator.key_result(FakeQuartz.kCGEventKeyDown, key, 0x3D, {})
+ up = translator.key_result(FakeQuartz.kCGEventKeyUp, key, 0x3D, {})
+ self.assertEqual(down.messages, [
+ {"type": protocol.MSG_KEYDOWN, "data": {"key": name}},
+ {"type": protocol.MSG_KEYUP, "data": {"key": name}},
+ ])
+ self.assertEqual(up.messages, [])
+ repeat = translator.key_result(FakeQuartz.kCGEventKeyDown,
+ {**key, FakeQuartz.kCGKeyboardEventAutorepeat: 1}, 0x3D, {})
+ self.assertEqual(repeat.messages, [])
+
+ def test_hangul_at_home_stays_here_and_a_letter_still_passes(self):
+ for keycode in (0x68, 0x00):
+ for event_type in (FakeQuartz.kCGEventKeyDown, FakeQuartz.kCGEventKeyUp):
+ event = {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGEventSourceStateID: HID}
+ self.assertIs(self.tap(event_type, event), event)
+
+ def test_hangul_while_away_is_one_tap_and_its_release_stays_here(self):
+ redirect_to(self.controller)
+ self.sent()
+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x68, FakeQuartz.kCGEventSourceStateID: HID}
+ up = dict(down)
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventKeyDown, down))
+ self.assertIs(self.tap(FakeQuartz.kCGEventKeyUp, up), up)
+ self.assertEqual(self.sent(), [
+ (protocol.MSG_KEYDOWN, {"key": "hangul"}),
+ (protocol.MSG_KEYUP, {"key": "hangul"}),
+ ])
+
def test_flags_changed_caps_lock_never_calls_event_converters_on_tap_thread(self):
event = {FakeQuartz.kCGKeyboardEventKeycode: CAPS_LOCK_KEY_CODE, "flags": 0}
calls = []
diff --git a/mac_app/tests/test_corner_marks.py b/mac_app/tests/test_corner_marks.py
index 42c3039..792a91d 100644
--- a/mac_app/tests/test_corner_marks.py
+++ b/mac_app/tests/test_corner_marks.py
@@ -184,7 +184,7 @@ class CanvasCornerGeometry(unittest.TestCase):
halo = canvas.corner_halo_layers[(BEE, "corner", "top_right")]
chevron = pad.sublayers()[0]
for layer, wanted in ((pad, (182, 32, 16, 16)), (halo, (179, 29, 22, 22)),
- (chevron, (187, 36, 7, 7))):
+ (chevron, (186.5, 36.5, 7, 7))):
bounds = Quartz.CGPathGetBoundingBox(layer.path())
actual = (bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height)
self.assertEqual(actual, wanted)
diff --git a/mac_app/tests/test_i18n_pages.py b/mac_app/tests/test_i18n_pages.py
new file mode 100644
index 0000000..ed85d84
--- /dev/null
+++ b/mac_app/tests/test_i18n_pages.py
@@ -0,0 +1,161 @@
+"""The Mac window in another language, built offscreen.
+
+In the pseudo-language every string that went through core.i18n is bracketed, so text that is not
+bracketed skipped tr(). In Italian, the first real language, no label on the Crossing, Design and
+Overview pages or the pairing sheet is clipped or overlaps another at the narrowest window.
+"""
+
+import os
+import re
+import socket
+import unittest
+
+from core.i18n import install
+
+
+def walk(AppKit, view):
+ yield view
+ if isinstance(view, (AppKit.NSTextField, AppKit.NSButton)):
+ return
+ for child in view.subviews():
+ if not child.isHidden():
+ yield from walk(AppKit, child)
+
+
+class _Localised(unittest.TestCase):
+ LANGUAGE = ""
+
+ @classmethod
+ def setUpClass(cls):
+ os.environ["BEAMER_LANGUAGE"] = cls.LANGUAGE
+ install("auto")
+ from mac_app.tests.design_offscreen import AppKit, offscreen_control_window
+
+ cls.AppKit = AppKit
+ cls.control = offscreen_control_window()
+
+ @classmethod
+ def tearDownClass(cls):
+ os.environ.pop("BEAMER_LANGUAGE", None)
+ install("en")
+
+
+class PseudoLanguageTests(_Localised):
+ LANGUAGE = "qps"
+
+ def test_settings_pages_and_pairing_window_translate_visible_text(self):
+ from mac_app.tests.design_offscreen import settle
+ from mac_app.key_codes import KEY_SYMBOLS, KEY_TITLES
+
+ control = self.control
+ # The synthetic config supplies the peer, its address and port; the machine running the test
+ # shows its own name; recorded keys show their names and glyphs.
+ supplied = {"Windows PC", "192.0.2.20", "24820", "synthetic-render-only",
+ socket.gethostname(), socket.gethostname().split(".", 1)[0]}
+ supplied.update(KEY_TITLES.values())
+ supplied.update(KEY_SYMBOLS.values())
+ supplied.update(f"{symbol} {KEY_TITLES[key]}" for key, symbol in KEY_SYMBOLS.items())
+ for key in control.pages:
+ control._select_page(key)
+ settle(control.window)
+ with self.subTest(page=key):
+ self._assert_qps_text(walk(self.AppKit, control.window.contentView()), supplied)
+ control._select_page("overview")
+ control.panel._toggle_sheet()
+ settle(control.window)
+ self._assert_qps_text(walk(self.AppKit, control.window.contentView()), supplied)
+ self.assertFalse(control.window.isVisible())
+
+ def _assert_qps_text(self, views, supplied):
+ for view in views:
+ if isinstance(view, self.AppKit.NSTextField):
+ text = str(view.attributedStringValue().string())
+ elif isinstance(view, self.AppKit.NSButton):
+ text = str(view.title())
+ if isinstance(view, self.AppKit.NSPopUpButton):
+ for index in range(view.numberOfItems()):
+ self._assert_translated(str(view.itemTitleAtIndex_(index)), supplied)
+ else:
+ continue
+ self._assert_translated(text, supplied)
+ label = view.accessibilityLabel()
+ if label:
+ self._assert_translated(str(label), supplied)
+
+ def _assert_translated(self, text, supplied):
+ text = text.strip()
+ if not text or text in supplied or set(text) <= set("0123456789 ·:/.-%"):
+ return
+ if re.fullmatch(r"\d+(?:\.\d+)?(?: ms| px| pt| s|%)", text):
+ return
+ if re.fullmatch(r"— (?:ms|px|pt|s)", text):
+ return
+ # Language names stay in their own language; key symbols and the product name are not prose.
+ if text in {"Beamer", "English", "Italiano", "⌃", "⌥", "⇧", "⌘"}:
+ return
+ self.assertTrue(text.startswith("⟦") and text.endswith("⟧"), repr(text))
+
+
+class ItalianLayoutTests(_Localised):
+ LANGUAGE = "it"
+
+ def test_shake_sensitivity_range_fits_beside_its_italian_heading(self):
+ from mac_app.tests.design_offscreen import settle
+
+ control = self.control
+ control._select_page("crossing")
+ control.window.setFrame_display_(
+ ((100000, 100000), (max(320, control.window.minSize().width), 900)), False)
+ figure = control.shake_sensitivity_figure
+ original = figure.text
+ try:
+ for value in (50, 100, 200):
+ figure.set(text=str(value))
+ settle(control.window)
+ with self.subTest(sensitivity=value):
+ self._assert_label_geometry(control.pages["crossing"].documentView())
+ self.assertFalse(figure.view.hasAmbiguousLayout())
+ finally:
+ figure.set(text=original)
+ self.assertFalse(control.window.isVisible())
+
+ def test_labels_fit_at_the_narrowest_window(self):
+ from mac_app.tests.design_offscreen import settle
+
+ control = self.control
+ width = max(320, control.window.minSize().width)
+ for key in ("crossing", "design", "overview"):
+ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)
+ control._select_page(key)
+ settle(control.window)
+ with self.subTest(page=key):
+ self._assert_label_geometry(control.pages[key].documentView())
+ control._select_page("overview")
+ control.panel._toggle_sheet()
+ settle(control.window)
+ with self.subTest(page="pairing"):
+ self._assert_label_geometry(control.pages["overview"].documentView())
+ self.assertFalse(control.window.isVisible())
+
+ def _assert_label_geometry(self, root):
+ AppKit = self.AppKit
+ labels = [view for view in walk(AppKit, root) if isinstance(view, AppKit.NSTextField)]
+ for label in labels:
+ text = label.attributedStringValue()
+ available = label.cell().drawingRectForBounds_(label.bounds()).size.width
+ if label.cell().wraps():
+ measured = text.boundingRectWithSize_options_(
+ (available, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin)
+ self.assertLessEqual(measured.size.height, label.bounds().size.height + 1, str(text.string()))
+ else:
+ self.assertLessEqual(text.size().width, available + 1, str(text.string()))
+ frames = [(label, label.convertRect_toView_(label.bounds(), root)) for label in labels]
+ for index, (first, rect) in enumerate(frames):
+ for second, other in frames[index + 1:]:
+ overlap = AppKit.NSIntersectionRect(rect, other)
+ if overlap.size.width > 1 and overlap.size.height > 1:
+ self.fail(f"labels overlap: {first.stringValue()!r} and {second.stringValue()!r}")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_idle_refresh.py b/mac_app/tests/test_idle_refresh.py
index 7ba3234..7359575 100644
--- a/mac_app/tests/test_idle_refresh.py
+++ b/mac_app/tests/test_idle_refresh.py
@@ -54,7 +54,7 @@ class IdleRefreshTests(unittest.TestCase):
windows_input=mock.Mock(), gesture_overlay=mock.Mock(),
measure_notch=mock.Mock(), set_menu_bar_symbol=mock.Mock(),
toggle_item=app._tray_item('toggle'), pause_item=app._tray_item('pause'),
- _machine_items=mock.Mock(), _direction_items=mock.Mock(),
+ _machine_items=mock.Mock(), _profile_items=mock.Mock(), _direction_items=mock.Mock(),
_refresh_tray_state=mock.Mock())
with mock.patch.object(self.window.window, 'isVisible', return_value=False), \
mock.patch.object(self.window, 'refresh') as refresh, \
diff --git a/mac_app/tests/test_input_injector_mac.py b/mac_app/tests/test_input_injector_mac.py
index b0eec0b..3d52bd5 100644
--- a/mac_app/tests/test_input_injector_mac.py
+++ b/mac_app/tests/test_input_injector_mac.py
@@ -6,10 +6,12 @@ table lookup, which is exactly the part that can be wrong without crashing."""
import unittest
import os
import sys
+from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import input_injector_mac as injector
+from key_codes import KEY_TITLES, SPECIAL_KEY_NAMES
from core.return_edge import Rect
@@ -28,6 +30,15 @@ class KeyPlanTests(unittest.TestCase):
self.assertEqual(self.plan("enter"), (0x24, None))
self.assertEqual(self.plan("left"), (0x7B, None))
+ def test_input_method_keys_land_on_jis_codes_without_modifier_flags(self):
+ for name, code in (("hangul", 0x68), ("hanja", 0x66)):
+ with self.subTest(name=name):
+ self.assertEqual(self.plan(name), (code, None))
+ self.assertEqual(injector.key_flags(code), 0)
+ self.assertEqual((SPECIAL_KEY_NAMES[0x68], SPECIAL_KEY_NAMES[0x66]), ("hangul", "hanja"))
+ self.assertEqual((KEY_TITLES["hangul"], KEY_TITLES["hanja"]), ("Han/Yeong", "Hanja"))
+ self.assertFalse({"hangul", "hanja"} & set(injector.MODIFIER_FLAG_NAMES))
+
def test_ctrl_on_the_pc_arrives_as_command(self):
# The Windows capture has already made the swap, so the injector's job
# is only to place "cmd" on the Command key -- but if that table ever
@@ -57,7 +68,11 @@ class KeyPlanTests(unittest.TestCase):
self.assertEqual(mods, set())
def test_an_unknown_name_sends_nothing(self):
- self.assertIsNone(self.plan("nonsense_key"))
+ old_names = {name: code for name, code in injector.KEY_NAME_TO_CODE.items() if name not in ("hangul", "hanja")}
+ with mock.patch.object(injector, "KEY_NAME_TO_CODE", old_names):
+ for name in ("hangul", "hanja"):
+ with self.subTest(name=name), self.assertLogs(injector.LOGGER, "WARNING"):
+ self.assertIsNone(self.plan(name))
class TextChunkTests(unittest.TestCase):
diff --git a/mac_app/tests/test_jump_key_recorder_layout.py b/mac_app/tests/test_jump_key_recorder_layout.py
index 854549f..b4fa286 100644
--- a/mac_app/tests/test_jump_key_recorder_layout.py
+++ b/mac_app/tests/test_jump_key_recorder_layout.py
@@ -13,6 +13,9 @@ import widgets
class JumpKeyRecorderLayoutTests(unittest.TestCase):
+ def test_input_method_toggles_are_not_shortcut_triggers(self):
+ self.assertTrue({"hangul", "hanja"} <= widgets.UNRECORDABLE_TRIGGERS)
+
def test_empty_key_uses_body_type_and_the_hint_sits_below(self):
recorder = widgets.JumpKeyRecorder()
font = recorder.key.view.attributedStringValue().attribute_atIndex_effectiveRange_(
diff --git a/mac_app/tests/test_phone_ui.py b/mac_app/tests/test_phone_ui.py
index c695d30..85c7474 100644
--- a/mac_app/tests/test_phone_ui.py
+++ b/mac_app/tests/test_phone_ui.py
@@ -57,7 +57,8 @@ class PhoneUiTests(unittest.TestCase):
controller=SimpleNamespace(book=self.book, _peers_up={}), windows_input=mock.Mock())
window.windows_input.server.links.return_value = [protocol.read_id(self.phone["id"])]
window.windows_input.server.caps_of.return_value = ["settings", "design_sync"]
- rows = SimpleNamespace(rows={}, addSubview_=mock.Mock(), reflow=mock.Mock())
+ rows = SimpleNamespace(rows={}, addSubview_=mock.Mock(), reflow=mock.Mock(),
+ control=SimpleNamespace(has_notch=True))
row = mock.Mock()
row.setup.return_value = row
with mock.patch.object(ledger, "Row") as constructor:
diff --git a/mac_app/tests/test_profiles_keyboard_pure.py b/mac_app/tests/test_profiles_keyboard_pure.py
new file mode 100644
index 0000000..1c0ceaf
--- /dev/null
+++ b/mac_app/tests/test_profiles_keyboard_pure.py
@@ -0,0 +1,72 @@
+"""Exercise the canvas key handler without loading AppKit or starting NSApplication.
+
+The native module cannot be imported in a sandbox without a window-server connection;
+extract its unchanged method bodies so this covers the real dispatch logic there too.
+"""
+
+import ast
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+
+SOURCE = Path(__file__).resolve().parents[1].joinpath("diagram.py").read_text()
+
+
+class PickerKeyboard(unittest.TestCase):
+ def canvas(self, picker=True):
+ tree = ast.parse(SOURCE)
+ atlas = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "AtlasCanvas")
+ methods = [node for node in atlas.body if isinstance(node, ast.FunctionDef)
+ and node.name in ("keyDown_", "select_tile", "reading_order")]
+ for node in methods:
+ node.decorator_list = []
+ atlas.bases, atlas.decorator_list, atlas.body = [], [], methods
+ namespace = {"AppKit": SimpleNamespace(NSEventModifierFlagShift=1),
+ "objc": SimpleNamespace(super=lambda *_: SimpleNamespace(keyDown_=mock.Mock()))}
+ exec(compile(ast.Module(body=[atlas], type_ignores=[]), "diagram.py", "exec"), namespace)
+ canvas = namespace["AtlasCanvas"]()
+ canvas.machine_picker, canvas.read_only, canvas.cycle_enabled = picker, False, False
+ canvas.selected = canvas.own_id = canvas.fixed_machine_id = "home"
+ canvas.tiles = {"home": dict(x=0, y=0, w=160, h=90),
+ "other": dict(x=160, y=0, w=160, h=90)}
+ canvas.on_select = mock.Mock()
+ canvas.on_rename = mock.Mock()
+ canvas._draw = mock.Mock()
+ canvas._show_recentre = lambda: False
+ return canvas
+
+ def event(self, code, shift=False):
+ return SimpleNamespace(keyCode=lambda: code, modifierFlags=lambda: int(shift))
+
+ def test_tab_and_shift_tab_focus_without_committing(self):
+ canvas = self.canvas()
+ canvas.keyDown_(self.event(48))
+ self.assertEqual(canvas.selected, "other")
+ self.assertTrue(canvas.keyboard_focus)
+ canvas.on_select.assert_not_called()
+ canvas.keyDown_(self.event(48, shift=True))
+ self.assertEqual(canvas.selected, "home")
+ canvas.on_select.assert_not_called()
+ canvas._draw.assert_called_with(False)
+
+ def test_return_and_space_commit_the_focused_machine(self):
+ canvas = self.canvas()
+ canvas.keyDown_(self.event(48))
+ canvas.keyDown_(self.event(36))
+ canvas.keyDown_(self.event(49))
+ self.assertEqual(canvas.on_select.call_args_list, [mock.call("other"), mock.call("other")])
+ canvas.on_rename.assert_not_called()
+
+ def test_tab_at_the_end_yields_focus_without_committing(self):
+ canvas = self.canvas()
+ canvas.selected = "other"
+ canvas.keyDown_(self.event(48))
+ self.assertEqual(canvas.selected, "other")
+ self.assertFalse(canvas.keyboard_focus)
+ canvas.on_select.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_profiles_map_ledger.py b/mac_app/tests/test_profiles_map_ledger.py
new file mode 100644
index 0000000..c72e809
--- /dev/null
+++ b/mac_app/tests/test_profiles_map_ledger.py
@@ -0,0 +1,253 @@
+"""Synthetic AppKit coverage for the profiles picker and remote ledger; run offscreen."""
+
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+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 diagram
+import ledger
+from core import crossing_state
+from test_crossing_page_machines import BEE, SEA, Page
+
+
+class ProfilesMap(unittest.TestCase):
+ def canvas(self, **options):
+ canvas = diagram.AtlasCanvas.alloc().initWithFrame_(((0, 0), (600, 260))).setup()
+ tiles = {"home": {"x": 0, "y": 0, "w": 160, "h": 90},
+ "other": {"x": 160, "y": 0, "w": 160, "h": 90}}
+ states = {"home": {"state": "this"},
+ "other": {"state": "edge", "linked": True, "crosses": True}}
+ canvas.show_layout(tiles, states, {"home": "This Mac", "other": "Other"},
+ "home", "other", **options)
+ return canvas
+
+ def test_profile_word_is_secondary_status_and_preserves_crossing_outcome(self):
+ canvas = self.canvas(tile_words={"home": "Desk", "other": "Own"}, machine_picker=True)
+ self.assertEqual(canvas.state_for_tile["other"].string(), "Own")
+ self.assertEqual(canvas.outcome_for_tile["other"].string(), "Crosses")
+ self.assertIn("Own", canvas._description())
+
+ def test_picker_draws_thirds_and_unlit_tracks_for_the_viewed_machine(self):
+ canvas = self.canvas(machine_picker=True)
+ canvas.selected = "home"
+ canvas.states["other"].update(picked_thirds=["middle"], lit_thirds=["middle"], edge_off=False)
+ canvas._draw(False)
+ segments = canvas._third_segments(canvas._map()[0])
+ self.assertEqual({part for _peer, part, *_ in segments}, {"start", "middle", "end"})
+ self.assertEqual(len([segment for segment in canvas.seam_segments if segment["kind"] == "track"]), 2)
+
+ def test_picker_includes_home_and_return_space_pick_instead_of_rename_or_cycle(self):
+ canvas = self.canvas(machine_picker=True)
+ selected, renamed = [], []
+ canvas.on_select = selected.append
+ canvas.on_rename = renamed.append
+ self.assertIn("home", canvas.reading_order())
+ canvas.select_tile("home")
+ for code in (36, 49):
+ event = mock.Mock()
+ event.keyCode.return_value = code
+ canvas.keyDown_(event)
+ self.assertEqual(selected, ["home", "home", "home"])
+ self.assertEqual(renamed, [])
+
+ def test_read_only_picker_selects_but_arrow_cannot_move_a_tile(self):
+ canvas = self.canvas(machine_picker=True, read_only=True)
+ before = dict(canvas.tiles["other"])
+ event = mock.Mock()
+ event.keyCode.return_value = 124
+ canvas.keyDown_(event)
+ self.assertEqual(canvas.tiles["other"], before)
+ canvas.select_tile("home")
+ self.assertEqual(canvas.selected, "home")
+
+ def test_picker_tab_moves_focus_without_committing_until_return_or_space(self):
+ canvas = self.canvas(machine_picker=True)
+ selected = []
+ canvas.on_select = selected.append
+ canvas.selected = "home"
+ event = mock.Mock()
+ event.keyCode.return_value = 48
+ event.modifierFlags.return_value = 0
+ canvas.keyDown_(event)
+ self.assertEqual(canvas.selected, "other")
+ self.assertTrue(canvas.keyboard_focus)
+ self.assertEqual(selected, [])
+ event.modifierFlags.return_value = AppKit.NSEventModifierFlagShift
+ canvas.keyDown_(event)
+ self.assertEqual(canvas.selected, "home")
+ self.assertEqual(selected, [])
+ for code in (36, 49):
+ event.keyCode.return_value = code
+ canvas.keyDown_(event)
+ self.assertEqual(selected, ["home", "home"])
+
+ def test_remote_unconnected_tile_says_set_elsewhere_without_amber(self):
+ canvas = self.canvas(machine_picker=True, fixed_machine_id="home")
+ canvas.own_id = "other"
+ canvas.states["home"].update(state="gap", linked=True, crosses=False)
+ canvas.selected = "other"
+ with mock.patch.object(diagram.theme, "tint", wraps=diagram.theme.tint) as tint:
+ canvas._draw(False)
+ self.assertEqual(canvas.outcome_for_tile["home"].string(), "Set elsewhere")
+ tile_calls = [call for call in tint.call_args_list if call.args[0] == canvas.layer_for_tile["home"]]
+ self.assertEqual(tile_calls[-1].kwargs["border"], "edge")
+
+ def test_tile_word_dots_use_signal_for_desk_and_own_only(self):
+ canvas = self.canvas(machine_picker=True)
+ for word, colour in (("Desk", "signal"), ("Own", "signal"),
+ ("Older", "ink_3"), ("Offline", "ink_3")):
+ with self.subTest(word=word):
+ canvas.tile_words["other"] = word
+ with mock.patch.object(diagram.theme, "tint", wraps=diagram.theme.tint) as tint:
+ canvas._draw(False)
+ dots = [call for call in tint.call_args_list if call.args[0] == canvas.dot_for_tile["other"]]
+ self.assertEqual(dots[-1].kwargs["background"], colour)
+
+ def test_picker_tiles_offer_pointing_hand_even_when_editable(self):
+ canvas = self.canvas(machine_picker=True)
+ event = mock.Mock()
+ event.locationInWindow.return_value = AppKit.NSMakePoint(300, 80)
+ with mock.patch.object(canvas, "tile_at", return_value="other"), \
+ mock.patch.object(canvas, "_resize_hit", return_value=None), \
+ mock.patch.object(canvas, "_third_hit", return_value=None), \
+ mock.patch.object(diagram.AppKit, "NSCursor") as cursor:
+ canvas.mouseMoved_(event)
+ cursor.pointingHandCursor.return_value.set.assert_called_once_with()
+ cursor.openHandCursor.assert_not_called()
+
+ def test_read_only_cannot_recentre_a_machine(self):
+ canvas = self.canvas(machine_picker=True, read_only=True)
+ canvas.tiles["other"]["y"] = 80
+ before = dict(canvas.tiles["other"])
+ self.assertFalse(canvas._show_recentre())
+ self.assertFalse(canvas.recentre_selected())
+ self.assertEqual(canvas.tiles["other"], before)
+
+ def test_viewed_machine_can_move_while_the_physical_home_tile_stays_fixed(self):
+ canvas = self.canvas(machine_picker=True, fixed_machine_id="home")
+ canvas.own_id = "other"
+ moved = []
+ canvas.on_layout_change = lambda tiles, key, **_kwargs: moved.append(key)
+ event = mock.Mock()
+ event.keyCode.return_value = 124
+ event.modifierFlags.return_value = 0
+ canvas.select_tile("other")
+ canvas.keyDown_(event)
+ self.assertEqual(moved, ["other"])
+ canvas.select_tile("home")
+ before = dict(canvas.tiles["home"])
+ # The fixed tile hands the key to NSView, which a mock event cannot reach.
+ with mock.patch.object(diagram.objc, "super"):
+ canvas.keyDown_(event)
+ self.assertEqual(canvas.tiles["home"], before)
+ self.assertEqual(moved, ["other"])
+
+ def test_peer_tile_selection_precedes_a_third_hit_in_picker_mode(self):
+ canvas = self.canvas(machine_picker=True, read_only=False)
+ selected = []
+ canvas.on_select = selected.append
+ event = mock.Mock()
+ event.locationInWindow.return_value = AppKit.NSMakePoint(300, 80)
+ event.clickCount.return_value = 1
+ event.modifierFlags.return_value = 0
+ with mock.patch.object(canvas, "window"), \
+ mock.patch.object(canvas, "tile_at", return_value="other"), \
+ mock.patch.object(canvas, "_resize_hit", return_value=None), \
+ mock.patch.object(canvas, "display_at", return_value=("other", None)), \
+ mock.patch.object(canvas, "_third_hit", return_value=("other", "start")), \
+ mock.patch.object(diagram.AppKit, "NSCursor"):
+ canvas.mouseDown_(event)
+ self.assertIsNone(canvas.third_pressed)
+ self.assertEqual(selected, ["other"])
+
+
+class ProfilesLedger(Page):
+ def test_disabled_edge_chips_draw_solid_neutral_borders_and_text(self):
+ chip = ledger.widgets.box(None, None, 5, cls=ledger.Chip).setup(lambda: None)
+ chip.setFrame_(((0, 0), (140, 26)))
+ for kind in ("free", "contact_on", "on", "kept"):
+ with self.subTest(kind=kind):
+ chip.apply(kind, "Right", ["middle"], False)
+ with mock.patch.object(ledger.AppKit, "NSGraphicsContext"), \
+ mock.patch.object(chip, "paint_box") as paint, \
+ mock.patch.object(ledger, "_icon") as icon, \
+ mock.patch.object(ledger, "_stroke") as stroke, \
+ mock.patch.object(ledger.widgets, "attributed") as attributed:
+ attributed.return_value.size.return_value.height = 12
+ chip.drawRect_(chip.bounds())
+ self.assertEqual(paint.call_args.args[:4], (None, "rule", 1.0, False))
+ self.assertEqual(attributed.call_args.kwargs["ink"], "ink_3")
+ self.assertEqual(icon.call_args.args[1], "ink_3")
+ self.assertTrue(all(call.args[1] == "ink_3" for call in stroke.call_args_list))
+
+ def test_disabled_corner_chips_draw_solid_neutral_borders(self):
+ button = ledger.widgets.box(None, None, 5, cls=ledger.CornerButton).setup("top_left", lambda: None)
+ button.setFrame_(((0, 0), (28, 28)))
+ for kind in ("on", "free"):
+ with self.subTest(kind=kind):
+ button.apply(kind, False)
+ with mock.patch.object(ledger.AppKit, "NSGraphicsContext"), \
+ mock.patch.object(button, "paint_box") as paint, \
+ mock.patch.object(ledger, "_stroke") as stroke:
+ button.drawRect_(button.bounds())
+ self.assertEqual(paint.call_args.args[:4], (None, "rule", 1.0, False))
+ self.assertEqual(stroke.call_args.args[1], "ink_3")
+
+ def test_remote_row_click_selects_destination_without_switching_viewed_machine(self):
+ window = self.two()
+ window._profile_event(crossing_state.set_same_ways, True)
+ window._atlas_selected(BEE)
+ window.crossing_ledger.rows[SEA].mouseDown_(None)
+ self.assertEqual(window.viewed_machine, BEE)
+ self.assertEqual(window.chosen_peer, SEA)
+ self.assertTrue(window.crossing_ledger.rows[SEA].selected)
+
+ def test_remote_hides_local_controls_and_reallocates_the_keys_column(self):
+ window = self.two()
+ table = window.crossing_ledger
+ table.setFrame_(((0, 0), (800, 300)))
+ table.refresh(self.store.current(), BEE, remote=True, has_notch=False)
+ row = table.rows[BEE]
+ self.assertTrue(row.cells["keys"].isHidden())
+ self.assertTrue(row.rename.isHidden())
+ self.assertTrue(row.leave.isHidden())
+ self.assertTrue(table.headers[-1].view.isHidden())
+ self.assertTrue(table.headers[-2].view.isHidden())
+ self.assertTrue(row.cells["notch"].isHidden())
+ self.assertEqual(len(table.accessibilityColumns()), 3)
+ self.assertEqual(row.cells["corner"].frame().origin.x + row.cells["corner"].frame().size.width, 800)
+ self.assertEqual(row.cells["notch"].frame().size.width, 0)
+ self.assertEqual(row.cells["notch"].frame().size.height, 0)
+ self.assertFalse(row.notch.isEnabled())
+ self.assertTrue(row.no_notch.view.isHidden())
+ table.setFrame_(((0, 0), (400, 300)))
+ self.assertEqual(row.cells["notch"].frame().size.width, 0)
+ self.assertEqual(row.cells["notch"].frame().size.height, 0)
+ table.refresh(self.store.current(), BEE)
+ self.assertFalse(row.cells["notch"].isHidden())
+ self.assertEqual(len(table.accessibilityColumns()), 5)
+
+ def test_read_only_disables_edges_corners_and_notch_then_local_restores_controls(self):
+ window = self.two()
+ table = window.crossing_ledger
+ table.refresh(self.store.current(), BEE, remote=True, read_only=True, has_notch=True)
+ row = table.rows[BEE]
+ self.assertFalse(any(chip.enabled for chip in row.chips.values()))
+ self.assertFalse(any(button.enabled for button in row.corner_buttons.values()))
+ self.assertFalse(row.notch.isEnabled())
+ table.refresh(self.store.current(), BEE)
+ self.assertFalse(row.cells["keys"].isHidden())
+ self.assertFalse(row.rename.isHidden())
+ self.assertFalse(row.leave.isHidden())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_profiles_page.py b/mac_app/tests/test_profiles_page.py
new file mode 100644
index 0000000..6149067
--- /dev/null
+++ b/mac_app/tests/test_profiles_page.py
@@ -0,0 +1,558 @@
+"""Crossing profiles in the native page, built offscreen with synthetic desks.
+
+Run this module in its own process on macOS. It imports AppKit but starts no
+links, event taps or input capture, and never orders a window onto the screen.
+"""
+
+import copy
+import json
+import unittest
+from unittest import mock
+
+from test_crossing_page_machines import BEE, SEA, Page, kvm_bridge_app, press, rumps_module, token
+from core import crossing_state, profiles, protocol, settings_sync, ways
+
+
+def click(button):
+ view = getattr(button, "view", button)
+ if hasattr(view, "_ledger_target"):
+ press(view)
+ else:
+ view.performClick_(None)
+
+
+class ProfilePage(Page):
+ def desk(self, *, enabled=False, older=False):
+ window = self.build([
+ (BEE, token(100), "Bee", {"side": "right"}),
+ (SEA, token(150), "Sea", {"side": "left"}),
+ ])
+ self.own = self.store.current()["machine_id"]
+ settings = copy.deepcopy(self.store.current())
+ settings["name"] = "Studio"
+ settings["layout"] = {
+ self.own: dict(x=0, y=0, w=160, h=100),
+ BEE: dict(x=160, y=0, w=160, h=100),
+ SEA: dict(x=-160, y=0, w=160, h=100),
+ }
+ for peer in settings["peers"]:
+ peer["ways"] = dict(edge=True, thirds=list(ways.PARTS), edges=[],
+ corner=False, notch=False)
+ settings["zones"] = [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge"}]
+ for key in ("crossing_own", "crossing_desk"):
+ settings.pop(key, None)
+ settings, _ = profiles.before_load(settings, now=1_700_000_000)
+ settings, _ = profiles.after_load(settings, platform="mac", capable={BEE, SEA},
+ now=1_700_000_001)
+ if enabled:
+ settings = crossing_state.set_same_ways(
+ settings, True, platform="mac", capable={BEE, SEA}, now=1_700_000_002)["settings"]
+ desk = settings["crossing_desk"]
+ pid = desk["active"]["value"]
+ for machine, target in ((BEE, self.own), (SEA, BEE)):
+ row = profiles.canonical_row({target: {"ways": {
+ "edge": True, "thirds": list(ways.PARTS), "edges": [],
+ "corner": False, "notch": False,
+ }, "notch_return": False}})
+ desk["profiles"][pid]["rows"][machine] = dict(
+ value=row, set_at=1_700_000_003, by=machine)
+ desk["status"][machine] = dict(set_at=1_700_000_004, by=machine, value={
+ "platform": "windows", "app": "1.5.5", "in_force": "desk",
+ "profile": pid, "row": [1_700_000_003, machine], "waiting": [],
+ })
+ self.store.save_settings(settings)
+ self.controller.cfg = self.store.load()
+ self.controller.crossing_capable = mock.Mock(return_value={self.own, BEE, SEA})
+ window.windows_input.server.caps_of.side_effect = lambda ident: (
+ {"layout"} if older and ident == protocol.read_id(BEE)
+ else {"layout", "profiles"})
+ window._show_arrangement()
+ return window
+
+ def row_registers(self):
+ desk = self.store.current()["crossing_desk"]
+ return copy.deepcopy(desk["profiles"][desk["active"]["value"]]["rows"])
+
+ def texts(self, view):
+ result = []
+ if hasattr(view, "stringValue"):
+ result.append(view.stringValue())
+ for child in view.subviews():
+ result.extend(self.texts(child))
+ return result
+
+ def menu_tray(self):
+ tray = mock.Mock()
+ tray.controller = self.controller
+ tray.settings_store = self.store
+ tray.control_window = self.window
+ tray.menu = rumps_module.Menu()
+ tray.toggle_item = kvm_bridge_app.rumps.MenuItem(kvm_bridge_app.TOGGLE_ITEM)
+ tray.menu.add(tray.toggle_item)
+ tray.menu.add(kvm_bridge_app.rumps.MenuItem("Pause crossing"))
+ tray._send_keys = []
+ tray._profile_menu_key = None
+ tray.profile_item = None
+ return tray
+
+ def test_same_ways_off_keeps_local_ledger_without_profile_tabs(self):
+ window = self.desk()
+ self.assertFalse(window.ways_switch.value)
+ self.assertTrue(window.profile_tabs.isHidden())
+ self.assertEqual(set(window.crossing_ledger.rows), {BEE, SEA})
+ self.assertEqual(window.atlas_canvas.own_id, self.own)
+ self.assertFalse(window.crossing_ledger.rows[BEE].cells["keys"].isHidden())
+ before = copy.deepcopy(self.store.current())
+ window._atlas_selected(BEE)
+ self.assertEqual(window.viewed_machine, self.own)
+ self.assertEqual(window.chosen_peer, BEE)
+ self.assertEqual(self.store.current(), before)
+
+ def test_switch_enables_profile_tabs_and_desk_words_without_moving_tiles(self):
+ window = self.desk()
+ tiles = copy.deepcopy(window.atlas_canvas.tiles)
+ with mock.patch.object(self.controller, "crossing_event", wraps=self.controller.crossing_event) as event:
+ window.ways_switch._toggle()
+ self.assertIs(event.call_args.args[0], crossing_state.set_same_ways)
+ self.assertTrue(profiles.same_ways_on(self.store.current()))
+ self.assertFalse(window.profile_tabs.isHidden())
+ self.assertEqual(window.atlas_canvas.tiles, tiles)
+ self.assertIn(profiles.DESK_ID, window.profile_buttons)
+ for machine in (self.own, BEE, SEA):
+ self.assertEqual(window.atlas_canvas.tile_words[machine], "Desk")
+
+ def test_picking_another_machine_uses_its_row_and_hides_local_controls(self):
+ window = self.desk(enabled=True)
+ before = copy.deepcopy(self.store.current())
+ with mock.patch.object(profiles, "view_settings", wraps=profiles.view_settings) as view:
+ window._atlas_selected(BEE)
+ self.assertTrue(any(call.args[1] == BEE for call in view.call_args_list))
+ self.assertEqual(window.viewed_machine, BEE)
+ self.assertEqual(window.atlas_canvas.own_id, BEE)
+ self.assertEqual(set(window.crossing_ledger.rows), {self.own, SEA})
+ self.assertEqual(window.ledger_heading.text, "Bee's ways")
+ self.assertIn("Editing Bee's ways", window.edit_notice.text)
+ self.assertIn("Jump keys and permissions are set on Bee", window.remote_permissions_note.text)
+ self.assertEqual(window.remote_changes_note.text, "Changes go to Bee at once.")
+ for row in window.crossing_ledger.rows.values():
+ self.assertTrue(row.cells["keys"].isHidden())
+ self.assertTrue(row.rename.isHidden())
+ self.assertTrue(row.leave.isHidden())
+ for module in (window.pointer_module, window.resistance_module, window.shortcut_module):
+ self.assertTrue(module.view.isHidden())
+ self.assertEqual(self.store.current(), before)
+
+ def test_same_ways_shelves_left_out_machine_in_picker_and_remote_layout(self):
+ window = self.desk()
+ own = self.own
+ viewed, shelved = BEE, SEA
+ settings = self.store.current()
+ next(peer for peer in settings["peers"] if peer["id"] == shelved).update(
+ left_out=True)
+ settings["layout"][shelved] = copy.deepcopy(settings["layout"][viewed])
+ self.store.save_settings(settings)
+ window.controller.cfg = self.store.load()
+ window.ways_switch._toggle()
+ self.assertTrue(profiles.same_ways_on(self.store.current()))
+
+ window._atlas_selected(shelved)
+ self.assertEqual(window.viewed_machine, own)
+ window._atlas_selected(viewed)
+ viewed_settings = window._view_settings()
+ self.assertEqual(viewed_settings["machine_id"], viewed)
+ states = ways.compile_layout(viewed_settings, viewed_settings["layout"], platform="pc")["tiles"]
+ self.assertEqual(states[shelved]["state"], "dormant")
+ self.assertNotEqual(states.get(own, {}).get("state"), "overlap")
+ self.assertNotEqual(states.get(viewed, {}).get("state"), "overlap")
+ self.assertNotIn(shelved, window.atlas_canvas.tiles)
+
+ def test_remote_ledger_edit_calls_edit_other_and_changes_only_that_desk_row(self):
+ window = self.desk(enabled=True)
+ window._atlas_selected(BEE)
+ before = self.row_registers()
+ own_row = copy.deepcopy(self.store.current()["crossing_own"])
+ with mock.patch.object(self.controller, "crossing_event", wraps=self.controller.crossing_event) as event:
+ press(window.crossing_ledger.rows[self.own].contact())
+ self.assertIs(event.call_args.args[0], crossing_state.edit_other)
+ self.assertEqual(event.call_args.args[1:3], (BEE, self.own))
+ after = self.row_registers()
+ self.assertNotEqual(before[BEE], after[BEE])
+ self.assertEqual(before[self.own], after[self.own])
+ self.assertEqual(before[SEA], after[SEA])
+ self.assertEqual(self.store.current()["crossing_own"]["row"], own_row["row"])
+ self.assertFalse(after[BEE]["value"][self.own]["ways"]["edge"])
+
+ def test_back_button_restores_own_machine_and_local_controls(self):
+ window = self.desk(enabled=True)
+ window._atlas_selected(BEE)
+ click(window.back_ways_button)
+ self.assertEqual(window.viewed_machine, self.own)
+ self.assertEqual(window.atlas_canvas.own_id, self.own)
+ self.assertFalse(window.crossing_ledger.rows[BEE].cells["keys"].isHidden())
+ for module in (window.pointer_module, window.resistance_module, window.shortcut_module):
+ self.assertFalse(module.view.isHidden())
+
+ def test_switch_off_from_remote_view_restores_todays_local_ledger(self):
+ window = self.desk(enabled=True)
+ window._atlas_selected(BEE)
+ window.ways_switch._toggle()
+ self.assertFalse(profiles.same_ways_on(self.store.current()))
+ self.assertEqual(window.viewed_machine, self.own)
+ self.assertTrue(window.profile_tabs.isHidden())
+ self.assertEqual(set(window.crossing_ledger.rows), {BEE, SEA})
+ self.assertFalse(window.crossing_ledger.rows[BEE].cells["keys"].isHidden())
+
+ def test_map_return_and_space_pick_a_machine_without_changing_its_layout(self):
+ window = self.desk(enabled=True)
+ tiles = copy.deepcopy(window.atlas_canvas.tiles)
+ for code, machine in ((36, BEE), (49, SEA)):
+ with self.subTest(key=code):
+ window.atlas_canvas.selected = machine
+ event = mock.Mock()
+ event.keyCode.return_value = code
+ window.atlas_canvas.keyDown_(event)
+ self.assertEqual(window.viewed_machine, machine)
+ self.assertEqual(window.atlas_canvas.tiles, tiles)
+
+ def test_picker_tab_does_not_change_the_viewed_machine_or_settings(self):
+ window = self.desk(enabled=True)
+ before = copy.deepcopy(self.store.current())
+ event = mock.Mock()
+ event.keyCode.return_value = 48
+ event.modifierFlags.return_value = 0
+ window.atlas_canvas.keyDown_(event)
+ self.assertEqual(window.viewed_machine, self.own)
+ self.assertEqual(self.store.current(), before)
+
+ def test_remote_header_order_and_inline_back_link(self):
+ window = self.desk(enabled=True)
+ window._atlas_selected(BEE)
+ self.assertEqual(window.edit_notice.text, "Editing Bee's ways ·")
+ self.assertEqual(window.back_ways_button.title(), "Back to This Mac")
+ self.assertEqual(list(window.edit_header.arrangedSubviews()),
+ [window.edit_notice.view, window.back_ways_button])
+ body = list(window.ways_ledger_module.body.arrangedSubviews())
+ ordered = [window.edit_header, window.profile_status.view,
+ window.remote_changes_note.view, window.remote_permissions_note.view]
+ self.assertEqual([body.index(view) for view in ordered],
+ sorted(body.index(view) for view in ordered))
+
+ def test_home_shortcut_opens_overviews_same_shortcut_row(self):
+ window = self.desk(enabled=True)
+ window._atlas_selected(BEE)
+ with mock.patch.object(window.window, "makeFirstResponder_") as focus:
+ click(window.home_shortcut_button)
+ self.assertEqual(window.page, "overview")
+ focus.assert_called_with(window.same_checks["shortcut"])
+
+ def test_home_shortcut_formats_only_the_key_in_mono_in_translated_order(self):
+ window = self.desk(enabled=True)
+ translate = kvm_bridge_app.tr
+ def key_first(message):
+ if message == "Shortcut: {style} {key} ·":
+ return "{key} : {style} ·"
+ return translate(message)
+ with mock.patch.object(kvm_bridge_app, "tr", side_effect=key_first), \
+ mock.patch.object(kvm_bridge_app.widgets, "attributed",
+ wraps=kvm_bridge_app.widgets.attributed) as attributed:
+ window._show_profiles()
+ key = kvm_bridge_app.widgets.key_title(self.controller.cfg.trigger_key)
+ mono = [call for call in attributed.call_args_list if call.kwargs.get("mono")]
+ self.assertEqual(len(mono), 1)
+ self.assertEqual(mono[0].args[0], key)
+ self.assertTrue(window.home_shortcut_note.text.startswith(key + " : "))
+ self.assertEqual(window.home_shortcut_note.view.attributedStringValue().string(),
+ window.home_shortcut_note.text)
+
+ def test_profiles_actions_are_visible_and_protect_active_and_last_profile(self):
+ window = self.desk(enabled=True)
+ self.assertFalse(window.profile_actions.isHidden())
+ self.assertFalse(window.delete_profile_button.isEnabled())
+ with mock.patch.object(window, "_profile_name") as prompt:
+ click(window.new_profile_button)
+ prompt.assert_called_once_with()
+ with mock.patch.object(window, "_profile_name") as prompt:
+ click(window.rename_profile_button)
+ prompt.assert_called_once_with(profiles.DESK_ID)
+ window._profile_event(crossing_state.new_profile, "Sofa")
+ self.assertFalse(window.profile_switch_note.view.isHidden())
+ # Delete… offers every profile but the active one; the menu is built, not popped up.
+ self.assertTrue(window.delete_profile_button.isEnabled())
+ offered = [item.title() for item in window._delete_profile_menu().itemArray()]
+ self.assertEqual(offered, ["Sofa"])
+ window.ways_switch._toggle()
+ self.assertTrue(window.profile_actions.isHidden())
+ self.assertTrue(window.profile_switch_note.view.isHidden())
+
+ def test_off_intro_and_on_hint_use_their_own_instructions(self):
+ window = self.desk()
+ self.assertTrue(window.crossing_intro.text.startswith("Drag a machine on the map"))
+ self.assertEqual(window.ways_off_note.text,
+ "Set every machine's ways from this screen. Turning it on changes nothing until you do; each machine's own ways are kept.")
+ window.ways_switch._toggle()
+ self.assertTrue(window.crossing_intro.text.startswith("Click a machine on the map"))
+ self.assertFalse(window.atlas_canvas_hint.view.isHidden())
+ self.assertEqual(window.atlas_canvas_hint.text,
+ "Click a machine to set its ways · Tab and Return pick one from the keyboard")
+
+ def test_empty_archive_hides_toggle_and_own_band_matches_ledger_width(self):
+ window = self.desk(enabled=True)
+ settings = copy.deepcopy(self.store.current())
+ settings["crossing_own"]["saved"] = []
+ self.store.save_settings(settings)
+ window._show_profiles()
+ self.assertTrue(window.saved_toggle.isHidden())
+ window._select_page("crossing")
+ window.window.contentView().layoutSubtreeIfNeeded()
+ self.assertGreater(window.ways_ledger_module.view.frame().size.width, 0)
+ self.assertAlmostEqual(window.own_ways_module.view.frame().size.width,
+ window.ways_ledger_module.view.frame().size.width, delta=1)
+
+ def test_open_archive_fills_own_band_and_actions_align_at_the_right(self):
+ window = self.desk(enabled=True)
+ click(window.own_ways_button)
+ self.assertTrue(profiles.saved_list(self.store.current()))
+ click(window.saved_toggle)
+ window._select_page("crossing")
+ window.window.contentView().layoutSubtreeIfNeeded()
+ for pair in window._earlier_pairs:
+ pair.update_orientation(700)
+ window.window.contentView().layoutSubtreeIfNeeded()
+ ledger_width = window.ways_ledger_module.view.frame().size.width
+ self.assertGreater(ledger_width, 0)
+ self.assertAlmostEqual(window.own_ways_module.view.frame().size.width, ledger_width, delta=1)
+ for pair in window._earlier_pairs:
+ frame = pair.second.frame()
+ self.assertAlmostEqual(frame.origin.x + frame.size.width, pair.view.bounds().size.width, delta=1)
+ for restore, delete in window.earlier_buttons.values():
+ self.assertFalse(restore.isBordered())
+ self.assertFalse(delete.isBordered())
+
+ def test_profile_switch_hugs_and_tabs_mark_active_without_a_filled_add_button(self):
+ window = self.desk(enabled=True)
+ window._profile_event(crossing_state.new_profile, "Sofa")
+ window._select_page("crossing")
+ window.profile_top.update_orientation(700)
+ window.window.contentView().layoutSubtreeIfNeeded()
+ switch = window.ways_switch
+ words, track = switch.words.view.frame(), switch.track.frame()
+ # Label and toggle sit together (the Switch's own spacing), not split across the header.
+ self.assertLessEqual(track.origin.x - words.origin.x - words.size.width, 16)
+ self.assertFalse(window.add_profile_button.isBordered())
+ self.assertLessEqual(window.add_profile_button.frame().size.width, 24)
+ for button in window.profile_buttons.values():
+ self.assertEqual(button.view.layer().borderWidth(), 1)
+
+ def test_own_override_band_routes_keep_use_and_share_to_their_events(self):
+ window = self.desk(enabled=True)
+ self.assertFalse(window.own_ways_button.view.isHidden())
+ click(window.own_ways_button)
+ self.assertTrue(self.store.current()["crossing_own"]["use_own"])
+ self.assertFalse(window.use_desk_button.view.isHidden())
+ window._write_ways(BEE, edge=False)
+ self.assertFalse(window.share_ways_button.view.isHidden())
+ own_row = copy.deepcopy(self.store.current()["crossing_own"]["row"])
+ click(window.share_ways_button)
+ self.assertEqual(self.row_registers()[self.own]["value"], own_row)
+ click(window.use_desk_button)
+ self.assertFalse(self.store.current()["crossing_own"]["use_own"])
+
+ def test_earlier_ways_restore_preserves_saved_choices_and_delete_removes_one(self):
+ window = self.desk(enabled=True)
+ settings = copy.deepcopy(self.store.current())
+ earlier = copy.deepcopy(settings["crossing_own"]["row"])
+ earlier[BEE]["ways"]["edge"] = not earlier[BEE]["ways"]["edge"]
+ profiles.archive(settings, earlier, "older_version", 1_700_000_010)
+ saved_id = profiles.saved_list(settings)[0]["id"]
+ self.store.save_settings(settings)
+ window._show_profiles()
+ click(window.saved_toggle)
+ self.assertFalse(window.earlier_host.isHidden())
+ self.assertEqual(window.saved_toggle.title(), "Earlier ways ▴")
+ self.assertIn("From an older Beamer", " ".join(self.texts(window.earlier_host)))
+ restore, _delete = window.earlier_buttons[saved_id]
+ click(restore)
+ self.assertTrue(self.store.current()["crossing_own"]["use_own"])
+ self.assertEqual(self.store.current()["crossing_own"]["row"], profiles.canonical_row(earlier))
+ self.assertIn(saved_id, [item["id"] for item in profiles.saved_list(self.store.current())])
+ _restore, delete = window.earlier_buttons[saved_id]
+ click(delete)
+ self.assertNotIn(saved_id, [item["id"] for item in profiles.saved_list(self.store.current())])
+
+ def test_way_home_switch_calls_set_shake_for_the_current_profile(self):
+ window = self.desk(enabled=True)
+ self.assertTrue(window.shake_switch.value)
+ with mock.patch.object(self.controller, "crossing_event", wraps=self.controller.crossing_event) as event:
+ window.shake_switch._toggle()
+ self.assertIs(event.call_args.args[0], crossing_state.set_shake)
+ self.assertFalse(profiles.shake_on(self.store.current()))
+ self.assertFalse(window.shake_switch.value)
+
+ def test_way_home_sensitivity_calls_the_profile_event_and_shows_its_value(self):
+ window = self.desk(enabled=True)
+ with mock.patch.object(self.controller, "crossing_event", wraps=self.controller.crossing_event) as event:
+ window._shake_sensitivity_changed(150)
+ self.assertIs(event.call_args.args[0], crossing_state.set_shake_sensitivity)
+ self.assertEqual(profiles.shake_sensitivity(self.store.current()), 150)
+ self.assertEqual(window.shake_sensitivity_figure.text, "150")
+
+ def test_way_home_sensitivity_arrows_save_ten_percent_or_one_with_option(self):
+ window = self.desk(enabled=True)
+ window.shake_sensitivity.nudge(1)
+ self.assertEqual(profiles.shake_sensitivity(self.store.current()), 110)
+ window.shake_sensitivity.nudge(1, fine=True)
+ self.assertEqual(profiles.shake_sensitivity(self.store.current()), 111)
+ self.assertEqual(window.shake_sensitivity_figure.text, "111")
+
+ def test_no_way_back_warning_names_every_machine_without_an_edge_home(self):
+ window = self.desk(enabled=True)
+ settings = copy.deepcopy(self.store.current())
+ desk = settings["crossing_desk"]
+ pid = desk["active"]["value"]
+ for machine in (BEE, SEA):
+ desk["profiles"][pid]["rows"][machine]["value"] = {}
+ self.store.save_settings(settings)
+ missing = profiles.no_way_back(self.store.current(), self.own)
+ self.assertTrue(missing, "the synthetic desk must exercise a missing way back")
+ window._show_profiles()
+ for name in missing:
+ self.assertIn(f"{name} has no way back to This Mac except the shortcut and a shake.",
+ window.home_warning.text)
+
+ def test_older_machine_is_labelled_read_only_and_ledger_cannot_write(self):
+ window = self.desk(enabled=True, older=True)
+ self.assertEqual(window.atlas_canvas.tile_words[BEE], "Older")
+ window._atlas_selected(BEE)
+ self.assertIn("Read only", window.profile_status.text)
+ before = copy.deepcopy(self.store.current())
+ with mock.patch.object(self.controller, "crossing_event", wraps=self.controller.crossing_event) as event:
+ window._write_ways(self.own, edge=False)
+ event.assert_not_called()
+ self.assertEqual(self.store.current(), before)
+ for row in window.crossing_ledger.rows.values():
+ self.assertTrue(all(not chip.enabled for chip in row.chips.values()))
+ self.assertTrue(all(not button.enabled for button in row.corner_buttons.values()))
+
+ def test_offline_capable_machine_keeps_editable_ways_for_its_next_connection(self):
+ window = self.desk(enabled=True)
+ window.windows_input.server.links.return_value = [protocol.read_id(SEA)]
+ window._show_arrangement()
+ self.assertEqual(window.atlas_canvas.tile_words[BEE], "Offline")
+ window._atlas_selected(BEE)
+ self.assertIn("Offline. It takes these when it next connects", window.profile_status.text)
+ before = self.row_registers()[BEE]
+ window._write_ways(self.own, edge=False)
+ self.assertNotEqual(self.row_registers()[BEE], before)
+
+ def test_disconnected_older_machine_remains_read_only(self):
+ window = self.desk(enabled=True, older=True)
+ window.windows_input.server.links.return_value = [protocol.read_id(SEA)]
+ window._show_arrangement()
+ window._atlas_selected(BEE)
+ self.assertEqual(window.atlas_canvas.tile_words[BEE], "Older")
+ self.assertIn("Read only", window.profile_status.text)
+ before = copy.deepcopy(self.store.current())
+ window._write_ways(self.own, edge=False)
+ self.assertEqual(self.store.current(), before)
+
+ def test_named_profile_tabs_switch_and_removal_preserves_the_active_profile(self):
+ window = self.desk(enabled=True)
+ window._profile_event(crossing_state.new_profile, "Sofa")
+ sofa = next(item["id"] for item in profiles.profile_list(self.store.current()) if item["name"] == "Sofa")
+ self.assertIn(sofa, window.profile_buttons)
+ self.assertFalse(window.profile_buttons[profiles.DESK_ID].view.menu().itemAtIndex_(1).isEnabled())
+ self.assertTrue(window.profile_buttons[sofa].view.menu().itemAtIndex_(1).isEnabled())
+ click(window.profile_buttons[sofa])
+ self.assertEqual(self.store.current()["crossing_desk"]["active"]["value"], sofa)
+ self.assertFalse(window.profile_buttons[sofa].view.menu().itemAtIndex_(1).isEnabled())
+ window._profile_event(crossing_state.remove_profile, sofa)
+ self.assertIn(sofa, window.profile_buttons)
+ click(window.profile_buttons[profiles.DESK_ID])
+ window._profile_event(crossing_state.rename_profile, sofa, "Reading")
+ self.assertEqual(next(item["name"] for item in profiles.profile_list(self.store.current())
+ if item["id"] == sofa), "Reading")
+ window._profile_event(crossing_state.remove_profile, sofa)
+ self.assertNotIn(sofa, window.profile_buttons)
+ self.assertEqual([item["id"] for item in profiles.profile_list(self.store.current())], [profiles.DESK_ID])
+
+ def test_older_version_load_notice_is_shown_and_consumed_once(self):
+ window = self.desk(enabled=True)
+ raw = json.loads(self.store.path.read_text())
+ peer = next(entry for entry in raw["peers"] if entry["id"] == BEE)
+ peer["ways"]["edge"] = not peer["ways"]["edge"]
+ self.store.path.write_text(json.dumps(raw))
+ self.store.load_settings()
+ self.assertIn("older_version", self.store.profile_load_notes)
+ window._ways_module()
+ self.assertEqual(window.older_ways_notice.text,
+ "This machine kept the ways set while it ran an older Beamer.")
+ self.assertFalse(window.older_ways_notice.view.isHidden())
+ self.assertFalse(self.store.take_profile_load_note("older_version"))
+ self.store.load_settings()
+ self.assertFalse(self.store.take_profile_load_note("older_version"))
+
+ def test_menu_profile_checks_active_and_click_switches_the_profile(self):
+ window = self.desk(enabled=True)
+ window._profile_event(crossing_state.new_profile, "Sofa")
+ sofa = next(item["id"] for item in profiles.profile_list(self.store.current()) if item["name"] == "Sofa")
+ tray = self.menu_tray()
+ kvm_bridge_app.TrayApp._profile_items(tray)
+ self.assertIn("Profile", tray.menu)
+ children = tray.profile_item
+ # Keyed by profile id, so two profiles with one name never share an item; titled by name.
+ self.assertEqual({child.title for child in children.values()}, {"Desk", "Sofa"})
+ self.assertEqual(children[profiles.DESK_ID].state, 1)
+ self.assertEqual(children[sofa].state, 0)
+ with mock.patch.object(self.controller, "crossing_event", wraps=self.controller.crossing_event) as event:
+ children[sofa].callback(children[sofa])
+ self.assertIs(event.call_args.args[0], crossing_state.switch_profile)
+ self.assertEqual(event.call_args.args[1], sofa)
+ self.assertEqual(self.store.current()["crossing_desk"]["active"]["value"], sofa)
+ kvm_bridge_app.TrayApp._profile_items(tray)
+ self.assertEqual(tray.profile_item[profiles.DESK_ID].state, 0)
+ self.assertEqual(tray.profile_item[sofa].state, 1)
+
+ def test_menu_profile_submenu_is_absent_with_one_profile_or_same_ways_off(self):
+ window = self.desk(enabled=True)
+ tray = self.menu_tray()
+ kvm_bridge_app.TrayApp._profile_items(tray)
+ self.assertIsNone(tray.profile_item)
+ self.assertNotIn("Profile", tray.menu)
+ window._profile_event(crossing_state.new_profile, "Sofa")
+ kvm_bridge_app.TrayApp._profile_items(tray)
+ self.assertIn("Profile", tray.menu)
+ window.ways_switch._toggle()
+ kvm_bridge_app.TrayApp._profile_items(tray)
+ self.assertIsNone(tray.profile_item)
+ self.assertNotIn("Profile", tray.menu)
+
+ def test_desk_frame_dispatches_once_without_echoing_same_settings_or_layout(self):
+ window = self.desk(enabled=True)
+ frame = profiles.frames(profiles.desk_message(self.store.current()))[0]
+ data = settings_sync.desk_message_data({"on": True, "set_at": 1_700_000_020,
+ "by": BEE}, frame)
+ outcome = {"changed": False, "settings": self.store.current()}
+ with mock.patch.object(self.controller, "receive_desk", return_value=outcome) as receive, \
+ mock.patch.object(window, "_send_same") as send, \
+ mock.patch.object(window, "_receive_layout") as layout, \
+ mock.patch.object(window, "refresh"):
+ window.apply_same(data, BEE)
+ receive.assert_called_once()
+ self.assertEqual(receive.call_args.args, (data, BEE))
+ self.assertTrue(receive.call_args.kwargs["linked"])
+ send.assert_not_called()
+ layout.assert_not_called()
+
+ def test_desk_full_outcome_is_explained_in_the_existing_page_note(self):
+ window = self.desk(enabled=True)
+ outcome = {"changed": False, "accepted": False, "reason": "desk_full",
+ "settings": self.store.current()}
+ with mock.patch.object(self.controller, "crossing_event", return_value=outcome):
+ result = window._profile_event(crossing_state.new_profile, "Sofa")
+ self.assertEqual(result["reason"], "desk_full")
+ self.assertEqual(window.message_label.text,
+ "The desk is full. Remove an unused profile before adding more ways.")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_profiles_sync_mac.py b/mac_app/tests/test_profiles_sync_mac.py
new file mode 100644
index 0000000..330db5d
--- /dev/null
+++ b/mac_app/tests/test_profiles_sync_mac.py
@@ -0,0 +1,178 @@
+"""Profiles over fake links and a synthetic book; no application or real input."""
+
+import copy
+import json
+import sys
+import threading
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+import bridge
+import settings_store
+from bridge_fakes import FakeClipboard, FakeQuartz, make_config, quiet_logger
+from fake_link import FakeLink
+from core import crossing_state, profiles, protocol, receiver
+from core.tests.test_profiles import A, B, C, raw
+
+
+class ProfileSyncTests(unittest.TestCase):
+ def setUp(self):
+ self.held, _ = profiles.before_load(raw(), now=100)
+ self.held, _ = profiles.after_load(self.held, platform="mac", now=100)
+ self.held["peers"].append(dict(id=C, port=24820, send=True, allow_drive=True))
+ self.saved = []
+
+ def save(settings):
+ self.saved.append(copy.deepcopy(settings))
+ self.held = copy.deepcopy(settings)
+
+ self.controller = bridge.KVMController(make_config(), quartz=FakeQuartz,
+ clipboard=FakeClipboard(), logger=quiet_logger(), link_factory=FakeLink)
+ self.controller.book = receiver.PeerBook(lambda: self.held, save, threading.RLock())
+ self.controller.announce = lambda: [protocol.settings_msg(dict(
+ on=False, set_at=9, by=A, groups=[], layout={"tiles": {}}, design_sync={}))]
+ self.sent = []
+ self.controller._peers_up = {B: self.link(B), C: self.link(C)}
+ self.controller.zones_changed = lambda: None
+ # What linked peers were last told, as after the app's first publish at start.
+ self.controller._desk_published = profiles.desk_message(self.held)
+
+ def link(self, peer, caps=("settings", "profiles", "layout")):
+ return SimpleNamespace(peer_id=peer, caps=frozenset(caps), live=lambda: True,
+ post=lambda message: self.sent.append((peer, message)))
+
+ def desks(self):
+ return [(peer, message["data"]) for peer, message in self.sent
+ if message["type"] == protocol.MSG_SETTINGS and "desk" in message["data"]]
+
+ def test_local_register_edits_use_separate_frames_and_only_profile_peers(self):
+ self.controller._peers_up[C] = self.link(C, ("settings", "layout"))
+ outcome = crossing_state.set_same_ways(self.held, True, platform="mac", now=200)
+ with mock.patch.object(profiles, "MAX_DESK_BYTES", 240):
+ self.controller.carry_crossing(outcome)
+ desks = self.desks()
+ self.assertGreater(len(desks), 1)
+ self.assertEqual({peer for peer, _ in desks}, {B})
+ for _, data in desks:
+ self.assertEqual(data["on"], False)
+ self.assertEqual(data["set_at"], 9)
+ self.assertEqual(data["by"], A)
+ self.assertNotIn("layout", data)
+ self.assertNotIn("design_sync", data)
+ self.assertTrue(any("on" in data["desk"] for _, data in desks))
+
+ def test_a_change_made_outside_a_crossing_event_still_reaches_linked_peers(self):
+ # App review: pairing (and a load that reconciled) saved desk changes no event carried.
+ changed = crossing_state.set_same_ways(self.held, True, platform="mac", now=200)["settings"]
+ self.held = changed
+ self.controller._peers_up[C] = self.link(C, ("settings", "layout"))
+ self.controller.publish_desk()
+ desks = self.desks()
+ self.assertEqual({peer for peer, _ in desks}, {B}, "only peers with profiles")
+ sent = [data["desk"] for _, data in desks]
+ self.assertTrue(any("on" in desk for desk in sent))
+ self.sent.clear()
+ self.controller.publish_desk()
+ self.assertEqual(self.desks(), [], "an unchanged desk is not sent again")
+
+ def test_forward_goes_to_others_and_answer_only_to_source(self):
+ forward = {"on": dict(value=True, set_at=202, by=B)}
+ answer = {"active": dict(value=profiles.DESK_ID, set_at=203, by=A)}
+ outcome = crossing_state._outcome(self.held, forward=forward, answer=answer)
+ self.controller.carry_crossing(outcome, source=B)
+ self.assertEqual([(peer, data["desk"]) for peer, data in self.desks()],
+ [(C, forward), (B, answer)])
+
+ def test_inbound_link_gets_desk_without_duplicating_outbound(self):
+ self.controller.responder = SimpleNamespace(links=lambda: [protocol.read_id(B), protocol.read_id(C)],
+ caps_of=lambda ident: ("settings", "profiles"),
+ send=lambda ident, message: self.sent.append((protocol.id_text(ident), message)))
+ self.controller._peers_up.pop(C)
+ self.controller._send_desk({"on": dict(value=False, set_at=0, by="")})
+ self.assertEqual([peer for peer, _ in self.desks()], [B, C])
+
+ def test_link_up_sends_whole_desk_only_to_that_peer(self):
+ self.controller._announce_paired = lambda link: None
+ self.controller.crossing_link_up = lambda peer: None
+ self.controller._announce_to(self.controller._peers_up[B], {})
+ desks = self.desks()
+ self.assertEqual({peer for peer, _ in desks}, {B})
+ self.assertEqual(desks[0][1]["desk"]["profiles"][profiles.DESK_ID]["name"]["value"], "Desk")
+
+ def test_arrival_runs_crossing_event_and_saves_before_rearming(self):
+ stages = []
+ self.controller.zones_changed = lambda: stages.append("zones")
+ self.controller.responder = SimpleNamespace(links=lambda: [],
+ peers_changed=lambda: stages.append("peers"), rearm=lambda: stages.append("rearm"))
+ data = dict(on=False, set_at=200, by=B,
+ desk={"on": dict(value=True, set_at=200, by=B)})
+ outcome = self.controller.receive_desk(data, B, linked=True, now=201)
+ self.assertTrue(outcome["accepted"])
+ self.assertEqual(self.held["crossing_desk"]["on"]["value"], True)
+ self.assertTrue(self.saved)
+ self.assertEqual(stages, ["zones", "peers", "rearm"])
+ self.assertTrue(self.controller.desk_last_heard[B])
+
+ def test_unlinked_and_malformed_arrivals_do_not_change_settings(self):
+ data = dict(on=False, set_at=200, by=B,
+ desk={"on": dict(value=True, set_at=200, by=B)})
+ self.assertFalse(self.controller.receive_desk(data, B, linked=False, now=201)["accepted"])
+ self.assertIsNone(self.controller.receive_desk({"desk": {}}, B, linked=True, now=201))
+ self.assertFalse(self.saved)
+ self.assertFalse(self.controller.desk_last_heard.get(B, False))
+
+ def test_profile_capability_and_last_heard_reset_survive_reconnect(self):
+ self.assertIn(B, self.controller.profiles_capable())
+ self.controller.desk_last_heard[B] = True
+ self.controller.reset_desk_peer(B)
+ self.controller._peers_up.clear()
+ self.assertIn(B, self.controller.profiles_capable())
+ self.assertFalse(self.controller.desk_last_heard.get(B, False))
+
+ def test_new_profile_event_does_not_inject_unsupported_capable_keyword(self):
+ outcome = self.controller.crossing_event(crossing_state.new_profile, "Sofa", platform="mac", now=201)
+ self.assertTrue(outcome["accepted"])
+ self.assertIn("Sofa", [item["name"] for item in profiles.profile_list(self.held)])
+
+ def test_inbound_announcement_sends_full_desk_and_caches_capability(self):
+ from windows_input import WindowsInput
+ inbound = WindowsInput.__new__(WindowsInput)
+ inbound._controller = self.controller
+ inbound.server = SimpleNamespace(links=lambda: [protocol.read_id(B)],
+ caps_of=lambda ident: frozenset(("settings", "layout", "profiles")),
+ send=lambda ident, message: self.sent.append((protocol.id_text(ident), message)))
+ self.controller.responder = inbound.server
+ self.controller._peers_up.clear()
+ self.controller.crossing_link_up = lambda peer: None
+ inbound._announce(protocol.read_id(B))
+ self.assertEqual({peer for peer, _ in self.desks()}, {B})
+ self.controller._peers_up.clear()
+ inbound.server.links = lambda: []
+ self.assertIn(B, self.controller.profiles_capable())
+
+
+class LoadNoteTests(unittest.TestCase):
+ def test_older_version_note_is_in_memory_and_consumed_once(self):
+ import tempfile
+ with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[2]) as directory:
+ store = settings_store.SettingsStore(Path(directory) / "settings.json")
+ held, _ = profiles.before_load(raw(), now=100)
+ held, _ = profiles.after_load(held, platform="mac", now=100)
+ held = store.save_settings(held)
+ held["peers"][0]["ways"]["thirds"] = ["end"]
+ store.path.write_text(json.dumps(held))
+ loaded = store.load_settings()
+ self.assertEqual(loaded["crossing_own"]["row"][B]["ways"]["thirds"], ["end"])
+ self.assertTrue(store.take_profile_load_note("older_version"))
+ self.assertFalse(store.take_profile_load_note("older_version"))
+ self.assertNotIn("profile_load_notes", loaded)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_settings_layout_acceptance.py b/mac_app/tests/test_settings_layout_acceptance.py
index b2f41cf..30620b5 100644
--- a/mac_app/tests/test_settings_layout_acceptance.py
+++ b/mac_app/tests/test_settings_layout_acceptance.py
@@ -27,6 +27,20 @@ class SettingsLayoutAcceptanceTests(unittest.TestCase):
kvm_bridge_app.theme.init_fonts()
cls.control = offscreen_control_window()
+ def test_capped_profile_buttons_do_not_narrow_the_ledger_when_stacked(self):
+ control = self.control
+ control._select_page("crossing")
+ for width in (320, 426, 512, 900, 426):
+ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)
+ settle(control.window)
+ body = control.pages["crossing"].documentView().subviews()[0]
+ module = control.ways_ledger_module.view
+ with self.subTest(width=width):
+ self.assertAlmostEqual(module.frame().size.width, body.frame().size.width, delta=1)
+ self.assertFalse(module.hasAmbiguousLayout())
+ self.assertLessEqual(control.own_ways_button.view.frame().size.width, 240 + 1)
+ self.assertFalse(control.window.isVisible())
+
def test_all_six_pages_share_the_centred_column_at_every_width_and_density(self):
from mac_app.tests.settings_layout_offscreen import render
control = self.control
diff --git a/mac_app/tests/test_settings_v6.py b/mac_app/tests/test_settings_v6.py
index 977824b..44e67df 100644
--- a/mac_app/tests/test_settings_v6.py
+++ b/mac_app/tests/test_settings_v6.py
@@ -1138,8 +1138,7 @@ class OverlapTests(Base):
self.assertNotIn("part", zones)
self.assertEqual(self.store.current()["peers"][0]["ways"]["thirds"], list(ways.PARTS))
- def test_an_old_file_with_two_notches_keeps_the_first_machine(self):
- # 1.5.3: the notch reaches one machine; an old file that ticked two keeps the first in ways order.
+ def test_two_legacy_notches_keep_only_the_first_machine_in_ways_order(self):
def two_notches(s):
s["peers"][0]["id"] = PEER_ID
s["zones"] = [{**z, "peer": PEER_ID} for z in s["zones"]]
@@ -1150,7 +1149,7 @@ class OverlapTests(Base):
s["zones"].append({"peer": SECOND_ID, "kind": "notch"})
saved = self.compiled(two_notches)
self.assertEqual([peer["ways"]["notch"] for peer in saved["peers"]], [True, False])
- self.assertEqual([zone["kind"] for zone in saved["zones"]].count("notch"), 1)
+ self.assertEqual([zone["peer"] for zone in saved["zones"] if zone["kind"] == "notch"], [PEER_ID])
if __name__ == "__main__":
diff --git a/mac_app/tests/test_shake_mac.py b/mac_app/tests/test_shake_mac.py
new file mode 100644
index 0000000..1c33892
--- /dev/null
+++ b/mac_app/tests/test_shake_mac.py
@@ -0,0 +1,250 @@
+"""Synthetic Quartz deltas and fake links, without AppKit UI or real input."""
+
+import copy
+import sys
+import threading
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from bridge import KVMController
+from bridge_fakes import FakeClock, FakeClipboard, FakeQuartz, PAIRED_TOKEN, make_config, quiet_logger, redirect_to
+from fake_link import FakeLink
+from core import profiles, receiver
+from core.tests.test_profiles import B, raw
+from core.tests.test_shake import qualifying_trace
+
+
+class ShakeMacTests(unittest.TestCase):
+ def setUp(self):
+ FakeQuartz.hid_keys = set()
+ FakeQuartz.hid_buttons = set()
+ self.clock = FakeClock(0)
+ self.held, _ = profiles.before_load(raw(), now=100)
+ self.held, _ = profiles.after_load(self.held, platform="mac", now=100)
+ self.held["peers"][0].update(token=PAIRED_TOKEN, name="Desk PC")
+ self.controller = KVMController(make_config(), quartz=FakeQuartz, clock=self.clock,
+ clipboard=FakeClipboard(), logger=quiet_logger(), link_factory=FakeLink)
+ self.controller.book = receiver.PeerBook(lambda: self.held, self.save, threading.RLock())
+ self.alerts = []
+ self.controller.on_user_alert = lambda title, text: self.alerts.append(text)
+ self.controller._set_cursor_follows_mouse = lambda value: None
+ self.controller._warp_cursor_to_pin = lambda: None
+ self.controller._capture_cursor_pin_point = lambda: (0, 0)
+ redirect_to(self.controller, B)
+
+ def save(self, settings):
+ self.held = copy.deepcopy(settings)
+
+ def trace(self, start=.31):
+ results = []
+ self.firing = None
+ for t, dx, dy in qualifying_trace(start=start):
+ self.clock.value = t
+ event = {FakeQuartz.kCGMouseEventDeltaX: dx, FakeQuartz.kCGMouseEventDeltaY: dy}
+ away = self.controller.redirecting
+ results.append(self.controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, event, None))
+ if away and not self.controller.redirecting and self.firing is None:
+ self.firing = results[-1]
+ # The notice is written off the event tap, on its own thread.
+ for thread in threading.enumerate():
+ if thread.name == "Beamer-shake-notice":
+ thread.join(2)
+ return results
+
+ def start_redirecting_with_trigger(self):
+ self.controller.set_redirecting(False)
+ self.controller._primary_link.up(self.controller, ident=bytes([2]) * 16, name="Desk PC")
+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}
+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}
+ for t, event in ((10.0, down), (10.03, up), (10.2, down), (10.22, up)):
+ self.clock.value = t
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, event, None)
+ self.assertTrue(self.controller.redirecting)
+ self.assertFalse(self.controller.shake._held)
+
+ def test_first_shake_after_trigger_double_tap_returns_home_without_intervening_motion(self):
+ self.start_redirecting_with_trigger()
+
+ self.trace(start=10.7)
+
+ self.assertFalse(self.controller.redirecting)
+ self.assertIsNone(self.controller.owner.on)
+
+ def test_first_shake_after_trigger_double_tap_returns_home_after_small_move(self):
+ self.start_redirecting_with_trigger()
+ self.clock.value = 10.3
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved,
+ {FakeQuartz.kCGMouseEventDeltaX: 1, FakeQuartz.kCGMouseEventDeltaY: 0}, None)
+
+ self.trace(start=10.7)
+
+ self.assertFalse(self.controller.redirecting)
+ self.assertIsNone(self.controller.owner.on)
+
+ def test_shake_returns_home_once_and_drops_firing_motion(self):
+ returns = []
+ original = self.controller.set_redirecting
+
+ def home(*args, **kwargs):
+ returns.append((args, kwargs))
+ return original(*args, **kwargs)
+
+ self.controller.set_redirecting = home
+ self.trace()
+ self.assertIsNone(self.firing, "the event that fired the shake reached this Mac's pointer")
+ self.assertFalse(self.controller.redirecting)
+ self.assertIsNone(self.controller.owner.on)
+ self.assertEqual(len(returns), 1)
+ self.assertTrue(returns[0][1]["came_home"])
+ self.assertEqual(self.held["shake_notices"], 1)
+ self.assertEqual(len(self.alerts), 1)
+
+ def test_float_deltas_reach_detector_before_integer_rounding(self):
+ deltas = []
+ self.controller.shake.motion = lambda t, dx, dy: deltas.append((dx, dy)) or True
+ self.clock.value = .4
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved,
+ {FakeQuartz.kCGMouseEventDeltaX: .25, FakeQuartz.kCGMouseEventDeltaY: -.75}, None)
+ self.assertEqual(deltas, [(.25, -.75)])
+ self.assertTrue(self.controller.outbound.empty())
+ self.assertFalse(self.controller.redirecting)
+
+ def test_button_and_key_hold_prevent_shake_until_all_released(self):
+ self.clock.value = .3
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventLeftMouseDown, {}, None)
+ key = {FakeQuartz.kCGKeyboardEventKeycode: 0, "unicode": "a"}
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyDown, key, None)
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventLeftMouseUp, {}, None)
+ self.trace()
+ self.assertTrue(self.controller.redirecting)
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyUp, key, None)
+ self.trace(start=1.1)
+ self.assertFalse(self.controller.redirecting)
+
+ def test_returning_input_clears_keys_released_while_receiving(self):
+ self.clock.value = .3
+ shift = {FakeQuartz.kCGKeyboardEventKeycode: 56, "unicode": ""}
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyDown, shift, None)
+ self.controller.set_receiving(True)
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyUp, shift, None)
+ self.controller.set_receiving(False)
+ redirect_to(self.controller, B)
+
+ self.trace(start=1.1)
+
+ self.assertFalse(self.controller.redirecting)
+ self.assertIsNone(self.controller.owner.on)
+
+ def test_returning_input_keeps_keys_still_down(self):
+ shift = {FakeQuartz.kCGKeyboardEventKeycode: 56, "unicode": ""}
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyDown, shift, None)
+ FakeQuartz.hid_keys.add(56)
+ self.controller.set_receiving(True)
+ self.controller.set_receiving(False)
+
+ self.assertIn(("key", 56), self.controller._shake_presses)
+
+ def test_returning_input_maps_middle_button_to_hid_index(self):
+ event = {FakeQuartz.kCGMouseEventButtonNumber: 2}
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventOtherMouseDown, event, None)
+ FakeQuartz.hid_buttons.add(2)
+ self.controller.set_receiving(True)
+ self.controller.set_receiving(False)
+
+ self.assertIn(("button", "middle"), self.controller._shake_presses)
+
+ def test_reconcile_keeps_fresh_button_down_during_hid_query(self):
+ self.clock.value = .3
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventLeftMouseDown, {}, None)
+ button_state = FakeQuartz.CGEventSourceButtonState
+
+ def fresh_down(cls, source, button):
+ down = button_state(source, button)
+ if button == 0:
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventLeftMouseDown, {}, None)
+ return down
+
+ with patch.object(FakeQuartz, "CGEventSourceButtonState", classmethod(fresh_down)):
+ self.controller._shake_reconcile_input_state()
+
+ self.assertIn(("button", "left"), self.controller._shake_presses)
+ self.trace(start=1.1)
+ self.assertTrue(self.controller.redirecting)
+
+ def test_reconcile_removes_button_released_at_hid(self):
+ self.clock.value = .3
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventLeftMouseDown, {}, None)
+
+ self.controller._shake_reconcile_input_state()
+
+ self.assertNotIn(("button", "left"), self.controller._shake_presses)
+ self.trace(start=1.1)
+ self.assertFalse(self.controller.redirecting)
+
+ def test_scroll_resets_motion_and_starts_quiet_period(self):
+ self.clock.value = .3
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventScrollWheel, {}, None)
+ for t, dx, dy in qualifying_trace(start=.31):
+ if t > .55:
+ break
+ self.clock.value = t
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved,
+ {FakeQuartz.kCGMouseEventDeltaX: dx, FakeQuartz.kCGMouseEventDeltaY: dy}, None)
+ self.assertTrue(self.controller.redirecting)
+ self.trace(start=1.1)
+ self.assertFalse(self.controller.redirecting)
+
+ def test_settings_disable_shake_while_away(self):
+ self.held["crossing_own"]["shake"] = False
+ self.controller.zones_changed()
+ self.trace()
+ self.assertTrue(self.controller.redirecting)
+ self.assertFalse(self.alerts)
+
+ def test_press_started_at_home_still_blocks_shake_after_leaving(self):
+ self.controller.set_redirecting(False)
+ key = {FakeQuartz.kCGKeyboardEventKeycode: 0, "unicode": "a"}
+ other = {FakeQuartz.kCGKeyboardEventKeycode: 1, "unicode": "s"}
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyDown, key, None)
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyDown, other, None)
+ redirect_to(self.controller, B)
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyUp, key, None)
+ self.trace()
+ self.assertTrue(self.controller.redirecting)
+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyUp, other, None)
+ self.trace(start=1.1)
+ self.assertFalse(self.controller.redirecting)
+
+ def test_notice_stops_after_three_returns(self):
+ self.held["shake_notices"] = 3
+ self.trace()
+ self.assertFalse(self.controller.redirecting)
+ self.assertEqual(self.held["shake_notices"], 3)
+ self.assertFalse(self.alerts)
+
+ def test_home_hold_resets_edge_pressure_until_mouse_has_been_quiet(self):
+ self.trace()
+ feeds = []
+ from crossing import CrossingEngine
+ self.controller.crossing = CrossingEngine.from_config(dict(self.controller.cfg.crossing, methods=["edge"]))
+ self.controller._crossing_ready = lambda peer: True
+ self.controller._current_desktop_bounds = lambda: (0, 0, 100, 100)
+ self.controller._current_displays = lambda: []
+ from crossing import Step
+ self.controller.crossing.feed = lambda *args, **kwargs: feeds.append(args) or Step()
+ event = {"location": (99, 50), FakeQuartz.kCGMouseEventDeltaX: 20}
+ self.clock.value += .1
+ self.controller._handle_local_mouse(FakeQuartz.kCGEventMouseMoved, event)
+ self.assertFalse(feeds)
+ self.clock.value += .201
+ self.controller._handle_local_mouse(FakeQuartz.kCGEventMouseMoved, event)
+ self.assertEqual(len(feeds), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_tile_resize_mac.py b/mac_app/tests/test_tile_resize_mac.py
new file mode 100644
index 0000000..19a1ca4
--- /dev/null
+++ b/mac_app/tests/test_tile_resize_mac.py
@@ -0,0 +1,244 @@
+"""Mac resize interaction coverage; deliberately not run by the edits-only worker."""
+
+import copy
+import sys
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+import AppKit
+import Quartz
+
+AppKit.NSApplication.sharedApplication()
+
+import diagram
+from core import crossing_state, ways
+from test_crossing_page_machines import BEE, Page, token
+from wake import WakingController
+
+
+class TileResizeMac(Page):
+ def setUp(self):
+ super().setUp()
+ capture = mock.patch.object(WakingController, "start_input_capture")
+ capture.start()
+ self.addCleanup(capture.stop)
+
+ def canvas(self, *, selected=BEE, read_only=False):
+ window = self.build([(BEE, token(100), "Bee", {"side": "right"})])
+ canvas = window.atlas_canvas
+ own = canvas.own_id
+ tiles = {own: {"x": 0, "y": 0, "w": 160, "h": 100},
+ BEE: {"x": 160, "y": 0, "w": 160, "h": 100}}
+ window._atlas_layout_changed(tiles, BEE, snap=False)
+ canvas.setFrame_(((0, 0), (188, canvas.HEIGHT)))
+ canvas.show_layout(tiles, canvas.states, {own: "This Mac", BEE: "Bee"}, own,
+ selected, read_only=read_only)
+ return window, canvas
+
+ def event(self, canvas, point, *, key=124, flags=0):
+ canvas.window = mock.Mock()
+ canvas.convertPoint_fromView_ = mock.Mock(return_value=AppKit.NSMakePoint(*point))
+ event = mock.Mock()
+ event.locationInWindow.return_value = AppKit.NSMakePoint(*point)
+ event.clickCount.return_value = 1
+ event.keyCode.return_value = key
+ event.modifierFlags.return_value = flags
+ return event
+
+ def start_resize(self, canvas, key=BEE):
+ frame = canvas._map()[0][key]
+ # The middle of the drawn grip: its outer 5 px on a shared seam belong to that edge's third.
+ point = (frame[0] + frame[2] - 7, frame[1] + frame[3] - 7)
+ event = self.event(canvas, point)
+ canvas.mouseDown_(event)
+ return event, point
+
+ def test_grip_drag_uses_frozen_scale_keeps_aspect_and_commits_one_drop(self):
+ window, canvas = self.canvas()
+ before = copy.deepcopy(canvas.tiles[BEE])
+ scale = canvas._map()[1]
+ with mock.patch.object(diagram.AppKit, "NSCursor"), \
+ mock.patch.object(window.controller, "crossing_event", wraps=window.controller.crossing_event) as drop:
+ event, point = self.start_resize(canvas)
+ self.assertTrue(canvas.dragging["resize"])
+ for dx in (40, 80):
+ canvas.convertPoint_fromView_.return_value = AppKit.NSMakePoint(point[0] + dx * scale, point[1])
+ canvas.mouseDragged_(event)
+ drop.assert_not_called()
+ self.assertEqual(canvas._map()[1], scale)
+ self.assertEqual(canvas.tiles[BEE], {**before, "w": 240, "h": 150})
+ canvas.mouseUp_(event)
+ canvas.mouseUp_(event)
+ drop.assert_called_once()
+ self.assertIs(drop.call_args.args[0], crossing_state.drop)
+ self.assertEqual(drop.call_args.kwargs["snap_radius"], 0)
+ self.assertEqual(self.store.current()["layout"][BEE], {**before, "w": 240, "h": 150})
+ self.assertEqual(canvas.last_announcement, "Bee resized.")
+
+ def test_grip_drag_clamps_both_limits_without_shelving_or_snapping(self):
+ for delta, target in ((10000, ways.RESIZE_MAX), (-10000, ways.RESIZE_MIN)):
+ with self.subTest(target=target), mock.patch.object(diagram.AppKit, "NSCursor"):
+ _window, canvas = self.canvas()
+ canvas.on_layout_change = mock.Mock()
+ canvas.on_leave_out = mock.Mock()
+ event, point = self.start_resize(canvas)
+ canvas.convertPoint_fromView_.return_value = AppKit.NSMakePoint(point[0] + delta, point[1] + delta)
+ canvas.mouseDragged_(event)
+ self.assertIsNone(canvas.snap_preview())
+ canvas.mouseUp_(event)
+ self.assertEqual(canvas.tiles[BEE]["w"], target)
+ self.assertEqual(canvas.tiles[BEE]["h"], round(target * 100 / 160))
+ self.assertEqual((canvas.tiles[BEE]["x"], canvas.tiles[BEE]["y"]), (160, 0))
+ canvas.on_layout_change.assert_called_once_with(canvas.tiles, BEE, snap=False)
+ canvas.on_leave_out.assert_not_called()
+
+ def test_grip_visibility_on_selection_and_hover_and_read_only(self):
+ _window, canvas = self.canvas(selected=None)
+ self.assertTrue(canvas.resize_layers[BEE].isHidden())
+ frame = canvas._map()[0][BEE]
+ event = self.event(canvas, (frame[0] + frame[2] - 3, frame[1] + frame[3] - 3))
+ with mock.patch.object(diagram.AppKit, "NSCursor"):
+ canvas.mouseMoved_(event)
+ self.assertFalse(canvas.resize_layers[BEE].isHidden())
+ canvas._resize_cursor().set.assert_called()
+ canvas.mouseExited_(event)
+ self.assertTrue(canvas.resize_layers[BEE].isHidden())
+ canvas.selected = BEE
+ canvas._draw(False)
+ self.assertFalse(canvas.resize_layers[BEE].isHidden())
+ canvas.show_layout(canvas.tiles, canvas.states, canvas.labels, canvas.own_id, BEE, read_only=True)
+ self.assertTrue(canvas.resize_layers[BEE].isHidden())
+ self.assertIsNone(canvas._resize_hit(AppKit.NSMakePoint(frame[0] + frame[2] - 3, frame[1] + frame[3] - 3)))
+
+ def test_a_tile_inside_the_band_keeps_its_end_third_and_its_grip(self):
+ window, canvas = self.canvas()
+ tiles = {canvas.own_id: {"x": 0, "y": 0, "w": 160, "h": 100},
+ BEE: {"x": 160, "y": 0, "w": 4, "h": 100}}
+ window._atlas_layout_changed(tiles, BEE, snap=False)
+ canvas.show_layout(tiles, canvas.states, canvas.labels, canvas.own_id, BEE)
+ frames, _scale = canvas._map()
+ x, y, width, height = canvas._resize_rect(frames[BEE])
+ self.assertLessEqual(width, 5)
+ _peer, _third, _side, _start, end = next(segment for segment in canvas._third_segments(frames)
+ if segment[1] == "end")
+ band = AppKit.NSMakePoint(end[0], end[1] - 1)
+ self.assertEqual(canvas._third_hit(band), (BEE, "end"))
+ self.assertIsNone(canvas._resize_hit(band))
+ outside = AppKit.NSMakePoint(x + width + 6, y + height + 3)
+ self.assertIsNone(canvas._third_hit(outside))
+ self.assertEqual(canvas._resize_hit(outside), BEE)
+
+ def test_no_grip_for_shelved_or_other_machines_split_displays(self):
+ window, canvas = self.canvas()
+ canvas.tiles[BEE]["displays"] = {"main": {"x": 0, "y": 0, "w": 160, "h": 100}}
+ canvas.tiles[BEE]["display_offsets"] = {"main": {"x": 30, "y": 20}}
+ canvas._draw(False)
+ self.assertTrue(canvas.resize_layers[BEE].isHidden())
+ canvas.on_layout_change = mock.Mock()
+ canvas.keyDown_(self.event(canvas, (0, 0), flags=AppKit.NSEventModifierFlagOption))
+ canvas.on_layout_change.assert_not_called()
+ window._set_atlas_left_out(BEE, True)
+ self.assertNotIn(BEE, canvas.tiles)
+ self.assertNotIn(BEE, canvas.resize_layers)
+
+ def test_option_arrows_resize_one_eighth_and_keep_origin(self):
+ for key, dimensions in ((124, (180, 112)), (125, (180, 112)),
+ (123, (140, 88)), (126, (140, 88))):
+ with self.subTest(key=key):
+ _window, canvas = self.canvas()
+ event = self.event(canvas, (0, 0), key=key, flags=AppKit.NSEventModifierFlagOption)
+ canvas.keyDown_(event)
+ saved = self.store.current()["layout"][BEE]
+ self.assertEqual((saved["w"], saved["h"]), dimensions)
+ self.assertEqual((saved["x"], saved["y"]), (160, 0))
+ self.assertEqual(canvas.last_announcement, "Bee resized.")
+
+ def test_this_mac_can_resize_but_stays_fixed_in_position(self):
+ _window, canvas = self.canvas()
+ canvas.selected = canvas.own_id
+ canvas._draw(False)
+ canvas.keyDown_(self.event(canvas, (0, 0), key=123, flags=AppKit.NSEventModifierFlagOption))
+ saved = self.store.current()["layout"][canvas.own_id]
+ self.assertEqual(saved, {"x": 0, "y": 0, "w": 140, "h": 88})
+
+ def test_read_only_keyboard_and_unchanged_drag_do_not_commit(self):
+ _window, canvas = self.canvas(read_only=True)
+ canvas.on_layout_change = mock.Mock()
+ canvas.keyDown_(self.event(canvas, (0, 0), flags=AppKit.NSEventModifierFlagOption))
+ canvas.on_layout_change.assert_not_called()
+ _window, canvas = self.canvas()
+ canvas.on_layout_change = mock.Mock()
+ with mock.patch.object(diagram.AppKit, "NSCursor"):
+ event, _point = self.start_resize(canvas)
+ canvas.mouseUp_(event)
+ canvas.on_layout_change.assert_not_called()
+
+ def test_writable_profiles_grip_keeps_the_viewed_layout(self):
+ _window, canvas = self.canvas()
+ canvas.show_layout(canvas.tiles, canvas.states, canvas.labels, canvas.own_id,
+ BEE, machine_picker=True, read_only=False)
+ canvas.on_select = mock.Mock()
+ canvas.on_layout_change = mock.Mock()
+ with mock.patch.object(diagram.AppKit, "NSCursor"):
+ event, point = self.start_resize(canvas)
+ scale = canvas.dragging["scale"]
+ canvas.convertPoint_fromView_.return_value = AppKit.NSMakePoint(point[0] + 80 * scale, point[1])
+ canvas.mouseDragged_(event)
+ canvas.mouseUp_(event)
+ canvas.on_select.assert_not_called()
+ canvas.on_layout_change.assert_called_once_with(canvas.tiles, BEE, snap=False)
+ self.assertEqual((canvas.tiles[BEE]["w"], canvas.tiles[BEE]["h"]), (240, 150))
+
+ def test_local_split_tile_can_resize_and_preserves_scaled_offsets(self):
+ _window, canvas = self.canvas()
+ own = canvas.own_id
+ canvas.tiles[own]["display_offsets"] = {"main": {"x": 16, "y": 8}}
+ canvas.on_layout_change = mock.Mock()
+ canvas.on_select = mock.Mock()
+ with mock.patch.object(diagram.AppKit, "NSCursor"):
+ event, point = self.start_resize(canvas, own)
+ scale = canvas.dragging["scale"]
+ canvas.convertPoint_fromView_.return_value = AppKit.NSMakePoint(point[0] + 80 * scale, point[1])
+ canvas.mouseDragged_(event)
+ canvas.mouseUp_(event)
+ canvas.on_select.assert_not_called()
+ self.assertEqual(canvas.selected, own)
+ self.assertEqual(canvas.tiles[own]["display_offsets"], {"main": {"x": 24, "y": 12}})
+ canvas.on_layout_change.assert_called_once_with(canvas.tiles, own, snap=False)
+
+ def test_option_arrows_at_limits_do_not_commit_unchanged_size(self):
+ for target, key in ((ways.RESIZE_MIN, 123), (ways.RESIZE_MAX, 124)):
+ with self.subTest(target=target):
+ _window, canvas = self.canvas()
+ canvas.tiles[BEE] = ways.resize_tile(canvas.tiles[BEE], target)
+ canvas.on_layout_change = mock.Mock()
+ canvas.keyDown_(self.event(canvas, (0, 0), key=key, flags=AppKit.NSEventModifierFlagOption))
+ self.assertEqual(canvas.tiles[BEE]["w"], target)
+ canvas.on_layout_change.assert_not_called()
+
+ def test_small_tile_elides_name_and_keeps_full_tooltip_and_accessibility(self):
+ _window, canvas = self.canvas()
+ name = "A very long machine name that cannot fit"
+ canvas.labels[BEE] = name
+ canvas.tiles[BEE] = ways.resize_tile(canvas.tiles[BEE], ways.RESIZE_MIN)
+ canvas._draw(False)
+ title = canvas.label_for_tile[BEE]
+ self.assertEqual(title.string(), name)
+ self.assertEqual(title.truncationMode(), Quartz.kCATruncationEnd)
+ frame = canvas._title_rect(BEE, canvas._map()[0][BEE])
+ point = AppKit.NSMakePoint(frame[0] + 1, frame[1] + 1)
+ self.assertEqual(canvas.view_stringForToolTip_point_userData_(canvas, 0, point, 2), name)
+ element = next(child for child in canvas.accessibilityChildren() if child.key == BEE)
+ self.assertEqual(element.accessibilityLabel(), name)
+ self.assertIn("Option", element.accessibilityHelp())
+ self.assertIn("resize", canvas._description())
+
+ def test_off_hint_mentions_corner_resize_and_profiles_on_hint_is_preserved(self):
+ window, _canvas = self.canvas()
+ self.assertTrue(window.atlas_canvas_hint.text.endswith(" · drag a corner to resize"))
+ window.ways_switch._toggle()
+ self.assertEqual(window.atlas_canvas_hint.text,
+ "Click a machine to set its ways · Tab and Return pick one from the keyboard")
diff --git a/mac_app/tests/test_window_geometry.py b/mac_app/tests/test_window_geometry.py
index 1e2134e..0601bfa 100644
--- a/mac_app/tests/test_window_geometry.py
+++ b/mac_app/tests/test_window_geometry.py
@@ -2,6 +2,7 @@ import sys
import unittest
import logging
import threading
+import time
from pathlib import Path
from unittest import mock
@@ -9,6 +10,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import kvm_bridge_app
import settings_store
+from core import profiles
def offscreen_control_window():
@@ -23,7 +25,12 @@ def offscreen_control_window():
store = object.__new__(settings_store.SettingsStore)
store.lock = threading.RLock()
store._handed_token = token
- store._cache = store._complete({**store._fresh(), "peers": []})
+ store.profile_load_notes = set()
+ store._profile_load_notes_seen = set()
+ # The profile state a real read adds (SettingsStore._read), which the Crossing page needs.
+ settings, _notes = profiles.before_load({**store._fresh(), "peers": []})
+ store._cache, _changes = profiles.after_load(
+ store._complete(settings), platform="mac", capable=(), now=time.time(), app=settings_store.PROFILE_APP_VERSION)
store.save = mock.Mock(return_value=cfg)
logger = logging.getLogger("test-window-geometry")
from wake import WakingController
diff --git a/mac_app/tests/test_window_resize.py b/mac_app/tests/test_window_resize.py
index 20e8bba..92f9d5c 100644
--- a/mac_app/tests/test_window_resize.py
+++ b/mac_app/tests/test_window_resize.py
@@ -27,6 +27,35 @@ def measured_stack(vertical=True, spacing=10.0):
class WindowResizeTests(unittest.TestCase):
+ def test_expanded_earlier_ways_gives_spare_width_to_caption_without_ambiguity(self):
+ from core import crossing_state
+
+ control = offscreen_control_window()
+ control._select_page("crossing")
+ store = control.settings_store
+ store._cache = crossing_state.set_same_ways(
+ store.current(), True, platform="mac", now=1792067000)["settings"]
+ control._show_profiles()
+ control._toggle_earlier()
+ self.assertFalse(control.earlier_host.isHidden())
+ self.assertFalse(control.own_ways_module.view.isHidden())
+ self.assertTrue(control._earlier_pairs)
+ action_widths = {}
+ for width in (640, 1000, 1600, 640):
+ control.window.setFrame_display_(((100000, 100000), (width, 800)), False)
+ settle(control.window)
+ for index, pair in enumerate(control._earlier_pairs):
+ with self.subTest(width=width, pair=index):
+ for view in (pair.view, pair.first, pair.second):
+ self.assertFalse(view.isHiddenOrHasHiddenAncestor())
+ self.assertFalse(view.hasAmbiguousLayout())
+ before = view.frame()
+ view.exerciseAmbiguityInLayout()
+ self.assertEqual(view.frame(), before)
+ action_widths.setdefault(index, pair.second.frame().size.width)
+ self.assertAlmostEqual(pair.second.frame().size.width, action_widths[index], delta=1)
+ self.assertGreater(pair.first.frame().size.width, 0)
+
def test_page_breakpoint_jitter_keeps_the_current_typography(self):
control = offscreen_control_window()
control._apply_width(700)
diff --git a/mac_app/wake.py b/mac_app/wake.py
index d619765..2d7c938 100644
--- a/mac_app/wake.py
+++ b/mac_app/wake.py
@@ -8,6 +8,7 @@ import threading
from bridge import KVMController
from core import protocol
+from core.i18n import tr
from core.wol import WAKE_WINDOW_SECONDS, lookup_mac, mac_from_arp_output, magic_packet, parse_mac, send_magic_packet
__all__ = [
@@ -23,11 +24,11 @@ NOT_WOKEN_SUFFIX = " did not wake"
def waking_status(name):
- return f"Waking {name}…"
+ return tr("Waking {name}…").format(name=name)
def not_woken_status(name):
- return f"{name}{NOT_WOKEN_SUFFIX}"
+ return tr("{name} did not wake").format(name=name)
class WakingController(KVMController):
@@ -64,7 +65,7 @@ class WakingController(KVMController):
def _wake_name(self, peer=None):
peer = peer or self._in_question()
name = self._label(lambda entry: entry.get("id") == peer) if peer else None
- return name or self.peer_label or self.cfg.pc_name or self.cfg.host or "the other machine"
+ return name or self.peer_label or self.cfg.pc_name or self.cfg.host or tr("the other machine")
def _wake_address(self, peer):
"""`peer`'s (hardware address, host): its entry's; a Config-built controller's flat settings'."""
@@ -135,22 +136,22 @@ class WakingController(KVMController):
self.logger.warning("wake-on-LAN packet not sent: %s", exc)
self._waking = False
self.connection_status = not_woken_status(name)
- self._alert("Beamer", "Could not send the wake-up packet")
+ self._alert("Beamer", tr("Could not send the wake-up packet"))
return
self.logger.info("sent wake-on-LAN to %s", host)
- self._alert("Beamer", waking_status(name))
+ self._alert("Beamer", tr("Waking {name}…").format(name=name))
while not self.stop_event.wait(self.WAKE_POLL_SECONDS):
if self._awake(peer):
self._waking = False
self.logger.info("%s woke and connected", name)
- self._alert("Beamer", f"{name} is awake — switch again to send input")
+ self._alert("Beamer", tr("{name} is awake — switch again to send input").format(name=name))
return
if self.clock() - started >= WAKE_WINDOW_SECONDS:
break
self._waking = False
self.connection_status = not_woken_status(name)
self.logger.warning("%s did not answer within %.0fs of the wake-on-LAN packet", name, WAKE_WINDOW_SECONDS)
- self._alert("Beamer", not_woken_status(name))
+ self._alert("Beamer", tr("{name} did not wake").format(name=name))
def _peer_up(self, link, fields):
super()._peer_up(link, fields)
diff --git a/mac_app/widgets.py b/mac_app/widgets.py
index 9890d21..19ccb6b 100644
--- a/mac_app/widgets.py
+++ b/mac_app/widgets.py
@@ -19,6 +19,7 @@ import objc
import media_keys
import motion
import theme
+from core.i18n import N_, tr
from core.locale import americanise
from ignored_titles import is_modifier_release, recorded_entry
from key_codes import KEY_NAME_TO_CODE, PRINTABLE_KEY_FALLBACKS, SPECIAL_KEY_NAMES, key_cap, key_title
@@ -61,8 +62,11 @@ class SideBySide:
constraint.setActive_(True)
self.stacked_widths = [child.widthAnchor().constraintEqualToAnchor_(self.view.widthAnchor())
for child in (first, second)]
- for constraint in self.stacked_widths:
- constraint.setPriority_(1000)
+ # A capped button cannot fill a wider row; its cap must not shrink the whole module.
+ self.stacked_priorities = [489 if _width_cap(child) is not None else 1000
+ for child in (first, second)]
+ for constraint, priority in zip(self.stacked_widths, self.stacked_priorities):
+ constraint.setPriority_(priority)
AppKit.NSLayoutConstraint.activateConstraints_(self.stacked_widths)
self.view.setIdentifier_("side-by-side")
self._beside = False
@@ -88,8 +92,8 @@ class SideBySide:
if beside == self._beside:
return
self._beside = beside
- for constraint in self.stacked_widths:
- constraint.setPriority_(1 if beside else 1000)
+ for constraint, priority in zip(self.stacked_widths, self.stacked_priorities):
+ constraint.setPriority_(1 if beside else priority)
self.view.setOrientation_(
AppKit.NSUserInterfaceLayoutOrientationHorizontal if beside
else AppKit.NSUserInterfaceLayoutOrientationVertical
@@ -1289,7 +1293,7 @@ class MenuChoice:
self.popup = _autolayout(AppKit.NSPopUpButton.alloc().initWithFrame_pullsDown_(((0, 0), (0, 0)), False))
self.popup.setFont_(theme.font(theme.TYPE['body']))
self.popup.setAutoenablesItems_(False)
- self.popup.setAccessibilityLabel_('Match design with')
+ self.popup.setAccessibilityLabel_(tr('Match design with'))
self.view.addSubview_(self.popup)
# Native popup frames extend beyond their alignment rect by seven points.
pin(self.popup, self.view, (0, 4, 0, 4))
@@ -1352,7 +1356,7 @@ class Selector:
row = stack(vertical=False, spacing=0)
row.setDistribution_(AppKit.NSStackViewDistributionFillEqually)
self.halves = {}
- for side, title in (("mac", "Mac"), ("windows", "Windows")):
+ for side, title in (("mac", tr("Mac")), ("windows", tr("Windows"))):
half = box()
words = Label(title, theme.TYPE["eyebrow"], 700, "ink_3", tracking=theme.TRACKING["selector"], upper=True,
align=AppKit.NSTextAlignmentCenter)
@@ -1611,9 +1615,9 @@ class Ruler:
self.on_change(value)
-# Loaded if a config names them, never offered by the recorder, as on Windows: typing keys a
-# double-tap or a hold would take from every app.
-UNRECORDABLE_TRIGGERS = {"enter", "tab", "space", "backspace", "esc"}
+# Loaded if a config names them, never offered by the recorder: typing keys and input-method
+# toggles are unsuitable as a double-tap or hold trigger.
+UNRECORDABLE_TRIGGERS = {"enter", "tab", "space", "backspace", "esc", "hangul", "hanja"}
class KeyRecorder:
@@ -1622,23 +1626,28 @@ class KeyRecorder:
Recorded through a local event monitor rather than the event tap, so it works before either
Mac permission is granted."""
- RECORDING_TITLE = "Press a key…"
- HINT = "Click, then press the key"
- RECORDING_HINT = "Click again to cancel"
+ RECORDING_TITLE = N_("Press a key…")
+ HINT = N_("Click, then press the key")
+ RECORDING_HINT = N_("Click again to cancel")
- def __init__(self, value, on_change=None):
+ def __init__(self, value, on_change=None, *, hint=HINT, recording_title=RECORDING_TITLE,
+ recording_hint=RECORDING_HINT):
self.value = value
self.on_change = on_change
+ self.hint_text = hint
+ self.recording_title = recording_title
+ self.recording_hint = recording_hint
self.monitor = None
# The keycap's thicker bottom edge is the outer box showing through a 3pt gap.
self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])
- self.view.setAccessibilityLabel_(f"Shortcut key, {key_title(value)}")
+ # Translators: {key} is the key combination recorded by the person.
+ self.view.setAccessibilityLabel_(tr("Shortcut key, {key}").format(key=key_title(value)))
face = box("ground", radius=theme.RADIUS["keycap"] - 1)
self.view.addSubview_(face)
pin(face, self.view, (1, 1, 3, 1))
self.key = Label(key_title(value), theme.TYPE["keycap"], mono=True, tracking=-0.02, wrap=True)
squeeze(self.key.view)
- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight, wrap=True)
+ self.hint = Label(self.hint_text, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight, wrap=True)
line = stack(spacing=8)
line.addArrangedSubview_(self.key.view)
line.addArrangedSubview_(self.hint.view)
@@ -1649,14 +1658,15 @@ class KeyRecorder:
def set_value(self, value):
self.value = value
self.key.set(key_title(value))
- self.view.setAccessibilityLabel_(f"Shortcut key, {key_title(value)}")
+ # Translators: {key} is the key combination recorded by the person.
+ self.view.setAccessibilityLabel_(tr("Shortcut key, {key}").format(key=key_title(value)))
def _clicked(self):
if self.monitor is not None:
self._stop()
return
- self.key.set(self.RECORDING_TITLE, ink="signal")
- self.hint.set(self.RECORDING_HINT)
+ self.key.set(self.recording_title, ink="signal")
+ self.hint.set(self.recording_hint)
paint(self.view, "signal")
mask = AppKit.NSEventMaskKeyDown | AppKit.NSEventMaskFlagsChanged
self.monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(mask, self._recorded)
@@ -1680,26 +1690,31 @@ class KeyRecorder:
AppKit.NSEvent.removeMonitor_(self.monitor)
self.monitor = None
self.key.set(key_title(self.value), ink="ink")
- self.hint.set(self.HINT)
+ self.hint.set(self.hint_text)
paint(self.view, "edge")
class JumpKeyRecorder:
"""Records a modifier chord for a peer-specific local jump key."""
- HINT = "Click, then press a key combination"
+ HINT = N_("Click, then press a key combination")
- def __init__(self, value="", on_change=None, on_arm=None, compact=False):
+ def __init__(self, value="", on_change=None, on_arm=None, compact=False, *, hint=HINT,
+ recording_title=N_("Press a key combination…"), recording_hint=N_("Click again to cancel")):
self.value = value or ""
self.on_change = on_change
self.on_arm = on_arm
+ self.hint_text = hint
+ self.recording_title = recording_title
+ self.recording_hint = recording_hint
self.monitor = None
self.compact = compact
self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])
- self.view.setAccessibilityLabel_("Jump straight here key, " + self._title())
+ # Translators: {key} is the key combination recorded by the person.
+ self.view.setAccessibilityLabel_(tr("Jump straight here key, {key}").format(key=self._title()))
if compact:
self.key = Label("", theme.TYPE["small"], ink="ink_2", wrap=True)
- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", wrap=True)
+ self.hint = Label(self.hint_text, theme.TYPE["small"], ink="ink_3", wrap=True)
for label in (self.key, self.hint):
label.view.setTranslatesAutoresizingMaskIntoConstraints_(True)
self.view.addSubview_(label.view)
@@ -1710,7 +1725,7 @@ class JumpKeyRecorder:
pin(face, self.view, (1, 1, 3, 1))
self.key = Label(self._title(), theme.TYPE["body"], ink="ink_3", wrap=True)
squeeze(self.key.view)
- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentLeft, wrap=True)
+ self.hint = Label(self.hint_text, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentLeft, wrap=True)
self.line = stack(spacing=5)
self.line.addArrangedSubview_(self.key.view)
self.line.addArrangedSubview_(self.hint.view)
@@ -1724,7 +1739,7 @@ class JumpKeyRecorder:
symbols = {"ctrl": "⌃", "alt": "⌥", "shift": "⇧", "cmd": "⌘"}
parts = self.value.split("+")
title = "".join(symbols.get(part, part) for part in parts[:-1]) + " " + key_title(parts[-1])
- self.key.set(title.strip() if has_value else "Set a key", size=theme.TYPE["small"] if has_value else 12.5,
+ self.key.set(title.strip() if has_value else tr("Set a key"), size=theme.TYPE["small"] if has_value else 12.5,
ink=ink or ("ink" if has_value else "ink_2"), mono=has_value)
self.hint.view.setHidden_(True)
paint(self.view, "well" if has_value else None, "edge" if has_value else None, radius=4)
@@ -1738,21 +1753,22 @@ class JumpKeyRecorder:
def _title(self):
if not self.value:
- return "Choose a key combination"
+ return tr("Choose a key combination")
names = {"ctrl": "Control", "alt": "Option", "shift": "Shift", "cmd": "Command"}
return " ".join(names.get(part, key_title(part)) for part in self.value.split("+"))
def set_value(self, value):
self.value = value or ""
self._show_title()
- self.view.setAccessibilityLabel_("Jump straight here key, " + self._title())
+ # Translators: {key} is the key combination recorded for a machine.
+ self.view.setAccessibilityLabel_(tr("Jump straight here key, {key}").format(key=self._title()))
def _clicked(self):
if self.monitor is not None:
self._stop()
return
- self.key.set("Press a key combination…", size=theme.TYPE["body"], ink="signal", mono=False)
- self.hint.set("Click again to cancel")
+ self.key.set(self.recording_title, size=theme.TYPE["body"], ink="signal", mono=False)
+ self.hint.set(self.recording_hint)
paint(self.view, "signal")
if self.compact:
self.hint.view.setHidden_(False)
@@ -1797,7 +1813,7 @@ class JumpKeyRecorder:
AppKit.NSEvent.removeMonitor_(self.monitor)
self.monitor = None
self._show_title()
- self.hint.set(self.HINT)
+ self.hint.set(self.hint_text)
if not self.compact:
paint(self.view, "edge")
if was_armed and self.on_arm is not None:
@@ -1829,25 +1845,30 @@ class IgnoredRecorder:
that refusal. Recorded through a local event monitor, same as KeyRecorder, so it works before
either Mac permission is granted."""
- TITLE = "Add a key or button"
- RECORDING_TITLE = "Press a key or button…"
- HINT = "Click, then press it"
- RECORDING_HINT = "Click again to cancel"
+ TITLE = N_("Add a key or button")
+ RECORDING_TITLE = N_("Press a key or button…")
+ HINT = N_("Click, then press it")
+ RECORDING_HINT = N_("Click again to cancel")
- def __init__(self, trigger_code, on_recorded=None):
+ def __init__(self, trigger_code, on_recorded=None, *, title=TITLE, recording_title=RECORDING_TITLE,
+ hint=HINT, recording_hint=RECORDING_HINT):
self.trigger_code = trigger_code
self.on_recorded = on_recorded
+ self.title_text = title
+ self.recording_title = recording_title
+ self.hint_text = hint
+ self.recording_hint = recording_hint
self.monitor = None
self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])
- self.view.setAccessibilityLabel_("Add a key or button that stays on this Mac")
+ self.view.setAccessibilityLabel_(tr("Add a key or button that stays on this Mac"))
face = box("ground", radius=theme.RADIUS["keycap"] - 1)
self.view.addSubview_(face)
pin(face, self.view, (1, 1, 3, 1))
# Body size, unlike the shortcut's keycap: this is an action at the foot of a list, and at
# keycap size it outweighed the entries above it.
- self.title = Label(self.TITLE, theme.TYPE["body"], 600, wrap=True)
+ self.title = Label(self.title_text, theme.TYPE["body"], 600, wrap=True)
squeeze(self.title.view)
- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight, wrap=True)
+ self.hint = Label(self.hint_text, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight, wrap=True)
line = stack(spacing=8)
line.addArrangedSubview_(self.title.view)
line.addArrangedSubview_(self.hint.view)
@@ -1862,8 +1883,8 @@ class IgnoredRecorder:
if self.monitor is not None:
self._stop()
return
- self.title.set(self.RECORDING_TITLE, ink="signal")
- self.hint.set(self.RECORDING_HINT)
+ self.title.set(self.recording_title, ink="signal")
+ self.hint.set(self.recording_hint)
paint(self.view, "signal")
mask = (
AppKit.NSEventMaskKeyDown
@@ -1906,8 +1927,8 @@ class IgnoredRecorder:
if self.monitor is not None:
AppKit.NSEvent.removeMonitor_(self.monitor)
self.monitor = None
- self.title.set(self.TITLE, ink="ink")
- self.hint.set(self.HINT)
+ self.title.set(self.title_text, ink="ink")
+ self.hint.set(self.hint_text)
paint(self.view, "edge")
@@ -1956,7 +1977,7 @@ class CodeBoxes:
])
container.heightAnchor().constraintEqualToConstant_(48).setActive_(True)
control.setDelegate_(self.delegate)
- control.setAccessibilityLabel_(f"Digit {index + 1}")
+ control.setAccessibilityLabel_(tr("Digit {n}").format(n=index + 1))
self.view.addArrangedSubview_(container)
self.fields.append(control)
self._held = [""] * digits
@@ -2112,8 +2133,9 @@ class Sidebar:
self.dot_insets = []
for index, (key, name, symbol, *_rest) in enumerate(pages):
row = pressable(lambda key=key: self._choose(key), role=AppKit.NSAccessibilityRadioButtonRole)
+ name = tr(name)
row.setAccessibilityLabel_(name)
- row.setToolTip_(f"{name} ⌘{index + 1}")
+ row.setToolTip_(tr("{name} ⌘{key}").format(name=name, key=index + 1))
row.ring_inset = 2.0
row.sidebar_owner = self
row.heightAnchor().constraintEqualToConstant_(36).setActive_(True)
@@ -2264,7 +2286,8 @@ class Sidebar:
dot.setHidden_(tone is None)
if tone is not None:
paint(dot, tone)
- row.setAccessibilityLabel_(name if tone is None else f"{name}, needs attention")
+ # Translators: {name} is a settings page name.
+ row.setAccessibilityLabel_(name if tone is None else tr("{name}, needs attention").format(name=name))
class _Overlay(AppKit.NSView):
diff --git a/mac_app/windows_input.py b/mac_app/windows_input.py
index 71d9aed..f2b0a13 100644
--- a/mac_app/windows_input.py
+++ b/mac_app/windows_input.py
@@ -71,6 +71,7 @@ class WindowsInput:
arrangement_callback=self._on_arrangement,
settings_callback=self._on_settings,
paired_callback=self._on_paired,
+ link_callback=self._on_link,
announce=self._announce,
)
controller.responder = self.server
@@ -171,6 +172,8 @@ class WindowsInput:
state, and who else this Mac has, unless this Mac has a link of its own open to it (that
link carries them)."""
if self._outbound_up(peer):
+ if "profiles" in (self.server.caps_of(peer) or ()):
+ self._controller.send_desk_to(protocol.id_text(peer))
return []
text = protocol.id_text(peer)
entry = next((item for item in self._controller.book.peers() if item.get("id") == text), None)
@@ -187,11 +190,21 @@ class WindowsInput:
if entry.get("port") != 0:
self._controller.crossing_link_up(text)
caps = self.server.caps_of(peer) or frozenset()
+ self._controller.profiles_capable()
+ self._controller.reset_desk_peer(text)
+ if entry.get("port") != 0 and "profiles" in caps:
+ self._controller.send_desk_to(text)
if entry.get("port") != 0 and "settings" in caps and "layout" not in caps:
messages += [dict(m, data=settings_sync.for_capabilities(m.get("data", {}), caps))
for m in self._controller.announce() if m.get("type") == protocol.MSG_SETTINGS]
return messages
+ def _on_link(self, peer, up):
+ if up:
+ self._controller.profiles_capable()
+ if up or not self._outbound_up(peer):
+ self._controller.reset_desk_peer(protocol.id_text(peer))
+
def _on_arrangement(self, peer, read) -> None:
if self._arrangement_callback is None:
return
diff --git a/scripts/ui_audit/qt_audit.py b/scripts/ui_audit/qt_audit.py
index 9495de2..274efa5 100644
--- a/scripts/ui_audit/qt_audit.py
+++ b/scripts/ui_audit/qt_audit.py
@@ -340,6 +340,12 @@ def main():
kvm.sys = SimpleNamespace(platform=branch_platform, executable=sys.executable, frozen=False)
kvm.platform_parts.WAYLAND = args.platform == "linux-wayland"
kvm.OWN_PLATFORM = "windows" if args.platform == "windows" else "linux"
+ if args.platform == "windows" and not sys.platform.startswith("win"):
+ # The Windows page off Windows: the branch passes the Windows hook's seam callback, which
+ # this platform's capture has no use for.
+ native_hooks = kvm.capture_win.Hooks
+ kvm.capture_win = SimpleNamespace(**vars(kvm.capture_win))
+ kvm.capture_win.Hooks = lambda *callbacks, on_seam=None: native_hooks(*callbacks)
if args.platform != "windows":
kvm.firewall_win = linux_stand_ins.firewall
app_config.default_config_path = lambda: settings_path
diff --git a/tools/i18n_extract.py b/tools/i18n_extract.py
new file mode 100644
index 0000000..cacb1ed
--- /dev/null
+++ b/tools/i18n_extract.py
@@ -0,0 +1,309 @@
+"""Write locales/beamer.pot from the source, bring every locales/<code>.po in step, and check them.
+
+ python3 tools/i18n_extract.py # rewrite beamer.pot, add new strings to each .po, drop gone ones
+ python3 tools/i18n_extract.py --check # exit 1 if beamer.pot is stale or a translation breaks its {fields}
+ python3 tools/i18n_extract.py --check --complete # and on any untranslated string: before a release
+ python3 tools/i18n_extract.py --review it # write docs/i18n/it-review.html for a translator
+
+Standard library only. Strings are found by reading the source, never by importing it, so the
+tool runs anywhere, without AppKit or Qt: tr("..."), trn("...", "...", n), trc("context", "...")
+and N_("...").
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import html
+import re
+import sys
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+
+from core import i18n # noqa: E402
+
+
+SOURCES = ("core", "mac_app", "win_app")
+LOCALES = ROOT / "locales"
+TEMPLATE = LOCALES / "beamer.pot"
+FIELD = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)[^{}]*\}")
+HEADER = {
+ "Project-Id-Version": "Beamer",
+ "MIME-Version": "1.0",
+ "Content-Type": "text/plain; charset=UTF-8",
+ "Content-Transfer-Encoding": "8bit",
+}
+
+
+def source_files():
+ for folder in SOURCES:
+ for path in sorted((ROOT / folder).glob("*.py")):
+ yield path
+
+
+def _literal(node):
+ return node.value if isinstance(node, ast.Constant) and isinstance(node.value, str) else None
+
+
+def _branches(node) -> list[str]:
+ """The literal strings an argument can be: tr("Put back" if out else "Leave out") is two."""
+ if isinstance(node, ast.IfExp):
+ return _branches(node.body) + _branches(node.orelse)
+ text = _literal(node)
+ return [text] if text else []
+
+
+def extract(paths=None) -> dict:
+ """{(context, msgid, plural): {places: [file:line, ...], notes: [...]}} for every marked string, in source order."""
+ found: dict = {}
+ for path in paths or source_files():
+ text = path.read_text(encoding="utf-8")
+ lines = text.splitlines()
+ tree = ast.parse(text, str(path))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ name = node.func.id if isinstance(node.func, ast.Name) else node.func.attr if isinstance(node.func, ast.Attribute) else ""
+ args = [_literal(arg) for arg in node.args]
+ if name in ("tr", "N_") and node.args:
+ keys = [(None, text, None) for text in _branches(node.args[0])]
+ elif name == "trn" and len(args) >= 2 and args[0] and args[1]:
+ keys = [(None, args[0], args[1])]
+ elif name == "trc" and len(node.args) >= 2 and args[0]:
+ keys = [(args[0], text, None) for text in _branches(node.args[1])]
+ else:
+ continue
+ # The file, not the line: a line number would make the template stale on every edit above it.
+ where = path.relative_to(ROOT).as_posix()
+ note = _translator_note(lines, node.lineno)
+ for key in keys:
+ entry = found.setdefault(key, {"places": [], "notes": []})
+ if where not in entry["places"]:
+ entry["places"].append(where)
+ if note and note not in entry["notes"]:
+ entry["notes"].append(note)
+ return found
+
+
+def _translator_note(lines: list[str], lineno: int) -> str:
+ """The "# Translators: ..." comment block ending on the line above a call, if there is one."""
+ block, index = [], lineno - 2
+ while index >= 0 and lines[index].strip().startswith("#"):
+ block.insert(0, lines[index].strip().lstrip("#").strip())
+ index -= 1
+ for at, line in enumerate(block):
+ if line.startswith("Translators:"):
+ return " ".join([line[len("Translators:"):].strip()] + block[at + 1:])
+ return ""
+
+
+def _quote(text: str) -> str:
+ body = text.replace("\\", "\\\\").replace('"', '\\"').replace("\t", "\\t")
+ if "\n" not in body:
+ return f'"{body}"'
+ lines = body.split("\n")
+ parts = [f'"{line}\\n"' for line in lines[:-1]] + ([f'"{lines[-1]}"'] if lines[-1] else [])
+ return '""\n' + "\n".join(parts)
+
+
+def _key(entry) -> tuple:
+ return (entry.get("msgctxt"), entry["msgid"], entry.get("msgid_plural"))
+
+
+def render(entries: list[dict], header: dict) -> str:
+ out = ['msgid ""', 'msgstr ""']
+ out += [f'"{name}: {value}\\n"' for name, value in header.items()]
+ for entry in entries:
+ out.append("")
+ out += entry.get("comments", [])
+ if entry.get("flags"):
+ out.append("#, " + ", ".join(sorted(entry["flags"])))
+ if entry.get("msgctxt") is not None:
+ out.append("msgctxt " + _quote(entry["msgctxt"]))
+ out.append("msgid " + _quote(entry["msgid"]))
+ if entry.get("msgid_plural") is not None:
+ out.append("msgid_plural " + _quote(entry["msgid_plural"]))
+ for index, text in enumerate(entry["msgstr"]):
+ out.append(f"msgstr[{index}] " + _quote(text))
+ else:
+ out.append("msgstr " + _quote(entry["msgstr"][0] if entry["msgstr"] else ""))
+ return "\n".join(out) + "\n"
+
+
+def header_of(entries: list[dict]) -> dict:
+ for entry in entries:
+ if entry["msgid"] == "" and "msgctxt" not in entry:
+ lines = entry["msgstr"][0].split("\n") if entry["msgstr"] else []
+ return dict(line.split(": ", 1) for line in lines if ": " in line)
+ return {}
+
+
+def plural_count(header: dict) -> int:
+ match = re.search(r"nplurals\s*=\s*(\d+)", header.get("Plural-Forms", ""))
+ return int(match.group(1)) if match else 2
+
+
+def template_entries(found: dict) -> list[dict]:
+ entries = []
+ for (context, msgid, plural), seen in found.items():
+ entry = {"msgid": msgid, "msgstr": ["", ""] if plural else [""], "flags": set(),
+ "comments": ["#. " + note for note in seen["notes"]] + ["#: " + " ".join(seen["places"])]}
+ if "{" in msgid or (plural and "{" in plural):
+ entry["flags"].add("python-brace-format")
+ if context is not None:
+ entry["msgctxt"] = context
+ if plural is not None:
+ entry["msgid_plural"] = plural
+ entries.append(entry)
+ return entries
+
+
+def merge(template: list[dict], existing: list[dict], plurals: int) -> list[dict]:
+ """The template's entries in its order, each carrying the translation and translator comments
+ an existing .po already has; strings gone from the source are dropped (git keeps them)."""
+ known = {_key(entry): entry for entry in existing if entry["msgid"]}
+ merged = []
+ for entry in template:
+ old = known.get(_key(entry))
+ new = dict(entry, flags=set(entry["flags"]))
+ if "msgid_plural" in entry:
+ new["msgstr"] = list(old["msgstr"]) if old else [""] * plurals
+ else:
+ new["msgstr"] = list(old["msgstr"][:1]) if old else [""]
+ if old:
+ notes = [line for line in old["comments"] if not line.startswith(("#:", "#."))]
+ new["comments"] = notes + entry["comments"]
+ new["flags"] |= old["flags"] & {"fuzzy"}
+ merged.append(new)
+ return merged
+
+
+def problems(entries: list[dict], template: list[dict], plurals: int) -> list[str]:
+ """Every missing, empty or broken translation, as one line each."""
+ wanted = {_key(entry) for entry in template}
+ have = {_key(entry): entry for entry in entries if entry["msgid"]}
+ found = []
+ for key in wanted - have.keys():
+ found.append(f"missing: {key[1]!r}")
+ for key in have.keys() - wanted:
+ found.append(f"not in the source any more: {key[1]!r}")
+ for key, entry in have.items():
+ if key not in wanted:
+ continue
+ sources = [entry["msgid"]] + ([entry["msgid_plural"]] if "msgid_plural" in entry else [])
+ fields = set().union(*(set(FIELD.findall(text)) for text in sources))
+ if "msgid_plural" in entry and len(entry["msgstr"]) != plurals:
+ found.append(f"wrong number of plural forms: {entry['msgid']!r}")
+ for text in entry["msgstr"]:
+ if not text.strip():
+ found.append(f"untranslated: {entry['msgid']!r}")
+ break
+ if set(FIELD.findall(text)) - fields:
+ found.append(f"unknown {{field}} in translation of {entry['msgid']!r}: {text!r}")
+ missing = fields - set(FIELD.findall(text))
+ # A singular may leave out {n} ("un computer"); nothing else may go.
+ if missing - ({"n", "count"} if "msgid_plural" in entry else set()):
+ found.append(f"translation of {entry['msgid']!r} drops {sorted(missing)}: {text!r}")
+ try:
+ text.format(**{name: "x" for name in FIELD.findall(text)})
+ except (ValueError, IndexError, KeyError) as error:
+ found.append(f"translation of {entry['msgid']!r} does not format ({error}): {text!r}")
+ return sorted(found)
+
+
+def catalogues():
+ return sorted(path for path in LOCALES.glob("*.po"))
+
+
+def review_page(code: str, entries: list[dict]) -> str:
+ """One page a translator can read and mark up without the code: English, translation, where
+ it shows, and any note for them."""
+ name = i18n.LANGUAGES.get(code, code)
+ rows, new = [], 0
+ for entry in entries:
+ if not entry["msgid"]:
+ continue
+ english = entry["msgid"] + (f"\n— plural —\n{entry['msgid_plural']}" if "msgid_plural" in entry else "")
+ target = "\n— plural —\n".join(entry["msgstr"]) if "msgid_plural" in entry else (entry["msgstr"] or [""])[0]
+ notes = [line[2:].strip() for line in entry["comments"] if line.startswith("#.") or line.startswith("# ")]
+ places = " ".join(line[2:].strip() for line in entry["comments"] if line.startswith("#:"))
+ context = entry.get("msgctxt") or ""
+ # A "# New in <version>: awaiting ..." comment marks a string added since the translator last checked.
+ fresh = any(line.startswith("# New in ") for line in entry["comments"])
+ new += fresh
+ rows.append(
+ ("<tr class=new>" if fresh else "<tr>") + "<td class=n>{n}</td><td>{en}{ctx}</td><td lang={code}>{it}</td><td class=note>{note}<div class=where>{where}</div></td></tr>".format(
+ n=len(rows) + 1, en=html.escape(english).replace("\n", "<br>"),
+ ctx=f"<div class=ctx>({html.escape(context)})</div>" if context else "",
+ code=code, it=html.escape(target).replace("\n", "<br>"),
+ note=html.escape(" ".join(notes)), where=html.escape(places)))
+ return f"""<!doctype html>
+<html lang=en-GB><meta charset=utf-8><title>Beamer — {html.escape(name)} for checking</title>
+<style>
+body{{font:15px/1.45 -apple-system,"Segoe UI",system-ui,sans-serif;margin:2rem auto;max-width:72rem;padding:0 1rem;color:#1d1d1f}}
+h1{{font-size:1.4rem}} p{{max-width:46rem}}
+table{{border-collapse:collapse;width:100%}} td,th{{border-top:1px solid #ddd;padding:.45rem .6rem;vertical-align:top;text-align:left}}
+th{{position:sticky;top:0;background:#fff}} td.n{{color:#888;width:2.5rem}} td:nth-child(2),td:nth-child(3){{width:36%}}
+.ctx,.where{{color:#888;font-size:.8rem}} .note{{font-size:.85rem;color:#555}}
+code{{background:#f3f3f3;padding:0 .2rem}} tr.new td{{background:#fff6d6}}
+</style>
+<h1>Beamer in {html.escape(name)} — every string, for checking</h1>
+<p>Left is the English Beamer shows today; right is the {html.escape(name)} draft. Words in braces, like
+<code>{{name}}</code>, are filled in by Beamer (a machine's name, a number) and must stay as they are,
+though they can move within the sentence. To correct a line, quote its number with the fix, or edit
+<code>locales/{code}.po</code> directly. {len(rows)} strings.{f" The {new} on a yellow background are new and not yet checked." if new else ""}</p>
+<table><tr><th>#</th><th>English</th><th>{html.escape(name)}</th><th>Note · where it shows</th></tr>
+{chr(10).join(rows)}
+</table>
+"""
+
+
+def main() -> int:
+ # Catalogue lines carry "…" and "→": a Windows console's legacy code page cannot print them.
+ sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace")
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--check", action="store_true")
+ parser.add_argument("--complete", action="store_true", help="with --check: fail on any untranslated string too")
+ parser.add_argument("--review", metavar="CODE")
+ options = parser.parse_args()
+
+ template = template_entries(extract())
+ pot = render(template, dict(HEADER, **{"Language": "en_GB"}))
+ if options.review:
+ path = LOCALES / f"{options.review}.po"
+ out = ROOT / "docs" / "i18n" / f"{options.review}-review.html"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(review_page(options.review, i18n.parse_po(path.read_text(encoding="utf-8"))), encoding="utf-8")
+ print(out.relative_to(ROOT))
+ return 0
+ if options.check:
+ # A string not yet translated shows in English, so only --complete (a release) fails on
+ # one; a stale template or a translation that breaks its {fields} always fails.
+ failed, pending = [], []
+ if not TEMPLATE.exists() or TEMPLATE.read_text(encoding="utf-8") != pot:
+ failed.append(f"{TEMPLATE.relative_to(ROOT)} is stale: run python3 tools/i18n_extract.py")
+ for path in catalogues():
+ entries = i18n.parse_po(path.read_text(encoding="utf-8"))
+ for line in problems(entries, template, plural_count(header_of(entries))):
+ soft = line.startswith(("missing:", "untranslated:", "not in the source any more:"))
+ (pending if soft and not options.complete else failed).append(f"{path.relative_to(ROOT)}: {line}")
+ print("\n".join(failed + pending) or f"{len(template)} strings, catalogues complete")
+ if pending and not failed:
+ print(f"{len(pending)} waiting for translation; they show in English until then")
+ return 1 if failed else 0
+
+ LOCALES.mkdir(exist_ok=True)
+ TEMPLATE.write_text(pot, encoding="utf-8")
+ for path in catalogues():
+ entries = i18n.parse_po(path.read_text(encoding="utf-8"))
+ header = header_of(entries)
+ path.write_text(render(merge(template, entries, plural_count(header)), header), encoding="utf-8")
+ print(f"{len(template)} strings")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/phone_vectors.json b/tools/phone_vectors.json
index 0fb1901..0114745 100644
--- a/tools/phone_vectors.json
+++ b/tools/phone_vectors.json
@@ -1974,6 +1974,8 @@
"f7",
"f8",
"f9",
+ "hangul",
+ "hanja",
"home",
"insert",
"launch_app1",
@@ -2048,6 +2050,8 @@
"114": "volume_down",
"115": "volume_up",
"119": "pause",
+ "122": "hangul",
+ "123": "hanja",
"125": "cmd",
"126": "cmd_r",
"127": "menu",
diff --git a/tools/x11_proof.py b/tools/x11_proof.py
index 963cb6a..98632fa 100644
--- a/tools/x11_proof.py
+++ b/tools/x11_proof.py
@@ -159,6 +159,12 @@ def proof_injection_and_capture():
keys, _, _ = seen.take(0.15)
check(f"modifier {pressed} reads back as {named}", [(k[0], k[1]) for k in keys] == [(named, True), (named, False)], keys)
+ for name, code in (("hangul", 122), ("hanja", 123)):
+ inject_x11.inject_key(name, True)
+ inject_x11.inject_key(name, False)
+ keys, _, _ = seen.take(0.15)
+ check(f"{name} reads back as itself on evdev {code}", [k[:3] for k in keys] == [(name, True, code), (name, False, code)], keys)
+
inject_x11.inject_key("q", True, us="q")
inject_x11.inject_key("q", False, us="q")
keys, _, _ = seen.take()
diff --git a/uk.co.kalkman.beamer.json b/uk.co.kalkman.beamer.json
index 2d91ae0..da4ea48 100644
--- a/uk.co.kalkman.beamer.json
+++ b/uk.co.kalkman.beamer.json
@@ -97,7 +97,7 @@
"buildsystem": "simple",
"build-commands": [
"install -d /app/share/beamer",
- "cp -r core win_app VERSION /app/share/beamer/",
+ "cp -r core win_app locales VERSION /app/share/beamer/",
"install -Dm755 flatpak/beamer /app/bin/beamer",
"install -Dm644 tools/flatpak_import_probe.py /app/share/beamer/tools/flatpak_import_probe.py",
"install -Dm644 tools/wayland_proof.py /app/share/beamer/tools/wayland_proof.py",
@@ -112,6 +112,7 @@
"sources": [
{"type": "dir", "path": "core", "dest": "core", "skip": ["tests", "__pycache__"]},
{"type": "dir", "path": "win_app", "dest": "win_app", "skip": ["tests", "__pycache__", ".venv", "build", "dist", "Output"]},
+ {"type": "dir", "path": "locales", "dest": "locales", "skip": ["beamer.pot"]},
{"type": "dir", "path": "flatpak", "dest": "flatpak"},
{"type": "file", "path": "tools/flatpak_import_probe.py", "dest": "tools"},
{"type": "file", "path": "tools/wayland_proof.py", "dest": "tools"},
diff --git a/win_app/app_config.py b/win_app/app_config.py
index ac625e6..15bbacf 100644
--- a/win_app/app_config.py
+++ b/win_app/app_config.py
@@ -14,6 +14,8 @@ import hashlib
import json
import logging
import os
+import shutil
+import sys
import tempfile
import threading
import time
@@ -26,12 +28,32 @@ from core import ignored
from core import peerlist
from core import protocol
from core import receiver
+from core import i18n
from core import return_edge
from core import ways, crossing_state
+from core import profiles
from core.pairing import local_address_towards
import tokens
LOGGER = logging.getLogger(__name__)
+_PROFILE_LOAD_NOTES = {}
+
+
+def load_notes(path: Path) -> list:
+ """Consume notices discovered while loading this file, without storing UI flags in it."""
+ with SETTINGS_LOCK:
+ return sorted(_PROFILE_LOAD_NOTES.pop(Path(path).resolve(), set()))
+
+
+def _remember_profile_notes(path, notes):
+ if "older_version" in notes:
+ _PROFILE_LOAD_NOTES.setdefault(Path(path).resolve(), set()).add("older_version")
+
+try:
+ PROFILE_APP_VERSION = (Path(getattr(sys, "_MEIPASS", None) or Path(__file__).resolve().parent.parent)
+ / "VERSION").read_text().strip()
+except OSError:
+ PROFILE_APP_VERSION = profiles.APP_VERSION
# Today's two styles and five colours, then every crossing effect and colour pack in effects.py.
@@ -103,6 +125,7 @@ class Config:
check_updates: bool = True
# Every address the window shows is hidden.
hide_addresses: bool = False
+ language: str = "auto"
# Same on all machines: the Crossing and Design pages kept in step with the Mac's, and the unix
# seconds of the last change to that or to a shared value; see settings_sync.
same_on_both: bool = False
@@ -146,6 +169,10 @@ class Config:
# Only the machine in use shows a pointer: this PC's while it drives another, and after a driver
# lets go of it until it moves (core/idle_pointer). This machine's own choice, never shared.
hide_idle_pointer: bool = True
+ # Linux on Wayland: a key combination bound through the desktop's GlobalShortcuts portal sends
+ # input out while it is at home, where the double-tap cannot be seen. Off until chosen, since
+ # turning it on asks the desktop's permission. This machine's own choice, never shared.
+ home_shortcut: 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 = ""
@@ -238,12 +265,16 @@ def validate_config(config: Config) -> None:
raise ConfigError(f"modifier_style must be one of: {', '.join(MODIFIER_STYLES)}")
if not isinstance(config.block_while_dragging, bool):
raise ConfigError("block_while_dragging must be true or false")
+ if not isinstance(config.language, str) or (config.language != "auto" and config.language not in i18n.LANGUAGES):
+ raise ConfigError("language must be auto or a supported language code")
if not isinstance(config.hold_full_screen, bool):
raise ConfigError("hold_full_screen must be true or false")
if not isinstance(config.show_in_tray, bool):
raise ConfigError("show_in_tray must be true or false")
if not isinstance(config.hide_idle_pointer, bool):
raise ConfigError("hide_idle_pointer must be true or false")
+ if not isinstance(config.home_shortcut, bool):
+ raise ConfigError("home_shortcut must be true or false")
if not isinstance(config.mac_hardware_address, str):
raise ConfigError("mac_hardware_address must be text")
if not isinstance(config.crossing_methods, list) or any(
@@ -365,6 +396,7 @@ def config_from_dict(raw: dict) -> Config:
allow_mac_to_drive=raw.get("allow_mac_to_drive", True),
check_updates=raw.get("check_updates", True),
hide_addresses=raw.get("hide_addresses", False),
+ language=raw.get("language", "auto"),
same_on_both=raw.get("same_on_both", False),
same_set_at=_stamp(raw.get("same_set_at", 0)),
same_groups=raw.get("same_groups", ["crossing", "design", "shortcut", "names"]
@@ -391,6 +423,7 @@ def config_from_dict(raw: dict) -> Config:
hold_full_screen=raw.get("hold_full_screen", False),
show_in_tray=raw.get("show_in_tray", True),
hide_idle_pointer=raw.get("hide_idle_pointer", True),
+ home_shortcut=raw.get("home_shortcut", 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 "",
@@ -449,6 +482,7 @@ def config_to_dict(config: Config) -> dict:
"allow_mac_to_drive": config.allow_mac_to_drive,
"check_updates": config.check_updates,
"hide_addresses": config.hide_addresses,
+ "language": config.language,
"same_on_both": config.same_on_both,
"same_set_at": int(config.same_set_at),
"same_groups": list(config.same_groups),
@@ -474,6 +508,7 @@ def config_to_dict(config: Config) -> dict:
"hold_full_screen": config.hold_full_screen,
"show_in_tray": config.show_in_tray,
"hide_idle_pointer": config.hide_idle_pointer,
+ "home_shortcut": config.home_shortcut,
"mac_hardware_address": config.mac_hardware_address,
"mac_host": config.mac_host,
"mac_return_edge": config.mac_return_edge,
@@ -673,6 +708,7 @@ def learn_peer_id(settings: dict, index: int, peer_id: str) -> None:
def _write_json(path: Path, payload: dict) -> None:
"""A new file beside the old, then a rename over it."""
+ _backup_before_profile_upgrade(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary_path = None
try:
@@ -714,8 +750,11 @@ def load_settings(path: Path) -> dict:
legacy = _read_object(legacy_config_path(path))
if not path.exists():
settings = migrate(legacy)
+ settings, notes = profiles.before_load(settings)
+ _remember_profile_notes(path, notes)
settings = crossing_state.migrate(settings, "pc")["settings"]
settings = crossing_state.paired(settings, platform="pc", own_displays={}, now=time.time())["settings"]
+ settings, _ = profiles.after_load(settings, platform="pc", now=time.time(), app=PROFILE_APP_VERSION)
_write_json(path, settings)
return settings
settings = _read_object(path)
@@ -725,6 +764,9 @@ def load_settings(path: Path) -> dict:
or not all(isinstance(entry, dict) for entry in settings["peers"] + settings["zones"])
):
raise SettingsFileError(f"{path} is not a version {SCHEMA} Beamer settings file, and is left as it is")
+ original = copy.deepcopy(settings)
+ settings, notes = profiles.before_load(settings)
+ _remember_profile_notes(path, notes)
if any("way_back_by" in entry and not isinstance(entry["way_back_by"], str) for entry in settings["peers"]):
raise SettingsFileError(f"{path} has a peer way_back_by that is not text, and is left as it is")
if any("in_use" in entry and not isinstance(entry["in_use"], bool) for entry in settings["peers"]):
@@ -768,7 +810,12 @@ def load_settings(path: Path) -> dict:
settings = outcome["settings"]
if remigrated:
settings = crossing_state.paired(settings, platform="pc", own_displays={}, now=time.time())["settings"]
- if remigrated or phones_repaired or intents_repaired or outcome["changed"]:
+ settings, _ = profiles.after_load(settings, platform="pc", now=time.time(), app=PROFILE_APP_VERSION)
+ if (remigrated or phones_repaired or intents_repaired or outcome["changed"] or "older_version" in notes
+ or _without_profile_state(settings) != _without_profile_state(original)
+ # Once the file holds profile state, a load's reconcile (its status, an older Beamer's
+ # edit folded in) is saved; only an upgrade waits for the first real save.
+ or "crossing_own" in original and settings != original):
_write_json(path, settings)
return settings
@@ -946,6 +993,46 @@ def write_settings(path: Path, settings: dict) -> None:
_write_json(path, settings)
+def _without_profile_state(settings: dict) -> dict:
+ result = copy.deepcopy(settings)
+ for name in ("crossing_own", "crossing_desk", "crossing_own_unreadable", "crossing_desk_unreadable",
+ "_crossing_profiles_upgrade_pending"):
+ result.pop(name, None)
+ return result
+
+
+def _backup_before_profile_upgrade(path: Path) -> None:
+ """Keep the exact schema-6 source before the first save of a profile-migrated file."""
+ backup = path.with_name("settings.json.before-1.5.5")
+ if backup.exists():
+ return
+ try:
+ source = path.read_bytes()
+ except FileNotFoundError:
+ return
+ except OSError:
+ raise
+ raw = json.loads(source)
+ if not isinstance(raw, dict) or raw.get("schema") != SCHEMA:
+ return
+ own, desk = raw.get("crossing_own"), raw.get("crossing_desk")
+ if profiles._local_shape(own, desk):
+ return
+ temporary_path = None
+ try:
+ descriptor, temporary_name = tempfile.mkstemp(prefix=f".{backup.name}.", dir=path.parent)
+ os.close(descriptor)
+ temporary_path = Path(temporary_name)
+ shutil.copyfile(path, temporary_path)
+ try:
+ os.link(temporary_path, backup)
+ except FileExistsError:
+ pass
+ finally:
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
+
+
def set_own(path: Path, **fields) -> None:
"""Writes fields that belong to this PC rather than to a peer (`port`, `hide_addresses`) straight into the
settings, which works with no machine paired and leaves every peer entry as it is."""
diff --git a/win_app/build.spec b/win_app/build.spec
index 8f3fb58..bf057c3 100644
--- a/win_app/build.spec
+++ b/win_app/build.spec
@@ -12,7 +12,9 @@ analysis = Analysis(
# The repo root, for core/, which both apps share.
pathex=[str(source_dir), str(source_dir.parent)],
binaries=[],
- datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"), (str(source_dir.parent / "VERSION"), ".")],
+ datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"),
+ (str(source_dir.parent / "VERSION"), ".")]
+ + [(str(path), "locales") for path in (source_dir.parent / "locales").glob("*.po")],
# core/effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see; they are
# among core_modules. segno is imported inside a try in qr_code.py, so it is named here as well.
hiddenimports=["nacl", "_cffi_backend", "segno", "win32com.client", "pythoncom", "pywintypes"] + app_modules + core_modules,
diff --git a/win_app/capture_portal.py b/win_app/capture_portal.py
index 34275c8..bc78d90 100644
--- a/win_app/capture_portal.py
+++ b/win_app/capture_portal.py
@@ -67,6 +67,7 @@ from capture_x11 import ( # noqa: F401 (the same evdev names and titles as X11
from core import keytable
from core import return_edge as crossing
import desktop_portal
+import inject_portal
import portal
LOGGER = logging.getLogger(__name__)
@@ -93,6 +94,11 @@ HOME_AGAIN_SECONDS = 0.5
# ei events that arrive before the portal's Activated signal says which barrier, held until it does.
EARLY_MAX = 64
EARLY_SECONDS = 1.0
+# A shortcut push must trigger capture before this deadline expires.
+PUSH_SECONDS = 1.5
+PUSH_INSET_PX = 4
+PUSH_STEPS = 6
+PUSH_STEP_PX = 24
# libei's scroll is in the desktop's pixels; mutter and weston send 10 for one wheel click.
PIXELS_PER_NOTCH = 10.0
# evdev's button codes, as X numbers them for capture_x11's table.
@@ -411,6 +417,7 @@ class Hooks:
self._ei_factory = ei or _ei_receiver
self._tokens = tokens or portal.TokenStore("input-capture")
self._clock = clock
+ self._push_lock = threading.Lock()
self._whole_edges = linux_desktop.desktop() == "kde"
self._unmatched_displays_logged = set()
self._thread: Optional[threading.Thread] = None
@@ -427,9 +434,11 @@ class Hooks:
self._reset()
def _reset(self) -> None:
+ self._pending_push = None
self._activation: Optional[int] = None
self._press: Optional[Press] = None
self._away = False
+ self._last_wall: Optional[str] = None
self._home_since: Optional[float] = None
self._early: List[tuple] = []
self._early_at = 0.0
@@ -461,6 +470,42 @@ class Hooks:
def barriers_from(self, models: Callable[[], list]) -> None:
self._models = models
+ def push_through(self, models, on_captured, on_failed, timeout=PUSH_SECONDS) -> bool:
+ """Push the local pointer through one of the target peer's placed barriers."""
+ with self._push_lock:
+ if self._session is None or self._activation is not None or self._pending_push is not None:
+ return False
+ display_map = desktop_portal.display_map()
+ selected = barriers(models, self._zones, display_map=display_map,
+ warn_unmatched=self._warn_unmatched_display)
+ if not selected:
+ return False
+ wall, (x1, y1, x2, y2) = selected[0]
+ if wall == "right":
+ start = (x1 - PUSH_INSET_PX, (y1 + y2) // 2)
+ elif wall == "left":
+ start = (x1 + PUSH_INSET_PX, (y1 + y2) // 2)
+ elif wall == "bottom":
+ start = ((x1 + x2) // 2, y1 - PUSH_INSET_PX)
+ else:
+ start = ((x1 + x2) // 2, y1 + PUSH_INSET_PX)
+ with self._push_lock:
+ if self._session is None or self._activation is not None or self._pending_push is not None:
+ return False
+ pending = (self._clock() + timeout, wall, on_captured, on_failed)
+ self._pending_push = pending
+
+ # Checked when the session runs it, which can be after the deadline though _tick has not
+ # yet cleared the push.
+ def wanted() -> bool:
+ with self._push_lock:
+ return self._pending_push is pending and self._clock() <= pending[0]
+
+ nx, ny = _NORMAL[wall]
+ moves = [(nx * PUSH_STEP_PX, ny * PUSH_STEP_PX) for _ in range(PUSH_STEPS)]
+ inject_portal.push(*start, moves, wanted)
+ return True
+
@property
def grabbed(self) -> bool:
return self._activation is not None
@@ -651,6 +696,7 @@ class Hooks:
barrier = options.get("barrier_id")
# 0 is a push that met two barriers at once (a corner's two walls); the pointer says which.
wall = self._walls.get(barrier) if barrier else self._wall_at(point)
+ self._last_wall = wall
self._activation = activation
self._frame = []
desktop_portal.set_captured(True)
@@ -667,6 +713,19 @@ class Hooks:
return
self._press = Press(wall, point, self._zones, self._clock)
desktop_portal.note_position(*self._press.point)
+ with self._push_lock:
+ pending = self._pending_push
+ if pending is not None and pending[0] >= self._clock() and pending[1] == wall:
+ self._pending_push = None
+ else:
+ pending = None
+ if pending is not None:
+ try:
+ pending[2]()
+ except Exception:
+ LOGGER.exception("The shortcut push capture callback failed; letting input go")
+ self._let_go(self._press.point)
+ return
early, self._early = self._early, []
for event, sequence in early:
if self._current(sequence):
@@ -721,6 +780,35 @@ class Hooks:
if self.on_home is not None:
self.on_home()
+ def _consume_shake_home(self) -> bool:
+ # The hooks are handed the sender's bound callbacks rather than the sender, so its one-shot
+ # "this way home was a shake" flag is reached through on_motion's owner.
+ sender = getattr(self._on_motion, "__self__", None)
+ consume = getattr(sender, "_consume_shake_home", None)
+ return bool(consume()) if callable(consume) else False
+
+ def _shake_release_point(self, point: Tuple[int, int]) -> Tuple[int, int]:
+ wall = self._last_wall
+ candidates = [rect for edge, rect in self._placed if edge == wall]
+ if not candidates:
+ return point
+ x, y = point
+
+ def distance(rect):
+ x1, y1, x2, y2 = rect
+ return max(x1 - x, 0, x - x2) + max(y1 - y, 0, y - y2)
+
+ x1, y1, x2, y2 = min(candidates, key=distance)
+ if wall == "left":
+ x = x1 + 24
+ elif wall == "right":
+ x = x2 - 24
+ elif wall == "top":
+ y = y1 + 24
+ elif wall == "bottom":
+ y = y2 - 24
+ return x, y
+
def _let_go(self, point: Tuple[int, int]) -> None:
"""Release at `point`. Input counts as held until the Release has gone, and a Release that
fails ends the session, whose closing lets go of input whatever else has failed."""
@@ -757,6 +845,17 @@ class Hooks:
return False
def _tick(self) -> None:
+ with self._push_lock:
+ pending = self._pending_push
+ if pending is not None and self._clock() > pending[0]:
+ self._pending_push = None
+ else:
+ pending = None
+ if pending is not None:
+ try:
+ pending[3]()
+ except Exception:
+ LOGGER.exception("The shortcut push failure callback failed")
session = self._session
if self._activation is None:
# Input away with nothing captured (a switch that passed input_held() just before a
@@ -784,6 +883,9 @@ class Hooks:
if self._away_wanted():
self._home_since = None
return
+ if self._consume_shake_home():
+ self._let_go(self._shake_release_point(desktop_portal.cursor_position()))
+ return
now = self._clock()
if self._home_since is None:
self._home_since = now
@@ -821,6 +923,11 @@ class Hooks:
self._walls = {index + 1: wall for index, (wall, _position) in enumerate(placed) if index + 1 not in failed}
if failed:
LOGGER.warning("The desktop refused %d of %d edge barriers", len(failed), len(placed))
+ # Once per session: without it the log cannot tell a capture waiting on the desktop's
+ # dialog from one that is ready and simply not crossed yet (14-10-2026, Fedora).
+ if session.enabled and not getattr(session, "announced", False):
+ session.announced = True
+ LOGGER.info("Input capture is ready: %d of %d edge barriers placed", len(placed) - len(failed), len(placed))
def _warn_unmatched_display(self, display: str) -> None:
if display in self._unmatched_displays_logged:
diff --git a/win_app/capture_win.py b/win_app/capture_win.py
index 24f107e..e1ee887 100644
--- a/win_app/capture_win.py
+++ b/win_app/capture_win.py
@@ -182,7 +182,8 @@ def internal_seam_position(point, monitors, display_map, models):
# What the Keyboard page calls a recorded key, in Windows' own words.
VK_TITLES: Dict[int, str] = {
- 0x08: "Backspace", 0x09: "Tab", 0x0D: "Enter", 0x13: "Pause", 0x14: "Caps Lock", 0x1B: "Esc",
+ 0x08: "Backspace", 0x09: "Tab", 0x0D: "Enter", 0x13: "Pause", 0x14: "Caps Lock", 0x15: "Han/Yeong",
+ 0x19: "Hanja", 0x1B: "Esc",
0x20: "Space", 0x21: "Page Up", 0x22: "Page Down", 0x23: "End", 0x24: "Home", 0x25: "Left",
0x26: "Up", 0x27: "Right", 0x28: "Down", 0x2C: "Print Screen", 0x2D: "Insert", 0x2E: "Delete",
0x5B: "Left Windows", 0x5C: "Right Windows", 0x5D: "Menu", 0x6A: "Num *", 0x6B: "Num +",
@@ -252,6 +253,8 @@ VK_TO_NAME: Dict[int, str] = {
0x0D: "enter",
0x13: "pause",
0x14: "caps_lock",
+ 0x15: "hangul",
+ 0x19: "hanja",
0x1B: "esc",
0x20: "space",
0x21: "page_up",
@@ -308,7 +311,7 @@ for _index in range(13, 21):
# System and browser keys are never the trigger: they are what the stays-on-this-PC list is for.
# The undifferentiated 0x10-0x12 never reach the hook.
-NOT_TRIGGER_VKS = {0x10, 0x11, 0x12} | set(range(0xA6, 0xB8))
+NOT_TRIGGER_VKS = {0x10, 0x11, 0x12, 0x15, 0x19} | set(range(0xA6, 0xB8))
# Loaded if a config names them, never offered by the recorder, as on the Mac: Backspace, Tab,
# Enter, Esc and Space are typing keys a double-tap or a hold would take from every app, and
# Windows gives a window no key-down for Print Screen, so it cannot be recorded at all.
diff --git a/win_app/capture_x11.py b/win_app/capture_x11.py
index de7e58a..5b09fb2 100644
--- a/win_app/capture_x11.py
+++ b/win_app/capture_x11.py
@@ -125,6 +125,7 @@ KEYPAD_NAMES = {0xFF95: "home", 0xFF96: "left", 0xFF97: "up", 0xFF98: "right", 0
_TITLES = {
"shift": "Left Shift", "shift_r": "Right Shift", "ctrl": "Left Ctrl", "ctrl_r": "Right Ctrl",
"alt": "Left Alt", "alt_r": "Right Alt", "cmd": "Left Super", "cmd_r": "Right Super", "caps_lock": "Caps Lock",
+ "hangul": "Han/Yeong", "hanja": "Hanja",
"backspace": "Backspace", "tab": "Tab", "enter": "Enter", "esc": "Esc", "space": "Space", "delete": "Delete",
"insert": "Insert", "home": "Home", "end": "End", "page_up": "Page Up", "page_down": "Page Down", "left": "Left",
"right": "Right", "up": "Up", "down": "Down", "menu": "Menu", "print_screen": "Print Screen", "pause": "Pause",
@@ -144,7 +145,7 @@ VK_TITLES[96] = "Num Enter"
# trigger also reaches apps at home, so Print Screen stays out as on Windows.
NOT_TRIGGER_VKS = {code for code, physical in keytable.EVDEV_NAMES.items()
if physical.startswith(("media_", "volume_", "browser_", "brightness_", "mic_"))
- or physical in ("search", "mail", "calculator")}
+ or physical in ("search", "mail", "calculator", "hangul", "hanja")}
UNRECORDABLE_TRIGGER_VKS = {code for code, physical in keytable.EVDEV_NAMES.items()
if physical in ("backspace", "tab", "enter", "esc", "space", "print_screen")}
diff --git a/win_app/crossing_ledger.py b/win_app/crossing_ledger.py
index ec935ad..da79a08 100644
--- a/win_app/crossing_ledger.py
+++ b/win_app/crossing_ledger.py
@@ -6,7 +6,8 @@ from PySide6.QtWidgets import (QAccessibleWidget, QCheckBox, QFrame, QGraphicsOp
QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit, QPushButton,
QSizePolicy, QStyle, QStyleOptionButton, QVBoxLayout, QWidget)
-from core import ways
+from core.i18n import N_, tr
+from core import profiles, ways
import theme
import widgets
@@ -41,8 +42,9 @@ def _quiet_style(button):
button.setStyleSheet(f"QPushButton {{ color: {theme.colour('ink_2')}; background: transparent; border: 0; padding: 0; font-size: {round(theme.TYPE['note'])}px; font-weight: 400; text-align: left; }} QPushButton:focus {{ border: 1px solid {theme.colour('signal')}; }}")
-SIDE_NAMES = {"left": "Left", "right": "Right", "top": "Top", "bottom": "Bottom"}
-CORNER_TITLES = {corner: corner.replace("_", " ").capitalize() for corner in ways.CORNERS}
+SIDE_NAMES = {"left": N_("Left"), "right": N_("Right"), "top": N_("Top"), "bottom": N_("Bottom")}
+CORNER_TITLES = {"top_left": N_("Top left"), "top_right": N_("Top right"),
+ "bottom_left": N_("Bottom left"), "bottom_right": N_("Bottom right")}
CHIP_HEIGHT = 26
@@ -179,8 +181,11 @@ class _Chip(QPushButton):
segment.setEnabled(segments_enabled)
title = ways.part_names(self.side)[third]
lit = edge_on and third in picked
- segment.setAccessibleName(f"{SIDE_NAMES[self.side]} edge, {title.lower()} third, {'on' if lit else 'off'}")
- segment.setToolTip(f"{title} third: click to {'leave it out' if lit else 'turn it on'}")
+ segment.setAccessibleName(tr("{side} edge, {third} third, {state}").format(
+ side=tr(SIDE_NAMES[self.side]),
+ third=tr(ways.PART_NAMES_LOWER[title.lower()]), state=tr("on" if lit else "off")))
+ segment.setToolTip(tr("{third} third: click to {action}").format(
+ third=tr(title), action=tr("leave it out" if lit else "turn it on")))
segment.blockSignals(True)
segment.setChecked(lit)
segment.blockSignals(False)
@@ -273,6 +278,8 @@ class _Chip(QPushButton):
elif kind == "held":
border, ink, icon = _tone("rule"), _tone("ink_3"), _tone("ink_3")
painter.setOpacity(.45)
+ if not live:
+ border, fill, ink, icon, dashed = _tone("rule"), None, _tone("ink_3"), _tone("ink_3"), False
if pressed:
border, fill, ink, dashed = _tone("signal"), _mix("signal_dim", "signal", .12), _tone("ink"), False
elif hover:
@@ -299,7 +306,7 @@ class _Chip(QPushButton):
bar_x = self.width() - 10 - 22
for index, third in enumerate(ways.PARTS):
on = self.edge_on and third in self.picked
- stroke = QPen(_tone("signal" if on else "edge"), 3 if on else 1.5)
+ stroke = QPen(_tone("ink_3" if not live else "signal" if on else "edge"), 3 if on else 1.5)
stroke.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(stroke)
start = bar_x + 1 + index * 7.3
@@ -340,31 +347,34 @@ class EdgeChips(QWidget):
lock = "Left out: Put back to change its ways"
for side in ways.EDGES:
chip, kind = self.chips[side], self.kinds[side]
- title = SIDE_NAMES[side]
+ title = tr(SIDE_NAMES[side])
if kind == "unavailable" or left_out and kind in ("free", "held"):
# A left-out row shows only the ways it keeps.
chip.hide()
continue
- held_by = labels.get(sides[side].get("by"), "Another machine") if kind == "held" else ""
+ held_by = labels.get(sides[side].get("by"), tr("Another machine")) if kind == "held" else ""
if kind == "contact":
- answer = "turn it off" if edge_on else "turn it on"
- chip.set_state("contact", title, edge_on, lock if left_out else f"{title} edge: touches {name}; click to {answer}",
- f"{title} edge, touches {name}, {'on' if edge_on else 'off'}", edge_on, picked,
+ answer = tr("turn it off" if edge_on else "turn it on")
+ chip.set_state("contact", title, edge_on,
+ tr("Left out: Put back to change its ways") if left_out else tr("{side} edge: touches {name}; click to {action}").format(side=title, name=name, action=answer),
+ tr("{side} edge, touches {name}, {state}").format(side=title, name=name, state=tr("on" if edge_on else "off")), edge_on, picked,
enabled=not left_out, segments_enabled=not left_out)
elif kind == "on":
- chip.set_state("on", f"{title}, wraps", True, lock if left_out else f"{title} edge wraps round to {name}; click to remove",
- f"{title} edge, wraps round, on", enabled=not left_out)
+ chip.set_state("on", tr("{side}, wraps").format(side=title), True, tr("Left out: Put back to change its ways") if left_out else tr("{side} edge wraps round to {name}; click to remove").format(side=title, name=name),
+ tr("{side} edge, wraps round, on").format(side=title), enabled=not left_out)
elif kind == "kept":
- chip.set_state("kept", f"{title}, wraps", False,
- lock if left_out else (f"{title} edge wraps round to {name} once Edge is on; click to turn Edge on" if not edge_on
- else f"{title} edge: none of it is free just now; click to remove"),
- f"{title} edge, wraps round, kept", enabled=not left_out)
+ tip = tr("Left out: Put back to change its ways") if left_out else (
+ tr("{side} edge wraps round to {name} once Edge is on; click to turn Edge on").format(side=title, name=name) if not edge_on
+ else tr("{side} edge: none of it is free just now; click to remove").format(side=title))
+ chip.set_state("kept", tr("{side}, wraps").format(side=title), False, tip,
+ tr("{side} edge, wraps round, kept").format(side=title), enabled=not left_out)
elif kind == "held":
- chip.set_state("held", f"{title}, {held_by}", False, f"{title} edge: {held_by}'s",
- f"{title} edge, held by {held_by}", enabled=False)
+ chip.set_state("held", tr("{side}, {name}").format(side=title, name=held_by), False,
+ tr("{side} edge: {name}'s").format(side=title, name=held_by),
+ tr("{side} edge, held by {name}").format(side=title, name=held_by), enabled=False)
else:
- chip.set_state("free", title, False, lock if left_out else f"{title} edge: click to wrap round to {name}",
- f"{title} edge, wraps round, off", enabled=not left_out)
+ chip.set_state("free", title, False, tr("Left out: Put back to change its ways") if left_out else tr("{side} edge: click to wrap round to {name}").format(side=title, name=name),
+ tr("{side} edge, wraps round, off").format(side=title), enabled=not left_out)
chip.show()
self.updateGeometry()
@@ -379,8 +389,10 @@ class _CornerButton(QPushButton):
super().__init__()
self.corner, self.kind = corner, "unavailable"
self.setCheckable(True)
+ # No min-width or min-height in the sheet: a style sheet's minimum replaces the one
+ # setFixedSize sets, and the grid then squashed the square to 28 x 19 and clipped the bracket.
self.setFixedSize(28, 28)
- self.setStyleSheet("QPushButton { padding: 0; min-width: 0; min-height: 0; }")
+ self.setStyleSheet("QPushButton { padding: 0; }")
self.clicked.connect(lambda _checked=False: callback(self.corner))
def nextCheckState(self):
@@ -426,6 +438,8 @@ class _CornerButton(QPushButton):
border, bracket, dashed = _tone("signal", .35), _tone("signal", .5), False
elif kind == "unavailable":
opacity = .4
+ if not self.isEnabled():
+ border, fill, bracket, dashed, opacity = _tone("rule"), None, _tone("ink_3"), False, 1.0
if pressed:
border, fill, dashed = _tone("signal"), _mix("signal_dim", "signal", .12), False
bracket = _tone("ink")
@@ -441,7 +455,10 @@ class _CornerButton(QPushButton):
painter.drawRoundedRect(QRectF(self.rect()).adjusted(.5, .5, -.5, -.5), 5, 5)
vertical, horizontal = self.corner.split("_")
dx, dy = (1 if horizontal == "left" else -1), (1 if vertical == "top" else -1)
- x, y = (10 if horizontal == "left" else 18), (10 if vertical == "top" else 18)
+ # The 7 px bracket sits centred in the square, its corner towards the square's corner.
+ inset_x, inset_y = (self.width() - 7) / 2, (self.height() - 7) / 2
+ x = inset_x if horizontal == "left" else self.width() - inset_x
+ y = inset_y if vertical == "top" else self.height() - inset_y
stroke = QPen(bracket, 1.8)
stroke.setCapStyle(Qt.PenCapStyle.RoundCap)
stroke.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
@@ -479,17 +496,17 @@ class CornerGrid(QWidget):
lock = "Left out: Put back to change its ways"
for corner, button in self.buttons.items():
kind = corners.get(corner, {}).get("state", "unavailable")
- title = CORNER_TITLES[corner]
+ title = tr(CORNER_TITLES[corner])
if kind == "held":
- holder = labels.get(corners[corner].get("by"), "Another machine")
- button.set_state("held", lock if left_out else f"{holder}'s corner", f"{title} corner, held by {holder}", False)
+ holder = labels.get(corners[corner].get("by"), tr("Another machine"))
+ button.set_state("held", tr("Left out: Put back to change its ways") if left_out else tr("{name}'s corner").format(name=holder), tr("{corner} corner, held by {name}").format(corner=title, name=holder), False)
elif kind == "unavailable":
- button.set_state("unavailable", lock if left_out else f"Place {name} beside this {platform_word} first",
- f"{title} corner, unavailable", False)
+ button.set_state("unavailable", tr("Left out: Put back to change its ways") if left_out else tr("Place {name} beside this {platform} first").format(name=name, platform=platform_word),
+ tr("{corner} corner, unavailable").format(corner=title), False)
else:
on = kind == "on"
- button.set_state(kind, lock if left_out else f"{title} corner: click to turn it {'off' if on else 'on'}",
- f"{title} corner, {'on' if on else 'off'}", not left_out)
+ button.set_state(kind, tr("Left out: Put back to change its ways") if left_out else tr("{corner} corner: click to turn it {state}").format(corner=title, state=tr("off" if on else "on")),
+ tr("{corner} corner, {state}").format(corner=title, state=tr("on" if on else "off")), not left_out)
class _Name(QLabel):
@@ -537,7 +554,7 @@ class _Jump(widgets.JumpKeyRecorder):
def set_value(self, value):
super().set_value(value)
if not value and not self.armed:
- self.key.setText("Set a key")
+ self.key.setText(tr("Set a key"))
self._reflect_style()
def _reflect_style(self):
@@ -589,7 +606,7 @@ class _Cycle(QCheckBox):
# Machine, Edges, Corners, Keys: minimum width and stretch, the spec's minmax(132, 1.3fr), minmax(220, 2fr), 70, minmax(128, 1fr).
-COLUMNS = (("Machine", 132, 13), ("Edges", 220, 20), ("Corners", 70, 0), ("Keys", 128, 10))
+COLUMNS = ((N_("Machine"), 132, 13), (N_("Edges"), 220, 20), (N_("Corners"), 70, 0), (N_("Keys"), 128, 10))
class LedgerRow(QFrame):
@@ -599,6 +616,7 @@ class LedgerRow(QFrame):
def __init__(self, peer, owner):
super().__init__()
self.peer, self.owner, self.selected, self.narrow = peer, owner, False, None
+ self.remote = self.remote_mac = self.read_only = False
self.setProperty("ledger_role", "row")
self.setProperty("vernier", "plain")
self.setMinimumWidth(0)
@@ -635,7 +653,7 @@ class LedgerRow(QFrame):
self.edit.hide()
self.edit.returnPressed.connect(self.save_name)
self.edit.installEventFilter(self)
- self.rename_hint = widgets.label("Return saves, Escape cancels · Only on this PC", "small", wrap=True)
+ self.rename_hint = widgets.label(tr("Return saves, Escape cancels · Only on this PC"), "small", wrap=True)
self.rename_hint.hide()
machine.addWidget(self.name)
machine.addWidget(self.edit)
@@ -643,8 +661,8 @@ class LedgerRow(QFrame):
machine.addLayout(status_line)
actions = QHBoxLayout()
actions.setSpacing(10)
- self.rename = _quiet("Rename", self.begin_rename)
- self.leave = _quiet("Leave out", lambda: owner._canvas_left_out(peer, not self.left_out))
+ self.rename = _quiet(tr("Rename"), self.begin_rename)
+ self.leave = _quiet(tr("Leave out"), lambda: owner._canvas_left_out(peer, not self.left_out))
actions.addWidget(self.rename)
actions.addWidget(self.leave)
actions.addStretch()
@@ -655,7 +673,7 @@ class LedgerRow(QFrame):
edges.setContentsMargins(0, 0, 0, 0)
edges.setSpacing(2)
edges.addWidget(self.edge_chips, 0, Qt.AlignmentFlag.AlignTop)
- self.edge_note = widgets.label("Place it on the map", "small", wrap=True)
+ self.edge_note = widgets.label(tr("Place it on the map"), "small", wrap=True)
edges.addWidget(self.edge_note, 0, Qt.AlignmentFlag.AlignTop)
edges.addStretch()
self.corner_grid = CornerGrid(peer, owner)
@@ -668,30 +686,53 @@ class LedgerRow(QFrame):
keys.setSpacing(4)
self.cycle = _Cycle()
self.cycle.setFont(theme.font(theme.TYPE["body"]))
- self.cycle.setToolTip("In the shortcut's cycle")
+ self.cycle.setToolTip(tr("In the shortcut's cycle"))
self.cycle.toggled.connect(lambda on: owner._set_shortcut_cycle(peer, on))
keys.addWidget(self.cycle)
jump = QHBoxLayout()
jump.setSpacing(5)
- jump.addWidget(widgets.label("Jump", "small"))
+ jump.addWidget(widgets.label(tr("Jump"), "small"))
self.jump = _Jump(lambda value: owner._ledger_jump(peer, value), owner._jump_arming)
jump.addWidget(self.jump, 0, Qt.AlignmentFlag.AlignLeft)
- self.clear = _quiet("Clear", lambda: owner._ledger_jump(peer, ""))
- self.clear.setAccessibleName("Clear jump key")
+ self.clear = _quiet(tr("Clear"), lambda: owner._ledger_jump(peer, ""))
+ self.clear.setAccessibleName(tr("Clear jump key"))
jump.addWidget(self.clear)
jump.addStretch()
keys.addLayout(jump)
keys.addStretch()
+ self.notch_cell = QWidget(self)
+ self.notch_cell.setProperty("vernier", "plain")
+ self.notch_cell.setProperty("ledger_role", "cell")
+ notch_layout = QVBoxLayout(self.notch_cell)
+ notch_layout.setContentsMargins(0, 0, 0, 0)
+ notch_layout.setSpacing(4)
+ self.notch = QCheckBox(tr("Notch"))
+ self.notch.toggled.connect(lambda on: owner._write_ways(peer=peer, notch=on))
+ notch_layout.addWidget(self.notch)
+ self.notch_return = QCheckBox(tr("Return here"))
+ self.notch_return.toggled.connect(lambda on: owner._write_ways(peer=peer, notch_return=on))
+ notch_layout.addWidget(self.notch_return)
+ notch_layout.addStretch()
self.effect = QGraphicsOpacityEffect(self)
self.setGraphicsEffect(self.effect)
self.reflow(False)
- def reflow(self, narrow):
- if self.narrow == narrow:
+ def reflow(self, narrow, remote=None, remote_mac=None):
+ remote = self.remote if remote is None else remote
+ remote_mac = self.remote_mac if remote_mac is None else remote_mac
+ if (self.narrow, self.remote, self.remote_mac) == (narrow, remote, remote_mac):
return
- self.narrow = narrow
- for cell in self.cells:
+ self.narrow, self.remote, self.remote_mac = narrow, remote, remote_mac
+ for cell in (*self.cells, self.notch_cell):
self.grid.removeWidget(cell)
+ self.keys.setVisible(not remote)
+ self.notch_cell.setVisible(remote_mac)
+ self.rename.setVisible(not remote)
+ self.leave.setVisible(not remote)
+ if remote:
+ self.jump.cancel()
+ self.cancel_name()
+ cells = self.cells[:3] + ([self.notch_cell] if remote_mac else [] if remote else [self.keys])
for col in range(4):
self.grid.setColumnMinimumWidth(col, 0)
self.grid.setColumnStretch(col, 0)
@@ -699,17 +740,20 @@ class LedgerRow(QFrame):
self.grid.addWidget(self.machine, 0, 0, 1, 2)
self.grid.addWidget(self.edge, 1, 0, 1, 2)
self.grid.addWidget(self.corner_cell, 2, 0)
- self.grid.addWidget(self.keys, 2, 1)
+ if len(cells) == 4:
+ self.grid.addWidget(cells[3], 2, 1)
self.grid.setColumnMinimumWidth(0, COLUMNS[2][1])
self.grid.setColumnStretch(1, 1)
else:
- for index, (cell, (_title, minimum, stretch)) in enumerate(zip(self.cells, COLUMNS)):
+ for index, (cell, (_title, minimum, stretch)) in enumerate(zip(cells, COLUMNS)):
self.grid.addWidget(cell, 0, index)
self.grid.setColumnMinimumWidth(index, minimum)
self.grid.setColumnStretch(index, stretch)
def reflect(self, settings, entry, name, side, linked, selected, trigger, labels, legacy="", reach=None):
- seen = (theme.is_dark(), id(settings), repr(entry), name, side, linked, selected, trigger, repr(labels), legacy, repr(reach))
+ self.read_only = bool(getattr(self.owner, "_profile_read_only", lambda: False)())
+ seen = (theme.is_dark(), id(settings), repr(entry), name, side, linked, selected, trigger,
+ repr(labels), legacy, repr(reach), self.remote, self.remote_mac, self.read_only)
if seen == getattr(self, "_reflection_seen", None):
return
self._reflection_seen = seen
@@ -721,14 +765,15 @@ class LedgerRow(QFrame):
self.machine.setAccessibleName(name)
self.name.set_name(name)
self.name.setStyleSheet(f"color: {theme.colour('ink' if linked and not self.left_out else 'ink_2')}")
- platform = {"windows": "Windows", "macos": "macOS", "linux": "Linux"}.get(entry.get("platform"), "Computer")
- status = "Left out" if self.left_out else "Linked" if linked else "Offline, ways kept"
- self.status.setText(legacy or f"{platform} · {status}")
+ platform = {"windows": N_("Windows"), "macos": N_("macOS"), "linux": N_("Linux")}.get(
+ entry.get("platform"), N_("Computer"))
+ status = tr("Left out") if self.left_out else tr("Linked") if linked else tr("Offline, ways kept")
+ self.status.setText(legacy if legacy else tr("{platform} · {status}").format(platform=tr(platform), status=status))
self.status.setStyleSheet(f"color: {theme.colour('amber' if legacy else 'ink_3')}")
self.dot.setStyleSheet(f"background: {theme.colour('amber' if legacy else 'signal' if linked and not self.left_out else 'ink_3')}; border-radius: 3px;")
- self.status.setAccessibleDescription("Linked" if linked else status)
- self.leave.setText("Put back" if self.left_out else "Leave out")
- self.leave.setToolTip("Left out machines stay paired and linked. The shortcut, menu and clipboard still reach them." if self.left_out else "Leave this machine out of crossings")
+ self.status.setAccessibleDescription(tr("Linked") if linked else status)
+ self.leave.setText(tr("Put back" if self.left_out else "Leave out"))
+ self.leave.setToolTip(tr("Left out machines stay paired and linked. The shortcut, menu and clipboard still reach them." if self.left_out else "Leave this machine out of crossings"))
held = ways.ways(settings, self.peer)
picked = ways.picked_thirds(held["methods"], held["parts"])
edge_on = bool(picked)
@@ -740,13 +785,28 @@ class LedgerRow(QFrame):
contact = next((edge for edge, value in sides.items() if value.get("state") == "contact"), "")
self.edge_chips.reflect(sides, name, labels, edge_on, picked if edge_on else (), contact, self.left_out)
self.edge_note.setVisible(not self.edge_chips.any_shown())
- self.corner_grid.reflect(corners, name, labels, "PC", self.left_out)
+ self.corner_grid.reflect(corners, name, labels, tr("Mac") if self.remote_mac else tr("PC"), self.left_out)
+ self.edge_chips.setEnabled(not self.read_only)
+ self.corner_grid.setEnabled(not self.read_only)
+ self.notch_cell.setEnabled(not self.read_only and not self.left_out)
+ notch_on = "notch" in held["methods"]
+ for check, value in ((self.notch, notch_on),
+ (self.notch_return, entry.get("notch_return", False))):
+ check.blockSignals(True)
+ check.setChecked(bool(value))
+ check.blockSignals(False)
+ self.notch.setAccessibleName(tr("Notch, on") if notch_on else tr("Notch, off"))
+ self.notch.setToolTip(tr("Push into the notch to reach {name}").format(name=name))
+ self.notch_return.setVisible(notch_on)
+ self.notch_return.setAccessibleName(tr("Return through the notch, on") if self.notch_return.isChecked()
+ else tr("Return through the notch, off"))
+ self.notch_return.setToolTip(tr("Coming back from {name}, arrive just below the notch").format(name=name))
self.cycle.blockSignals(True)
self.cycle.setText(trigger)
self.cycle.setChecked(entry.get("shortcut_cycle", True))
self.cycle.blockSignals(False)
self.jump.set_value(entry.get("jump_key", ""))
- self.jump.setToolTip(f"Press {self.jump.key.text()} to send input to {name}; press again to bring it home." if self.jump.value else f"Choose a key combination to jump to {name} and back.")
+ self.jump.setToolTip(tr("Press {key} to send input to {name}; press again to bring it home.").format(key=self.jump.key.text(), name=name) if self.jump.value else tr("Choose a key combination to jump to {name} and back.").format(name=name))
self.clear.setVisible(bool(self.jump.value))
self.effect.setOpacity(.5 if self.left_out or not linked else 1)
self.update()
@@ -756,6 +816,8 @@ class LedgerRow(QFrame):
self.reflect(*self._reflection)
def begin_rename(self):
+ if self.remote or self.read_only:
+ return
self.edit.setText(self.entry.get("label") or self.entry.get("name") or "")
self.name.hide()
self.edit.show()
@@ -764,7 +826,8 @@ class LedgerRow(QFrame):
self.edit.selectAll()
def save_name(self):
- self.owner._rename_canvas_peer(self.peer, self.edit.text().strip()[:64])
+ if not self.remote and not self.read_only:
+ self.owner._rename_canvas_peer(self.peer, self.edit.text().strip()[:64])
self.cancel_name()
def cancel_name(self):
@@ -800,7 +863,7 @@ class CrossingLedger(QWidget):
self.owner, self.rows, self.narrow = owner, {}, False
self.setProperty("ledger_role", "table")
self.setProperty("vernier", "plain")
- self.setAccessibleName("How each machine is reached")
+ self.setAccessibleName(tr("How each machine is reached"))
self.setMinimumWidth(0)
self.column = QVBoxLayout(self)
self.column.setContentsMargins(0, 0, 0, 0)
@@ -811,9 +874,9 @@ class CrossingLedger(QWidget):
head.setContentsMargins(12, 0, 0, 8)
head.setHorizontalSpacing(16)
for index, (title, minimum, stretch) in enumerate(COLUMNS):
- label = widgets.Eyebrow(title)
+ label = widgets.Eyebrow(tr(title))
label.setProperty("ledger_role", "columnheader")
- label.setAccessibleName(title)
+ label.setAccessibleName(tr(title))
head.addWidget(label, 0, index)
head.setColumnMinimumWidth(index, minimum)
head.setColumnStretch(index, stretch)
@@ -829,6 +892,19 @@ class CrossingLedger(QWidget):
def reflect(self, settings, layout, labels, chosen, live, trigger, legacy=None, reach=None):
self.header.setStyleSheet(f"border-bottom: 1px solid {theme.colour('rule')};")
+ remote = bool(getattr(self.owner, "_profile_remote", lambda: False)())
+ if remote and hasattr(self.owner, "_crossing_view_settings"):
+ settings = self.owner._crossing_view_settings()
+ remote_mac = (remote and hasattr(self.owner, "_profile_settings")
+ and hasattr(self.owner, "_profile_machine")
+ and profiles.view_platform(self.owner._profile_settings(), self.owner._profile_machine()) == "mac")
+ head = self.header.layout()
+ last_header = head.itemAtPosition(0, 3).widget()
+ last_header.setVisible(not remote or remote_mac)
+ last_header.setText(tr("Notch") if remote_mac else tr("Keys"))
+ last_header.setAccessibleName(tr("Notch") if remote_mac else tr("Keys"))
+ head.setColumnMinimumWidth(3, COLUMNS[3][1] if not remote or remote_mac else 0)
+ head.setColumnStretch(3, COLUMNS[3][2] if not remote or remote_mac else 0)
entries = {p["id"]: p for p in settings.get("peers", [])}
order = sorted(entries, key=lambda p: (0, layout[p]["x"], layout[p]["y"]) if p in layout else (1, 0, 0))
for peer in self.rows.keys() - entries.keys():
@@ -843,14 +919,14 @@ class CrossingLedger(QWidget):
if row is None:
row = LedgerRow(peer, self.owner)
self.rows[peer] = row
- row.reflow(self.narrow)
+ row.reflow(self.narrow, remote, remote_mac)
if self.column.indexOf(row) != index + 1:
self.column.insertWidget(index + 1, row)
own = layout.get(settings.get("machine_id"))
tile = layout.get(peer)
contact = ways._rect_contact(own, tile) if own and tile else None
side = contact[0] if contact and contact[0] != "corner" else ""
- row.reflect(settings, entries[peer], labels.get(peer, "Other machine"), side, live(peer), chosen == peer, trigger, labels, (legacy or {}).get(peer, ""), (reach or {}).get(peer))
+ row.reflect(settings, entries[peer], labels.get(peer, tr("Other machine")), side, live(peer), chosen == peer, trigger, labels, (legacy or {}).get(peer, ""), (reach or {}).get(peer))
self.setVisible(bool(entries))
def resizeEvent(self, event):
diff --git a/win_app/desktop_win.py b/win_app/desktop_win.py
index fae0728..58cf9d7 100644
--- a/win_app/desktop_win.py
+++ b/win_app/desktop_win.py
@@ -101,6 +101,10 @@ _refused_under = [None]
def set_cursor_position(x: int, y: int) -> None:
+ set_cursor_position_with_callback(x, y)
+
+
+def set_cursor_position_with_callback(x: int, y: int, on_placed=None, *, place_if_current=None) -> None:
"""SetCursorPos returns FALSE with no error code, and SendInput is dropped
in silence, whenever Windows' UIPI puts the foreground window above
Beamer's integrity level, so a SendInput move is no fallback. The one such
@@ -109,14 +113,25 @@ def set_cursor_position(x: int, y: int) -> None:
else in front is named in the log."""
_require()
x, y = int(x), int(y)
- if user32.SetCursorPos(x, y):
- _refused_under[0] = None
+ def place():
+ if user32.SetCursorPos(x, y):
+ _refused_under[0] = None
+ if on_placed is not None:
+ on_placed()
+ return True
+ return False
+
+ # Only the warp and its completion share the receiver's ownership lock. Service restart
+ # scheduling stays outside it, and every deferred retry validates its visit again.
+ result = place_if_current(place) if place_if_current is not None else place()
+ if result is not False:
return
error = ctypes.get_last_error()
import input_injector
# Placed through this function again, so a refusal after the restart is logged too.
- if input_injector.release_gameinput_foreground(after=lambda: set_cursor_position(x, y)):
+ if input_injector.release_gameinput_foreground(after=lambda: set_cursor_position_with_callback(
+ x, y, on_placed, place_if_current=place_if_current)):
return
blocker = input_injector.foreground_class()
# A hold at the return edge lands here on every move, so once per blocker.
diff --git a/win_app/diagram.py b/win_app/diagram.py
index a722997..af02d06 100644
--- a/win_app/diagram.py
+++ b/win_app/diagram.py
@@ -3,6 +3,7 @@ strip in Resistance. Geometry is pages_win's, pure and tested; this file only pa
from __future__ import annotations
+from core.i18n import N_, tr, trc
import sys
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, QTimer
@@ -16,7 +17,9 @@ import tokens
from core import ways
from core.resistance_strip import MAX_RESISTANCE, resistance_x
-OTHER = "Other machine"
+OTHER = N_("Other machine")
+DASHBOARD_NAME = N_("This PC")
+DIRECTION_NAMES = {"left": N_("left"), "right": N_("right"), "top": N_("top"), "bottom": N_("bottom")}
ATLAS_TILE = (160, 100)
SCREEN = (120.0, 75.0)
GAP = 14.0
@@ -31,6 +34,8 @@ QUIET_ALPHA = 0.55
# The clear space centred on each third boundary of the selected machine's seam and tracks.
THIRD_GAP = 2.0
CYCLE_BOX = 16.0
+RESIZE_GRIP = 16.0
+RESIZE_HELP = N_("Tile size can be changed by dragging a corner or pressing Alt+arrow.")
def _colour(name: str, alpha: float = 1.0) -> QColor:
@@ -88,7 +93,7 @@ class ArrangementDiagram(QWidget):
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
- self.setAccessibleName("Arrangement")
+ self.setAccessibleName(tr("Arrangement"))
policy = QSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
policy.setHeightForWidth(True)
self.setSizePolicy(policy)
@@ -124,7 +129,7 @@ class ArrangementDiagram(QWidget):
metrics = QFontMetrics(theme.font(tokens.TYPE["small"], 600))
needed = max((metrics.boundingRect(QRectF(0, 0, max(1, rect[2] - 8), 10000).toRect(),
int(Qt.TextFlag.TextWrapAnywhere), name).height() + 4
- for rect, name in [(pc, "This PC"), *[(rect, self._labels.get(key, OTHER))
+ for rect, name in [(pc, tr(DASHBOARD_NAME)), *[(rect, self._labels.get(key, tr(OTHER)))
for key, rect in zip(keys, rects)]]), default=screen[1])
if needed > min([pc[3], *(rect[3] for rect in rects)]):
screen = (screen[0], screen[1] * needed / max(1, min([pc[3], *(rect[3] for rect in rects)])))
@@ -150,7 +155,7 @@ class ArrangementDiagram(QWidget):
self._state = state
self._machines = machines
alone = len(machines) == 1
- self._labels = {machine["key"]: machine["label"] or OTHER for machine in machines}
+ self._labels = {machine["key"]: machine["label"] or tr(OTHER) for machine in machines}
if shortcut:
self._cap_text = pages_win.trigger_phrase(key_name, style)
self._unplaced = "" if alone else pages_win.unplaced_line(
@@ -208,10 +213,10 @@ class ArrangementDiagram(QWidget):
for key, rect in rects.items():
painter.setOpacity(self._places[key][3])
named = self._marks.get(("named", key), 0.0)
- self._screen(painter, QRectF(*rect), self._labels.get(key, OTHER), "panel", _blend("edge", "ink_3", named),
+ self._screen(painter, QRectF(*rect), self._labels.get(key, tr(OTHER)), "panel", _blend("edge", "ink_3", named),
_blend("ink_3", "ink", named), radius)
painter.setOpacity(1.0)
- self._screen(painter, QRectF(*pc), "This PC", "well", _colour("edge"), _colour("ink_2"), radius)
+ self._screen(painter, QRectF(*pc), tr(DASHBOARD_NAME), "well", _colour("edge"), _colour("ink_2"), radius)
# The machines not shown first, so the chosen one's marks lie over theirs where they meet.
for key, level in sorted(self._marks.items(), key=lambda item: self._marks.get(("lead", item[0][1]), 0.0)
if len(item[0]) > 1 else 0.0):
@@ -338,7 +343,7 @@ class AtlasCanvas(QWidget):
"""One tile per paired machine, laid out around this screen with shared edge snaps."""
def __init__(self, parent=None, on_drop=None, on_rename=None, on_leave_out=None, on_cycle=None,
- on_select=None, on_third=None):
+ on_select=None, on_third=None, on_edit_machine=None):
super().__init__(parent)
self.on_drop = on_drop or (lambda *_: None)
self.on_rename = on_rename or (lambda *_: None)
@@ -346,6 +351,12 @@ class AtlasCanvas(QWidget):
self.on_cycle = on_cycle or (lambda *_: None)
self.on_select = on_select or (lambda *_: None)
self.on_third = on_third or (lambda *_: None)
+ self.on_edit_machine = on_edit_machine or (lambda *_: None)
+ self.profile_mode = False
+ self.remote = False
+ self.read_only = False
+ self._profile_press = None
+ self._profile_press_point = None
self.on_announce = None
self.on_hint = None
self.on_rename_state = None
@@ -353,7 +364,7 @@ class AtlasCanvas(QWidget):
self.setMaximumHeight(268)
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.setMouseTracking(True)
- self.setAccessibleName("Crossing layout")
+ self.setAccessibleName(tr("Crossing layout"))
self.setToolTip("")
self.tiles = {}
self.labels = {}
@@ -367,6 +378,7 @@ class AtlasCanvas(QWidget):
self.cycle_mode = "last"
self.capable = set()
self._drag = None
+ self._resizing = False
self._drag_display = None
self._display_offset_start = None
self._dragged_display = False
@@ -387,7 +399,7 @@ class AtlasCanvas(QWidget):
self._scale = 1.0
self._bounds = (0, 0, 1, 1)
self._recentre_colours = None
- self.recentre_button = QPushButton("Recentre", self)
+ self.recentre_button = QPushButton(tr("Recentre"), self)
self.recentre_button.setFont(theme.font(tokens.TYPE["note"]))
self.recentre_button.setFixedSize(76, 26)
self.recentre_button.clicked.connect(self.recentre)
@@ -404,7 +416,8 @@ class AtlasCanvas(QWidget):
def set_tiles(self, tiles, labels, states, selected, cycle_mode="last", cycle=None, capable=(), own_id=None,
rename_values=None):
- seen = (tiles, labels, states, selected, cycle_mode, cycle, tuple(sorted(capable or ())), own_id, rename_values)
+ seen = (tiles, labels, states, selected, cycle_mode, cycle, tuple(sorted(capable or ())), own_id,
+ rename_values, self.profile_mode, self.remote, self.read_only)
if seen == getattr(self, "_tiles_seen", None):
return
self._tiles_seen = seen
@@ -417,7 +430,12 @@ class AtlasCanvas(QWidget):
self.cycle = dict(cycle or {})
self.capable = set(capable)
self.own_id = own_id
- if own_id in self.tiles:
+ if (self.remote or self.read_only) and self._rename_peer is not None:
+ self._rename_peer = None
+ self.rename_edit.hide()
+ if self.on_rename_state:
+ self.on_rename_state(False)
+ if own_id in self.tiles and not self.remote:
own_detail = self.states.get(own_id, {}).get("detail") or \
("Linux" if sys.platform.startswith("linux") else "Windows")
self.states.setdefault(own_id, {}).update(
@@ -427,7 +445,9 @@ class AtlasCanvas(QWidget):
own_detail = self.states.get(own_id, {}).get("detail", "")
if own_id in self.tiles and own_detail:
description.append(own_detail)
- self.setAccessibleDescription("; ".join(description))
+ if not self.read_only and any(peer not in self.shelf_ids for peer in self.tiles):
+ description.append(tr(RESIZE_HELP))
+ self.setAccessibleDescription(trc("list", "; ").join(description))
self._geometry()
if self._drag is None:
self.update()
@@ -444,15 +464,19 @@ class AtlasCanvas(QWidget):
self.update()
def set_cycle(self, peer, enabled):
+ if self.remote or self.read_only:
+ return
self.cycle[peer] = bool(enabled)
self.on_cycle(peer, bool(enabled))
self.update()
def put_back(self, peer):
- self.on_leave_out(peer, False)
+ if not self.remote and not self.read_only:
+ self.on_leave_out(peer, False)
def leave_out(self, peer):
- self.on_leave_out(peer, True)
+ if not self.remote and not self.read_only:
+ self.on_leave_out(peer, True)
def animate_tile(self, peer, target, done=None):
current = self.tiles[peer]
@@ -489,6 +513,37 @@ class AtlasCanvas(QWidget):
return peer, frame["display"]
return None, None
+ def _can_resize(self, peer):
+ return not self.read_only and peer in self.tiles and peer not in self.shelf_ids
+
+ def _resize_grip_rect(self, peer):
+ if not self._can_resize(peer) or peer not in (self.selected, self._hover):
+ return None
+ rect = self.tile_rect(peer)
+ size = min(RESIZE_GRIP, rect.width(), rect.height())
+ grip = QRectF(rect.right()-size, rect.bottom()-size, size, size)
+ for other, tile in self.tiles.items():
+ if other == peer or other in self.shelf_ids:
+ continue
+ for display in tile.get("display_offsets", {}):
+ if display in tile.get("displays", {}) and grip.intersects(self.display_rect(other, display)):
+ return None
+ return grip
+
+ def _resize_at(self, point):
+ # An edge third's 5 px band wins over a grip it overlaps: the selected peer's and the
+ # hovered tile's corners sit on the end third of a shared side.
+ if self._third_segment_at(point) is not None:
+ return None
+ for peer in reversed(list(self.tiles)):
+ grip = self._resize_grip_rect(peer)
+ # A tile drawn smaller than the grip has its whole grip inside the band of the side it
+ # shares; the hit area keeps the full grip size, reaching out past the corner.
+ if grip is not None and QRectF(grip.left(), grip.top(), max(grip.width(), RESIZE_GRIP),
+ max(grip.height(), RESIZE_GRIP)).contains(point):
+ return peer
+ return None
+
def _geometry(self):
self._sync_recentre()
if self._drag:
@@ -538,6 +593,8 @@ class AtlasCanvas(QWidget):
+ (targets[side]["y"]-tile["y"])**2)
def _can_recentre(self):
+ if self.read_only:
+ return False
side = self._recentre_side()
if side is None:
return False
@@ -550,7 +607,7 @@ class AtlasCanvas(QWidget):
def _sync_recentre(self):
button = self.recentre_button
button.move(self.width()-button.width()-10, 10)
- button.setAccessibleName(f"Recentre {self.labels.get(self.selected, OTHER)}")
+ button.setAccessibleName(tr("Recentre {name}").format(name=self.labels.get(self.selected, tr(OTHER))))
colours = tuple(theme.colour(name) for name in ("panel", "ink_3", "ink", "edge", "ink_2"))
if colours != self._recentre_colours:
panel, ink_3, ink, edge, ink_2 = colours
@@ -563,10 +620,15 @@ class AtlasCanvas(QWidget):
button.setVisible(self._can_recentre())
button.raise_()
- def _commit_tile(self, peer):
+ def _commit_tile(self, peer, resized=False):
+ if self.read_only:
+ return
accepted = self.on_drop({key: dict(tile) for key, tile in self.tiles.items()}, peer) is not False
if accepted:
- self._announce_move(peer)
+ if resized:
+ self.announce(tr("{name} resized.").format(name=self.labels.get(peer, tr(OTHER))))
+ else:
+ self._announce_move(peer)
self._geometry()
self.update()
@@ -579,7 +641,7 @@ class AtlasCanvas(QWidget):
self.animate_tile(peer, target, done=lambda: self._commit_tile(peer))
def snap_preview(self):
- if not self._drag or self._drag == self._own_id() or self._drag_display is not None:
+ if not self._drag or self._resizing or self._drag == self._own_id() or self._drag_display is not None:
return None
tile = self.tiles[self._drag]
others = {key: value for key, value in self.tiles.items()
@@ -771,6 +833,8 @@ class AtlasCanvas(QWidget):
self.wrap_label_rects.append((side, text, box))
def _third_segment_at(self, point):
+ if self.read_only:
+ return None
own_id, peer = self._own_id(), self.selected
if (own_id not in self.tiles or peer not in self.tiles or peer == own_id
or peer in self.shelf_ids):
@@ -815,7 +879,8 @@ class AtlasCanvas(QWidget):
pen = QPen(_colour("ground", opacity), 1.8)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(pen)
- point = QPointF(x - 3 * dx, y - 3 * dy)
+ # The 7 px bracket centred on the vertex, as in the 16 px pad around it.
+ point = QPointF(x - 3.5 * dx, y - 3.5 * dy)
painter.drawLine(point, QPointF(point.x() + 7 * dx, point.y()))
painter.drawLine(point, QPointF(point.x(), point.y() + 7 * dy))
@@ -831,15 +896,18 @@ class AtlasCanvas(QWidget):
return rect.top()+7 if rect.height() >= 56 else rect.center().y()-11
def _shows_cycle(self, peer):
- return self.cycle_mode == "ticked" and peer != self._own_id() and peer not in self.shelf_ids
+ return (not self.remote and not self.read_only and self.cycle_mode == "ticked"
+ and peer != self._own_id() and peer not in self.shelf_ids)
@staticmethod
def _cycle_box(rect):
"""The shortcut-cycle tick: its own column at the right end of the name's line, or in the
- bottom-right corner of a tile 44 to 56pt tall, under the name."""
+ bottom row of a tile 44 to 56pt tall, leaving its corner free for the resize grip."""
if 44 <= rect.height() < 56:
- return QRectF(rect.right() - 8 - CYCLE_BOX, rect.bottom() - 4 - CYCLE_BOX, CYCLE_BOX, CYCLE_BOX)
- return QRectF(rect.right() - 8 - CYCLE_BOX, AtlasCanvas._title_top(rect) + 11 - CYCLE_BOX/2,
+ return QRectF(rect.right() - RESIZE_GRIP - 4 - CYCLE_BOX,
+ rect.bottom() - 4 - CYCLE_BOX, CYCLE_BOX, CYCLE_BOX)
+ margin = RESIZE_GRIP + 4 if rect.height() < 44 else 8
+ return QRectF(rect.right() - margin - CYCLE_BOX, AtlasCanvas._title_top(rect) + 11 - CYCLE_BOX/2,
CYCLE_BOX, CYCLE_BOX)
@staticmethod
@@ -890,10 +958,13 @@ class AtlasCanvas(QWidget):
inactive = peer in self.shelf_ids or self.in_use.get(peer, True) is False
fill = "well" if is_own else "panel"
line = "edge" if is_own else "ink_2" if chosen else "amber" if state in ("gap", "between", "set-elsewhere", "overlap") else "edge"
+ if self.profile_mode:
+ line = "ink_2" if self.remote and is_own else "edge"
if inactive:
fill, line = "ground", "ink_2" if chosen and not is_own else "rule"
painter.setOpacity(0.55 if inactive else 1.0)
- painter.setPen(QPen(_colour(line), 2.0 if chosen and not is_own else 1.0))
+ outlined = (self.remote and is_own) if self.profile_mode else (chosen and not is_own)
+ painter.setPen(QPen(_colour(line), 2.0 if outlined else 1.0))
painter.setBrush(_colour(fill))
painter.drawRoundedRect(rect, tokens.RADIUS["button"], tokens.RADIUS["button"])
if tile.get("displays"):
@@ -904,6 +975,8 @@ class AtlasCanvas(QWidget):
painter.drawRoundedRect(screen_rect, 2, 2)
state_data = self.states.get(peer, {})
dot_colour = "signal" if state_data.get("linked") else "amber" if state_data.get("legacy") else "ink_3"
+ if self.profile_mode:
+ dot_colour = "signal" if state_data.get("profile_word") in (tr("Desk"), tr("Own")) else "ink_3"
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(_colour(dot_colour))
if rect.height() >= 56:
@@ -921,7 +994,7 @@ class AtlasCanvas(QWidget):
painter.drawText(title_room, Qt.AlignmentFlag.AlignCenter,
painter.fontMetrics().elidedText(title, Qt.TextElideMode.ElideRight,
max(1, round(title_room.width()))))
- detail = state_data.get("detail", "")
+ detail = state_data.get("profile_word", "") if self.profile_mode else state_data.get("detail", "")
if detail and rect.height() >= 56:
painter.setPen(_colour("ink_2"))
painter.setFont(theme.font(tokens.TYPE["note"]))
@@ -946,7 +1019,7 @@ class AtlasCanvas(QWidget):
"Drag to connect" if state == "gap" else "Overlaps" if state == "overlap" else
outcome_for_tile(state, state_data.get("crosses", is_own), is_own,
state_data.get("other_name", "")))
- if foot and not legacy and rect.height() >= 78:
+ if foot and (not legacy or self.profile_mode) and rect.height() >= 78:
painter.setPen(_colour("signal" if foot == "Crosses" else "amber" if foot in
("Drag to connect", "Overlaps") else "ink_3"))
painter.setFont(theme.font(tokens.TYPE["note"]))
@@ -1012,7 +1085,7 @@ class AtlasCanvas(QWidget):
if peer == own_id or peer not in self.tiles or peer in self.shelf_ids:
continue
alpha = (1.0 if data.get("linked", True) else .55) * (1.0 if peer == self.selected else .7)
- name = self.labels.get(peer, OTHER)
+ name = self.labels.get(peer, tr(OTHER))
for side in self._wrap_sides(data):
self._paint_wrap(painter, own_rect, side, name, False, alpha, peer)
crossing = set(self._wrap_sides(data))
@@ -1040,7 +1113,7 @@ class AtlasCanvas(QWidget):
for peer in (one, two)):
continue
contact = ways._rect_contact(self.tiles[one], self.tiles[two])
- if contact:
+ if contact and not self.profile_mode:
self._paint_contact(painter, self.tiles[one], self.tile_rect(one), contact, "amber")
snapped = self.snap_preview()
if snapped is not None:
@@ -1054,6 +1127,16 @@ class AtlasCanvas(QWidget):
contact = ways._rect_contact(self.tiles[own_id], snapped)
if contact:
self._paint_contact(painter, self.tiles[own_id], self.tile_rect(own_id), contact, alpha=0.5)
+ for peer in self.tiles:
+ grip = self._resize_grip_rect(peer)
+ if grip is not None:
+ pen = QPen(_colour("ink_2"), 1.5)
+ pen.setCapStyle(Qt.PenCapStyle.RoundCap)
+ painter.setPen(pen)
+ for length in (4, 8):
+ length = min(length, max(1, grip.width()-4))
+ painter.drawLine(QPointF(grip.right()-3-length, grip.bottom()-3),
+ QPointF(grip.right()-3, grip.bottom()-3-length))
if self.hasFocus() and self.selected in self.tiles and self._keyboard_focus:
painter.setPen(QPen(_colour("ink_2"), 2.0))
painter.setBrush(Qt.BrushStyle.NoBrush)
@@ -1061,15 +1144,47 @@ class AtlasCanvas(QWidget):
painter.end()
def _own_id(self):
- return self.own_id or next((peer for peer, label in self.labels.items() if label == "This PC"), None)
+ return self.own_id or next((peer for peer, label in self.labels.items() if label == tr(DASHBOARD_NAME)), None)
def mousePressEvent(self, event):
point = event.position()
+ peer = self._resize_at(point)
+ if peer is not None and event.button() == Qt.MouseButton.LeftButton:
+ motion.stop(self, f"tile:{peer}")
+ self.selected = peer
+ self._drag = peer
+ self._resizing = True
+ self._drag_start = QPointF(point)
+ self._tile_start = dict(self.tiles[peer])
+ self._profile_press = None
+ self.setFocus(Qt.FocusReason.MouseFocusReason)
+ self._keyboard_focus = False
+ self.setCursor(Qt.CursorShape.SizeFDiagCursor)
+ if not self.profile_mode and peer != self._own_id():
+ self.on_select(peer)
+ self.update()
+ event.accept()
+ return
third = self._third_at(point)
if third is not None:
self._third_press = third
event.accept()
return
+ if self.profile_mode:
+ self._profile_press = next((peer for peer in reversed(list(self.tiles))
+ if self.tile_rect(peer).contains(point)), None)
+ self._profile_press_point = QPointF(point)
+ if self._profile_press is not None and (self.read_only or self._profile_press == self._own_id()
+ or self._profile_press in self.shelf_ids):
+ self.selected = self._profile_press
+ self.setFocus(Qt.FocusReason.MouseFocusReason)
+ self._keyboard_focus = False
+ self.update()
+ event.accept()
+ return
+ if self.read_only:
+ event.accept()
+ return
display_peer, display = self.display_at(point)
if display_peer is not None and display_peer != self._own_id():
offsets = self.tiles[display_peer].get("display_offsets", {})
@@ -1088,7 +1203,8 @@ class AtlasCanvas(QWidget):
self._tile_start = dict(self.tiles[display_peer])
self.setFocus(Qt.FocusReason.MouseFocusReason)
self._keyboard_focus = False
- self.on_select(display_peer)
+ if not self.profile_mode:
+ self.on_select(display_peer)
self.update()
event.accept()
return
@@ -1101,6 +1217,7 @@ class AtlasCanvas(QWidget):
event.accept()
return
if self._shows_cycle(peer) and self._cycle_hit_rect(rect).contains(point):
+ self._profile_press = None
self.set_cycle(peer, not self.cycle.get(peer, True))
event.accept()
return
@@ -1111,7 +1228,8 @@ class AtlasCanvas(QWidget):
self._tile_start = dict(self.tiles[peer])
self.setFocus(Qt.FocusReason.MouseFocusReason)
self._keyboard_focus = False
- self.on_select(peer)
+ if not self.profile_mode:
+ self.on_select(peer)
self.update()
event.accept()
return
@@ -1119,9 +1237,12 @@ class AtlasCanvas(QWidget):
def mouseMoveEvent(self, event):
if self._drag:
- self.setCursor(Qt.CursorShape.ClosedHandCursor)
+ self.setCursor(Qt.CursorShape.SizeFDiagCursor if self._resizing else Qt.CursorShape.ClosedHandCursor)
delta = event.position() - self._drag_start
- if self._drag_display is not None:
+ if self._resizing:
+ self.tiles[self._drag] = ways.resize_from_drag(
+ self._tile_start, delta.x()/self._scale, delta.y()/self._scale)
+ elif self._drag_display is not None:
tile = self.tiles[self._drag]
offsets = dict(tile.get("display_offsets", {}))
offsets[self._drag_display] = {
@@ -1144,18 +1265,48 @@ class AtlasCanvas(QWidget):
if hovered != self._hover:
self._hover = hovered
self.update()
- if third is not None:
+ resize_peer = self._resize_at(event.position())
+ if resize_peer is not None:
+ self.setToolTip(self.labels.get(resize_peer, ""))
+ self.setCursor(Qt.CursorShape.SizeFDiagCursor)
+ elif third is not None:
self.setToolTip(self._third_tooltip(*third))
self.setCursor(Qt.CursorShape.PointingHandCursor)
else:
self.setToolTip(self.labels.get(hovered, "") if hovered else "")
- self.setCursor(Qt.CursorShape.OpenHandCursor if hovered and hovered != self._own_id()
+ self.setCursor(Qt.CursorShape.OpenHandCursor if hovered and hovered != self._own_id() and not self.read_only
+ else Qt.CursorShape.PointingHandCursor if hovered and self.profile_mode
else Qt.CursorShape.ArrowCursor)
- if hovered and self._shows_cycle(hovered) and self._cycle_hit_rect(self.tile_rect(hovered)).contains(event.position()):
- QToolTip.showText(self.mapToGlobal(event.position().toPoint()), "In the shortcut's cycle", self)
+ if resize_peer is None and hovered and self._shows_cycle(hovered) and self._cycle_hit_rect(self.tile_rect(hovered)).contains(event.position()):
+ QToolTip.showText(self.mapToGlobal(event.position().toPoint()), tr("In the shortcut's cycle"), self)
super().mouseMoveEvent(event)
+ def leaveEvent(self, event):
+ self._hover = None
+ if not self._drag:
+ self.setCursor(Qt.CursorShape.ArrowCursor)
+ self.update()
+ super().leaveEvent(event)
+
def mouseReleaseEvent(self, event):
+ profile_peer = self._profile_press
+ self._profile_press = None
+ if (self.profile_mode and profile_peer is not None and self._profile_press_point is not None
+ and not self._split_on_release and not self._group_on_release
+ and (event.position() - self._profile_press_point).manhattanLength() < 4):
+ if self._drag is not None:
+ self.tiles[self._drag] = dict(self._tile_start)
+ self._geometry()
+ self._drag = None
+ self._drag_display = None
+ self._display_offset_start = None
+ self._dragged_display = False
+ self._split_on_release = self._group_on_release = False
+ self.setCursor(Qt.CursorShape.ArrowCursor)
+ self.on_edit_machine(profile_peer)
+ self.update()
+ event.accept()
+ return
if self._third_press is not None:
pressed = self._third_press
self._third_press = None
@@ -1165,18 +1316,24 @@ class AtlasCanvas(QWidget):
return
peer = self._drag
if peer:
+ resized = self._resizing
snapped = self.snap_preview()
display = self._drag_display
moved_display = self._dragged_display
split_on_release = self._split_on_release
group_on_release = self._group_on_release
self._drag = None
+ self._resizing = False
self._drag_display = None
self._display_offset_start = None
self._dragged_display = False
self._split_on_release = False
self._group_on_release = False
self.setCursor(Qt.CursorShape.ArrowCursor)
+ if resized:
+ self._commit_tile(peer, resized=True)
+ event.accept()
+ return
if display is not None and not moved_display and (split_on_release or group_on_release):
tile = dict(self.tiles[peer])
offsets = dict(tile.get("display_offsets", {}))
@@ -1196,7 +1353,7 @@ class AtlasCanvas(QWidget):
self.update()
event.accept()
return
- if display is None and event.position().y() > self.height() - 4:
+ if display is None and not self.remote and event.position().y() > self.height() - 4:
self.on_leave_out(peer, True)
self.update()
event.accept()
@@ -1211,11 +1368,14 @@ class AtlasCanvas(QWidget):
super().mouseReleaseEvent(event)
def mouseDoubleClickEvent(self, event):
+ if self.remote or self.read_only:
+ event.accept()
+ return
peer = next((key for key in self.tiles if key not in self.shelf_ids
and self.tile_rect(key).contains(event.position())), None)
if peer == self._own_id():
if self.on_hint:
- self.on_hint("Rename this computer on Overview.")
+ self.on_hint(tr("Rename this computer on Overview."))
event.accept()
return
if peer is not None and peer != self._own_id():
@@ -1226,6 +1386,14 @@ class AtlasCanvas(QWidget):
def keyPressEvent(self, event):
self._keyboard_focus = True
+ if (self.profile_mode and self.selected in self.tiles
+ and event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter, Qt.Key.Key_Space)):
+ self.on_edit_machine(self.selected)
+ event.accept()
+ return
+ if self.read_only:
+ super().keyPressEvent(event)
+ return
if event.key() == Qt.Key.Key_C and not event.modifiers():
self.recentre()
event.accept()
@@ -1241,6 +1409,17 @@ class AtlasCanvas(QWidget):
return
moves = {Qt.Key.Key_Left: (-1, 0), Qt.Key.Key_Right: (1, 0),
Qt.Key.Key_Up: (0, -1), Qt.Key.Key_Down: (0, 1)}
+ if event.key() in moves and event.modifiers() & Qt.KeyboardModifier.AltModifier:
+ if self._can_resize(self.selected) and self._drag is None:
+ peer = self.selected
+ motion.stop(self, f"tile:{peer}")
+ tile = self.tiles[peer]
+ long_side = max(tile["w"], tile["h"])
+ dx, dy = moves[event.key()]
+ self.tiles[peer] = ways.resize_tile(tile, long_side + (dx+dy)*long_side/8)
+ self._commit_tile(peer, resized=True)
+ event.accept()
+ return
if event.key() in moves and self.selected in self.shelf_ids:
event.accept()
return
@@ -1260,7 +1439,8 @@ class AtlasCanvas(QWidget):
super().keyPressEvent(event)
def focusNextPrevChild(self, next):
- peers = [peer for peer in self.tiles if peer != self._own_id() and peer not in self.shelf_ids]
+ peers = [peer for peer in self.tiles if self.profile_mode or
+ (peer != self._own_id() and peer not in self.shelf_ids)]
peers.sort(key=lambda peer: (self.tiles[peer]["y"] + self.tiles[peer]["h"] / 2,
self.tiles[peer]["x"] + self.tiles[peer]["w"] / 2))
rows = []
@@ -1278,7 +1458,8 @@ class AtlasCanvas(QWidget):
target = index + (1 if next else -1)
if 0 <= target < len(peers):
self.selected = peers[target]
- self.on_select(self.selected)
+ if not self.profile_mode:
+ self.on_select(self.selected)
self._keyboard_focus = True
self.update()
return True
@@ -1297,7 +1478,7 @@ class AtlasCanvas(QWidget):
else:
side = "corner"
state = self.states.get(peer, {})
- position = f"{side} of This PC" if side != "corner" else "at a corner of This PC"
+ position = tr("{side} of This PC").format(side=tr(DIRECTION_NAMES[side])) if side != "corner" else tr("at a corner of This PC")
part = None
if own:
along, start, span = ((tile["y"] + tile["h"] / 2, own["y"], own["h"])
@@ -1307,13 +1488,18 @@ class AtlasCanvas(QWidget):
parts = state.get("thirds", [])
chosen_part = parts[0] if parts else part
part_name = pages_win.part_names(side).get(chosen_part, chosen_part) if chosen_part else ""
- detail = f", {part_name.lower()} third" if part_name else ""
- result = state.get("announcement", "Crosses.")
- message = f"{self.labels.get(peer, OTHER)}, {position}{detail}. {result}"
+ detail = tr(", {part} third").format(part=tr(ways.PART_NAMES_LOWER[part_name.lower()])) if part_name else ""
+ result = state.get("announcement", tr("Crosses."))
+ # Translators: {name} is a machine name; {position} is relative to this PC; {detail} optionally names the third crossed.
+ message = tr("{name}, {position}{detail}. {result}").format(
+ name=self.labels.get(peer, OTHER), position=position, detail=detail, result=result)
self.announce(message)
def announce(self, message):
- self.setAccessibleDescription(message)
+ description = message
+ if not self.read_only and any(peer not in self.shelf_ids for peer in self.tiles):
+ description += " " + tr(RESIZE_HELP)
+ self.setAccessibleDescription(description)
QAccessible.updateAccessibility(QAccessibleAnnouncementEvent(self, message))
if self.on_announce:
self.on_announce(message)
@@ -1324,7 +1510,7 @@ class AtlasCanvas(QWidget):
super().focusInEvent(event)
def begin_rename(self, peer):
- if peer not in self.tiles or peer in self.shelf_ids or peer == self._own_id():
+ if self.remote or self.read_only or peer not in self.tiles or peer in self.shelf_ids or peer == self._own_id():
return
rect = self.tile_rect(peer).toRect()
self.selected = peer
@@ -1344,7 +1530,7 @@ class AtlasCanvas(QWidget):
if self.on_rename_state:
self.on_rename_state(False)
self.setFocus(Qt.FocusReason.OtherFocusReason)
- if peer:
+ if peer and not self.remote and not self.read_only:
self.on_rename(peer, value)
def eventFilter(self, watched, event):
@@ -1378,11 +1564,11 @@ class PushStrip(QSlider):
self.setRange(0, MAX_RESISTANCE)
self.setSingleStep(10)
self.setPageStep(50)
- self.setAccessibleName("Resistance")
+ self.setAccessibleName(tr("Resistance"))
self.setMinimumHeight(self.HEIGHT)
self.setMaximumHeight(self.HEIGHT)
self.setCursor(Qt.CursorShape.PointingHandCursor)
- self._other = OTHER
+ self._other = tr(OTHER)
self._active_edge = "right"
self._pressure = 0.0
self._crossing = False
@@ -1397,7 +1583,7 @@ class PushStrip(QSlider):
return QSize(160, self.HEIGHT)
def set_other_name(self, name: str) -> None:
- name = name or OTHER
+ name = name or tr(OTHER)
if name != self._other:
self._other = name
self.update()
@@ -1439,10 +1625,10 @@ class PushStrip(QSlider):
def _update_accessibility_description(self) -> None:
pressure = int(round(self._pressure))
threshold = self.value()
- description = (
- f"Current pressure {pressure} of {threshold} pointer units at the {self._active_edge} edge."
- if pressure > 0 else f"No push. Current pressure is 0 of {threshold} pointer units."
- )
+ edge = tr(DIRECTION_NAMES[self._active_edge])
+ description = (tr("Current pressure {pressure} of {threshold} pointer units at the {edge} edge.").format(
+ pressure=pressure, threshold=threshold, edge=edge) if pressure > 0 else
+ tr("No push. Current pressure is 0 of {threshold} pointer units.").format(threshold=threshold))
self.setAccessibleDescription(description)
def keyPressEvent(self, event) -> None:
@@ -1520,7 +1706,7 @@ class PushStrip(QSlider):
painter.setPen(_colour("ink_3"))
local_rect = QRectF(8, 2, self.width() / 2 - 8, 15)
peer_rect = QRectF(self.width() / 2, 2, self.width() / 2 - 8, 15)
- painter.drawText(local_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, "THIS PC")
+ painter.drawText(local_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, tr("THIS PC"))
painter.drawText(peer_rect, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
self.peer_label_text())
diff --git a/win_app/firewall_win.py b/win_app/firewall_win.py
index 5c87d71..97ce77e 100644
--- a/win_app/firewall_win.py
+++ b/win_app/firewall_win.py
@@ -16,6 +16,7 @@ import sys
from typing import Iterable, Optional, Sequence
from core import protocol
+from core.i18n import tr
LOGGER = logging.getLogger(__name__)
@@ -182,40 +183,40 @@ def advise(status: FirewallStatus) -> Advice:
port = status.port
rule_profiles = ("Private",) + (("Domain",) if "DomainAuthenticated" in status.lan_profiles else ())
if status.error:
- return Advice(f"Beamer could not read the Windows Firewall: {status.error}", "Check again", "check")
+ return Advice(tr("Beamer could not read the Windows Firewall: {error}").format(error=status.error), tr("Check again"), "check")
if status.blocked:
advice = Advice(
- f"Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on "
+ tr("Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on "
"Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling "
- "does not clear it. Fixing it removes the block and adds the right rule for private networks.",
- "Fix the firewall",
+ "does not clear it. Fixing it removes the block and adds the right rule for private networks.").format(port=port),
+ tr("Fix the firewall"),
"repair",
rule_profiles,
)
elif not status.allowed:
advice = Advice(
- f"Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will "
+ tr("Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will "
"say this PC is unreachable. This happens when the installer was run without administrator rights. "
- "Fixing it adds the rule for private networks.",
- "Fix the firewall",
+ "Fixing it adds the rule for private networks.").format(port=port),
+ tr("Fix the firewall"),
"repair",
rule_profiles,
)
elif not status.covered and status.public_interfaces:
names = ", ".join(alias for _, alias in status.public_interfaces if alias) or "this network"
advice = Advice(
- f"Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and "
+ tr("Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and "
"your other machines cannot get in. Trusting it marks the network as private, which lets them in without "
- "opening the port on every other network this PC joins.",
- "Trust this network",
+ "opening the port on every other network this PC joins.").format(names=names),
+ tr("Trust this network"),
"trust",
)
elif not status.covered:
names = ", ".join(status.lan_profiles)
advice = Advice(
- f"Beamer's firewall rule does not apply on this network (Windows calls it {names}). "
- "Fixing it rewrites the rule to cover it.",
- "Fix the firewall",
+ tr("Beamer's firewall rule does not apply on this network (Windows calls it {names}). "
+ "Fixing it rewrites the rule to cover it.").format(names=names),
+ tr("Fix the firewall"),
"repair",
rule_profiles,
)
@@ -233,26 +234,27 @@ def advise(status: FirewallStatus) -> Advice:
"a machine that finds this PC cannot finish pairing with it",
))
advice = Advice(
- f"Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for "
- f"{' or for '.join(rule for rule, _ in missing)}, so {' and '.join(effect for _, effect in missing)}. "
- "Installs made before these rules existed are missing them. Fixing it adds what is missing "
- "and leaves the working rules alone.",
- "Fix the firewall",
+ tr("Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule for "
+ "{rules}, so {effects}. Installs made before these rules existed are missing them. Fixing it adds "
+ "what is missing and leaves the working rules alone.").format(
+ port=port, rules=" or for ".join(rule for rule, _ in missing),
+ effects=" and ".join(effect for _, effect in missing)),
+ tr("Fix the firewall"),
"repair",
rule_profiles,
)
else:
- where = "this private network" if "Private" in status.lan_profiles else "this network"
+ where = tr("this private network") if "Private" in status.lan_profiles else tr("this network")
return Advice(
- f"Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine "
- "discover this PC.",
- "Check again",
+ tr("Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine "
+ "discover this PC.").format(port=port, where=where),
+ tr("Check again"),
"check",
)
if not status.elevated:
return Advice(
- advice.sentence + " Beamer is not running as administrator, so it cannot make this change itself: "
- "quit Beamer and open it again from the Start menu.",
+ tr("{sentence} Beamer is not running as administrator, so it cannot make this change itself: "
+ "quit Beamer and open it again from the Start menu.").format(sentence=advice.sentence),
advice.button,
None,
advice.rule_profiles,
diff --git a/win_app/global_shortcut_portal.py b/win_app/global_shortcut_portal.py
new file mode 100644
index 0000000..94da8bd
--- /dev/null
+++ b/win_app/global_shortcut_portal.py
@@ -0,0 +1,113 @@
+"""Global shortcut session for Wayland desktops."""
+
+import logging
+import threading
+from typing import Callable, Optional
+
+import portal
+from core.i18n import tr
+
+LOGGER = logging.getLogger(__name__)
+
+INTERFACE = "org.freedesktop.portal.GlobalShortcuts"
+SHORTCUT_ID = "send-input"
+PREFERRED_TRIGGER = "LOGO+SHIFT+b"
+
+
+class GlobalShortcut:
+ def __init__(self, connect: Callable, on_activated: Callable[[], None], stopping: Callable[[], bool] = lambda: False) -> None:
+ self._connect = connect
+ self._on_activated = on_activated
+ self._stopping = stopping
+ self._stop = threading.Event()
+ self._lock = threading.Lock()
+ self._bus = None
+ self._portal = None
+ self._thread = None
+ self.available: Optional[bool] = None
+ self.refused = False
+ self.trigger_description: Optional[str] = None
+ self.session_handle: Optional[str] = None
+
+ def start(self) -> None:
+ if self._thread is not None and self._thread.is_alive():
+ return
+ self._stop.clear()
+ self._thread = threading.Thread(target=self._run, name="Beamer-global-shortcut", daemon=True)
+ self._thread.start()
+
+ def _is_stopping(self) -> bool:
+ return self._stop.is_set() or self._stopping()
+
+ def _set_trigger_description(self, shortcuts) -> None:
+ for shortcut_id, details in shortcuts:
+ if shortcut_id == SHORTCUT_ID:
+ self.trigger_description = details.get("trigger_description")
+ return
+
+ def _run(self) -> None:
+ try:
+ bus = self._connect()
+ with self._lock:
+ self._bus = bus
+ self._portal = portal.Portal(bus, self._is_stopping)
+ version = self._portal.version(INTERFACE)
+ self.available = version > 0
+ if not self.available:
+ LOGGER.info("The desktop does not provide the GlobalShortcuts portal")
+ return
+ results = self._portal.request(INTERFACE, "CreateSession", "a{sv}", lambda token: ({
+ "handle_token": ("s", token),
+ "session_handle_token": ("s", self._portal.token()),
+ },))
+ self.session_handle = results["session_handle"]
+ try:
+ bound = self._portal.request(INTERFACE, "BindShortcuts", "oa(sa{sv})sa{sv}", lambda token: (
+ self.session_handle,
+ [(SHORTCUT_ID, {
+ "description": ("s", tr("Send input to another machine")),
+ "preferred_trigger": ("s", PREFERRED_TRIGGER),
+ })],
+ "",
+ {"handle_token": ("s", token)},
+ ))
+ except portal.Refused:
+ self.refused = True
+ LOGGER.info("The desktop declined Beamer's global shortcut")
+ return
+ self._set_trigger_description(bound.get("shortcuts", []))
+ while not self._is_stopping():
+ for _path, interface, member, body in self._portal.signals(timeout=0.1):
+ if interface != INTERFACE or not body or body[0] != self.session_handle:
+ continue
+ if member == "Activated" and len(body) > 1 and body[1] == SHORTCUT_ID:
+ try:
+ self._on_activated()
+ except Exception:
+ LOGGER.exception("The global shortcut callback failed")
+ elif member == "ShortcutsChanged" and len(body) > 1:
+ self._set_trigger_description(body[1])
+ except portal.Refused:
+ self.refused = True
+ LOGGER.info("The desktop declined Beamer's global shortcut")
+ except Exception:
+ if not self._is_stopping():
+ LOGGER.exception("The global shortcut portal session failed")
+
+ def stop(self) -> None:
+ self._stop.set()
+ with self._lock:
+ bus = self._bus
+ if self.session_handle is not None and self._portal is not None:
+ try:
+ self._portal.call(portal.SESSION, "Close", path=self.session_handle)
+ except Exception:
+ pass
+ if bus is not None:
+ try:
+ bus.close()
+ except Exception:
+ pass
+ thread = self._thread
+ if thread is not None:
+ thread.join(timeout=2.0)
diff --git a/win_app/inject_portal.py b/win_app/inject_portal.py
index a2fd1a3..6bdbc35 100644
--- a/win_app/inject_portal.py
+++ b/win_app/inject_portal.py
@@ -801,6 +801,17 @@ def move_to(x: int, y: int) -> None:
remote().submit(lambda session: session.place(x, y))
+def push(x: int, y: int, moves: List[Tuple[int, int]], wanted: Callable[[], bool]) -> None:
+ def go(session: Remote) -> None:
+ if not wanted():
+ return
+ session.place(x, y)
+ for dx, dy in moves:
+ session.move_by(dx, dy)
+
+ remote().submit(go)
+
+
def inject_mouse_button(button: str, down: bool) -> None:
code = BUTTONS.get(button)
if code is None:
diff --git a/win_app/input_injector.py b/win_app/input_injector.py
index 65ae3c2..9f12727 100644
--- a/win_app/input_injector.py
+++ b/win_app/input_injector.py
@@ -175,6 +175,8 @@ VK_MAP = {
"cmd": 0x5B,
"cmd_r": 0x5C,
"caps_lock": 0x14,
+ "hangul": 0x15,
+ "hanja": 0x19,
"insert": 0x2D,
"menu": 0x5D,
"num_lock": 0x90,
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index e035025..49f1357 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -7,6 +7,7 @@ import ctypes
import copy
from dataclasses import replace
import functools
+import html
import json
import logging
from logging.handlers import RotatingFileHandler
@@ -18,7 +19,7 @@ import tempfile
import threading
from typing import Optional
-from PySide6.QtCore import QEvent, QObject, QPointF, QRectF, QSize, QStandardPaths, QTimer, Qt, QUrl, Signal
+from PySide6.QtCore import QEvent, QObject, QPointF, QRectF, QSize, QStandardPaths, QTimer, Qt, QUrl, Signal, QProcess
from PySide6.QtGui import QAction, QColor, QCursor, QDesktopServices, QIcon, QKeySequence, QPainter, QPixmap, QShortcut, QStandardItem, QStandardItemModel
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from PySide6.QtWidgets import (
@@ -63,6 +64,7 @@ from app_config import (
)
from core import crash_log
from core.capture_types import DeadKey, TextInput
+from core.i18n import tr
from core import effects
from diagram import AtlasCanvas, PushStrip
from edge_glow import EdgeGlow, PreviewLoop
@@ -84,14 +86,20 @@ import hardware_win
import peers_view
import platform_parts
import qr_code
+import quit_signals as quit_signals_module
+import global_shortcut_portal
+import portal
from core import protocol
from core import settings_sync
+from core import i18n
+from core.i18n import matches_translation, N_, joined, tr, trc
from core import receiver
from core.receiver import LinkResponder, ServerState
from core import return_edge
from core import settings_sync
-from core import ways, crossing_state
+from core import ways, crossing_state, profiles
from sender import OWN_PLATFORM, LinkSender
+from shake_stroke import shake_stroke
import theme
import tray_glyph
import tokens
@@ -110,21 +118,21 @@ except OSError:
VERSION = "dev"
HOME_PAGE = "https://kalkmancode.co.uk/beamer"
-HOME_PAGE_TEXT = "Beamer's website"
+HOME_PAGE_TEXT = N_("Beamer's website")
STATUS_TITLES = {
- ServerState.STOPPED: "Receiver stopped",
- ServerState.WAITING: "Waiting for a machine",
- ServerState.CONNECTED: "Machine connected",
- ServerState.ERROR: "Receiver needs attention",
+ ServerState.STOPPED: N_("Receiver stopped"),
+ ServerState.WAITING: N_("Waiting for a machine"),
+ ServerState.CONNECTED: N_("Machine connected"),
+ ServerState.ERROR: N_("Receiver needs attention"),
}
# The short word beside the sidebar's link dot -- STATUS_TITLES is a sentence, this is one word.
SIDEBAR_LINK_WORDS = {
- ServerState.STOPPED: "Stopped",
- ServerState.WAITING: "Waiting",
- ServerState.CONNECTED: "Connected",
- ServerState.ERROR: "Error",
+ ServerState.STOPPED: N_("Stopped"),
+ ServerState.WAITING: N_("Waiting"),
+ ServerState.CONNECTED: N_("Connected"),
+ ServerState.ERROR: N_("Error"),
}
HEADING_ROLE = {
@@ -136,23 +144,29 @@ HEADING_ROLE = {
EDGE_CHOICES = pages_win.SIDE_CHOICES
CORNER_CHOICES = (
- ("top_left", "Top-left"),
- ("top_right", "Top-right"),
- ("bottom_left", "Bottom-left"),
- ("bottom_right", "Bottom-right"),
+ ("top_left", N_("Top-left")),
+ ("top_right", N_("Top-right")),
+ ("bottom_left", N_("Bottom-left")),
+ ("bottom_right", N_("Bottom-right")),
)
-TRIGGER_STYLE_CHOICES = (("double_tap", "Double-tap"), ("hold", "Hold"))
+TRIGGER_STYLE_CHOICES = (("double_tap", N_("Double-tap")), ("hold", N_("Hold")))
MODIFIER_STYLE_CHOICES = (
- ("semantic", "Same shortcuts"),
- ("positional", "Same positions"),
- ("mac_layout", "Mac keyboard layout"),
+ ("semantic", N_("Same shortcuts")),
+ ("positional", N_("Same positions")),
+ ("mac_layout", N_("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.",
+ "semantic": N_("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": N_("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": N_("To a Mac: Alt becomes Command and Win becomes Option; Ctrl stays Control."),
+}
+IGNORED_NOTES = {
+ "filled": N_("These keep working on this PC while its input is on another machine: a mouse's back button for "
+ "this PC's browser, say, or a volume key for its speakers."),
+ "empty": N_("Nothing yet. Every key and button goes to the machine that has input. Add one to keep "
+ "it here: a mouse's back button for this PC's browser, say, or a volume key for its speakers."),
}
FULL_SCREEN_CHECK_MS = 1000
# How long a dragged slider waits, still, before the value it settled on is written to disk.
@@ -265,6 +279,14 @@ class ColumnFit(QObject):
width = round(page_column_width(self.scroll.width() - 16))
if width != self.column.width():
self.column.setFixedWidth(width)
+ for label in self.column.findChildren(QLabel):
+ if label.isVisible() and label.wordWrap():
+ label.setMinimumHeight(label.heightForWidth(label.width()))
+ layout = self.column.layout()
+ if layout is not None:
+ layout.activate()
+ self.column.setMinimumHeight(layout.sizeHint().height())
+ self.scroll.widget().updateGeometry()
def eventFilter(self, watched, event) -> bool:
if event.type() in (QEvent.Type.Resize, QEvent.Type.Show):
@@ -299,6 +321,7 @@ class StatusBridge(QObject):
arrangement = Signal(str, str, int, str, object, object)
# Either link, carrying a peer's Same on all machines state: (peer id, data).
settings = Signal(str, object)
+ shook_home = Signal(object)
alert = Signal(str, str)
# (version, url) when a newer Beamer is out, else None.
update = Signal(object)
@@ -420,12 +443,16 @@ def design_readout():
class _DesignChoiceSlider:
def __init__(self, name, minimum, maximum, step, scale, stops, preset_names):
+ self.is_length = name.lower() == "length"
self.scale = scale
self.stops = stops
self.preset_names = preset_names
- self.description = ("Sets the effect's playback time." if name == "Length"
- else "Sets effect depth relative to the shorter screen edge.")
- self.slider = widgets.Ruler(name, maximum, minimum, step=step, page_step=step * 5)
+ self.description_template = (N_("Sets the effect's playback time.") if self.is_length
+ else N_("Sets effect depth relative to the shorter screen edge."))
+ self.value_description_template = (N_("Sets the effect's playback time. Current value: {value}.") if self.is_length
+ else N_("Sets effect depth relative to the shorter screen edge. Current value: {value}."))
+ self.description = tr(self.description_template)
+ self.slider = widgets.Ruler(tr("Length") if self.is_length else tr("Size"), maximum, minimum, step=step, page_step=step * 5)
self.slider.setMaximumWidth(240)
self.view = self.slider
self.slider.setAccessibleDescription(self.description)
@@ -434,7 +461,7 @@ class _DesignChoiceSlider:
@property
def value(self):
numeric = self.slider.value() / self.scale
- return effects.length_preset(numeric) if self.slider.accessibleName() == "Length" else effects.size_preset(numeric)
+ return effects.length_preset(numeric) if self.is_length else effects.size_preset(numeric)
def set_value(self, preset):
index = next((i for i, (key, _name) in enumerate(self.preset_names) if key == preset), 1)
@@ -453,7 +480,7 @@ class _DesignChoiceSlider:
self.slider.blockSignals(blocked)
def set_accessible_value(self, value):
- self.slider.setAccessibleDescription(f"{self.description} Current value: {value}.")
+ self.slider.setAccessibleDescription(tr(self.value_description_template).format(value=value))
def set_enabled(self, enabled: bool) -> None:
self.slider.setEnabled(bool(enabled))
@@ -470,6 +497,14 @@ class WindowsApplication(QWidget):
# What the tray icon was last drawn from (drive state, receiver state, taskbar ink); unset until the first draw.
_tray_icon_key = None
+ def eventFilter(self, watched, event):
+ if watched in (getattr(self, "profile_header", None), getattr(self, "profile_override_row", None)) and event.type() in (QEvent.Type.Resize, QEvent.Type.Show):
+ narrow = watched.width() < 420
+ watched.layout().setDirection(QBoxLayout.Direction.TopToBottom if narrow else QBoxLayout.Direction.LeftToRight)
+ if watched is self.profile_header:
+ watched.layout().setAlignment(self.same_ways_switch, Qt.AlignmentFlag.AlignLeft if narrow else Qt.AlignmentFlag.AlignRight)
+ return super().eventFilter(watched, event)
+
def paintEvent(self, event) -> None:
super().paintEvent(event)
if self._start_after_first_paint and not self._startup_painted:
@@ -497,6 +532,9 @@ class WindowsApplication(QWidget):
self._closing = False
self._same_settings_signature = object()
self._same_before_sync = None
+ self._profile_last_heard = {}
+ self._shake_enabled = None
+ self._shake_sensitivity = None
self._displays_signature = object()
self._design_follow_signature = object()
self.tray_available = QSystemTrayIcon.isSystemTrayAvailable()
@@ -527,6 +565,7 @@ class WindowsApplication(QWidget):
self.bridge.peers_changed.connect(self._on_peers_changed)
self.bridge.arrangement.connect(self._on_arrangement)
self.bridge.settings.connect(self._on_settings)
+ self.bridge.shook_home.connect(self._on_shake)
self.bridge.update.connect(self._on_update)
self.bridge.rules_ready.connect(self._listen)
self.bridge.permission.connect(self._on_permission)
@@ -659,6 +698,13 @@ class WindowsApplication(QWidget):
self.hooks.barriers_from(self.sender.zone_models)
self.hooks.on_home = lambda: self.sender.set_redirecting(False)
self.sender.input_held = lambda: self.hooks.holding
+ self.sender.push_out = lambda peer, on_captured, on_failed: self.hooks.push_through(
+ self.sender.models_toward(peer), on_captured, on_failed,
+ )
+ self.global_shortcut = global_shortcut_portal.GlobalShortcut(
+ portal.JeepneyBus,
+ lambda: self.sender.toggle_shortcut() if not self.sender.redirecting else None,
+ )
if hasattr(platform_parts.injector, "on_problem"):
platform_parts.injector.on_problem = lambda sentence: self.bridge.alert.emit("Beamer", sentence)
if self.permission_state is not None and hasattr(platform_parts.injector, "on_permission"):
@@ -680,10 +726,12 @@ class WindowsApplication(QWidget):
self._design_seen = self._design_fields()
self._apply_input_scale(self._config)
self._host = self._config.host
+ if self._config.home_shortcut and getattr(self, "global_shortcut", None) is not None:
+ self.global_shortcut.start()
self._paired = bool(self.book.peers())
if self._paired:
self._status = ServerState.WAITING
- self._status_detail = f"Ready on TCP port {self._config.port}"
+ self._status_detail = tr("Ready on TCP port {port}").format(port=self._config.port)
else:
self._status = ServerState.ERROR
self._status_detail = "Not paired yet: press Pair a machine on Overview"
@@ -706,7 +754,7 @@ class WindowsApplication(QWidget):
appearance = self._config.appearance if self._config is not None else "system"
theme.set_dark(theme.wants_dark(appearance, theme.system_dark()))
- self.setWindowTitle("Beamer")
+ self.setWindowTitle(tr("Beamer"))
self.resize(900, 640)
self.setMinimumSize(320, 300)
self.setWindowIcon(QIcon(str(ICON_PATH)))
@@ -745,7 +793,7 @@ class WindowsApplication(QWidget):
row_layout.setSpacing(0)
self.sidebar = widgets.Sidebar(
- pages_win.PAGES, self._select_page, foot=f"Beamer {VERSION}\n{HOME_PAGE_TEXT}", on_foot=self.open_home_page,
+ pages_win.PAGES, self._select_page, foot=tr("Beamer {version}\n{link}").format(version=VERSION, link=tr(HOME_PAGE_TEXT)), on_foot=self.open_home_page,
foot_tip=HOME_PAGE,
)
self.sidebar.setFixedWidth(theme.SIDEBAR_WIDTH)
@@ -764,7 +812,7 @@ class WindowsApplication(QWidget):
self.footer_note = widgets.label(pages_win.footer("overview"), "note", wrap=True)
footer_layout.addWidget(self.footer_note)
footer_layout.addStretch(1)
- self.quit_button = QPushButton("Quit Beamer")
+ self.quit_button = QPushButton(tr("Quit Beamer"))
self.quit_button.clicked.connect(self.quit)
footer_layout.addWidget(self.quit_button)
outer.addWidget(footer)
@@ -782,7 +830,7 @@ class WindowsApplication(QWidget):
}
self._page_indexes: dict = {}
for key, name, purpose in pages_win.PAGES:
- scroll, layout = self._page_shell(name, purpose, pages_win.SCOPE.get(key), key)
+ scroll, layout = self._page_shell(tr(name), tr(purpose), tr(pages_win.SCOPE[key]) if key in pages_win.SCOPE else None, key)
builders[key](layout, current)
layout.addStretch(1)
self._page_indexes[key] = self.stack.addWidget(scroll)
@@ -883,13 +931,13 @@ class WindowsApplication(QWidget):
self._refresh_peers()
def _name_module(self, current: Config) -> QWidget:
- module = widgets.Module("This machine")
+ module = widgets.Module(tr("This machine"))
line = QHBoxLayout()
self.own_name_label = widgets.label(current.name or platform.node(), "readout", wrap=True)
self.own_name_label.setMinimumWidth(0)
self.own_name_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
line.addWidget(self.own_name_label, 1)
- self.own_name_rename = widgets.ActionButton("Rename")
+ self.own_name_rename = widgets.ActionButton(tr("Rename"))
self.own_name_rename.setProperty("vernier", "small")
self.own_name_rename.setMinimumWidth(self.own_name_rename.sizeHint().width())
self.own_name_rename.clicked.connect(self._begin_own_rename)
@@ -912,7 +960,7 @@ class WindowsApplication(QWidget):
self.own_name_label.setVisible(False)
self.own_name_rename.setVisible(False)
self.own_name_edit.setVisible(True)
- self.own_name_note.setText("Only on this computer" if sys.platform.startswith("linux") else "Only on this PC")
+ self.own_name_note.setText(tr("Only on this computer" if sys.platform.startswith("linux") else "Only on this PC"))
self.own_name_note.setVisible(not settings_sync.group_on(self._config, "names"))
self.own_name_edit.setFocus()
self.own_name_edit.selectAll()
@@ -927,7 +975,7 @@ class WindowsApplication(QWidget):
app_config.write_settings(self.config_path, settings)
except (ConfigError, OSError) as exc:
LOGGER.exception("This PC's name could not be saved")
- self.footer_note.setText(f"Could not save this PC's name: {exc}")
+ self.footer_note.setText(tr("Could not save this PC's name: {error}").format(error=exc))
self._cancel_own_rename()
return
self._config = replace(self._config, name=label)
@@ -952,30 +1000,32 @@ class WindowsApplication(QWidget):
app_config.write_settings(self.config_path, settings)
except (ConfigError, OSError) as exc:
LOGGER.exception("A machine's name could not be saved")
- self.footer_note.setText(f"Could not save the machine's name: {exc}")
+ self.footer_note.setText(tr("Could not save the machine's name: {error}").format(error=exc))
return
self._refresh_peers()
if settings_sync.group_on(self._config, "names"):
self._send_same()
def _permissions_module(self) -> QWidget:
- module = widgets.Module("Linux permissions")
+ module = widgets.Module(tr("Linux permissions"))
module.body.addWidget(widgets.label(
- "Beamer requests keyboard and pointer access when each Wayland session starts.", "note", wrap=True,
+ tr("Beamer requests keyboard and pointer access when each Wayland session starts."), "note", wrap=True,
))
self.permission_rows = {}
- titles = {"capture": "Send input — Input Capture", "remote": "Receive input — Remote Desktop"}
+ titles = {"capture": N_("Send input — Input Capture"), "remote": N_("Receive input — Remote Desktop")}
for direction, title in titles.items():
row = QVBoxLayout()
line = QHBoxLayout()
line.setSpacing(10)
- name = widgets.label(title, "body", wrap=True)
+ name = widgets.label(tr(title), "body", wrap=True)
name.setMinimumWidth(0)
line.addWidget(name, 1)
- status = widgets.label("Not requested", "note")
- status.setMinimumWidth(92)
+ status = widgets.label(tr("Not requested"), "note")
+ # As wide as the longest status in this language, so a change of state never moves the button.
+ status.setMinimumWidth(max(status.fontMetrics().horizontalAdvance(tr(word))
+ for word in pages_win.PERMISSION_STATUS_LABELS.values()))
line.addWidget(status)
- retry = QPushButton("Ask again")
+ retry = QPushButton(tr("Ask again"))
retry.clicked.connect(lambda _checked=False, key=direction: self._ask_permission_again(key))
line.addWidget(retry)
row.addLayout(line)
@@ -993,9 +1043,7 @@ class WindowsApplication(QWidget):
if direction not in rows:
return
status_label, detail_label, retry = rows[direction]
- status_label.setText({
- "not_requested": "Not requested", "ready": "Ready", "refused": "Refused", "unavailable": "Unavailable",
- }[status])
+ status_label.setText(tr(pages_win.PERMISSION_STATUS_LABELS[status]))
detail_label.setText(detail)
detail_label.setVisible(bool(detail))
retry.setVisible(retryable)
@@ -1007,16 +1055,16 @@ class WindowsApplication(QWidget):
self.permission_state.report(direction, "unavailable", str(exc))
def _tray_module(self, current: Config) -> QWidget:
- module = widgets.Module("Tray")
- self.tray_switch = widgets.Switch("Show in tray")
+ module = widgets.Module(tr("Tray"))
+ self.tray_switch = widgets.Switch(tr("Show in tray"))
self.tray_switch.setFont(theme.font(theme.TYPE["body"]))
self.tray_switch.setChecked(current.show_in_tray)
self.tray_switch.setEnabled(self.tray_available)
self.tray_switch.toggled.connect(self._set_show_in_tray)
module.body.addWidget(self.tray_switch)
module.body.addWidget(widgets.label(
- "With it off, closing the window quits Beamer. Open Beamer again to bring the window back."
- if self.tray_available else "This desktop has no system tray, so Beamer's window is all there is: closing it quits Beamer.",
+ tr("With it off, closing the window quits Beamer. Open Beamer again to bring the window back.")
+ if self.tray_available else tr("This desktop has no system tray, so Beamer's window is all there is: closing it quits Beamer."),
"note", wrap=True))
return module
@@ -1028,18 +1076,18 @@ class WindowsApplication(QWidget):
self.tray.setVisible(self.tray_shown())
def _updates_module(self, current: Config) -> QWidget:
- module = widgets.Module("Updates")
- self.updates_switch = widgets.Switch("Check for updates")
+ module = widgets.Module(tr("Updates"))
+ self.updates_switch = widgets.Switch(tr("Check for updates"))
self.updates_switch.setFont(theme.font(theme.TYPE["body"]))
self.updates_switch.setChecked(current.check_updates)
self.updates_switch.toggled.connect(self._set_check_updates)
module.body.addWidget(self.updates_switch)
module.body.addWidget(widgets.label(
- "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself.",
+ tr("Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."),
"note",
wrap=True,
))
- self.update_button = QPushButton("Download")
+ self.update_button = QPushButton(tr("Download"))
self.update_button.setProperty("vernier", "primary")
self.update_button.clicked.connect(self.open_update)
self.update_button.setVisible(False)
@@ -1059,9 +1107,9 @@ class WindowsApplication(QWidget):
def _on_update(self, found) -> None:
"""(version, url) for a newer release, or None; on the GUI thread."""
self._update = found
- self.update_button.setText(f"Download Beamer {found[0]}" if found else "Download")
+ self.update_button.setText(tr("Download Beamer {version}").format(version=found[0]) if found else tr("Download"))
motion.set_shown(self.update_button, found is not None)
- self.header_action.setText(f"Beamer {found[0]} is available…" if found else f"Beamer {VERSION}")
+ self.header_action.setText(tr("Beamer {version} is available…").format(version=found[0]) if found else tr("Beamer {version}").format(version=VERSION))
self.header_action.setEnabled(found is not None)
def open_update(self) -> None:
@@ -1073,7 +1121,7 @@ class WindowsApplication(QWidget):
QDesktopServices.openUrl(QUrl.fromLocalFile(str(folder)))
def _link_module(self) -> QWidget:
- module = widgets.Module("Link")
+ module = widgets.Module(tr("Link"))
heading_row = QHBoxLayout()
heading_row.setSpacing(10)
self.led = widgets.Led()
@@ -1086,7 +1134,7 @@ class WindowsApplication(QWidget):
module.body.addWidget(self.status_detail)
where_row = QHBoxLayout()
where_row.setSpacing(6)
- where_row.addWidget(widgets.label("Input:", "note"))
+ where_row.addWidget(widgets.label(tr("Input:"), "note"))
self.location_readout = widgets.label("", "readout", wrap=True)
where_row.addWidget(self.location_readout, 1)
module.body.addLayout(where_row)
@@ -1096,7 +1144,7 @@ class WindowsApplication(QWidget):
trip_row = QHBoxLayout(self.round_trip_row)
trip_row.setContentsMargins(0, 0, 0, 0)
trip_row.setSpacing(6)
- trip_row.addWidget(widgets.label("Delay:", "note"))
+ trip_row.addWidget(widgets.label(tr("Delay:"), "note"))
self.round_trip_readout = widgets.label("", "readout", wrap=True)
trip_row.addWidget(self.round_trip_readout, 1)
self.round_trip_row.setVisible(False)
@@ -1106,33 +1154,33 @@ class WindowsApplication(QWidget):
def _input_module(self) -> QWidget:
"""The everyday buttons: send input across without the shortcut or an edge, and hold the
edges for a while."""
- module = widgets.Module("Keyboard and mouse")
- self.redirect_button = widgets.ElidingActionButton("Send input across")
+ module = widgets.Module(tr("Keyboard and mouse"))
+ self.redirect_button = widgets.ElidingActionButton(tr("Send input across"))
self.redirect_button.setProperty("vernier", "primary")
self.redirect_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.redirect_button.clicked.connect(self.toggle_redirect)
module.body.addWidget(self.redirect_button)
# Why the button above is dimmed, while it is.
- self.redirect_note = widgets.label("Switch on This PC drives it for a machine above to send input from here.",
+ self.redirect_note = widgets.label(tr("Switch on This PC drives it for a machine above to send input from here."),
"note", wrap=True)
self.redirect_note.setVisible(False)
module.body.addWidget(self.redirect_note)
self.wayland_send_note = widgets.label(
- "On Wayland the desktop lets input go to another machine only when the pointer pushes through an "
- "edge, so this button cannot send it.", "note", wrap=True)
+ tr("On Wayland the desktop lets input go to another machine only when the pointer pushes through an "
+ "edge, so this button cannot send it."), "note", wrap=True)
self.wayland_send_note.setVisible(False)
module.body.addWidget(self.wayland_send_note)
self.send_hint = widgets.label("", "note", wrap=True)
self.send_hint.setVisible(False)
module.body.addWidget(self.send_hint)
- self.pause_button = QPushButton("Pause crossing")
+ self.pause_button = QPushButton(tr("Pause crossing"))
self.pause_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.pause_button.clicked.connect(self.toggle_pause)
self.crossing_state = widgets.label("", "note", wrap=True)
# 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 this PC's edges while an app on it is full screen")
+ self.hold_switch = widgets.Switch(tr("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 False)
self.hold_switch.toggled.connect(self._set_hold_full_screen)
@@ -1140,21 +1188,21 @@ class WindowsApplication(QWidget):
own_note = self._own_note()
module.body.addWidget(own_note)
hold_note = widgets.label(
- "This screen decides, including when another machine drives it. On, a full-screen app here holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer can go home or onward through the configured ways.", "note", wrap=True)
+ tr("This screen decides, including when another machine drives it. On, a full-screen app here holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer can go home or onward through the configured ways."), "note", wrap=True)
module.body.addWidget(hold_note)
- self.hold_switch.setToolTip("This screen's setting applies to every pointer on it.")
- self.pointer_switch = widgets.Switch("Hide the pointer on the machine not in use")
+ self.hold_switch.setToolTip(tr("This screen's setting applies to every pointer on it."))
+ self.pointer_switch = widgets.Switch(tr("Hide the pointer on the machine not in use"))
self.pointer_switch.setFont(theme.font(theme.TYPE["body"]))
self.pointer_switch.setChecked(self._config.hide_idle_pointer if self._config else True)
self.pointer_switch.toggled.connect(self._set_hide_idle_pointer)
module.body.addWidget(self.pointer_switch)
pointer_note = widgets.label(
- "This PC's pointer hides while it drives another machine, and after another machine stops driving it, "
- "until its own mouse moves.", "note", wrap=True)
+ tr("This PC's pointer hides while it drives another machine, and after another machine stops driving it, "
+ "until its own mouse moves."), "note", wrap=True)
module.body.addWidget(pointer_note)
self.wayland_crossing_note = widgets.label(
- "On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an "
- "edge, so the edges are never held for one and a drag can cross.", "note", wrap=True)
+ tr("On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an "
+ "edge, so the edges are never held for one and a drag can cross."), "note", wrap=True)
module.body.addWidget(self.wayland_crossing_note)
for widget in (self.hold_switch, own_note, hold_note):
widget.setVisible(not platform_parts.WAYLAND)
@@ -1168,11 +1216,11 @@ class WindowsApplication(QWidget):
"""Names the machine the button sends input to, which is the one the shortcut would pick."""
target = self.sender.shortcut_target()
if target is not None and target in self._labels_by_id:
- return f"Send input to {self._labels_by_id[target]}"
+ return tr("Send input to {name}").format(name=self._labels_by_id[target])
sendable = [entry for entry in peerlist.desktops(self._peer_entries)
if entry.get("in_use", True) is True and entry.get("send")]
# The entry migrated from 1.4.x has no id to pick it by until its first link.
- return f"Send input to {self._shown(peerlist.labels(self._peer_entries)[sendable[0]['token']])}" if len(sendable) == 1 else "Send input across"
+ return tr("Send input to {name}").format(name=self._shown(peerlist.labels(self._peer_entries)[sendable[0]['token']])) if len(sendable) == 1 else tr("Send input across")
def toggle_redirect(self) -> None:
self.sender.toggle()
@@ -1220,12 +1268,20 @@ class WindowsApplication(QWidget):
def _on_alert(self, title: str, message: str) -> None:
if self._closing:
return
- if message.startswith("Can't cross to"):
+ if matches_translation(
+ message, "Can't cross to {name}: it is being driven from {other}.",
+ "Can't cross to {name}: another machine is driving it.",
+ "Can't cross to {name}: it is driving {other}.",
+ "Can't cross to {name}: it is driving another machine."):
self._last_refusal = message
self._refresh_tray_state()
if not self._refusal_notices.allow(message):
return
- if message.startswith("Cannot switch"):
+ if matches_translation(
+ message, "Cannot switch — {status}", "Cannot switch — {reason}",
+ "Cannot switch — {name} could not be reached while this PC is being driven",
+ "Cannot switch — {name} could not be reached",
+ "Cannot switch — on this desktop input goes to another machine only by pushing the pointer through an edge"):
QApplication.beep()
if sys.platform.startswith("linux"):
import portal
@@ -1236,35 +1292,37 @@ class WindowsApplication(QWidget):
self.tray.showMessage(title, self._shown(message), QIcon(str(ICON_PATH)), 4000)
def _same_module(self, current: Config) -> QWidget:
- module = widgets.Module("Settings")
- module.body.addWidget(widgets.label("Same on all machines", "body"))
+ module = widgets.Module(tr("Settings"))
+ module.body.addWidget(widgets.label(tr("Same on all machines"), "body", wrap=True))
self.same_checks = {}
- for key, title in (("crossing", "Crossing"), ("design", "Design"),
- ("shortcut", "Shortcut"), ("names", "Names")):
- check = widgets.QCheckBox(title)
+ self.same_ways_summary = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.same_ways_summary)
+ for key, title in (("crossing", N_("Crossing")), ("design", N_("Design")),
+ ("shortcut", N_("Shortcut")), ("names", N_("Names"))):
+ check = widgets.QCheckBox(tr(title))
check.setFont(theme.font(theme.TYPE["body"]))
check.setChecked(key in current.same_groups if key != "everything" else len(current.same_groups) == 4)
check.toggled.connect(lambda on, name=key: self._same_group_toggled(name, on))
module.body.addWidget(check)
self.same_checks[key] = check
self.same_content_note = widgets.label(
- "Crossing shares resistance and drag protection. Design shares effects, colour, length, size and arrival animation. "
- "Shortcut shares shortcut on/off, trigger key and style, and destination. Names shares this machine's name and paired-machine labels.",
+ tr("Crossing shares resistance and drag protection. Design shares effects, colour, length, size and arrival animation. "
+ "Shortcut shares shortcut on/off, trigger key and style, and destination. Names shares this machine's name and paired-machine labels."),
"note", wrap=True)
module.body.addWidget(self.same_content_note)
- check = widgets.QCheckBox("Everything")
+ check = widgets.QCheckBox(tr("Everything"))
check.setFont(theme.font(theme.TYPE["body"]))
check.setChecked(len(current.same_groups) == 4)
check.toggled.connect(lambda on: self._same_group_toggled("everything", on))
module.body.addWidget(check)
self.same_checks["everything"] = check
self.same_everything_note = widgets.label(
- "Shares every group and can replace local values on this machine.", "note", wrap=True)
+ tr("Shares every group and can replace local values on this machine."), "note", wrap=True)
module.body.addWidget(self.same_everything_note)
self.same_old_note = widgets.label(
- "Older Beamer versions share known Crossing and Design settings without group choices.", "note-amber", wrap=True)
+ tr("Older Beamer versions share known Crossing and Design settings without group choices."), "note-amber", wrap=True)
module.body.addWidget(self.same_old_note)
- self.same_revert = QPushButton("Revert")
+ self.same_revert = QPushButton(tr("Revert"))
self.same_revert.setProperty("vernier", "small")
self.same_revert.clicked.connect(self._revert_same)
module.body.addWidget(self.same_revert)
@@ -1301,6 +1359,8 @@ class WindowsApplication(QWidget):
self._same_settings_signature = signature
else:
stored = self._window_settings()
+ self.same_ways_summary.setText(tr("Ways: set on the Crossing page · {state}").format(
+ state=tr("On") if profiles.same_ways_on(stored) else tr("Off")))
self._same_before_sync = stored.get("same_before_sync")
revert = settings_sync.snapshot_available(self._same_before_sync)
desktops = peerlist.desktops(self._peer_entries)
@@ -1488,7 +1548,7 @@ class WindowsApplication(QWidget):
self._design_follow_model = model
choice.setModel(model)
model.clear()
- none = QStandardItem("None")
+ none = QStandardItem(tr("None"))
none.setData("", Qt.ItemDataRole.UserRole)
model.appendRow(none)
for entry, why_not in rows:
@@ -1626,6 +1686,42 @@ class WindowsApplication(QWidget):
def _send_to(self, peer: bytes, message: dict) -> bool:
return self.sender.send_to(peer, message) or self.server.send(peer, message)
+ def _desk_messages(self, desk: dict, caps) -> list:
+ if "profiles" not in caps:
+ return []
+ envelope = self._same_state()
+ return [protocol.settings_msg(settings_sync.for_capabilities(
+ settings_sync.desk_message_data(envelope, frame), caps)) for frame in profiles.frames(desk)]
+
+ def _carry_desk(self, outcome, *, source=None) -> None:
+ source_id = protocol.read_id(source) if isinstance(source, str) else source
+ self._publish_desk(outcome["settings"])
+ for peer, caps in self._peer_caps().items():
+ desk = outcome["forward"] if peer != source_id else outcome["answer"]
+ if desk:
+ for message in self._desk_messages(desk, caps):
+ self._send_to(peer, message)
+
+ def _publish_desk(self, settings=None) -> None:
+ """Send every desk register changed since the last publish, whatever changed it: a crossing
+ event, a pairing, a peer removed, a load that reconciled. Receivers ignore one they hold."""
+ if settings is None:
+ try:
+ with app_config.SETTINGS_LOCK:
+ settings = app_config.load_settings(self.config_path)
+ except (OSError, ValueError, app_config.SettingsFileError):
+ LOGGER.exception("could not read the settings to publish the desk")
+ return
+ desk = profiles.desk_message(settings)
+ # The first publish sends the whole desk: it is what any linked peer was last told.
+ held, self._desk_published = getattr(self, "_desk_published", {}), desk
+ paths = profiles.changed_paths(held, desk)
+ if paths:
+ changed = profiles.desk_message({"crossing_desk": desk}, paths)
+ for peer, caps in self._peer_caps().items():
+ for message in self._desk_messages(changed, caps):
+ self._send_to(peer, message)
+
def _announce(self, peer: bytes) -> list:
"""What this PC tells a peer on every new link (section 3): the side it holds for the peer,
once one has been set; the peers it may send to, when it may send to this one; and its
@@ -1634,6 +1730,7 @@ class WindowsApplication(QWidget):
return []
if any(protocol.read_id(item.get("id")) == peer and item.get("port") == 0 for item in self.book.peers()):
return []
+ self._profile_last_heard[protocol.id_text(peer)] = time.time()
with app_config.SETTINGS_LOCK:
settings = app_config.load_settings(self.config_path)
held_settings = copy.deepcopy(settings)
@@ -1649,7 +1746,7 @@ class WindowsApplication(QWidget):
# picture here would overtake the arrangement, especially for a gap peer.
carry = dict(outcome, tell=[ident for ident in outcome["tell"] if ident != protocol.id_text(peer)],
send_picture=False)
- self._carry_crossing(carry, redraw=False)
+ self._carry_crossing(carry, source=protocol.id_text(peer), redraw=False)
if outcome["send_picture"]:
self._send_same(source=peer, layout_only=True)
peers = outcome["settings"]["peers"]
@@ -1670,6 +1767,8 @@ class WindowsApplication(QWidget):
if entry.get("port") != 0 and set(self._peer_caps().get(peer, ())) & {"settings", "layout"}:
messages.append(protocol.settings_msg(settings_sync.for_capabilities(
self._same_state(), self._peer_caps().get(peer, ()))))
+ messages.extend(self._desk_messages(profiles.desk_message(outcome["settings"]),
+ self._peer_caps().get(peer, ())))
return messages
def _driver_platform(self) -> str:
@@ -1691,7 +1790,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", "design_sync", "layout", "displays", "ping_rtt")
+ "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync", "layout", "profiles", "displays", "ping_rtt")
if not (cap == "gestures" and OWN_PLATFORM == "linux")],
"port": self._settings_port,
}
@@ -1758,6 +1857,17 @@ class WindowsApplication(QWidget):
self.own_name_label.setText(own_name or platform.node())
self._refresh_peers()
source_id = protocol.read_id(peer)
+ if source_id is not None and "profiles" in self._peer_caps().get(source_id, ()):
+ desk_state = profiles.read_desk_state(data)
+ if desk_state is not None:
+ with app_config.SETTINGS_LOCK:
+ outcome = crossing_state.desk_arrived(
+ app_config.load_settings(self.config_path), desk_state, source=peer,
+ linked=self._live(peer), **self._crossing_event_args())
+ self._profile_last_heard[peer] = None
+ self._carry_crossing(outcome, source=peer)
+ if isinstance(data, dict) and "desk" in data:
+ data = {key: value for key, value in data.items() if key != "desk"}
if source_id is not None and "layout" in self._peer_caps().get(source_id, ()):
layout_state = settings_sync.read_layout_state(data)
if layout_state is not None:
@@ -1855,8 +1965,8 @@ class WindowsApplication(QWidget):
self._refresh_design_follow()
def _sign_in_module(self) -> QWidget:
- module = widgets.Module("At sign-in")
- self.logon_switch = widgets.Switch("Start Beamer when you sign in")
+ module = widgets.Module(tr("At sign-in"))
+ self.logon_switch = widgets.Switch(tr("Start Beamer when you sign in"))
self.logon_switch.setFont(theme.font(theme.TYPE["body"]))
exe = autostart_win.installed_exe()
account_known = True
@@ -1876,15 +1986,15 @@ class WindowsApplication(QWidget):
self.logon_switch.toggled.connect(self._set_start_at_logon)
module.body.addWidget(self.logon_switch)
if exe and not account_known:
- hint = "Windows could not identify the signed-in account, so start at sign-in is unavailable."
+ hint = tr("Windows could not identify the signed-in account, so start at sign-in is unavailable.")
elif exe and not can_start:
- hint = "Start at sign-in needs the same administrator account that runs Beamer."
+ hint = tr("Start at sign-in needs the same administrator account that runs Beamer.")
elif enabled:
- hint = "Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps."
+ hint = tr("Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps.")
elif exe:
- hint = "When enabled, a logon task starts Beamer elevated without a UAC prompt, so it can send input to administrator apps."
+ hint = tr("When enabled, a logon task starts Beamer elevated without a UAC prompt, so it can send input to administrator apps.")
else:
- hint = "Only the installed app can start at sign-in."
+ hint = tr("Only the installed app can start at sign-in.")
self.logon_hint = widgets.label(hint, "note", wrap=True)
module.body.addWidget(self.logon_hint)
return module
@@ -1900,15 +2010,16 @@ class WindowsApplication(QWidget):
self.logon_switch.blockSignals(True)
self.logon_switch.setChecked(not enabled)
self.logon_switch.blockSignals(False)
- self.logon_hint.setText(f"Windows refused: {exc}")
+ self.logon_hint.setText(tr("Windows refused: {error}").format(error=exc))
return
- self.logon_hint.setText("In the tray, with no window.")
+ self.logon_hint.setText(tr("In the tray, with no window."))
# -- Crossing -----------------------------------------------------------------------------
def _crossing_page(self, layout, current: Config) -> None:
self.crossing_document = layout.parentWidget().parentWidget()
- intro = widgets.label("Drag a machine on the map to where it sits. The ledger says how each one is reached; click a row to pick it on the map.", "note", wrap=True)
+ intro = widgets.label("", "note", wrap=True)
+ self.profile_intro = intro
intro.setMaximumWidth(560)
# A VBox measures capped labels at the full column width, losing a wrapped line.
intro_line = QHBoxLayout()
@@ -1917,6 +2028,9 @@ class WindowsApplication(QWidget):
intro_line.addStretch()
layout.addLayout(intro_line)
layout.addWidget(self._ways_module(current))
+ layout.addWidget(self._profile_override_module())
+ layout.addWidget(self._profile_ledger_module())
+ layout.addWidget(self._way_home_module())
self.pointer_module = self._pointer_module(current)
layout.addWidget(self.pointer_module)
desktop = linux_desktop.desktop() if sys.platform.startswith("linux") else ""
@@ -1960,51 +2074,465 @@ class WindowsApplication(QWidget):
return row
def _ways_module(self, current: Config) -> QWidget:
- from crossing_ledger import CrossingLedger
- module = widgets.Module("Machines", heading=True)
+ from crossing_ledger import _Flow
+ module = widgets.Module("", heading=True)
+ module.eyebrow.hide()
self.ways_module = module
+ self.profile_header = QWidget()
+ self.profile_header.setProperty("vernier", "plain")
+ header = QHBoxLayout(self.profile_header)
+ header.setContentsMargins(0, 0, 0, 0)
+ header.setSpacing(12)
+ self.profile_tabs = QWidget()
+ self.profile_tabs.setProperty("vernier", "plain")
+ self.profile_tabs_layout = _Flow(self.profile_tabs)
+ self.profile_buttons = {}
+ header.addWidget(self.profile_tabs, 1)
+ self.same_ways_switch = widgets.Switch(tr("Same ways on every machine"))
+ self.same_ways_switch.toggled.connect(lambda on: self._profile_event(crossing_state.set_same_ways, on))
+ header.addWidget(self.same_ways_switch)
+ self.profile_header.installEventFilter(self)
+ module.body.addWidget(self.profile_header)
+ self.profile_actions = QWidget()
+ self.profile_actions.setProperty("vernier", "plain")
+ actions = _Flow(self.profile_actions)
+ self.profile_new = QPushButton(tr("New profile…"))
+ self.profile_new.clicked.connect(lambda: self._ask_profile_name())
+ # A click on a tab switches the whole desk, so a tab cannot be picked for an action: Rename
+ # names the active profile, and Delete offers the others (the active one never goes).
+ self.profile_rename = QPushButton(tr("Rename"))
+ self.profile_rename.clicked.connect(
+ lambda: self._ask_profile_name(self._profile_settings()["crossing_desk"]["active"]["value"]))
+ self.profile_delete = QPushButton(tr("Delete…"))
+ self.profile_delete.clicked.connect(self._show_profile_delete_menu)
+ for button in (self.profile_new, self.profile_rename, self.profile_delete):
+ button.setProperty("vernier", "small")
+ button.setFlat(True)
+ actions.addWidget(button)
+ module.body.addWidget(self.profile_actions)
+ self.profile_off_note = widgets.label(tr("Set every machine's ways from this screen. Turning it on changes nothing until you do; each machine's own ways are kept."), "note", wrap=True)
+ module.body.addWidget(self.profile_off_note)
+ self.profile_name_row = QWidget()
+ name_line = QHBoxLayout(self.profile_name_row)
+ name_line.setContentsMargins(0, 0, 0, 0)
+ self.profile_name = QLineEdit()
+ self.profile_name.setMaxLength(32)
+ self.profile_name.setAccessibleName(tr("Profile name"))
+ name_line.addWidget(self.profile_name, 1)
+ save = QPushButton(tr("Save"))
+ save.clicked.connect(self._save_profile_name)
+ self.profile_name.returnPressed.connect(self._save_profile_name)
+ name_line.addWidget(save)
+ cancel = QPushButton(tr("Cancel"))
+ cancel.clicked.connect(self.profile_name_row.hide)
+ name_line.addWidget(cancel)
+ self.profile_name_row.hide()
+ module.body.addWidget(self.profile_name_row)
+ self.profile_note = widgets.label("", "note-amber", wrap=True)
+ self.profile_note.hide()
+ module.body.addWidget(self.profile_note)
self.atlas_canvas = AtlasCanvas(
on_drop=self._layout_dropped, on_rename=self._rename_canvas_peer,
on_leave_out=self._canvas_left_out, on_cycle=self._set_shortcut_cycle,
- on_select=self._choose_machine, on_third=self._canvas_third)
+ on_select=self._choose_machine, on_third=self._canvas_third,
+ on_edit_machine=self._edit_profile_machine)
self.atlas_canvas.on_hint = self.atlas_canvas.announce
self.atlas_canvas.setMinimumHeight(260)
self.atlas_canvas.setMaximumHeight(260)
self.atlas_canvas.ledger_height = True
module.body.addWidget(self.atlas_canvas)
self.atlas_canvas_hint = widgets.label(
- "Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out",
+ tr("Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"),
"note", wrap=True)
module.body.addWidget(self.atlas_canvas_hint)
if sys.platform.startswith("linux"):
- module.body.addWidget(widgets.label("Seam crossings need X11 on Linux.", "note", wrap=True))
+ module.body.addWidget(widgets.label(tr("Seam crossings need X11 on Linux."), "note", wrap=True))
legend = QWidget()
legend.setProperty("vernier", "plain")
line = QHBoxLayout(legend)
line.setContentsMargins(0, 0, 0, 0)
line.setSpacing(6)
- for tone, text in (("signal", "Crosses"), ("ink_3", "Offline, ways kept")):
+ for tone, text in (("signal", N_("Crosses")), ("ink_3", N_("Offline, ways kept"))):
dot = QLabel()
dot.setFixedSize(6, 6)
dot.setStyleSheet(f"background: {theme.colour(tone)}; border-radius: 3px")
line.addWidget(dot)
- line.addWidget(widgets.label(text, "note"))
+ line.addWidget(widgets.label(tr(text), "note", wrap=True))
line.addSpacing(12)
line.addStretch()
module.body.addWidget(legend)
+ self.profile_switch_note = widgets.label(tr("Switching moves every machine to this profile's places and ways."), "note", wrap=True)
+ module.body.addWidget(self.profile_switch_note)
+ return module
+
+ def _profile_ledger_module(self) -> QWidget:
+ from crossing_ledger import CrossingLedger
+ module = widgets.Module("", heading=True)
+ self.profile_ledger_module = module
+ module.eyebrow.setProperty("profile_heading", True)
+ self.profile_editing_row = QWidget()
+ self.profile_editing_row.setProperty("vernier", "plain")
+ editing = QHBoxLayout(self.profile_editing_row)
+ editing.setContentsMargins(0, 0, 0, 0)
+ editing.setSpacing(6)
+ self.profile_editing = widgets.ElidingLabel("")
+ self.profile_editing.setProperty("vernier", "body")
+ editing.addWidget(self.profile_editing)
+ self.profile_back = QPushButton(tr("Back to This PC"))
+ self.profile_back.setProperty("vernier", "small")
+ self.profile_back.setFlat(True)
+ self.profile_back.clicked.connect(lambda: self._edit_profile_machine(self._config.machine_id))
+ editing.addWidget(self.profile_back)
+ editing.addStretch()
+ module.body.addWidget(self.profile_editing_row)
+ self.profile_machine_status = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.profile_machine_status)
+ self.profile_remote_note = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.profile_remote_note)
+ self.profile_permissions_note = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.profile_permissions_note)
self.crossing_ledger = CrossingLedger(self)
module.body.addWidget(self.crossing_ledger)
module.body.addWidget(widgets.label(
- "Each chip is a side of this screen; click one to add or remove it. The side a machine touches "
+ tr("Each chip is a side of this screen; click one to add or remove it. The side a machine touches "
"crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. "
- "A corner is a diagonal push, shown as a square on the map.", "note", wrap=True))
+ "A corner is a diagonal push, shown as a square on the map."), "note", wrap=True))
+ return module
+
+ def _profile_override_module(self) -> QWidget:
+ from crossing_ledger import _Flow
+ module = widgets.Module("", heading=True)
+ self.profile_override = module
+ self.profile_override_row = QWidget()
+ self.profile_override_row.setProperty("vernier", "plain")
+ own_line = QHBoxLayout(self.profile_override_row)
+ own_line.setContentsMargins(0, 0, 0, 0)
+ self.profile_keep_own = QPushButton(tr("Keep this machine's own ways"))
+ self.profile_keep_own.setProperty("vernier", "small")
+ self.profile_keep_own.clicked.connect(lambda: self._profile_event(crossing_state.set_own_ways, True))
+ own_line.addWidget(self.profile_keep_own)
+ self.profile_archive_toggle = QPushButton(tr("Earlier ways"))
+ self.profile_archive_toggle.setProperty("vernier", "small")
+ self.profile_archive_toggle.setCheckable(True)
+ own_line.addWidget(self.profile_archive_toggle)
+ own_line.addStretch()
+ self.profile_override_row.installEventFilter(self)
+ module.body.addWidget(self.profile_override_row)
+ actions = QWidget()
+ actions.setProperty("vernier", "plain")
+ self.profile_own_actions = actions
+ line = _Flow(actions)
+ self.profile_use_desk = QPushButton(tr("Use the desk's ways"))
+ self.profile_use_desk.clicked.connect(lambda: self._profile_event(crossing_state.set_own_ways, False))
+ line.addWidget(self.profile_use_desk)
+ self.profile_share_mine = QPushButton(tr("Share mine with the desk"))
+ self.profile_share_mine.clicked.connect(lambda: self._profile_event(crossing_state.share_mine))
+ line.addWidget(self.profile_share_mine)
+ module.body.insertWidget(1, actions)
+ self.profile_archive = QWidget()
+ self.profile_archive.setProperty("vernier", "plain")
+ self.profile_archive_rows = QVBoxLayout(self.profile_archive)
+ self.profile_archive_rows.setContentsMargins(0, 0, 0, 0)
+ self.profile_archive_toggle.toggled.connect(self._profile_show_archive)
+ self.profile_archive.hide()
+ module.body.addWidget(self.profile_archive)
+ self.profile_load_note = widgets.label(tr("This machine kept the ways set while it ran an older Beamer."), "note-amber", wrap=True)
+ self.profile_load_note.hide()
+ module.body.addWidget(self.profile_load_note)
return module
+ def _profile_show_archive(self, opened):
+ self.profile_archive.setVisible(opened)
+ self.profile_archive_toggle.setText(tr("Earlier ways ▴") if opened else tr("Earlier ways ▾"))
+
+ def _way_home_module(self) -> QWidget:
+ module = widgets.Module(tr("Way home"), heading=True)
+ self.way_home_module = module
+ module.eyebrow.setProperty("profile_heading", True)
+ self.shake_home_switch = widgets.Switch(tr("Shake to come home"))
+ self.shake_home_switch.toggled.connect(lambda on: self._profile_event(crossing_state.set_shake, on))
+ module.body.addWidget(self.shake_home_switch)
+ self.shake_sensitivity = widgets.Ruler(tr("Shake sensitivity"), 200, minimum=50,
+ step=10, ticks=(50, 100, 150, 200))
+ self.shake_sensitivity.valueChanged.connect(self._shake_sensitivity_changed)
+ self.shake_sensitivity_figure = widgets.Figure("100 %")
+ self.shake_sensitivity_row = widgets.FormRow(
+ widgets.label(tr("Shake sensitivity"), "key"), self.shake_sensitivity_figure)
+ module.body.addWidget(self.shake_sensitivity_row)
+ module.body.addWidget(self.shake_sensitivity)
+ module.body.addWidget(widgets.label(tr("Shake the mouse or trackpad left and right a few times while you drive another machine, and input comes straight back to the machine you are using."), "note", wrap=True))
+ self.profile_shortcut = widgets.label("", "note", wrap=True)
+ self.profile_shortcut.setTextFormat(Qt.TextFormat.RichText)
+ self.profile_shortcut.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
+ self.profile_shortcut.linkActivated.connect(self._profile_open_shortcut)
+ module.body.addWidget(self.profile_shortcut)
+ module.body.addWidget(widgets.label(tr("Push back the way you came: where an edge leads back to This PC"), "note", wrap=True))
+ self.profile_no_return = widgets.label("", "note", wrap=True)
+ self.profile_no_return.setProperty("profile_warning", True)
+ module.body.addWidget(self.profile_no_return)
+ return module
+
+ def _profile_open_shortcut(self) -> None:
+ self._select_page("overview")
+ shortcut = self.same_checks["shortcut"]
+ shortcut.setFocus()
+ area = shortcut.parentWidget()
+ while area is not None and not isinstance(area, QScrollArea):
+ area = area.parentWidget()
+ if area is not None:
+ area.ensureWidgetVisible(shortcut)
+
+ def _profile_settings(self) -> dict:
+ try:
+ return self._window_settings()
+ except (ConfigError, OSError):
+ # Keep the settings-error window usable without touching the unreadable file.
+ if not hasattr(self, "_profile_empty_settings"):
+ config = self._config or default_config()
+ empty = app_config.migrate(None, machine_id=config.machine_id)
+ self._profile_empty_settings, _ = profiles.before_load(empty)
+ return self._profile_empty_settings
+
+ def _profile_machine(self) -> str:
+ settings = self._profile_settings()
+ chosen = getattr(self, "_profile_viewed", None)
+ if not profiles.same_ways_on(settings) or chosen not in profiles.machines_on_desk(settings):
+ return settings["machine_id"]
+ return chosen
+
+ def _profile_remote(self) -> bool:
+ return self._profile_machine() != self._profile_settings()["machine_id"]
+
+ def _profile_caps(self, machine, settings=None) -> set:
+ settings = settings or self._profile_settings()
+ if machine == settings["machine_id"]:
+ return {"layout", "profiles"}
+ known = self._design_peer_caps()
+ if machine in known:
+ return set(known[machine])
+ entry = ways._entry(settings, machine) or {}
+ if "caps" in entry:
+ return set(entry["caps"])
+ # Relayed machines have no local handshake; their own status proves profiles support.
+ return {"layout", "profiles"} if machine in settings["crossing_desk"].get("status", {}) else set()
+
+ def _profile_read_only(self) -> bool:
+ return self._profile_remote() and "profiles" not in self._profile_caps(self._profile_machine())
+
+ def _crossing_view_settings(self) -> dict:
+ settings = self._profile_settings()
+ if profiles.same_ways_on(settings):
+ viewed = profiles.view_settings(settings, self._profile_machine())
+ platforms = {entry["id"]: entry.get("platform") for entry in settings["peers"]}
+ platforms[settings["machine_id"]] = "linux" if sys.platform.startswith("linux") else "windows"
+ for entry in viewed["peers"]:
+ if platforms.get(entry["id"]):
+ entry["platform"] = platforms[entry["id"]]
+ return viewed
+ return self._crossing_settings()
+
+ @_crossing_refresh
+ def _edit_profile_machine(self, machine) -> None:
+ self._profile_viewed = machine
+ self._chosen = None
+ self.atlas_canvas.selected = machine
+ self._reflect_ways()
+
+ @_crossing_refresh
+ def _profile_event(self, event, *args) -> bool:
+ if self._config is None:
+ return False
+ full_args = (crossing_state.set_same_ways, crossing_state.set_own_ways,
+ crossing_state.switch_profile, crossing_state.restore_saved)
+ options = self._crossing_event_args() if event in full_args else dict(platform="pc", now=time.time())
+ try:
+ with app_config.SETTINGS_LOCK:
+ settings = app_config.load_settings(self.config_path)
+ outcome = event(settings, *args, **options)
+ if not outcome.get("accepted", True):
+ message = {"desk_full": tr("This desk is full. Remove an unused profile before adding more ways."),
+ "invalid_name": tr("Give the profile a name of 1 to 32 characters.")}.get(
+ outcome.get("reason"), tr("These ways could not be changed."))
+ self.profile_note.setText(message)
+ self.profile_note.show()
+ return False
+ self.profile_note.hide()
+ self._carry_crossing(outcome)
+ self._show_same()
+ if hasattr(self, "profile_menu"):
+ self._refresh_tray_profiles()
+ return True
+ except (ConfigError, OSError):
+ LOGGER.exception("The profile could not be saved")
+ self.profile_note.setText(tr("These ways could not be saved. Try again."))
+ self.profile_note.show()
+ return False
+
+ def _ask_profile_name(self, profile_id=None) -> None:
+ self._profile_naming = profile_id
+ held = next((item for item in profiles.profile_list(self._profile_settings()) if item["id"] == profile_id), None)
+ self.profile_name.setText(held["name"] if held else "")
+ self.profile_name_row.show()
+ self.profile_name.setFocus()
+ self.profile_name.selectAll()
+
+ def _save_profile_name(self) -> None:
+ profile_id = getattr(self, "_profile_naming", None)
+ args = (profile_id, self.profile_name.text()) if profile_id else (self.profile_name.text(),)
+ if self._profile_event(crossing_state.rename_profile if profile_id else crossing_state.new_profile, *args):
+ self.profile_name_row.hide()
+
+ def _profile_delete_menu(self) -> QMenu:
+ """The profiles Delete… offers: every one but the active profile."""
+ settings = self._profile_settings()
+ active = settings["crossing_desk"]["active"]["value"]
+ menu = QMenu(self.profile_delete)
+ for item in profiles.profile_list(settings):
+ if item["id"] != active:
+ menu.addAction(item["label"], lambda p=item["id"]: self._profile_event(crossing_state.remove_profile, p))
+ return menu
+
+ def _show_profile_delete_menu(self) -> None:
+ self._profile_delete_menu().exec(self.profile_delete.mapToGlobal(self.profile_delete.rect().bottomLeft()))
+
+ def _profile_tab_menu(self, profile_id, button, point) -> None:
+ menu = QMenu(button)
+ menu.addAction(tr("Rename"), lambda: self._ask_profile_name(profile_id))
+ remove = menu.addAction(tr("Delete"), lambda: self._profile_event(crossing_state.remove_profile, profile_id))
+ settings = self._profile_settings()
+ remove.setEnabled(len(profiles.profile_list(settings)) > 1 and
+ settings["crossing_desk"]["active"]["value"] != profile_id)
+ menu.exec(button.mapToGlobal(point))
+
+ def _reflect_profiles(self, settings) -> None:
+ config = self._config or default_config()
+ on = profiles.same_ways_on(settings)
+ remote = self._profile_remote()
+ machine = self._profile_machine()
+ name = self._profile_machine_name(settings, machine)
+ self.profile_intro.setText(tr("Click a machine on the map to set its ways. The ledger says how it reaches each other machine.") if on else
+ tr("Drag a machine on the map to where it sits. The ledger says how each one is reached; click a row to pick it on the map."))
+ self.same_ways_switch.blockSignals(True)
+ self.same_ways_switch.setChecked(on)
+ self.same_ways_switch.blockSignals(False)
+ self.same_ways_switch.setEnabled(self._config is not None)
+ self.profile_tabs.setVisible(on)
+ self.profile_actions.setVisible(on)
+ self.atlas_canvas_hint.setText(tr("Click a machine to set its ways · Tab and Return pick one from the keyboard") if on else
+ tr("Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize"))
+ self.atlas_canvas_hint.show()
+ self.profile_off_note.setVisible(not on)
+ self.profile_switch_note.setVisible(on and len(profiles.profile_list(settings)) > 1)
+ if not on:
+ self.profile_name_row.hide()
+ tab_items = profiles.profile_list(settings)
+ tab_signature = tuple((item["id"], item["label"]) for item in tab_items)
+ if tab_signature != getattr(self, "_profile_tabs_seen", None):
+ self._profile_tabs_seen = tab_signature
+ while self.profile_tabs_layout.count():
+ item = self.profile_tabs_layout.takeAt(0)
+ item.widget().deleteLater()
+ self.profile_buttons = {}
+ for item in tab_items:
+ pid = item["id"]
+ button = QPushButton(tr("Desk") if pid == profiles.DESK_ID and item["name"] == "Desk" else item["label"])
+ button.setCheckable(True)
+ button.setProperty("vernier", "choice")
+ button.setMinimumWidth(button.sizeHint().width())
+ button.installEventFilter(self)
+ button.clicked.connect(lambda _checked=False, p=pid: self._profile_event(crossing_state.switch_profile, p))
+ button.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
+ button.customContextMenuRequested.connect(lambda point, p=pid, b=button: self._profile_tab_menu(p, b, point))
+ self.profile_tabs_layout.addWidget(button)
+ self.profile_buttons[pid] = button
+ add = QPushButton(tr("+"))
+ add.setProperty("vernier", "small")
+ add.setFlat(True)
+ add.setFixedWidth(24)
+ add.setAccessibleName(tr("New profile"))
+ add.clicked.connect(lambda: self._ask_profile_name())
+ self.profile_tabs_layout.addWidget(add)
+ for pid, button in self.profile_buttons.items():
+ button.setChecked(pid == settings["crossing_desk"]["active"]["value"])
+ self.profile_delete.setEnabled(len(tab_items) > 1)
+ own = settings["crossing_own"].get("use_own") is True
+ saved = profiles.saved_list(settings)
+ notes = app_config.load_notes(self.config_path)
+ self._profile_older_note = getattr(self, "_profile_older_note", False) or "older_version" in notes
+ self.profile_override.setVisible(not remote and (on or self._profile_older_note))
+ self.profile_override.eyebrow.setText(tr("This PC keeps its own ways") if own and on else "")
+ self.profile_override.eyebrow.setVisible(own and on)
+ self.profile_keep_own.setVisible(on and not own)
+ self.profile_use_desk.setVisible(on and own)
+ self.profile_own_actions.setVisible(on and own)
+ desk = settings["crossing_desk"]
+ desk_row = desk["profiles"][desk["active"]["value"]].get("rows", {}).get(settings["machine_id"], {}).get("value", {})
+ self.profile_share_mine.setVisible(on and own and settings["crossing_own"]["row"] != desk_row)
+ self.profile_archive_toggle.setVisible(on and bool(saved))
+ self.profile_archive_toggle.setText(tr("Earlier ways ▴") if self.profile_archive_toggle.isChecked() else tr("Earlier ways ▾"))
+ self.profile_override_row.setVisible(on and (not own or bool(saved)))
+ signature = repr(saved)
+ if signature != getattr(self, "_profile_saved_seen", None):
+ self._profile_saved_seen = signature
+ while self.profile_archive_rows.count():
+ self.profile_archive_rows.takeAt(0).widget().deleteLater()
+ for item in saved:
+ row = QWidget()
+ row.setProperty("vernier", "plain")
+ line = QHBoxLayout(row)
+ line.setContentsMargins(0, 0, 0, 0)
+ line.addWidget(widgets.label(pages_win.saved_ways_label(item, settings), "note", wrap=True), 1)
+ for title, event in ((tr("Restore"), crossing_state.restore_saved), (tr("Delete"), crossing_state.delete_saved)):
+ button = QPushButton(title)
+ button.setProperty("vernier", "small")
+ button.clicked.connect(lambda _checked=False, e=event, ident=item["id"]: self._profile_event(e, ident))
+ line.addWidget(button)
+ self.profile_archive_rows.addWidget(row)
+ self.profile_archive.setVisible(on and bool(saved) and self.profile_archive_toggle.isChecked())
+ self.profile_load_note.setVisible(self._profile_older_note)
+ self.profile_ledger_module.eyebrow.setText(tr("{name}'s ways").format(name=name))
+ self.profile_editing.setText(tr("Editing {name}'s ways ·").format(name=name))
+ self.profile_editing_row.setVisible(remote)
+ self.profile_editing.setVisible(remote)
+ self.profile_back.setVisible(remote)
+ self.profile_remote_note.setText(tr("Changes go to {name} at once.").format(name=name))
+ self.profile_remote_note.setVisible(remote and not self._profile_read_only())
+ self.profile_permissions_note.setText(tr("Jump keys and permissions are set on {name}.").format(name=name))
+ self.profile_permissions_note.setVisible(remote)
+ if "crossing" in self.scope_labels:
+ self.scope_labels["crossing"].setVisible(not on)
+ self.profile_machine_status.setVisible(remote)
+ if remote:
+ self.profile_machine_status.setText(profiles.machine_line(settings, machine, linked=self._live(machine),
+ caps=self._profile_caps(machine, settings), last_heard=getattr(self, "_profile_last_heard", {}).get(machine)))
+ self.shake_home_switch.blockSignals(True)
+ self.shake_home_switch.setChecked(profiles.shake_on(settings))
+ self.shake_home_switch.blockSignals(False)
+ self.shake_home_switch.setEnabled(self._config is not None)
+ self.shake_sensitivity.blockSignals(True)
+ self.shake_sensitivity.setValue(profiles.shake_sensitivity(settings))
+ self.shake_sensitivity_figure.setText(f"{self.shake_sensitivity.value()} %")
+ self.shake_sensitivity.blockSignals(False)
+ self.shake_sensitivity.setEnabled(self._config is not None)
+ key = TRIGGER_KEYS.get(config.trigger_key, config.trigger_key)
+ style = tr("hold {key}") if config.trigger_style == "hold" else tr("double-tap {key}")
+ keycap = '<span style="font-family: {}">{}</span>'.format(html.escape(theme.mono_font(theme.TYPE["note"]).family(), quote=True), html.escape(key))
+ link = '<a href="shortcut" style="color: {}">{}</a>'.format(theme.colour("ink_2"), html.escape(tr("Same → Shortcut")))
+ self.profile_shortcut.setText(tr("Shortcut: {shortcut} (set in {link})").format(shortcut=style.format(key=keycap), link=link))
+ names = profiles.no_way_back(settings, machine)
+ self.profile_no_return.setText("\n".join(tr("{name} has no way back to {machine} except the shortcut and a shake.").format(name=other, machine=name) for other in names))
+ self.profile_no_return.setVisible(bool(names))
+
+ def _profile_machine_name(self, settings, machine) -> str:
+ if machine == settings["machine_id"]:
+ return tr("This PC")
+ return self._shown(peerlist.label_for(settings["peers"], peer_id=machine) or
+ settings.get("layout", {}).get(machine, {}).get("name") or tr("Machine"))
+
def _pointer_module(self, current: Config) -> QWidget:
- module = widgets.Module("This machine's pointer", heading=True)
- self.dragging_switch = widgets.Switch("Don't cross while dragging with this PC's pointer")
- note = ("Applies when this physical pointer pushes through this screen's ways; "
- "visiting pointers are not protected by this switch.")
+ module = widgets.Module(tr("This machine's pointer"), heading=True)
+ self.dragging_switch = widgets.Switch(tr("Don't cross while dragging with this PC's pointer"))
+ note = tr("Applies when this physical pointer pushes through this screen's ways; visiting pointers are not protected by this switch.")
self.dragging_switch.setToolTip(note)
self.dragging_switch.setFont(theme.font(theme.TYPE["body"]))
self.dragging_switch.setChecked(current.block_while_dragging)
@@ -2039,7 +2567,8 @@ class WindowsApplication(QWidget):
return [(ident, self._shown(label)) for ident, label in pages_win.crossing_machines(self._peer_entries)]
def _chosen_machine(self) -> Optional[str]:
- ids = [entry.get("id") for entry in peerlist.desktops(self._peer_entries)]
+ entries = self._crossing_view_settings()["peers"] if self._profile_remote() else peerlist.desktops(self._peer_entries)
+ ids = [entry.get("id") for entry in entries]
return self._chosen if self._chosen in ids else (ids[0] if ids else None)
def _ways_in(self) -> set:
@@ -2054,21 +2583,28 @@ class WindowsApplication(QWidget):
@_crossing_refresh
def _choose_machine(self, peer: str) -> None:
self._chosen = peer
+ self.atlas_canvas.selected = peer
self._reflect_ways()
self._reflect_look()
@_crossing_refresh
def _layout_dropped(self, layout: dict, moved: str) -> bool:
- if not self._config or moved == self._config.machine_id or moved not in layout:
+ if not self._config or moved not in layout:
self._reflect_ways()
return False
with app_config.SETTINGS_LOCK:
settings = app_config.load_settings(self.config_path)
+ if moved == self._config.machine_id:
+ held = ways.derive_layout(settings)[moved]
+ if (not isinstance(layout[moved], dict)
+ or any(layout[moved].get(axis) != held[axis] for axis in ("x", "y"))):
+ self._reflect_ways()
+ return False
outcome = crossing_state.drop(settings, layout, moved, snap_radius=12 / max(self.atlas_canvas._scale, 0.001),
**self._crossing_event_args())
if not outcome["accepted"]:
self._reflect_ways()
- self.atlas_canvas.announce("That position cannot connect this machine.")
+ self.atlas_canvas.announce(tr("That position cannot connect this machine."))
return False
self._carry_crossing(outcome)
return True
@@ -2109,6 +2645,8 @@ class WindowsApplication(QWidget):
self.sender.refresh()
self.server.peers_changed()
self.server.rearm()
+ self._configure_shake(saved)
+ self._carry_desk(outcome, source=source)
for peer in outcome["tell"]:
self._tell(peer)
if outcome["send_picture"]:
@@ -2118,6 +2656,31 @@ class WindowsApplication(QWidget):
if redraw and outcome["changed"]:
self._reflect_ways()
self._reflect_look()
+ self._refresh_tray_profiles(outcome["settings"])
+
+ def _configure_shake(self, settings=None) -> None:
+ settings = app_config.load_settings(self.config_path) if settings is None else settings
+ enabled = profiles.shake_on(settings)
+ sensitivity = profiles.shake_sensitivity(settings)
+ if (enabled, sensitivity) != (self._shake_enabled, self._shake_sensitivity):
+ self.sender.set_shake(enabled, shake_stroke(capture_win, sensitivity), on_shake=self.bridge.shook_home.emit)
+ self._shake_enabled = enabled
+ self._shake_sensitivity = sensitivity
+
+ def _shake_sensitivity_changed(self, sensitivity: int) -> None:
+ self._profile_event(crossing_state.set_shake_sensitivity, sensitivity)
+
+ def _on_shake(self, peer) -> None:
+ with app_config.SETTINGS_LOCK:
+ settings = app_config.load_settings(self.config_path)
+ count = settings.get("shake_notices", 0)
+ count = count if type(count) is int and count >= 0 else 0
+ if count >= 3:
+ return
+ settings["shake_notices"] = count + 1
+ app_config.write_settings(self.config_path, settings)
+ self._on_alert(tr("Beamer"), tr("Shook home from {name}. Turn this off in Crossing → Way home.").format(
+ name=self._label_of(peer)))
def _displays_changed(self) -> None:
self._refresh_own_displays()
@@ -2205,16 +2768,19 @@ class WindowsApplication(QWidget):
peer = peer or self._chosen_machine()
if self._config is None or peer is None:
return False
+ if self._profile_read_only():
+ return False
with app_config.SETTINGS_LOCK:
settings = app_config.load_settings(self.config_path)
- entry = ways._entry(settings, peer)
+ viewed = profiles.view_settings(settings, self._profile_machine()) if self._profile_remote() else settings
+ entry = ways._entry(viewed, peer)
if entry is None or entry.get("left_out") is True:
return False
if "methods" in changes:
methods = changes.pop("methods")
changes.update(edge=bool(set(methods) & {"edge", "part"}))
# Corner only when its on/off changes, so an Edge write leaves several corners as they are.
- if ("corner" in methods) != bool(ways.ways(settings, peer)["corners"]):
+ if ("corner" in methods) != bool(ways.ways(viewed, peer)["corners"]):
changes["corner"] = "corner" in methods
if "edge" in methods:
changes["thirds"] = list(ways.PARTS)
@@ -2224,8 +2790,17 @@ class WindowsApplication(QWidget):
changes["corner_at"] = changes.pop("corner")
changes.pop("side", None)
try:
- outcome = crossing_state.edit_ways(settings, peer, **changes, **self._crossing_event_args())
+ if self._profile_remote():
+ outcome = crossing_state.edit_other(settings, self._profile_machine(), peer,
+ **changes, platform="pc", now=time.time())
+ else:
+ outcome = crossing_state.edit_ways(settings, peer, **changes, **self._crossing_event_args())
self._carry_crossing(outcome)
+ if outcome.get("reason") == "desk_full":
+ self.profile_note.setText(tr("This desk is full. Remove an unused profile before adding more ways."))
+ self.profile_note.show()
+ if not outcome.get("accepted", True):
+ return False
except (ConfigError, OSError):
LOGGER.exception("A machine's ways could not be saved")
self._reflect_ways()
@@ -2233,24 +2808,31 @@ class WindowsApplication(QWidget):
return True
def _ledger_edge(self, peer):
- held = ways.ways(self._crossing_settings(), peer)
+ held = ways.ways(self._crossing_view_settings(), peer)
methods, parts = ways.toggle_edge(held["methods"], held["parts"])
self._write_ways(peer=peer, methods=methods, parts=parts)
def _ledger_third(self, peer, third):
- held = ways.ways(self._crossing_settings(), peer)
+ held = ways.ways(self._crossing_view_settings(), peer)
if held["side"] not in ways.EDGES:
return
methods, parts = ways.toggle_third(held["methods"], held["parts"], third)
self._write_ways(peer=peer, methods=methods, parts=parts)
def _reach(self, settings: dict, peer: str) -> dict:
- return ways.reach(settings, peer, **{k: v for k, v in self._crossing_event_args().items() if k != "now"})
+ options = {k: v for k, v in self._crossing_event_args().items() if k != "now"}
+ if settings.get("machine_id") != self._profile_settings()["machine_id"]:
+ options.update(platform=profiles.view_platform(self._profile_settings(), settings["machine_id"]),
+ capable=set(settings.get("layout", {})), live=self._profile_live, gone=lambda _peer: False)
+ return ways.reach(settings, peer, **options)
+
+ def _profile_live(self, peer):
+ return peer == self._profile_settings()["machine_id"] or self._live(peer)
def _ledger_side(self, peer, side):
"""A wrap-around chip: free adds the side (turning Edge on), on removes it, kept with Edge
off turns Edge on and otherwise removes it. Held and unavailable sides change nothing."""
- settings = self._crossing_settings()
+ settings = self._crossing_view_settings()
if self._reach(settings, peer)["sides"][side]["state"] not in ("free", "on", "kept"):
return
held = ways.ways(settings, peer)
@@ -2264,7 +2846,7 @@ class WindowsApplication(QWidget):
self._write_ways(peer=peer, edges=[kept for kept in edges if kept != side])
def _ledger_corner(self, peer, corner):
- settings = self._crossing_settings()
+ settings = self._crossing_view_settings()
corners = list(ways.ways(settings, peer)["corners"])
# A corner already on can always be taken off; a new one needs a side contact and nobody else holding it.
if corner not in corners and self._reach(settings, peer)["corners"][corner]["state"] != "free":
@@ -2273,7 +2855,7 @@ class WindowsApplication(QWidget):
else corners + [corner])
def _ledger_jump(self, peer, value):
- if self._config is None:
+ if self._config is None or self._profile_remote():
return
try:
app_config.set_jump_key(self.config_path, peer, value, self._config.trigger_key)
@@ -2319,16 +2901,23 @@ class WindowsApplication(QWidget):
def _reflect_ways(self) -> None:
"""Refresh the map and existing ledger cells without replacing the page."""
config = self._config or default_config()
- settings = self._crossing_settings()
+ full = self._profile_settings()
+ self._reflect_profiles(full)
+ settings = self._crossing_view_settings()
+ remote = self._profile_remote()
+ viewed_id = settings["machine_id"]
chosen = self._chosen_machine()
- entries = peerlist.desktops(self._peer_entries)
- labels = {config.machine_id: "This PC"}
+ # Another machine's row lists its peers from its view; this machine's own, the cached entries.
+ entries = peerlist.desktops(settings["peers"] if remote else self._peer_entries)
+ labels = {config.machine_id: tr("This PC")}
labels.update({entry["id"]: self._shown(peerlist.label_for(entries, peer_id=entry["id"])
or f"Machine · {entry['id'][-6:]}")
for entry in entries})
- all_layout = ways.derive_layout({**settings, "layout": config.layout}, gap=0)
+ all_layout = ways.derive_layout(settings, gap=0)
labels.update({peer: tile.get("name") or f"Machine · {peer[-6:]}"
for peer, tile in all_layout.items() if peer not in labels})
+ if profiles.same_ways_on(full):
+ labels.update({peer: self._profile_machine_name(full, peer) for peer in all_layout})
left_out = {entry["id"] for entry in entries if entry.get("left_out")}
dormant = {entry["id"] for entry in entries if peerlist.dormant_reason(entry) is not None or self._gone(entry["id"])}
in_use = {entry["id"]: entry.get("in_use", True) for entry in entries}
@@ -2337,9 +2926,12 @@ class WindowsApplication(QWidget):
known_caps = self._design_peer_caps()
capable = {peer for peer, caps in known_caps.items() if "layout" in caps}
active = {**settings, "peers": [entry for entry in entries if entry["id"] not in shelved]}
- result = ways.compile_layout(active, layout, capable=capable)
+ if remote:
+ capable = set(layout)
+ result = ways.compile_layout(active, layout, capable=capable,
+ platform=profiles.view_platform(full, viewed_id))
tile_states = result.get("tiles", {})
- tile_states[config.machine_id] = {"state": "this", "detail": config.name or platform.node()}
+ tile_states[viewed_id] = {"state": "this", "detail": self._profile_machine_name(full, viewed_id)}
legacy = {}
ledger_reach = {entry["id"]: self._reach(settings, entry["id"]) for entry in entries}
for entry in entries:
@@ -2348,7 +2940,7 @@ class WindowsApplication(QWidget):
held = ways.ways(settings, peer)
picked = ways.picked_thirds(held["methods"], held["parts"])
touched = state.get("thirds")
- own, tile = layout.get(config.machine_id), layout.get(peer)
+ own, tile = layout.get(viewed_id), layout.get(peer)
contact = ways._rect_contact(own, tile) if own and tile else None
edge_on = bool(set(held["methods"]) & {"edge", "part"})
# Pads for the corners that cross now, from the compile, never the saved intent alone.
@@ -2359,7 +2951,7 @@ class WindowsApplication(QWidget):
thirds=picked, lit=[part for part in picked if touched is None or part in touched],
crosses=bool((edge_on and state.get("state") in ("edge", "part")) or state.get("wraps") or corners),
edge_off=not edge_on and not corners and bool(contact and contact[0] != "corner"),
- linked=self._live(peer))
+ linked=self._profile_live(peer))
if state["edge_off"]:
state["state"] = "gap"
platform_name = {"windows": "Windows", "macos": "macOS", "linux": "Linux"}.get(
@@ -2368,25 +2960,34 @@ class WindowsApplication(QWidget):
version = entry.get("app", "")
if peer in known_caps and peer not in capable and version:
version = version if version.startswith("Beamer ") else f"Beamer {version}"
- legacy[peer] = f"{version} · only sees which side"
+ legacy[peer] = tr("{version} · only sees which side").format(version=version)
state.update(legacy=True, legacy_label=legacy[peer])
- self.atlas_canvas.set_tiles(layout, labels, tile_states, chosen, config.shortcut_goes_to,
+ on = profiles.same_ways_on(full)
+ for peer in layout:
+ tile_states.setdefault(peer, {})["profile_word"] = profiles.tile_word(
+ full, peer, linked=self._profile_live(peer), caps=self._profile_caps(peer, full))
+ self.atlas_canvas.profile_mode = on
+ self.atlas_canvas.remote = remote
+ self.atlas_canvas.read_only = self._profile_read_only()
+ canvas_chosen = self.atlas_canvas.selected if on and self.atlas_canvas.selected in layout else chosen
+ self.atlas_canvas.set_tiles(layout, labels, tile_states, canvas_chosen, config.shortcut_goes_to,
{entry["id"]: entry.get("shortcut_cycle", True) for entry in entries},
- capable, own_id=config.machine_id,
+ capable, own_id=viewed_id,
rename_values={entry["id"]: self._shown(entry.get("label") or entry.get("name") or "")
for entry in entries})
self.atlas_canvas.set_left_out(left_out, in_use, dormant)
key = TRIGGER_KEYS.get(config.trigger_key, config.trigger_key)
- self.crossing_ledger.reflect(settings, all_layout, labels, chosen, self._live, key, legacy, ledger_reach)
+ self.crossing_ledger.reflect(settings, all_layout, labels, chosen, self._profile_live, key, legacy, ledger_reach)
self.dragging_switch.setEnabled(bool(self._ways_in() & {"edge", "part", "corner"}))
- self.pointer_module.setVisible(not platform_parts.WAYLAND)
- self.resistance_module.setVisible(True)
+ self.pointer_module.setVisible(not remote and not platform_parts.WAYLAND)
+ self.resistance_module.setVisible(not remote)
+ self.shortcut_module.setVisible(not remote)
self.shortcut_tile.blockSignals(True)
try:
self.shortcut_tile.setChecked("shortcut" in config.crossing_methods)
finally:
self.shortcut_tile.blockSignals(False)
- self.shortcut_tile.set_detail(f"{key}, to where input last went")
+ self.shortcut_tile.set_detail(tr("{key}, to where input last went").format(key=key))
self.shortcut_target_choice.set_value(config.shortcut_goes_to)
self._crossing_text(self.shortcut_target_note, pages_win.shortcut_destination_note(
config.shortcut_goes_to, config.trigger_style == "hold"))
@@ -2416,6 +3017,18 @@ class WindowsApplication(QWidget):
self._idle_pointer.cancel()
self._set_driving_pointer(bool(enabled) and self.sender.redirecting)
+ def _set_home_shortcut(self, enabled: bool) -> None:
+ """Wayland only: binding the shortcut asks the desktop, so it starts only when chosen."""
+ shortcut = getattr(self, "global_shortcut", None)
+ if self._config is None or shortcut is None:
+ return
+ self._config.home_shortcut = bool(enabled)
+ self._persist()
+ if enabled:
+ shortcut.start()
+ else:
+ shortcut.stop()
+
def _hiding_pointer(self) -> bool:
return self._idle_pointer is not None and (self._config is None or self._config.hide_idle_pointer)
@@ -2478,7 +3091,7 @@ class WindowsApplication(QWidget):
self._reflect_ways()
def _resistance_module(self, current: Config) -> QWidget:
- module = widgets.Module("Resistance")
+ module = widgets.Module(tr("Resistance"))
self.resistance_readout = widgets.Figure(f"{current.crossing_resistance_px} px")
module.body.addWidget(self.resistance_readout)
self.resistance_strip = PushStrip()
@@ -2493,7 +3106,7 @@ class WindowsApplication(QWidget):
return module
def _resistance_changed(self, value: int) -> None:
- self.resistance_readout.setText(f"{value} px")
+ self.resistance_readout.setText(tr("{value} px").format(value=value))
self._update_resistance_hint(value)
if self._config is None:
return
@@ -2506,13 +3119,13 @@ class WindowsApplication(QWidget):
def _update_resistance_hint(self, value: int) -> None:
side = ways.ways(self._crossing_settings(), self._chosen_machine())["side"]
- text = (
- "Switches the moment this PC's pointer touches the edge. Each screen supplies its own zones."
- if value == 0
- else "Follows this PC's mouse or trackpad on every screen; each screen supplies its own zones."
- )
- if value and side:
- text += f" This screen's {side} edge lights to show the resistance."
+ if value == 0:
+ text = tr("Switches the moment this PC's pointer touches the edge. Each screen supplies its own zones.")
+ elif side:
+ # Translators: {side} is the direction of this screen's edge.
+ text = tr("Follows this PC's mouse or trackpad on every screen; each screen supplies its own zones. This screen's {side} edge lights to show the resistance.").format(side=tr(ways.EDGE_NAMES[side]))
+ else:
+ text = tr("Follows this PC's mouse or trackpad on every screen; each screen supplies its own zones.")
if text != self.resistance_hint.text():
self.resistance_hint.setText(text)
@@ -2552,15 +3165,15 @@ class WindowsApplication(QWidget):
def _speed_module(self, current: Config) -> QWidget:
"""How a driving machine's pointer feels on this PC: it sends what its own acceleration made of
the hand's movement, and this PC's settings decide the rest."""
- module = widgets.Module("Another machine's pointer here")
+ module = widgets.Module(tr("Another machine's pointer here"))
self.speed_sliders = {}
self.speed_readouts = {}
- for key, name, value in (("pointer_speed", "Pointer speed", current.pointer_speed),
- ("scroll_speed", "Scroll speed", current.scroll_speed)):
- module.body.addWidget(widgets.label(name, "body"))
+ for key, name, value in (("pointer_speed", N_("Pointer speed"), current.pointer_speed),
+ ("scroll_speed", N_("Scroll speed"), current.scroll_speed)):
+ module.body.addWidget(widgets.label(tr(name), "body"))
row = QHBoxLayout()
row.setSpacing(10)
- slider = widgets.Ruler(name, 400, minimum=25)
+ slider = widgets.Ruler(tr(name), 400, minimum=25)
slider.setValue(round(value * 100))
slider.valueChanged.connect(lambda percent, key=key: self._speed_changed(key, percent))
row.addWidget(slider, 1)
@@ -2569,9 +3182,9 @@ class WindowsApplication(QWidget):
module.body.addLayout(row)
self.speed_sliders[key], self.speed_readouts[key] = slider, readout
module.body.addWidget(widgets.label(
- "For the trackpad or mouse of whichever machine drives this PC.", "note", wrap=True
+ tr("For the trackpad or mouse of whichever machine drives this PC."), "note", wrap=True
))
- self.reverse_scroll_switch = widgets.Switch("Reverse scrolling from other machines")
+ self.reverse_scroll_switch = widgets.Switch(tr("Reverse scrolling from other machines"))
self.reverse_scroll_switch.setFont(theme.font(theme.TYPE["body"]))
self.reverse_scroll_switch.setChecked(current.reverse_scroll)
self.reverse_scroll_switch.toggled.connect(self._reverse_scroll_changed)
@@ -2597,18 +3210,19 @@ class WindowsApplication(QWidget):
self.server.input_scale = receiver.InputScale(config.pointer_speed, config.scroll_speed, config.reverse_scroll)
def _modifier_module(self, current: Config) -> QWidget:
- module = widgets.Module("Modifier keys")
+ module = widgets.Module(tr("Modifier keys"))
self.modifier_choice = widgets.Choice(
- MODIFIER_STYLE_CHOICES, columns=3, current=current.modifier_style, on_change=self._set_modifier_style
+ tuple((value, tr(title)) for value, title in MODIFIER_STYLE_CHOICES),
+ columns=3, current=current.modifier_style, on_change=self._set_modifier_style
)
- self.modifier_choice.set_names("Modifier keys")
+ self.modifier_choice.set_names(tr("Modifier keys"))
module.body.addWidget(self.modifier_choice.view)
- self.modifier_note = widgets.label(MODIFIER_NOTES[current.modifier_style], "note", wrap=True)
+ self.modifier_note = widgets.label(tr(MODIFIER_NOTES[current.modifier_style]), "note", wrap=True)
module.body.addWidget(self.modifier_note)
return module
def _set_modifier_style(self, value: str) -> None:
- self.modifier_note.setText(MODIFIER_NOTES[value])
+ self.modifier_note.setText(tr(MODIFIER_NOTES[value]))
if self._config is None:
return
self._config.modifier_style = value
@@ -2616,14 +3230,16 @@ class WindowsApplication(QWidget):
self.sender.update_config(self._config)
def _ignored_module(self, current: Config) -> QWidget:
- module = widgets.Module("Stays on this PC")
+ module = widgets.Module(tr("Stays on this PC"))
self.ignored_note = widgets.label("", "note", wrap=True)
module.body.addWidget(self.ignored_note)
self.ignored_list = QVBoxLayout()
self.ignored_list.setSpacing(4)
module.body.addLayout(self.ignored_list)
- self.ignored_recorder = widgets.InputRecorder("Add a key or button", self._record_ignored, capture_win.hook_vk,
- mono=False)
+ self.ignored_recorder = widgets.InputRecorder(
+ tr("Add a key or button"), self._record_ignored, capture_win.hook_vk,
+ mono=False, hint=tr("Click, then press it"), recording_hint=tr("Click again to cancel"),
+ )
module.body.addWidget(self.ignored_recorder)
self._show_ignored(list(current.ignored_inputs))
return module
@@ -2641,21 +3257,15 @@ class WindowsApplication(QWidget):
row_layout.setContentsMargins(12, 2, 4, 2)
name = widgets.label(capture_win.input_title(entry), "readout")
row_layout.addWidget(name, 1)
- remove = QPushButton("Remove")
+ remove = QPushButton(tr("Remove"))
remove.setProperty("vernier", "remove")
remove.setMinimumHeight(widgets.MIN_TARGET)
remove.setCursor(Qt.CursorShape.PointingHandCursor)
- remove.setAccessibleName(f"Remove {capture_win.input_title(entry)}")
+ remove.setAccessibleName(tr("Remove {key}").format(key=capture_win.input_title(entry)))
remove.clicked.connect(lambda _checked=False, e=entry: self._remove_ignored(e))
row_layout.addWidget(remove)
self.ignored_list.addWidget(row)
- text = refused or (
- "These keep working on this PC while its input is on another machine: a mouse's back button for "
- "this PC's browser, say, or a volume key for its speakers."
- if entries
- else "Nothing yet. Every key and button goes to the machine that has input. Add one to keep "
- "it here: a mouse's back button for this PC's browser, say, or a volume key for its speakers."
- )
+ text = refused or tr(IGNORED_NOTES["filled" if entries else "empty"])
self.ignored_note.setText(text)
widgets.set_role(self.ignored_note, "note-amber" if refused else "note")
@@ -2664,7 +3274,7 @@ class WindowsApplication(QWidget):
return
entries = list(self._config.ignored_inputs)
if kind == "key" and value == TRIGGER_VKS.get(self._config.trigger_key):
- self._show_ignored(entries, "That key is the shortcut; it always stays with Beamer.")
+ self._show_ignored(entries, tr("That key is the shortcut; it always stays with Beamer."))
return
entry = ignored.key(value) if kind == "key" else ignored.button(value)
if entry not in entries:
@@ -2683,30 +3293,40 @@ class WindowsApplication(QWidget):
# A list the file refuses, past ignored.MAX_ENTRIES, or a disk that would not take it:
# the running app keeps what is saved, so the list shown is the one the next start uses.
self._config.ignored_inputs = previous
- self._show_ignored(list(previous), "That could not be saved, so the list is unchanged.")
+ self._show_ignored(list(previous), tr("That could not be saved, so the list is unchanged."))
return
self.sender.update_config(self._config)
self._show_ignored(entries)
def _shortcut_module(self, current: Config) -> QWidget:
- module = widgets.Module("Shortcut")
+ module = widgets.Module(tr("Shortcut"))
key = TRIGGER_KEYS.get(current.trigger_key, current.trigger_key)
- self.shortcut_tile = widgets.WayTile("Shortcut", f"{key}, to where input last went")
+ self.shortcut_tile = widgets.WayTile(tr("Shortcut"), tr("{key}, to where input last went").format(key=key))
self.shortcut_tile.setChecked("shortcut" in current.crossing_methods)
self.shortcut_tile.toggled.connect(lambda on: self._ways_changed("shortcut", on))
module.body.addWidget(self.shortcut_tile)
self.wayland_shortcut_note = widgets.label(
- "On Wayland the shortcut only brings input back: the desktop lets input go to another machine only "
+ tr("On Wayland the shortcut only brings input back: the desktop lets input go to another machine only "
"when the pointer pushes through an edge, and keys on the Stays on this PC list cannot stay here "
- "while input is away.", "note", wrap=True)
+ "while input is away."), "note", wrap=True)
self.wayland_shortcut_note.setVisible(platform_parts.WAYLAND)
module.body.addWidget(self.wayland_shortcut_note)
+ self.home_shortcut_switch = widgets.Switch(tr("Send input out with Super+Shift+B"))
+ self.home_shortcut_switch.setChecked(current.home_shortcut)
+ self.home_shortcut_switch.toggled.connect(self._set_home_shortcut)
+ self.home_shortcut_note = widgets.label(
+ tr("From here, where the double-tap cannot be seen, the key combination pushes the pointer through the "
+ "edge to the machine the shortcut goes to. The desktop asks once to allow it, and its keyboard "
+ "settings can change the keys."), "note", wrap=True)
+ for widget in (self.home_shortcut_switch, self.home_shortcut_note):
+ widget.setVisible(platform_parts.WAYLAND)
+ module.body.addWidget(widget)
self.shortcut_target_choice = widgets.Choice(
- (("last", "Last machine"), ("next", "Next in order"), ("ticked", "Next among ticked")),
+ (("last", tr("Last machine")), ("next", tr("Next in order")), ("ticked", tr("Next among ticked"))),
3, current.shortcut_goes_to, on_change=self._set_shortcut_goes_to,
)
- self.shortcut_target_choice.set_names("Shortcut goes to")
- self.shortcut_target_row = self._row(widgets.label("Shortcut goes to", "key"), self.shortcut_target_choice.view)
+ self.shortcut_target_choice.set_names(tr("Shortcut goes to"))
+ self.shortcut_target_row = self._row(widgets.label(tr("Shortcut goes to"), "key"), self.shortcut_target_choice.view)
self.shortcut_target_note = widgets.label("", "note", wrap=True)
note_policy = self.shortcut_target_note.sizePolicy()
note_policy.setVerticalPolicy(QSizePolicy.Policy.Minimum)
@@ -2716,10 +3336,9 @@ class WindowsApplication(QWidget):
self._record_trigger,
capture_win.hook_vk,
keys_only=True,
- name="Shortcut key",
+ name=tr("Shortcut key"),
+ hint=tr("Click, then press the key"), recording_hint=tr("Click again to cancel"),
)
- self.trigger_recorder.HINT = "Click, then press the key"
- self.trigger_recorder.hint.setText(self.trigger_recorder.HINT)
self.trigger_recorder.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
self.trigger_recorder.key.setFont(theme.mono_font(theme.TYPE["keycap"]))
self.trigger_recorder.hint.setAlignment(Qt.AlignmentFlag.AlignLeft)
@@ -2729,18 +3348,19 @@ class WindowsApplication(QWidget):
self.trigger_note.setVisible(False)
module.body.addWidget(self.trigger_note)
self.trigger_style_choice = widgets.Choice(
- TRIGGER_STYLE_CHOICES, columns=2, current=current.trigger_style, on_change=self._set_trigger_style
+ tuple((value, tr(title)) for value, title in TRIGGER_STYLE_CHOICES),
+ columns=2, current=current.trigger_style, on_change=self._set_trigger_style
)
- self.trigger_style_choice.set_names("How you press it")
- self.trigger_style_row = self._row(widgets.label("How you press it", "key"), self.trigger_style_choice.view)
+ self.trigger_style_choice.set_names(tr("How you press it"))
+ self.trigger_style_row = self._row(widgets.label(tr("How you press it"), "key"), self.trigger_style_choice.view)
module.body.addWidget(self.trigger_style_row)
module.body.addWidget(self.shortcut_target_row)
module.body.addWidget(self.shortcut_target_note)
self.style_hint = widgets.label("", "note", wrap=True)
self.double_tap_readout = widgets.Figure(f"{current.double_tap_ms} ms")
- head = widgets.FormRow(widgets.label("Time between taps", "key"), self.double_tap_readout)
+ head = widgets.FormRow(widgets.label(tr("Time between taps"), "key"), self.double_tap_readout)
# The Mac's range: the store takes 50 to 2000 ms, but only about 150 to 600 is useful.
- self.double_tap_slider = widgets.Ruler("Time between taps", 1000, minimum=50,
+ self.double_tap_slider = widgets.Ruler(tr("Time between taps"), 1000, minimum=50,
ticks=(50, 150, 300, 600, 1000), scale="sqrt")
self.double_tap_slider.setValue(current.double_tap_ms)
self.double_tap_slider.valueChanged.connect(self._double_tap_changed)
@@ -2759,8 +3379,8 @@ class WindowsApplication(QWidget):
name = next((n for n, vk in TRIGGER_VKS.items() if vk == value), None)
if name is None:
self.trigger_note.setText(
- "That key cannot be the shortcut. Choose a modifier such as Right Ctrl, a function "
- "key, or a key like Insert or Scroll Lock."
+ tr("That key cannot be the shortcut. Choose a modifier such as Right Ctrl, a function "
+ "key, or a key like Insert or Scroll Lock.")
)
self.trigger_note.setVisible(True)
return
@@ -2798,7 +3418,7 @@ class WindowsApplication(QWidget):
self._reflect_ways()
def _update_style_hint(self, style: str) -> None:
- text = (
+ text = tr(
"Input is on another machine for as long as the key is held. If you jump while holding the shortcut, releasing it brings input home."
if style == "hold"
else "Tap twice to switch; tap twice again to come back."
@@ -2807,7 +3427,7 @@ class WindowsApplication(QWidget):
self.style_hint.setText(text)
def _double_tap_changed(self, value: int) -> None:
- self.double_tap_readout.setText(f"{value} ms")
+ self.double_tap_readout.setText(tr("{value} ms").format(value=value))
if self._config is None:
return
self._config.double_tap_ms = int(value)
@@ -2822,12 +3442,12 @@ class WindowsApplication(QWidget):
layout.addWidget(self.look_module)
layout.addWidget(self.colour_module)
layout.addWidget(self._appearance_module(current))
- follow = widgets.Module("Match design with")
+ follow = widgets.Module(tr("Match design with"))
self.design_follow_choice = QComboBox()
self.design_follow_choice.setMaximumWidth(320)
self.design_follow_choice.currentIndexChanged.connect(self._design_follow_chosen)
- follow.body.addWidget(self._row(widgets.label("Machine", "key"), self.design_follow_choice))
- self.design_follow_note = widgets.label("None: this PC keeps its own Design.", "note", wrap=True)
+ follow.body.addWidget(self._row(widgets.label(tr("Machine"), "key"), self.design_follow_choice))
+ self.design_follow_note = widgets.label(tr("None: this PC keeps its own Design."), "note", wrap=True)
follow.body.addWidget(self.design_follow_note)
layout.addWidget(follow)
self._refresh_design_follow()
@@ -2836,18 +3456,18 @@ class WindowsApplication(QWidget):
def _appearance_module(self, current: Config) -> QWidget:
"""The settings window's own palette. Last on the page, and never hidden with the
crossing animations above it: it is chosen once, not part of what they show."""
- module = widgets.Module("Appearance")
+ module = widgets.Module(tr("Appearance"))
module.body.addWidget(self._own_note())
self.appearance_choice = widgets.Choice(
- (("system", "System"), ("light", "Light"), ("dark", "Dark")), 3, current.appearance,
+ (("system", tr("System")), ("light", trc("appearance", "Light")), ("dark", tr("Dark"))), 3, current.appearance,
on_change=self._appearance_chosen,
)
self.appearance_choice.set_width(252)
- module.body.addWidget(self._row(widgets.label("This window", "key"), self.appearance_choice.view))
+ module.body.addWidget(self._row(widgets.label(tr("This window"), "key"), self.appearance_choice.view))
if sys.platform.startswith("linux"):
- appearance_note = "System follows your Linux desktop's light or dark setting."
+ appearance_note = tr("System follows your Linux desktop's light or dark setting.")
else:
- appearance_note = "System follows Windows' light or dark setting."
+ appearance_note = tr("System follows Windows' light or dark setting.")
module.body.addWidget(widgets.label(appearance_note, "note", wrap=True))
return module
@@ -2860,8 +3480,8 @@ class WindowsApplication(QWidget):
self._persist()
def _on_screen_module(self, current: Config) -> QWidget:
- module = widgets.Module("On screen")
- self.glow_toggle = widgets.Switch("Animate crossings on this PC")
+ module = widgets.Module(tr("On screen"))
+ self.glow_toggle = widgets.Switch(tr("Animate crossings on this PC"))
self.glow_toggle.setFont(theme.font(theme.TYPE["body"]))
self.glow_toggle.setChecked(current.edge_glow)
self.glow_toggle.toggled.connect(self._apply_look)
@@ -2869,12 +3489,12 @@ class WindowsApplication(QWidget):
module.body.addWidget(self._own_note())
module.body.addWidget(
widgets.label(
- "Turns crossing and landing animations on or off on this screen. Saved style choices stay in place.",
+ tr("Turns crossing and landing animations on or off on this screen. Saved style choices stay in place."),
"note",
wrap=True,
)
)
- self.landing_toggle = widgets.Switch("Show where the pointer lands")
+ self.landing_toggle = widgets.Switch(tr("Show where the pointer lands"))
self.landing_toggle.setFont(theme.font(theme.TYPE["body"]))
self.landing_toggle.setChecked(current.shortcut_arrival)
self.landing_toggle.toggled.connect(self._apply_look)
@@ -2882,48 +3502,48 @@ class WindowsApplication(QWidget):
self.landing_row = self._row(
self.landing_toggle,
widgets.label(
- "For shortcut, menu and jump arrivals; requires Animate crossings on this screen.",
+ tr("For shortcut, menu and jump arrivals; requires Animate crossings on this screen."),
"note",
wrap=True,
),
)
self.landing_row.layout().setSpacing(12)
module.body.addWidget(self.landing_row)
- self.landing_toggle.setToolTip("Jump arrivals use this screen's landing animation too.")
+ self.landing_toggle.setToolTip(tr("Jump arrivals use this screen's landing animation too."))
return module
def _edge_look_module(self, current: Config) -> QWidget:
- module = widgets.Module("Style")
+ module = widgets.Module(tr("Style"))
module.body.addWidget(self._follow_banner())
colours = app_config.palette_colours(current.glow_colour)
- self.style_preview_hint = widgets.label("Hover to preview", "preview-hint")
+ self.style_preview_hint = widgets.label(tr("Hover to preview"), "preview-hint")
module.body.addWidget(self.style_preview_hint)
# Which animation the tiles below choose. Not saved: it only says which one is being worked on.
self.design_mode_choice = widgets.Choice(
- (("crossing", "Crossing"), ("switch", "Shortcut and menu")), 2, "crossing", on_change=self._preview_method
+ (("crossing", tr("Crossing")), ("switch", tr("Shortcut and menu"))), 2, "crossing", on_change=self._preview_method
)
- self.design_mode_choice.set_names("Style for")
+ self.design_mode_choice.set_names(tr("Style for"))
self.design_mode_choice.set_width(240)
- self.style_for_row = self._row(widgets.label("Style for", "key"), self.design_mode_choice.view)
+ self.style_for_row = self._row(widgets.label(tr("Style for"), "key"), self.design_mode_choice.view)
# Where every tile below plays its style: never switched off by the style, and what differs
# there is said beneath it. The edge or a corner; a PC has no notch to show.
self.effect_method_choice = widgets.Choice(
- (("edge", "Edge"), ("corner", "Corner")), 2, "edge", on_change=self._place_picked
+ (("edge", tr("Edge")), ("corner", tr("Corner"))), 2, "edge", on_change=self._place_picked
)
- self.effect_method_choice.set_names("Show at")
+ self.effect_method_choice.set_names(tr("Show at"))
self.effect_method_choice.set_width(176)
self._place_chosen = False
self.place_note = widgets.label("", "small", wrap=True)
- self.preview_at_row = self._row(widgets.label("Show at", "key"), self.effect_method_choice.view, self.place_note)
+ self.preview_at_row = self._row(widgets.label(tr("Show at"), "key"), self.effect_method_choice.view, self.place_note)
module.body.addWidget(self.style_for_row)
module.body.addWidget(self.preview_at_row)
self.effect_stills = {}
groups = []
for title, items in pages_win.style_groups():
# Glow and Beam as stills of the same scene as the effects, so every tile reads alike.
- tiles = [(style, name, detail, self.effect_stills.setdefault(style, EffectStill(style, colours)))
+ tiles = [(style, tr(name), tr(detail), self.effect_stills.setdefault(style, EffectStill(style, colours)))
for style, name, detail in items]
- groups.append((title, tiles))
+ groups.append((tr(title), tiles))
self.glow_style_choice = widgets.TileGroups(groups, current.glow_style, on_change=self._apply_look)
module.body.addWidget(self.glow_style_choice.view)
self.switch_stills = {}
@@ -2932,10 +3552,10 @@ class WindowsApplication(QWidget):
tiles = []
for choice, name, detail in items:
picture = self.switch_stills[choice] = SwitchStill(choice, current.glow_style, colours)
- tiles.append((choice, name, detail, picture))
- switch_groups.append((title, tiles))
+ tiles.append((choice, tr(name), tr(detail), picture))
+ switch_groups.append((tr(title), tiles))
self.switch_style_choice = widgets.TileGroups(switch_groups, current.shortcut_arrival_style, on_change=self._apply_look)
- self.switch_style_choice.view.setToolTip("For shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style.")
+ self.switch_style_choice.view.setToolTip(tr("For shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style."))
module.body.addWidget(self.switch_style_choice.view)
module.body.addSpacing(6)
# Each tile plays its preview while the pointer is over it.
@@ -2952,33 +3572,34 @@ class WindowsApplication(QWidget):
module.body.addSpacing(6)
# Every style and every switch plays at this length, so it follows the tiles either way.
self.length_choice = _DesignChoiceSlider(
- "Length", 25, 250, 5, 100, (0.5, 1.0, 2.0), effects.LENGTHS)
+ "length", 25, 250, 5, 100, (0.5, 1.0, 2.0), effects.LENGTHS)
self.size_choice = _DesignChoiceSlider(
- "Size", 20, 80, 1, 1000, (0.03, 0.045, 0.06), effects.SIZES)
+ "size", 20, 80, 1, 1000, (0.03, 0.045, 0.06), effects.SIZES)
self.frame_rate_choice = widgets.Choice(
- tuple((value, name) for value, name, _divisor in effects.FRAME_RATES),
+ tuple((value, tr(name)) for value, name, _divisor in effects.FRAME_RATES),
3, current.frame_rate, on_change=self._apply_look)
- self.frame_rate_choice.set_names("Frame rate")
+ self.frame_rate_choice.set_names(tr("Frame rate"))
self.frame_rate_choice.set_width(320)
self.length_readout = design_readout()
self.size_readout = design_readout()
for title, control, readout, description in (
- ("Length", self.length_choice, self.length_readout, "Sets the effect's playback time."),
- ("Size", self.size_choice, self.size_readout,
- "Sets depth relative to the shorter screen edge.")):
+ (N_("Length"), self.length_choice, self.length_readout, N_("Sets the effect's playback time.")),
+ (N_("Size"), self.size_choice, self.size_readout,
+ N_("Sets depth relative to the shorter screen edge."))):
+ title, description = tr(title), tr(description)
row = self._row(widgets.label(title, "key"), control.view, readout)
module.body.addWidget(row)
- module.body.addWidget(widgets.label(description, "small"))
- module.body.addWidget(self._row(widgets.label("Frame rate", "key"), self.frame_rate_choice.view))
+ module.body.addWidget(widgets.label(description, "small", wrap=True))
+ module.body.addWidget(self._row(widgets.label(tr("Frame rate"), "key"), self.frame_rate_choice.view))
self.length_choice.slider.valueChanged.connect(self._apply_look)
self.size_choice.slider.valueChanged.connect(self._apply_look)
self.length_choice.slider.sliderReleased.connect(self._apply_look)
self.size_choice.slider.sliderReleased.connect(self._apply_look)
- self.colour_module = widgets.Module("Colour")
- self.colour_note = widgets.label("For the crossing and the shortcut alike", "small")
+ self.colour_module = widgets.Module(tr("Colour"))
+ self.colour_note = widgets.label(tr("For the crossing and the shortcut alike"), "small", wrap=True)
self.colour_module.body.addWidget(self.colour_note)
self.glow_colour_choice = widgets.SwatchGroups(
- [(title, [(value, name, app_config.palette_colours(value)) for value, name in items])
+ [(tr(title), [(value, tr(name), app_config.palette_colours(value)) for value, name in items])
for title, items in pages_win.colour_groups()],
current.glow_colour,
on_change=self._apply_look,
@@ -3033,7 +3654,7 @@ class WindowsApplication(QWidget):
crossing_fx = (effects.preview_effect(style) if pages_win.effects_load_error() is None
else effects.CLASSIC.get(style))
if crossing_fx is not None:
- self.switch_style_choice.set_detail("match", f"Plays {crossing_fx.name}")
+ self.switch_style_choice.set_detail("match", tr("Plays {name}").format(name=tr(crossing_fx.name)))
edge = ways.ways(self._crossing_settings(), self._chosen_machine())["side"] or "right"
colour = self.glow_colour_choice.value or "signal"
methods = sorted(self._ways_in())
@@ -3075,24 +3696,24 @@ class WindowsApplication(QWidget):
self.place_note.setVisible(bool(note))
if switching and pages_win.effects_load_error() is None:
fx = effects.switch_effect(switch_style, style)
- self.effect_name.setText(("Same as crossing: " if switch_style == "match" else "") + fx.name)
+ self.effect_name.setText(tr("Same as crossing: {name}").format(name=tr(fx.name)) if switch_style == "match" else tr(fx.name))
else:
fx = (effects.preview_effect(style) if pages_win.effects_load_error() is None
else effects.CLASSIC.get(style)) or effects.CLASSIC["glow"]
- self.effect_name.setText(f"{fx.name}, {fx.intensity}")
+ self.effect_name.setText(tr("{name}, {intensity}").format(name=tr(fx.name), intensity=tr(fx.intensity)))
wayland_effects_unavailable = platform_parts.WAYLAND and (
not os.environ.get("DISPLAY") or self._effects_failed
)
self.effect_note.setText(
- "On Wayland the desktop does not let Beamer draw at the edges of the screen, so crossings show no "
- "effect on this machine. The other machines still show theirs."
+ tr("On Wayland the desktop does not let Beamer draw at the edges of the screen, so crossings show no "
+ "effect on this machine. The other machines still show theirs.")
if wayland_effects_unavailable
- else "The effects stopped working and are off until Beamer restarts, so crossings show Glow in "
- "the same colours. The log says why."
+ else tr("The effects stopped working and are off until Beamer restarts, so crossings show Glow in "
+ "the same colours. The log says why.")
if self._effects_failed
- else f"{fx.blurb} It plays around the pointer when the shortcut or a menu brings input to this PC."
+ else tr("{blurb} It plays around the pointer when the shortcut or a menu brings input to this PC.").format(blurb=tr(fx.blurb))
if switching
- else fx.blurb
+ else tr(fx.blurb)
)
colours = app_config.palette_colours(colour)
for still in (*self.effect_stills.values(), *self.switch_stills.values()):
@@ -3182,6 +3803,7 @@ class WindowsApplication(QWidget):
# next crossing: its way on is built from these settings when it arrives.
self.server.peers_changed()
self.sender.refresh()
+ self._configure_shake()
if shared or design_changed:
self._send_same()
self._refresh_design_follow()
@@ -3360,9 +3982,9 @@ class WindowsApplication(QWidget):
def _drive_status(self) -> str:
if self.sender.redirecting:
- return f"Driving {self._label_of(self.sender.owner)}"
+ return tr("Driving {name}").format(name=self._label_of(self.sender.owner))
driver = self.server.owner
- return f"Driven by {self._label_of(driver)}" if driver is not None else "Idle"
+ return tr("Driven by {name}").format(name=self._label_of(driver)) if driver is not None else tr("Idle")
def _refresh_tray_state(self) -> None:
state = self._shown(self._drive_status())
@@ -3407,7 +4029,7 @@ class WindowsApplication(QWidget):
driver = self.server.owner
route = (driver, self._identity()["id"]) if driver is not None else ()
if not route:
- return "Current chain: Idle"
+ return tr("Current chain: Idle")
identity = self._identity()
own_id = protocol.id_text(identity["id"])
names = []
@@ -3417,7 +4039,7 @@ class WindowsApplication(QWidget):
names.append(identity["name"])
else:
names.append(self._labels_by_id.get(protocol.read_id(key), "another machine"))
- return "Current chain: " + " → ".join(names)
+ return tr("Current chain: {names}").format(names=" → ".join(names))
def _edit_peer(self, token: str, **fields) -> bool:
try:
@@ -3575,6 +4197,8 @@ class WindowsApplication(QWidget):
self._send_paired()
self._refresh_peers()
self._sync_sending()
+ # A pairing or a removal changes this machine's status ("waiting"): every linked peer hears.
+ self._publish_desk()
def _sync_sending(self) -> None:
"""The links and the hooks that feed them run while some machine can be sent to, whatever changed the list."""
@@ -3601,7 +4225,7 @@ class WindowsApplication(QWidget):
remaining = bool(settings["peers"])
except (ConfigError, OSError):
LOGGER.exception("A machine could not be removed")
- self._on_alert("Beamer", "Beamer could not save the removal. Try again in a moment.")
+ self._on_alert("Beamer", tr("Beamer could not save the removal. Try again in a moment."))
return
LOGGER.info("Removed %s from the paired machines",
peerlist.label_for([removed], token=token) or "a machine")
@@ -3653,17 +4277,17 @@ class WindowsApplication(QWidget):
self._open_pairing_sheet()
service = self.pairing
if service is None:
- self.sheet.say_host("Pairing is not available: this PC's settings could not be read.", "note-fault")
+ self.sheet.say_host(tr("Pairing is not available: this PC's settings could not be read."), "note-fault")
return
if service.error:
- self.sheet.say_host(f"Pairing is not available: {service.error}", "note-fault")
+ self.sheet.say_host(tr("Pairing is not available: {error}").format(error=service.error), "note-fault")
return
self._cancel_code()
self.sheet.say_host("", "note")
try:
service.begin_nearby()
except pairing.PairingError as exc:
- self.sheet.say_host(f"Nearby pairing is not available: {exc}", "note-fault")
+ self.sheet.say_host(tr("Nearby pairing is not available: {error}").format(error=exc), "note-fault")
self._refresh_pairing()
def _choose_nearby(self, machine: dict) -> None:
@@ -3673,7 +4297,7 @@ class WindowsApplication(QWidget):
try:
service.choose_nearby(machine)
except pairing.PairingError as exc:
- self.sheet.say_host(f"Nearby pairing could not continue: {exc}", "note-fault")
+ self.sheet.say_host(tr("Nearby pairing could not continue: {error}").format(error=exc), "note-fault")
self._refresh_pairing()
def _confirm_nearby(self, sas: str, attempt: str) -> None:
@@ -3683,7 +4307,7 @@ class WindowsApplication(QWidget):
try:
service.confirm_nearby(sas, attempt)
except pairing.PairingError as exc:
- self.sheet.say_host(f"Nearby pairing could not continue: {exc}", "note-fault")
+ self.sheet.say_host(tr("Nearby pairing could not continue: {error}").format(error=exc), "note-fault")
self._refresh_pairing()
def _cancel_nearby(self) -> None:
@@ -3714,17 +4338,17 @@ class WindowsApplication(QWidget):
def _show_code(self) -> None:
if self.pairing is None:
- self.sheet.say_host("Pairing is not available: this PC's settings could not be read.", "note-fault")
+ self.sheet.say_host(tr("Pairing is not available: this PC's settings could not be read."), "note-fault")
return
if self.pairing.error:
- self.sheet.say_host(f"Pairing is not available: {self.pairing.error}", "note-fault")
+ self.sheet.say_host(tr("Pairing is not available: {error}").format(error=self.pairing.error), "note-fault")
return
self.sheet.say_host("", "note")
self.pairing.cancel_nearby()
try:
self.pairing.begin_pairing()
except pairing.PairingError as exc:
- text = peerlist.host_outcome_text("full", None) if str(exc) == pairing.ERROR_FULL else f"Pairing is not available: {exc}"
+ text = peerlist.host_outcome_text("full", None) if str(exc) == pairing.ERROR_FULL else tr("Pairing is not available: {error}").format(error=exc)
self.sheet.say_host(text, "note-fault")
return
self._code_address = self._pairing_address()
@@ -3761,14 +4385,14 @@ class WindowsApplication(QWidget):
self._code_address = address
rows, note = None, ""
if hide:
- note = "The QR holds this PC's address, so it is not shown while Hide addresses is on."
+ note = tr("The QR holds this PC's address, so it is not shown while Hide addresses is on.")
else:
text = service.qr_text(address) if address else None
if text is not None:
if self._qr_cache[0] != text:
self._qr_cache = (text, qr_code.modules(text))
rows = self._qr_cache[1]
- where = f"This PC's address: {address} · port {service.tcp_port}" if address else ""
+ where = tr("This PC's address: {address} · port {port}").format(address=address, port=service.tcp_port) if address else ""
self.sheet.show_code(code, service.seconds_left, self._shown(where), rows, note)
self._code_shown = True
return
@@ -3792,7 +4416,7 @@ class WindowsApplication(QWidget):
def _pair_clicked(self, machine: Optional[dict], address: str, code: str) -> None:
service = self.pairing
if service is None:
- self.sheet.say_pair("Pairing is not available: this PC's settings could not be read.", "note-fault")
+ self.sheet.say_pair(tr("Pairing is not available: this PC's settings could not be read."), "note-fault")
return
service.cancel_nearby()
self._pairing_target = machine["name"] if machine is not None else address
@@ -3820,7 +4444,7 @@ class WindowsApplication(QWidget):
return
self.sheet.clear_code()
label = peerlist.label_for(self.book.peers(), token=entry.get("token")) or "that machine"
- self.sheet.say_pair(self._shown(f"Paired with {label}."), "note-live")
+ self.sheet.say_pair(self._shown(tr("Paired with {name}.").format(name=label)), "note-live")
LOGGER.info("Paired with %s", label)
self._after_peers_edit()
@@ -3835,19 +4459,36 @@ class WindowsApplication(QWidget):
def _connection_page(self, layout, current: Config) -> None:
self._firewall_module(layout)
- privacy = widgets.Module("Addresses")
- self.hide_switch = widgets.Switch("Hide addresses")
+ privacy = widgets.Module(tr("Addresses"))
+ self.hide_switch = widgets.Switch(tr("Hide addresses"))
self.hide_switch.setFont(theme.font(theme.TYPE["body"]))
self.hide_switch.setChecked(self._hide_addresses())
self.hide_switch.toggled.connect(self._set_hide_addresses)
privacy.body.addWidget(self.hide_switch)
privacy.body.addWidget(widgets.label(
- "Hides every IP and hardware address in this window and the tray.",
+ tr("Hides every IP and hardware address in this window and the tray."),
"note",
wrap=True,
))
layout.addWidget(privacy)
- module = widgets.Module("This PC")
+ language = widgets.Module(tr("Language"))
+ language_choice = widgets.Choice(
+ [("auto", tr("Automatic"))] + [(code, name) for code, name in i18n.LANGUAGES.items()],
+ 3,
+ current.language,
+ self._set_language,
+ )
+ self.language_choice = language_choice
+ language.body.addWidget(language_choice.view)
+ self.language_note = widgets.label(tr("Beamer changes language when it next opens."), "note", wrap=True)
+ self.language_note.setVisible(False)
+ language.body.addWidget(self.language_note)
+ self.language_relaunch = QPushButton(tr("Relaunch Beamer"))
+ self.language_relaunch.clicked.connect(self.relaunch)
+ self.language_relaunch.setVisible(False)
+ language.body.addWidget(self.language_relaunch, 0, Qt.AlignmentFlag.AlignLeft)
+ layout.addWidget(language)
+ module = widgets.Module(tr("This PC"))
def field(caption, entry):
# The caption is the field's buddy and its accessible name, so a screen reader and
# Alt+letter both reach the field by what it is called.
@@ -3858,16 +4499,16 @@ class WindowsApplication(QWidget):
# Read-only: the address that faces the machines this PC knows, which is what another machine
# types to pair by address.
- self.host_readout = widgets.label(self._shown(self._host) or "Not known yet", "readout", wrap=True)
- self.host_readout.setAccessibleName("This PC's address")
- field("This PC's address", self.host_readout)
+ self.host_readout = widgets.label(self._shown(self._host) or tr("Not known yet"), "readout", wrap=True)
+ self.host_readout.setAccessibleName(tr("This PC's address"))
+ field(tr("This PC's address"), self.host_readout)
self.port_entry = QLineEdit(str(current.port))
self.port_entry.setMaximumWidth(240)
- field("This PC's listening port", self.port_entry)
+ field(tr("This PC's listening port"), self.port_entry)
self.save_message = widgets.label("", "note", wrap=True)
self.save_message.setVisible(False)
module.body.addWidget(self.save_message)
- self.save_button = QPushButton("Save and reconnect")
+ self.save_button = QPushButton(tr("Save and reconnect"))
self.save_button.setProperty("vernier", "primary")
self.save_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.save_button.clicked.connect(self.save)
@@ -3894,6 +4535,31 @@ class WindowsApplication(QWidget):
self._refresh_window()
self._refresh_tray_state()
+ def _set_language(self, language: str) -> None:
+ if language != "auto" and language not in i18n.LANGUAGES:
+ return
+ if self._config is None:
+ try:
+ app_config.set_own(self.config_path, language=language)
+ except (ConfigError, OSError):
+ LOGGER.exception("Language setting could not be saved")
+ return
+ self._kept_language = language
+ else:
+ self._config.language = language
+ self._persist()
+ self.language_note.setVisible(True)
+ self.language_relaunch.setVisible(True)
+
+ def relaunch(self) -> None:
+ executable = sys.executable
+ arguments = sys.argv[1:] if getattr(sys, "frozen", False) else sys.argv
+ if "--relaunched" not in arguments:
+ arguments = [*arguments, "--relaunched"]
+ started, _process_id = QProcess.startDetached(executable, arguments)
+ if started:
+ self.quit()
+
def save(self) -> None:
"""The Connection page's one setting is this PC's own port. It never touches a peer's entry, whose
port is that machine's own, and it works with nothing paired."""
@@ -3903,13 +4569,13 @@ class WindowsApplication(QWidget):
raise ValueError
app_config.set_own(self.config_path, port=port)
except (TypeError, ValueError):
- self.save_message.setText("port must be an integer from 1 to 65535")
+ self.save_message.setText(tr("port must be an integer from 1 to 65535"))
self.save_message.setVisible(True)
widgets.set_role(self.save_message, "note-fault")
return
except (ConfigError, OSError) as exc:
LOGGER.exception("Configuration could not be saved")
- QMessageBox.critical(self, "Save failed", str(exc))
+ QMessageBox.critical(self, tr("Save failed"), str(exc))
return
self._settings_port = port
if self._config is not None:
@@ -3918,7 +4584,7 @@ class WindowsApplication(QWidget):
self._apply_config(config)
else:
self._config = config
- self.save_message.setText("Saved.")
+ self.save_message.setText(tr("Saved."))
self.save_message.setVisible(True)
widgets.set_role(self.save_message, "note-live")
@@ -3939,6 +4605,7 @@ class WindowsApplication(QWidget):
self.server.peers_changed()
self._send_paired()
self.sender.update_config(config)
+ self._configure_shake()
configure_seams = getattr(self, "_configure_capture_seams", None)
if callable(configure_seams):
configure_seams(config)
@@ -3963,15 +4630,15 @@ class WindowsApplication(QWidget):
def _firewall_module(self, layout) -> None:
if sys.platform.startswith("linux"):
- title = "Linux firewall"
- checking = "Beamer's firewall check is not yet on Linux."
+ title = tr("Linux firewall")
+ checking = tr("Beamer's firewall check is not yet on Linux.")
else:
- title = "Windows Firewall"
- checking = "Checking Windows Firewall…"
+ title = tr("Windows Firewall")
+ checking = tr("Checking Windows Firewall…")
module = widgets.Module(title)
self.firewall_note = widgets.label(checking, "note", wrap=True)
module.body.addWidget(self.firewall_note)
- self.firewall_button = QPushButton("Checking…")
+ self.firewall_button = QPushButton(tr("Checking…"))
self.firewall_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.firewall_button.setEnabled(False)
self.firewall_button.clicked.connect(self._firewall_action)
@@ -3983,7 +4650,7 @@ class WindowsApplication(QWidget):
return str(Path(sys.executable).resolve()), port
def _check_firewall(self) -> None:
- self._run_firewall(firewall_win.status, "Checking…")
+ self._run_firewall(firewall_win.status, tr("Checking…"))
def _firewall_action(self) -> None:
# Only the built exe changes the firewall, by the button or on its own. From source the
@@ -4012,7 +4679,7 @@ class WindowsApplication(QWidget):
else:
self._check_firewall()
return
- self._run_firewall(job, "Fixing…")
+ self._run_firewall(job, tr("Fixing…"))
def _run_firewall(self, job, working: str) -> None:
"""One PowerShell at a time, off the GUI thread. A request arriving mid-run is folded
@@ -4032,7 +4699,7 @@ class WindowsApplication(QWidget):
result = job(exe, port)
except Exception as exc:
LOGGER.exception("Firewall job failed")
- result = firewall_win.FirewallStatus(port, False, False, (), (), False, (), firewall_win.is_elevated(), error=f"the change failed: {exc}")
+ result = firewall_win.FirewallStatus(port, False, False, (), (), False, (), firewall_win.is_elevated(), error=tr("the change failed: {error}").format(error=exc))
self.bridge.firewall.emit(result)
threading.Thread(target=work, name="Beamer-firewall", daemon=True).start()
@@ -4123,32 +4790,34 @@ class WindowsApplication(QWidget):
self.status_action.setEnabled(False)
menu.addSeparator()
# The version line; it becomes the way to a newer release when there is one.
- self.header_action = menu.addAction(f"Beamer {VERSION}")
+ self.header_action = menu.addAction(tr("Beamer {version}").format(version=VERSION))
self.header_action.setEnabled(False)
self.header_action.triggered.connect(self.open_update)
menu.addSeparator()
- self.redirect_action = menu.addAction("Send input across")
+ self.redirect_action = menu.addAction(tr("Send input across"))
self.redirect_action.triggered.connect(self.toggle_redirect)
- self.pause_action = menu.addAction("Pause crossing")
+ self.pause_action = menu.addAction(tr("Pause crossing"))
self.pause_action.triggered.connect(self.toggle_pause)
menu.addSeparator()
self.tray_menu = menu
# One tick per direction, each the same switch the Overview page shows, so either
# direction can be turned off while the other keeps working and the two never disagree.
- self.send_action = menu.addAction("This PC drives machines")
+ self.send_action = menu.addAction(tr("This PC drives machines"))
self.send_action.setCheckable(True)
self.send_action.triggered.connect(lambda on: self._set_every_peer("send", on))
- self.drive_action = menu.addAction("Machines drive this PC")
+ self.drive_action = menu.addAction(tr("Machines drive this PC"))
self.drive_action.setCheckable(True)
self.drive_action.triggered.connect(lambda on: self._set_every_peer("allow_drive", on))
+ self.profile_menu = menu.addMenu(tr("Profile"))
+ self._refresh_tray_profiles()
menu.addSeparator()
- self.open_action = menu.addAction("Settings…")
+ self.open_action = menu.addAction(tr("Settings…"))
self.open_action.triggered.connect(lambda _checked=False: self.show_window())
- menu.addAction("Reload configuration").triggered.connect(self.reload_config)
- menu.addAction("Open log folder").triggered.connect(self.open_log_folder)
+ menu.addAction(tr("Reload configuration")).triggered.connect(self.reload_config)
+ menu.addAction(tr("Open log folder")).triggered.connect(self.open_log_folder)
menu.addSeparator()
- menu.addAction("About Beamer").triggered.connect(self.show_about)
- menu.addAction("Quit Beamer").triggered.connect(self.quit)
+ menu.addAction(tr("About Beamer")).triggered.connect(self.show_about)
+ menu.addAction(tr("Quit Beamer")).triggered.connect(self.quit)
self.tray.setContextMenu(menu)
# Left click opens the window; right click is the
# context menu Qt already gives QSystemTrayIcon for free.
@@ -4156,13 +4825,49 @@ class WindowsApplication(QWidget):
self.tray.setVisible(self.tray_shown())
self._refresh_tray_state()
+ def _refresh_tray_profiles(self, settings=None) -> None:
+ if not hasattr(self, "profile_menu"):
+ return
+ self.profile_menu.menuAction().setVisible(False)
+ self.profile_menu.clear()
+ if self._config is None:
+ return
+ try:
+ settings = app_config.load_settings(self.config_path) if settings is None else settings
+ except (ConfigError, OSError):
+ return
+ entries = profiles.profile_list(settings)
+ visible = profiles.same_ways_on(settings) and len(entries) >= 2
+ self.profile_menu.menuAction().setVisible(visible)
+ if not visible:
+ return
+ active = settings["crossing_desk"]["active"]["value"]
+ for entry in entries:
+ label = tr("Desk") if entry["id"] == profiles.DESK_ID and entry["name"] == "Desk" else entry["label"]
+ action = self.profile_menu.addAction(label)
+ action.setCheckable(True)
+ action.setChecked(entry["id"] == active)
+ action.triggered.connect(lambda _checked=False, pid=entry["id"]: self._switch_tray_profile(pid))
+
+ def _switch_tray_profile(self, profile_id: str) -> None:
+ if self._config is None:
+ return
+ try:
+ with app_config.SETTINGS_LOCK:
+ settings = app_config.load_settings(self.config_path)
+ self._carry_crossing(crossing_state.switch_profile(
+ settings, profile_id, **self._crossing_event_args()))
+ except (ConfigError, OSError):
+ LOGGER.exception("The profile could not be saved")
+ self._refresh_tray_profiles()
+
def reload_config(self) -> None:
"""Re-reads settings.json, for the times it was edited outside the window, and shows it."""
try:
config = load_config(self.config_path, unpaired_ok=True)
except (ConfigError, OSError) as exc:
LOGGER.warning("Configuration not reloaded: %s", exc)
- self._on_alert("Beamer", f"Could not reload the configuration: {exc}")
+ self._on_alert("Beamer", tr("Could not reload the configuration: {error}").format(error=exc))
return
self._host = config.host
self._paired = bool(self.book.peers())
@@ -4291,6 +4996,7 @@ class WindowsApplication(QWidget):
if not self._any_send():
return
self._configure_trigger(config)
+ self._configure_shake()
try:
self.hooks.start()
except Exception as exc:
@@ -4393,8 +5099,13 @@ class WindowsApplication(QWidget):
if self._config is None or self._closing:
return
self._pull_peer_fields()
+ linked = {protocol.id_text(peer) for peer in self._peer_caps()}
+ self._profile_last_heard = {peer: heard for peer, heard in self._profile_last_heard.items() if peer in linked}
+ for peer in linked:
+ self._profile_last_heard.setdefault(peer, time.time())
self.sender.refresh()
self._refresh_peers()
+ self._publish_desk()
def _on_sending(self, connected: bool, detail: str) -> None:
self._sending_detail = detail
@@ -4501,13 +5212,12 @@ class WindowsApplication(QWidget):
def show_about(self) -> None:
box = QMessageBox(self)
- box.setWindowTitle("About Beamer")
+ box.setWindowTitle(tr("About Beamer"))
box.setIconPixmap(QIcon(str(ICON_PATH)).pixmap(QSize(64, 64), 1.0))
box.setTextFormat(Qt.TextFormat.RichText)
- box.setText(
- f"<b>Beamer {VERSION}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br>"
- f'<a href="{HOME_PAGE}" style="color: {theme.colour("signal")};">{HOME_PAGE_TEXT}</a>'
- )
+ box.setText(tr(
+ '<b>Beamer {version}</b><br>One keyboard and mouse for all your Macs and PCs.<br><br><a href="{url}" style="color: {colour};">{link}</a>'
+ ).format(version=VERSION, url=HOME_PAGE, colour=theme.colour("signal"), link=tr(HOME_PAGE_TEXT)))
box.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
for text in box.findChildren(QLabel):
text.setOpenExternalLinks(True)
@@ -4551,6 +5261,9 @@ class WindowsApplication(QWidget):
self.pairing.stop()
self.server.stop()
self._stop_sending()
+ shortcut = getattr(self, "global_shortcut", None)
+ if shortcut is not None:
+ shortcut.stop()
stop_injector = getattr(platform_parts.injector, "stop", None)
if stop_injector is not None:
stop_injector()
@@ -4744,7 +5457,7 @@ class WindowsApplication(QWidget):
self._refresh_tray_state()
self._refresh_tray_directions()
self._refresh_tray_machines()
- pause = "Resume crossing" if self.sender.crossing_paused else "Pause crossing"
+ pause = tr("Resume crossing" if self.sender.crossing_paused else "Pause crossing")
if self.pause_action.text() != pause:
self.pause_action.setText(pause)
if self.pause_button.text() != pause:
@@ -4766,7 +5479,7 @@ class WindowsApplication(QWidget):
# The machines' names go in the detail, not the heading: a long name wrapped the heading onto
# two lines at 640 wide and made the window scroll.
detail = self._shown(detail)
- heading = STATUS_TITLES[state]
+ heading = tr(STATUS_TITLES[state])
if heading != self.status_heading.text():
first = not self.status_heading.text()
shot = None if first else motion.snapshot(self.status_heading)
@@ -4777,7 +5490,7 @@ class WindowsApplication(QWidget):
if detail != self.status_detail.text():
self.status_detail.setText(detail)
widgets.set_role(self.status_detail, "note-fault" if state is ServerState.ERROR else "note")
- location = f"On {self._label_of(self.sender.owner)}" if self.sender.redirecting else "On this PC"
+ location = tr("On {name}").format(name=self._label_of(self.sender.owner)) if self.sender.redirecting else tr("On this PC")
if location != self.location_readout.text():
self.location_readout.setText(location)
trip = self.sender.round_trip_ms
@@ -4795,7 +5508,7 @@ class WindowsApplication(QWidget):
allowed = self._config is not None and self._any_send()
self.redirect_note.setVisible(not allowed and self._paired)
self.wayland_send_note.setVisible(allowed and not sending)
- pause_text = "Resume crossing" if self.sender.crossing_paused else "Pause crossing"
+ pause_text = tr("Resume crossing" if self.sender.crossing_paused else "Pause crossing")
if pause_text != self.pause_button.text():
self.pause_button.setText(pause_text)
self.pause_action.setText(pause_text)
@@ -4820,7 +5533,7 @@ class WindowsApplication(QWidget):
# Hidden while empty, or its spacing leaves a gap between the two switches.
self.send_hint.setVisible(bool(send_hint))
response_peer, response_time, response_connected = self._header_response_time()
- self.sidebar.set_link(tone, SIDEBAR_LINK_WORDS.get(state, "Unknown"), response_peer,
+ self.sidebar.set_link(tone, tr(SIDEBAR_LINK_WORDS.get(state, N_("Unknown"))), response_peer,
response_time, response_connected)
dormant = any(peerlist.dormant_reason(entry) for entry in self._peer_entries)
dots = pages_win.dots(self._config is None or not self._paired, self._firewall_tone, dormant)
@@ -4833,13 +5546,15 @@ class WindowsApplication(QWidget):
def _title(self) -> str:
with self._status_lock:
- return self._shown(f"Beamer — {self._status.value}: {self._status_detail}")
+ return self._shown(tr("Beamer — {status}: {detail}").format(
+ status=tr(SIDEBAR_LINK_WORDS[self._status]), detail=self._status_detail))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Beamer Windows receiver")
parser.add_argument("--config", type=Path, default=default_config_path(), help="path to settings.json")
parser.add_argument("--hidden", action="store_true", help="start in the tray without showing the window")
+ parser.add_argument("--relaunched", action="store_true", help=argparse.SUPPRESS)
return parser.parse_args()
@@ -4891,6 +5606,23 @@ def _claim_instance():
return lock.unlock if lock.tryLock(0) else None
+# A relaunched Beamer starts while the one it replaces still holds the lock, and waits this long
+# for it to quit rather than handing over to it.
+RELAUNCH_WAIT_SECONDS = 15
+
+
+def _claim_instance_waiting(seconds, claim=_claim_instance, sleep=time.sleep, clock=time.monotonic):
+ deadline = clock() + seconds
+ while True:
+ release = claim()
+ if release is not None:
+ return release
+ remaining = deadline - clock()
+ if remaining <= 0:
+ return None
+ sleep(min(0.1, remaining))
+
+
def activate_existing_instance(hidden: bool, activation_token: Optional[str] = None) -> bool:
if hidden:
return False
@@ -4909,6 +5641,8 @@ def main() -> None:
except OSError:
LOGGER.exception("Could not migrate the previous Windows sign-in task; keeping it for another attempt")
release = _claim_instance()
+ if release is None and arguments.relaunched:
+ release = _claim_instance_waiting(RELAUNCH_WAIT_SECONDS, claim=_claim_instance)
if release is None:
activate_existing_instance(arguments.hidden, os.environ.get("XDG_ACTIVATION_TOKEN"))
return
@@ -4929,7 +5663,7 @@ def main() -> None:
if not kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x8000): # ABOVE_NORMAL_PRIORITY_CLASS
LOGGER.warning("Could not raise Beamer's priority: %s", ctypes.WinError(ctypes.get_last_error()))
_stay_unthrottled(kernel32)
- instance_signal = None
+ instance_signal = quit_signals = None
try:
app = QApplication(sys.argv)
app.setApplicationName("Beamer")
@@ -4937,9 +5671,15 @@ def main() -> None:
app.setQuitOnLastWindowClosed(False)
theme.init_fonts()
app.setFont(theme.font(theme.TYPE["body"]))
+ try:
+ startup_config = app_config.load_config(arguments.config.expanduser().resolve(), unpaired_ok=True)
+ i18n.install(startup_config.language)
+ except ConfigError:
+ i18n.install("auto")
application = WindowsApplication(
arguments.config.expanduser().resolve(), start_after_first_paint=not arguments.hidden
)
+ quit_signals = quit_signals_module.QuitSignals(application.quit, parent=app)
instance_signal = InstanceSignal(application.show_window, parent=app)
if not instance_signal.listening:
LOGGER.warning("Could not start the second-launch listener: %s", instance_signal.server.errorString())
@@ -4949,6 +5689,8 @@ def main() -> None:
QTimer.singleShot(0, application.start)
sys.exit(app.exec())
finally:
+ if quit_signals is not None:
+ quit_signals.close()
if instance_signal is not None:
instance_signal.close()
release()
diff --git a/win_app/linux_stand_ins.py b/win_app/linux_stand_ins.py
index 9a40ad3..b3c972f 100644
--- a/win_app/linux_stand_ins.py
+++ b/win_app/linux_stand_ins.py
@@ -6,6 +6,8 @@ from dataclasses import dataclass
from types import SimpleNamespace
from typing import Optional
+from core.i18n import tr
+
unlock = SimpleNamespace(
is_locked=lambda: None,
signal_unlock=lambda: False,
@@ -39,7 +41,7 @@ firewall = SimpleNamespace(
FirewallStatus=FirewallStatus,
Advice=Advice,
status=lambda exe, port: FirewallStatus(port),
- advise=lambda status: Advice("Beamer's firewall check is not yet on Linux.", "Check again", None),
+ advise=lambda status: Advice(tr("Beamer's firewall check is not yet on Linux."), tr("Check again"), None),
repair=lambda exe, port, profiles: None,
trust_network=lambda indexes: None,
is_elevated=lambda: False,
diff --git a/win_app/machines_win.py b/win_app/machines_win.py
index 862174a..a362127 100644
--- a/win_app/machines_win.py
+++ b/win_app/machines_win.py
@@ -4,6 +4,7 @@ them and gives each the one function it calls back."""
from __future__ import annotations
+from core.i18n import tr
import math
import sys
from typing import Callable, Optional
@@ -235,7 +236,7 @@ class PairCodeLabel(QLabel, _PairCodeCells):
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
- self.setAccessibleName("Pairing code")
+ self.setAccessibleName(tr("Pairing code"))
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self._mouse_anchor = 0
self._cursor_position = 0
@@ -362,7 +363,7 @@ class PeerRow(QWidget):
name_layout.addWidget(self.led, 0, Qt.AlignmentFlag.AlignVCenter)
self.name = widgets.label("", "tile-name", wrap=True)
name_layout.addWidget(self.name, 1)
- self.rename_button = _button("Rename", "small")
+ self.rename_button = _button(tr("Rename"), "small")
self.rename_button.setMinimumWidth(self.rename_button.sizeHint().width())
self.rename_button.clicked.connect(self._begin_rename)
name_layout.addWidget(self.rename_button)
@@ -382,31 +383,31 @@ class PeerRow(QWidget):
column.addWidget(self.where)
self.detail = widgets.label("", "note", wrap=True)
column.addWidget(self.detail)
- self.repair_button = _button("Re-pair", "small")
+ self.repair_button = _button(tr("Re-pair"), "small")
self.repair_button.clicked.connect(lambda: self._on_repair(self.token))
column.addWidget(self.repair_button, 0, Qt.AlignmentFlag.AlignLeft)
- self.left_out_note = widgets.label("Left out of the layout. The shortcut and the menu still reach it.",
+ self.left_out_note = widgets.label(tr("Left out of the layout. The shortcut and the menu still reach it."),
"note-quiet", wrap=True)
self.left_out_note.setVisible(False)
column.addWidget(self.left_out_note)
- self.shortcut_cycle = QCheckBox("In the shortcut's cycle")
+ self.shortcut_cycle = QCheckBox(tr("In the shortcut's cycle"))
self.shortcut_cycle.setVisible(False)
self.shortcut_cycle.toggled.connect(lambda enabled: (on_cycle or (lambda *_: None))(self._entry.get("id"), enabled))
column.addWidget(self.shortcut_cycle)
- self.in_use = widgets.Switch("In use")
+ self.in_use = widgets.Switch(tr("In use"))
self.in_use.toggled.connect(lambda on: on_in_use(self.token, on))
- self.in_use.setToolTip("Off on this PC: no input or settings link to this machine. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.")
- self.left_out = _button("Leave out", "small")
+ self.in_use.setToolTip(tr("Off on this PC: no input or settings link to this machine. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect."))
+ self.left_out = _button(tr("Leave out"), "small")
self.left_out.clicked.connect(lambda: on_left_out(self.token, not self._left_out))
- self.send = widgets.Switch("This PC drives it")
- self.send.setToolTip("Input moves only when this PC enables this switch and the other machine enables It drives this PC.")
- self.allow = widgets.Switch("It drives this PC")
- self.allow.setToolTip("Input moves only when the other machine enables This machine drives it and this PC enables this switch.")
+ self.send = widgets.Switch(tr("This PC drives it"))
+ self.send.setToolTip(tr("Input moves only when this PC enables this switch and the other machine enables It drives this PC."))
+ self.allow = widgets.Switch(tr("It drives this PC"))
+ self.allow.setToolTip(tr("Input moves only when the other machine enables This machine drives it and this PC enables this switch."))
for switch in (self.send, self.allow):
switch.setFont(theme.font(theme.TYPE["body"]))
self.send.toggled.connect(lambda on: on_send(self.token, on))
self.allow.toggled.connect(lambda on: on_allow(self.token, on))
- self.remove_button = _button("Remove", "small")
+ self.remove_button = _button(tr("Remove"), "small")
self.remove_button.setMinimumHeight(widgets.MIN_TARGET)
self.remove_button.clicked.connect(lambda: self._ask(True))
controls = QBoxLayout(QBoxLayout.Direction.TopToBottom)
@@ -420,10 +421,10 @@ class PeerRow(QWidget):
self.direction_group = QWidget()
self.direction_group.setLayout(directions)
self.direction_group.setVisible(False)
- self.directions = _button("Directions", "small")
+ self.directions = _button(tr("Directions"), "small")
self.directions.setCheckable(True)
self.directions.toggled.connect(self.direction_group.setVisible)
- self.directions.toggled.connect(lambda on: self.directions.setText("Hide directions" if on else "Directions"))
+ self.directions.toggled.connect(lambda on: self.directions.setText(tr("Hide directions" if on else "Directions")))
for switch in (self.send, self.allow):
switch.setMaximumWidth(300)
controls.addStretch(1)
@@ -443,10 +444,10 @@ class PeerRow(QWidget):
sure.addWidget(self.confirm_text)
buttons = QHBoxLayout()
buttons.setSpacing(8)
- self.really = _button("Remove", "small")
+ self.really = _button(tr("Remove"), "small")
self.really.setMinimumHeight(widgets.MIN_TARGET)
self.really.clicked.connect(lambda: self._on_remove(self.token))
- self.keep = _button("Keep", "small")
+ self.keep = _button(tr("Keep"), "small")
self.keep.setMinimumHeight(widgets.MIN_TARGET)
self.keep.clicked.connect(lambda: self._ask(False))
buttons.addWidget(self.really)
@@ -479,8 +480,8 @@ class PeerRow(QWidget):
self.name.setVisible(False)
self.rename_button.setVisible(False)
self.rename_edit.setVisible(True)
- self.rename_note.setText("Only on this computer" if self._same_on is False and sys.platform.startswith("linux")
- else "Only on this PC")
+ self.rename_note.setText(tr("Only on this computer") if self._same_on is False and sys.platform.startswith("linux")
+ else tr("Only on this PC"))
self.rename_note.setVisible(not self._same_on)
self.rename_edit.setFocus()
self.rename_edit.selectAll()
@@ -514,16 +515,16 @@ class PeerRow(QWidget):
self.shortcut_cycle.setChecked(entry.get("shortcut_cycle", True))
self.shortcut_cycle.blockSignals(False)
self.repair_button.setVisible(dormant)
- self.repair_button.setAccessibleName(f"Re-pair {label}")
+ self.repair_button.setAccessibleName(tr("Re-pair {name}").format(name=label))
self.left_out.setVisible(not self._phone and not asking)
- self.left_out.setText("Put back" if self._left_out else "Leave out")
- self.left_out.setAccessibleName(f"{'Put back' if self._left_out else 'Leave out'} {label}")
+ self.left_out.setText(tr("Put back" if self._left_out else "Leave out"))
+ self.left_out.setAccessibleName(tr("{action} {name}").format(action=tr("Put back" if self._left_out else "Leave out"), name=label))
self.left_out_note.setVisible(self._left_out)
self.directions.setVisible(not self._phone and not asking)
self.direction_group.setVisible(not self._phone and not asking and self.directions.isChecked())
self.led.set_tone(state.tone)
for item, text in ((self.name, label), (self.word, state.word), (self.where, where), (self.detail, state.detail),
- (self.confirm_text, f"Remove {label}? {KEEP_NOTE}")):
+ (self.confirm_text, tr("Remove {name}? {note}").format(name=label, note=tr(KEEP_NOTE)))):
if item.text() != text:
item.setText(text)
for switch, value in ((self.in_use, entry.get("in_use", True) is True),
@@ -532,13 +533,13 @@ class PeerRow(QWidget):
switch.blockSignals(True)
switch.setChecked(value)
switch.blockSignals(False)
- self.word.setAccessibleName(f"{label}: {state.word}")
- self.remove_button.setAccessibleName(f"Remove {label}")
- self.in_use.setToolTip(f"Off on this PC: no input or settings link to {label}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.")
+ self.word.setAccessibleName(tr("{name}: {status}").format(name=label, status=state.word))
+ self.remove_button.setAccessibleName(tr("Remove {name}").format(name=label))
+ self.in_use.setToolTip(tr("Off on this PC: no input or settings link to {name}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.").format(name=label))
if self._phone:
- self.in_use.setToolTip(f"Off on this PC: {label} cannot connect or drive it. Turn it back on here to reconnect.")
- self.send.setToolTip(f"Input moves only when this PC enables this switch and {label} enables It drives this PC.")
- self.allow.setToolTip(f"Input moves only when {label} enables This PC drives it and this PC enables this switch.")
+ self.in_use.setToolTip(tr("Off on this PC: {name} cannot connect or drive it. Turn it back on here to reconnect.").format(name=label))
+ self.send.setToolTip(tr("Input moves only when this PC enables this switch and {name} enables It drives this PC.").format(name=label))
+ self.allow.setToolTip(tr("Input moves only when {name} enables This PC drives it and this PC enables this switch.").format(name=label))
class MachinesModule(widgets.Module):
@@ -549,7 +550,7 @@ class MachinesModule(widgets.Module):
on_cycle: Optional[Callable] = None, on_repair: Optional[Callable] = None,
on_pair_phone: Optional[Callable] = None,
on_pair_nearby: Optional[Callable] = None) -> None:
- super().__init__("Machines")
+ super().__init__(tr("Machines"))
self._callbacks = (on_send, on_allow, on_in_use, on_left_out, on_remove,
on_rename or (lambda *_: None), on_cycle,
on_repair or (lambda *_: None))
@@ -557,12 +558,12 @@ class MachinesModule(widgets.Module):
self.rows_layout = QVBoxLayout()
self.rows_layout.setContentsMargins(0, 0, 0, 0)
self.rows_layout.setSpacing(0)
- self.pair_button = _button("Pair a machine")
+ self.pair_button = _button(tr("Pair a machine"))
self.pair_button.clicked.connect(on_pair)
- self.pair_phone_button = _button("Pair a phone")
+ self.pair_phone_button = _button(tr("Pair a phone"))
self.pair_phone_button.setVisible(feature_flags.PAIRING_QR_VISIBLE)
self.pair_phone_button.clicked.connect(on_pair_phone or (lambda: None))
- self.pair_nearby_button = _button("Pair nearby", "primary")
+ self.pair_nearby_button = _button(tr("Pair nearby"), "primary")
self.pair_nearby_button.clicked.connect(on_pair_nearby or (lambda: None))
pair_actions = QBoxLayout(QBoxLayout.Direction.LeftToRight)
self.pair_actions = pair_actions
@@ -604,7 +605,7 @@ class MachinesModule(widgets.Module):
self.empty.setVisible(not items)
def set_pairing_open(self, opened: bool) -> None:
- text = "Cancel" if opened else "Pair a machine"
+ text = tr("Cancel" if opened else "Pair a machine")
if self.pair_button.text() != text:
self.pair_button.setText(text)
widgets.set_role(self.pair_button, "")
@@ -618,7 +619,7 @@ class QrView(QWidget):
super().__init__()
self._rows: list = []
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
- self.setAccessibleName("QR code for the pairing code")
+ self.setAccessibleName(tr("QR code for the pairing code"))
def set_rows(self, rows: list) -> None:
if rows != self._rows:
@@ -649,7 +650,7 @@ class PairingSheet(widgets.Module):
on_choose_nearby: Optional[Callable] = None,
on_confirm_nearby: Optional[Callable] = None,
on_cancel_nearby: Optional[Callable] = None) -> None:
- super().__init__("Pair a machine")
+ super().__init__(tr("Pair a machine"))
self._on_pair = on_pair
self._on_pick = on_pick
self._machines: list = []
@@ -660,10 +661,10 @@ class PairingSheet(widgets.Module):
self._on_choose_nearby = on_choose_nearby or (lambda *_: None)
self._on_confirm_nearby = on_confirm_nearby or (lambda *_: None)
self._on_cancel_nearby = on_cancel_nearby or (lambda: None)
- self.body.addWidget(widgets.label("Show a code on this PC", "tile-name"))
- self.show_button = _button("Show a code", "primary")
+ self.body.addWidget(widgets.label(tr("Show a code on this PC"), "tile-name", wrap=True))
+ self.show_button = _button(tr("Show a code"), "primary")
self.show_button.clicked.connect(on_show)
- self.cancel_button = _button("Cancel", "small")
+ self.cancel_button = _button(tr("Cancel"), "small")
self.cancel_button.setMinimumHeight(widgets.MIN_TARGET)
self.cancel_button.clicked.connect(on_cancel)
self.cancel_button.setVisible(False)
@@ -693,7 +694,7 @@ class PairingSheet(widgets.Module):
self.count_label = widgets.label("", "count")
self.count_label.setFont(theme.mono_font(theme.TYPE["body"]))
self.count_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
- self.count_label.setAccessibleName("Time left")
+ self.count_label.setAccessibleName(tr("Time left"))
box.addLayout(row)
count_row = QHBoxLayout()
count_row.addStretch(1)
@@ -717,11 +718,11 @@ class PairingSheet(widgets.Module):
nearby.setContentsMargins(0, 8, 0, 8)
nearby.setSpacing(8)
self.nearby_note = widgets.label("", "note", wrap=True)
- self.nearby_note.setAccessibleName("Nearby pairing status")
+ self.nearby_note.setAccessibleName(tr("Nearby pairing status"))
nearby.addWidget(self.nearby_note)
self.nearby_count = widgets.label("", "count")
self.nearby_count.setFont(theme.mono_font(theme.TYPE["body"]))
- self.nearby_count.setAccessibleName("Nearby pairing time left")
+ self.nearby_count.setAccessibleName(tr("Nearby pairing time left"))
nearby.addWidget(self.nearby_count)
self.nearby_choices = QWidget()
self.nearby_choices.setProperty("vernier", "plain")
@@ -740,11 +741,11 @@ class PairingSheet(widgets.Module):
nearby.addWidget(self.nearby_digits, 0, Qt.AlignmentFlag.AlignLeft)
nearby_buttons = QHBoxLayout()
nearby_buttons.setSpacing(8)
- self.nearby_confirm = _button("Confirm", "primary")
+ self.nearby_confirm = _button(tr("Confirm"), "primary")
self.nearby_confirm.setDefault(False)
self.nearby_confirm.setAutoDefault(False)
self.nearby_confirm.clicked.connect(self._confirm_nearby)
- self.nearby_cancel = _button("Cancel", "small")
+ self.nearby_cancel = _button(tr("Cancel"), "small")
self.nearby_cancel.setDefault(False)
self.nearby_cancel.setAutoDefault(False)
self.nearby_cancel.clicked.connect(self._on_cancel_nearby)
@@ -756,31 +757,31 @@ class PairingSheet(widgets.Module):
self.body.addWidget(self.nearby_box)
self.body.addWidget(widgets.rule(False))
- self.body.addWidget(widgets.label("Enter a code from another machine", "tile-name"))
- self.body.addWidget(widgets.label("On this network", "note-quiet"))
+ self.body.addWidget(widgets.label(tr("Enter a code from another machine"), "tile-name", wrap=True))
+ self.body.addWidget(widgets.label(tr("On this network"), "note-quiet"))
self.heard_layout = QVBoxLayout()
self.heard_layout.setContentsMargins(0, 0, 0, 0)
self.heard_layout.setSpacing(6)
self.body.addLayout(self.heard_layout)
- self.none_heard = widgets.label("No other machine is showing a code yet.", "note", wrap=True)
+ self.none_heard = widgets.label(tr("No other machine is showing a code yet."), "note", wrap=True)
self.body.addWidget(self.none_heard)
self.group = QButtonGroup(self)
self.group.setExclusive(True)
self.address = QLineEdit()
- self.address.setAccessibleName("Address of the other machine")
- self.address.setPlaceholderText("Address")
+ self.address.setAccessibleName(tr("Address of the other machine"))
+ self.address.setPlaceholderText(tr("Address"))
self.address.textEdited.connect(self._typed_address)
self.body.addWidget(self.address)
- self.body.addWidget(widgets.label("Not listed? Type its address.", "note-quiet"))
+ self.body.addWidget(widgets.label(tr("Not listed? Type its address."), "note-quiet", wrap=True))
self.code = PairCodeEdit()
- self.code.setAccessibleName("Code")
+ self.code.setAccessibleName(tr("Code"))
self.code.setValidator(QRegularExpressionValidator(QRegularExpression(r"[0-9 \s–—\-]{0,32}"), self.code))
self.code.setFont(theme.mono_font(20))
self.code.setFixedHeight(self.code.fontMetrics().height() + CODE_CELL_PAD_Y * 2 + 4)
self.code.textEdited.connect(self._typed_code)
self.code.returnPressed.connect(self._pair)
self.body.addWidget(self.code)
- self.pair_button = _button("Pair", "primary")
+ self.pair_button = _button(tr("Pair"), "primary")
self.pair_button.clicked.connect(self._pair)
self.body.addWidget(self.pair_button, 0, Qt.AlignmentFlag.AlignLeft)
self.pair_note = widgets.label("", "note", wrap=True)
@@ -814,10 +815,10 @@ class PairingSheet(widgets.Module):
"expired": "Nearby pairing expired. Press Pair nearby to try again.",
"not_saved": "The new peer could not be saved.",
}
- self.nearby_note.setText(copy.get(state, "Nearby pairing could not continue."))
+ self.nearby_note.setText(tr(copy.get(state, "Nearby pairing could not continue.")))
widgets.set_role(self.nearby_note, "note-fault" if state in {"refused", "expired", "not_saved"} else "note")
seconds_left = max(0, int(status.get("seconds_left", 0)))
- self.nearby_count.setText(f"Expires in {seconds_left} s")
+ self.nearby_count.setText(tr("Expires in {n} s").format(n=seconds_left))
self.nearby_count.setVisible(state in {"searching", "choosing", "exchanging", "confirm", "waiting"})
peers = status.get("peers") or []
@@ -855,13 +856,13 @@ class PairingSheet(widgets.Module):
self.nearby_choices.setVisible(state == "choosing")
selected_name = str((peer or {}).get("name") or "")
selected_platform = peers_view.platform_name(peer) if peer else ""
- selected = f"Selected: {selected_name} · {selected_platform}" if selected_name else ""
+ selected = tr("Selected: {name} · {platform}").format(name=selected_name, platform=selected_platform) if selected_name else ""
self.nearby_peer.setText(shown(selected) if selected else "")
self.nearby_peer.setVisible(bool(self.nearby_peer.text()))
sas = status.get("sas") if state in {"confirm", "waiting"} else None
grouped = f"{sas[:3]} {sas[3:]}" if isinstance(sas, str) and len(sas) == 6 and sas.isascii() and sas.isdigit() else ""
self.nearby_digits.setText(grouped)
- self.nearby_digits.setAccessibleName(f"Pairing digits {' '.join(sas)}" if grouped else "Pairing digits")
+ self.nearby_digits.setAccessibleName(tr("Pairing digits {digits}").format(digits=" ".join(sas)) if grouped else tr("Pairing digits"))
self.nearby_digits.setVisible(bool(grouped))
self.nearby_confirm.setVisible(state == "confirm")
self.nearby_confirm.setEnabled(state == "confirm" and bool(grouped) and bool(self._nearby_attempt))
@@ -873,8 +874,8 @@ class PairingSheet(widgets.Module):
shown = f"{code[:3]} {code[3:]}"
if self.code_label.text() != shown:
self.code_label.setText(shown)
- self.code_label.setAccessibleName(f"Pairing code {' '.join(code)}")
- self.count_label.setText(f"Expires in {seconds} s")
+ self.code_label.setAccessibleName(tr("Pairing code {digits}").format(digits=" ".join(code)))
+ self.count_label.setText(tr("Expires in {n} s").format(n=seconds))
self.drain.set_remaining(seconds)
if self.address_note.text() != address:
self.address_note.setText(address)
@@ -896,7 +897,7 @@ class PairingSheet(widgets.Module):
self.cancel_button.setVisible(False)
self.show_button.setVisible(True)
self.drain.set_remaining(0)
- self.code_label.setAccessibleName("Pairing code")
+ self.code_label.setAccessibleName(tr("Pairing code"))
self.code_box.setVisible(False)
@property
@@ -1009,7 +1010,7 @@ class PairingSheet(widgets.Module):
def busy(self, working: bool) -> None:
self._working = working
- self.pair_button.setText("Pairing…" if working else "Pair")
+ self.pair_button.setText(tr("Pairing…") if working else tr("Pair"))
self._refresh_pair_button()
def clear_code(self) -> None:
diff --git a/win_app/pages_win.py b/win_app/pages_win.py
index d76634a..f00cb0d 100644
--- a/win_app/pages_win.py
+++ b/win_app/pages_win.py
@@ -7,41 +7,67 @@ from __future__ import annotations
import re
import threading
+import time
from core import effects
from core import peerlist
-from core.ways import part_names, parts_phrase, toggle_part
+from core.i18n import N_, joined, tr, trc
+from core.ways import CORNER_NAMES_LOWER, EDGE_NAMES, part_names, parts_phrase, toggle_part
# (key, name, what the page is for), in sidebar order, which is setup order; Ctrl+1 is the first.
PAGES = (
- ("overview", "Overview",
- "The machines paired with this PC, where input is right now, and the controls you reach for "
- "every day. Pair a machine here first."),
- ("crossing", "Crossing",
- "Choose how the pointer or a key moves input to each machine, and how hard the edge "
- "pushes back first."),
- ("keyboard", "Keyboard",
- "How this PC's Ctrl and Windows keys arrive on another machine, the keys and buttons that stay "
- "here, and how fast another machine's pointer moves here."),
- ("design", "Design",
- "How crossing looks on this PC: the light as you push toward another machine, and where the "
- "pointer lands."),
- ("connection", "Connection",
- "This PC's network access, address and listening port; hide addresses in this window and tray."),
+ ("overview", N_("Overview"),
+ N_("The machines paired with this PC, where input is right now, and the controls you reach for "
+ "every day. Pair a machine here first.")),
+ ("crossing", N_("Crossing"),
+ N_("Choose how the pointer or a key moves input to each machine, and how hard the edge "
+ "pushes back first.")),
+ ("keyboard", N_("Keyboard"),
+ N_("How this PC's Ctrl and Windows keys arrive on another machine, the keys and buttons that stay "
+ "here, and how fast another machine's pointer moves here.")),
+ ("design", N_("Design"),
+ N_("How crossing looks on this PC: the light as you push toward another machine, and where the "
+ "pointer lands.")),
+ ("connection", N_("Connection"),
+ N_("This PC's network access, address and listening port; hide addresses in this window and tray.")),
)
KEYS = tuple(page[0] for page in PAGES)
# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for another
# machine's on the PC: each app sets only its own machine.
SCOPE = {
- "crossing": "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this PC's input for every destination.",
- "design": "Used on this screen. Shared animation settings may follow another machine; Animate and window appearance stay on this PC.",
- "keyboard": "Modifier keys and Stays here belong to this PC's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own.",
+ "crossing": N_("Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this PC's input for every destination."),
+ "design": N_("Used on this screen. Shared animation settings may follow another machine; Animate and window appearance stay on this PC."),
+ "keyboard": N_("Modifier keys and Stays here belong to this PC's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own."),
}
# With Same on all machines on, under each row of the shared pages that stays this PC's own.
-OWN_ROW = "This PC only."
+OWN_ROW = N_("This PC only.")
# The window's footer; the first sentence goes on Connection, whose changes wait for its button.
-FOOTER_APPLY = "Changes apply as you make them."
-FOOTER_TRAY = "Closing this window keeps Beamer running in the tray."
+FOOTER_APPLY = N_("Changes apply as you make them.")
+FOOTER_TRAY = N_("Closing this window keeps Beamer running in the tray.")
+FOOTER_BOTH = N_("Changes apply as you make them. Closing this window keeps Beamer running in the tray.")
+
+
+PERMISSION_STATUS_LABELS = {
+ "not_requested": N_("Not requested"), "ready": N_("Ready"),
+ "refused": N_("Refused"), "unavailable": N_("Unavailable"),
+}
+
+
+def saved_ways_label(item, settings):
+ reasons = {
+ "upgrade": N_("Before Beamer 1.5.5"), "older_version": N_("From an older Beamer"),
+ "sync_off": N_("When Same ways went off"), "seeded": N_("When Same ways went on"),
+ "edited": N_("Before you changed it"), "restored": N_("Before a restore"),
+ }
+ if item.get("why") == "replaced_by":
+ author = item.get("by")
+ name = (settings.get("name") if author == settings.get("machine_id") else
+ peerlist.label_for(settings.get("peers", []), peer_id=author)) or tr("another machine")
+ reason = tr("Before {name} changed it").format(name=name)
+ else:
+ reason = tr(reasons.get(item.get("why"), N_("Earlier ways"))) # N_ table: saved ways archive reasons
+ date = time.strftime("%d-%m-%Y", time.localtime(item.get("at", 0)))
+ return tr("{date} · {reason}").format(date=date, reason=reason)
class LinuxPermissionState:
@@ -96,7 +122,7 @@ def linux_permissions_visible(platform: str, wayland: bool) -> bool:
def footer(page: str) -> str:
- return FOOTER_TRAY if page == "connection" else f"{FOOTER_APPLY} {FOOTER_TRAY}"
+ return tr(FOOTER_TRAY if page == "connection" else FOOTER_BOTH)
def dots(config_error: bool, firewall_tone: str | None, dormant: bool = False) -> dict:
@@ -119,13 +145,14 @@ def dots(config_error: bool, firewall_tone: str | None, dormant: bool = False) -
# 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 = "Light"
+CLASSIC = N_("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."),
+ ("glow", N_("Glow"), N_("A band of light that deepens the harder you push.")),
+ ("beam", N_("Beam"), N_("A thin line with a comet of light running along it.")),
+ ("aperture", N_("Aperture"), N_("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"), ("aurora", "Aurora"))
+TODAY_COLOURS = (("signal", N_("Signal")), ("colourful", N_("Colourful")), ("ocean", N_("Ocean")),
+ ("sunset", N_("Sunset")), ("mono", N_("Mono")), ("aurora", N_("Aurora")))
def effects_load_error():
@@ -144,13 +171,13 @@ def style_groups() -> tuple:
# Glow and Beam's detail is their kind, as an effect's is its intensity; what they do is said
# under the preview.
if effects_load_error() is not None:
- return ((CLASSIC, tuple((value, name, effects.CLASSIC[value].intensity.capitalize())
+ return ((CLASSIC, tuple((value, name, effects.intensity_name(effects.CLASSIC[value].intensity))
for value, name, _blurb in TODAY_STYLES[:2])),)
- groups = [(CLASSIC, tuple((value, name, effects.CLASSIC[value].intensity.capitalize())
+ groups = [(CLASSIC, tuple((value, name, effects.intensity_name(effects.CLASSIC[value].intensity))
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)))
+ groups.append((title, tuple((fx.id, fx.name, effects.intensity_name(fx.intensity)) for fx in found)))
return tuple(groups)
@@ -181,19 +208,21 @@ def place_note(style: str, place: str, methods) -> str:
ways = {"edge": {"edge", "part"}, "corner": {"corner"}}[place]
if set(methods) & ways:
return ""
- return (f"{PLACES[place].capitalize()} is not one of this PC's ways in, so this only shows how it "
- "would look. Turn it on under Crossing.")
+ return tr("{place} is not one of this PC's ways in, so this only shows how it would look. Turn it on under Crossing.").format(
+ place=PLACES[place].capitalize())
def share_sentence(holders, side, name):
"""Name the machines already using the side the chosen machine wants."""
- names = holders[0] if len(holders) == 1 else ", ".join(holders[:-1]) + " and " + holders[-1]
- verb = "crosses" if len(holders) == 1 else "cross"
- # The sentence says what picking a third means: it goes to `name`.
- keep = f"stay with {holders[0]}" if len(holders) == 1 else "stay where they are"
- return (f"{names} already {verb} from the {side} edge of this PC. The thirds you pick go to {name}; "
- f"the rest {keep}.")
+ names = joined(holders)
+ if len(holders) == 1:
+ # Translators: {side} is the direction of the screen edge.
+ return tr("{names} already crosses from the {side} edge of this PC. The thirds you pick go to {name}; the rest stay with {holder}.").format(
+ names=names, side=tr(EDGE_NAMES.get(side, side)) if side in EDGE_NAMES else side, name=name, holder=holders[0])
+ # Translators: {side} is the direction of the screen edge.
+ return tr("{names} already cross from the {side} edge of this PC. The thirds you pick go to {name}; the rest stay where they are.").format(
+ names=names, side=tr(EDGE_NAMES.get(side, side)) if side in EDGE_NAMES else side, name=name)
# The Crossing page's ways in, in the page's order. Edge and Part of the edge are two readings of
@@ -214,7 +243,7 @@ def toggle_way(methods, way, on) -> list:
def not_learned_edge(name: str = "the other machine") -> str:
"""Under Where it is, while this PC holds no side for the machine named."""
- return f"Not learned yet: choose a side here or on {name}."
+ return tr("Not learned yet: choose a side here or on {name}.").format(name=name)
def crossing_machines(peers: list) -> list:
@@ -229,23 +258,20 @@ def crossing_state_sentence(paired, heard, sending, connected, armed, paused, fu
"""The Crossing page's line under Pause: why nothing can cross, first match wins, and only then
whether crossing is on, held or paused. `name` is the machine it is about."""
if not paired:
- return "Not paired yet, so no edge or shortcut moves input until you pair a machine above."
+ return tr("Not paired yet, so no edge or shortcut moves input until you pair a machine above.")
if not heard:
- return f"Waiting to hear from {name}. This PC cannot push into it until it has connected once."
+ return tr("Waiting to hear from {name}. This PC cannot push into it until it has connected once.").format(name=name)
if not sending:
- return f"This PC does not drive {name}, so edges and the shortcut do nothing."
+ return tr("This PC does not drive {name}, so edges and the shortcut do nothing.").format(name=name)
if not connected:
- return (
- f"Not connected to {name}, so edges and the shortcut do nothing yet. "
- "Check that it is switched on and lets this PC drive it."
- )
+ return tr("Not connected to {name}, so edges and the shortcut do nothing yet. Check that it is switched on and lets this PC drive it.").format(name=name)
if not armed:
- return "Only the shortcut is switched on; there is nothing to pause."
+ return tr("Only the shortcut is switched on; there is nothing to pause.")
if paused:
- return "Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts."
+ return tr("Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts.")
if full_screen_app is not None:
- return "Held: an app is full screen."
- return "On. Pause it to lean on an edge without switching."
+ return tr("Held: an app is full screen.")
+ return tr("On. Pause it to lean on an edge without switching.")
def crossing_state_blocked(paired, mac_heard, sending, connected) -> bool:
@@ -290,96 +316,116 @@ def switch_groups() -> tuple:
# The Crossing page's "Where your Mac is": the value is the edge of this PC that leads to the Mac.
-SIDE_CHOICES = (("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below"))
+SIDE_CHOICES = (("left", N_("Left")), ("right", N_("Right")), ("top", N_("Above")), ("bottom", N_("Below")))
# The ways in, as their rows read: the pointer's first, then the shortcut.
WAY_ROWS = (
("edge", "Edge", "One whole side"),
("corner", "Corner", "Push diagonally into a corner"),
("shortcut", "Shortcut", "Press a key to switch input"),
)
-CORNER_NAMES = {"top_left": "top-left", "top_right": "top-right", "bottom_left": "bottom-left", "bottom_right": "bottom-right"}
+CORNER_NAMES = {"top_left": N_("top-left"), "top_right": N_("top-right"), "bottom_left": N_("bottom-left"), "bottom_right": N_("bottom-right")}
def trigger_phrase(key_name: str, style: str) -> str:
"""The shortcut as the arrangement diagram's key cap line reads it: "Right Ctrl, twice"."""
- return f"{key_name}, {'held' if style == 'hold' else 'twice'}"
+ if style == "hold":
+ return tr("{key}, held").format(key=key_name)
+ return tr("{key}, twice").format(key=key_name)
-SHORTCUT_SEVERAL = "The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."
+SHORTCUT_SEVERAL = N_("The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input.")
-def _joined(items) -> str:
- return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
+def _or_join(items) -> str:
+ if len(items) == 1:
+ return items[0]
+ if len(items) == 2:
+ # Translators: Two ways to move input, offered as alternatives.
+ return trc("ways list", "{first} or {last}").format(first=items[0], last=items[1])
+ # Translators: Several ways to move input, offered as alternatives.
+ return trc("ways list", "{head} or {last}").format(head=", ".join(items[:-1]), last=items[-1])
-def ways_summary(methods, edge, parts, corner, key_name, style, name="the other machine", several=False) -> str:
+def ways_summary(methods, edge, parts, corner, key_name, style, name=None, several=False) -> str:
"""The Ways in module's first line: every way input leaves for the machine `name`, in one
sentence. With `several` machines paired the shortcut is not this one's, so it gets a sentence of
its own."""
+ if name is None:
+ name = tr("the other machine")
methods = set(methods)
if not edge:
# A PC's edge, thirds and corner all cross the side it holds; only the shortcut needs none.
if "shortcut" in methods and not several:
- press = f"hold {key_name}" if style == "hold" else f"press {key_name} twice"
- return (f"Input moves to {name} when you {press}. Its edges and corner wait until this PC knows "
- f"which side {name} is on.")
- return f"Nothing moves input to {name} until this PC knows which side it is on."
+ if style == "hold":
+ return tr("Input moves to {name} when you hold {key}. Its edges and corner wait until this PC knows which side {name} is on.").format(name=name, key=key_name)
+ return tr("Input moves to {name} when you press {key} twice. Its edges and corner wait until this PC knows which side {name} is on.").format(name=name, key=key_name)
+ return tr("Nothing moves input to {name} until this PC knows which side it is on.").format(name=name)
ways = []
if "edge" in methods:
- ways.append(f"push through the whole {edge} edge")
+ ways.append(tr("push through the whole {edge} edge").format(edge=tr(EDGE_NAMES[edge])))
if "part" in methods:
- ways.append(f"push through {parts_phrase(edge, parts)}")
+ ways.append(tr("push through {parts}").format(parts=parts_phrase(edge, parts)))
if "corner" in methods:
- ways.append(f"push diagonally into the {CORNER_NAMES.get(corner, corner)} corner")
+ ways.append(tr("push diagonally into the {corner} corner").format(
+ corner=tr(CORNER_NAMES[corner]) if corner in CORNER_NAMES else corner))
shortcut = "shortcut" in methods
if shortcut and not several:
- ways.append(f"hold {key_name}" if style == "hold" else f"press {key_name} twice")
- after = f" {SHORTCUT_SEVERAL}" if shortcut and several else ""
+ ways.append(tr("hold {key}").format(key=key_name) if style == "hold" else tr("press {key} twice").format(key=key_name))
if not ways and several:
- return f"No edge or corner leads to {name} yet: choose one below.{after}"
+ return (tr("No edge or corner leads to {name} yet: choose one below. The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input.").format(name=name) if shortcut else
+ tr("No edge or corner leads to {name} yet: choose one below.").format(name=name))
if not ways:
- return f"Nothing moves input to {name}: choose at least one way below."
- joined = ways[0] if len(ways) == 1 else ", ".join(ways[:-1]) + " or " + ways[-1]
- return f"Input moves to {name} when you {joined}.{after}"
+ return tr("Nothing moves input to {name}: choose at least one way below.").format(name=name)
+ phrase = _or_join(ways)
+ if shortcut and several:
+ return tr("Input moves to {name} when you {ways}. The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input.").format(name=name, ways=phrase)
+ return tr("Input moves to {name} when you {ways}.").format(name=name, ways=phrase)
def ways_note(methods, edge, parts, corner, key_name, style, name, several=False) -> str:
methods = set(methods)
- phrases = []
- if "shortcut" in methods:
- phrases.append(f"{'Hold' if style == 'hold' else 'Double-tap'} {key_name}")
+ shortcut = tr("Hold {key}").format(key=key_name) if style == "hold" else tr("Double-tap {key}").format(key=key_name)
pointer = []
if edge:
if "part" in methods:
pointer.append(parts_phrase(edge, parts))
elif "edge" in methods:
- pointer.append(f"the {edge} edge")
+ pointer.append(tr("the {edge} edge").format(edge=tr(EDGE_NAMES[edge])))
if "corner" in methods:
- pointer.append(f"the {(corner or 'top_right').replace('_', ' ')} corner")
+ pointer_corner = corner or "top_right"
+ pointer_name = (tr(CORNER_NAMES_LOWER[pointer_corner]) if pointer_corner in CORNER_NAMES_LOWER
+ else pointer_corner.replace("_", " "))
+ pointer.append(tr("the {corner} corner").format(corner=pointer_name))
if pointer:
- joined = pointer[0] if len(pointer) == 1 else ", ".join(pointer[:-1]) + " or " + pointer[-1]
- phrases.append(f"push through {joined}" + (f" to reach {name}" if several else ""))
- sentence = ", or ".join(phrases)
- return sentence[0].upper() + sentence[1:] + "." if sentence else "This PC is always in the shortcut's cycle."
+ detail = _or_join(pointer)
+ action = tr("push through {ways}").format(ways=detail)
+ action = tr("push through {ways} to reach {name}").format(ways=detail, name=name) if several else action
+ if "shortcut" in methods:
+ return tr("{shortcut}, or {action}.").format(shortcut=shortcut, action=action)
+ sentence = tr("{action}.").format(action=action)
+ return sentence[0].upper() + sentence[1:]
+ if "shortcut" in methods:
+ return tr("{shortcut}.").format(shortcut=shortcut)
+ return tr("This PC is always in the shortcut's cycle.")
def shortcut_destination_note(mode: str, hold: bool) -> str:
if mode == "last":
- note = "With Hold, input goes to the last machine."
+ note = tr("With Hold, input goes to the last machine.")
elif hold:
- note = "With Hold, input goes to the first ready machine in order."
+ note = tr("With Hold, input goes to the first ready machine in order.")
else:
- note = "The order follows the tiles from top to bottom, then left to right. This PC is always in the cycle."
+ note = tr("The order follows the tiles from top to bottom, then left to right. This PC is always in the cycle.")
if mode == "ticked":
- note += " Choose which machines join the cycle with the tick boxes on their tiles."
+ note += " " + tr("Choose which machines join the cycle with the tick boxes on their tiles.")
return note
# The arrangement diagram. Each side of this PC has an angle, and a machine's screen travels round
# this PC's between them: through a corner position, never across it.
SIDE_ANGLE = {"right": 0.0, "top": 90.0, "left": 180.0, "bottom": 270.0}
-SIDE_WORDS = {"right": "to the right of this PC", "left": "to the left of this PC", "top": "above this PC",
- "bottom": "below this PC"}
+SIDE_WORDS = {"right": N_("to the right of this PC"), "left": N_("to the left of this PC"), "top": N_("above this PC"),
+ "bottom": N_("below this PC")}
PART_ORDER = ("start", "middle", "end")
@@ -482,24 +528,31 @@ def layout_rects(width: float, top: float, placed: list, screen: tuple, gap: flo
def unplaced_line(labels: list) -> str:
"""The line under the diagram naming the machines that have no side yet; "" when none."""
- return f"Not placed yet: {_joined(labels)}" if labels else ""
+ return tr("Not placed yet: {machines}").format(machines=joined(labels)) if labels else ""
def diagram_description(machines: list, key_name: str, style: str, shortcut: bool) -> str:
"""The diagram's accessible description: where every machine is, then the chosen one's ways in.
Each machine is a dict with `label`, `side`, `methods`, `parts`, `corner` and `chosen`."""
- placed = [f"{machine['label']} is {SIDE_WORDS[machine['side']]}" for machine in machines
+ placed = [tr("{name} is {position}").format(name=machine["label"], position=tr(SIDE_WORDS[machine["side"]]))
+ for machine in machines
if machine.get("side") in SIDE_WORDS]
- sentences = [_joined(placed) + "."] if placed else []
+ sentences = [tr("{machines}.").format(machines=joined(placed))] if placed else []
line = unplaced_line([machine["label"] for machine in machines if machine.get("side") not in SIDE_WORDS])
if line:
- sentences.append(line + ".")
+ sentences.append(tr("{line}.").format(line=line))
chosen = next((machine for machine in machines if machine.get("chosen")), machines[0] if machines else None)
if chosen is not None:
methods = list(chosen.get("methods") or ()) + (["shortcut"] if shortcut else [])
sentences.append(ways_summary(methods, chosen.get("side") or "", chosen.get("parts") or (), chosen.get("corner") or "",
key_name, style, chosen["label"], several=len(machines) > 1))
- return " ".join(sentences)
+ if len(sentences) == 0:
+ return ""
+ if len(sentences) == 1:
+ return sentences[0]
+ if len(sentences) == 2:
+ return tr("{first} {second}").format(first=sentences[0], second=sentences[1])
+ return tr("{first} {second} {third}").format(first=sentences[0], second=sentences[1], third=sentences[2])
def side_segment(rect: tuple, side: str, start: float = 0.0, end: float = 1.0, inset: float = 0.0) -> tuple:
diff --git a/win_app/peers_view.py b/win_app/peers_view.py
index 9c9b6ae..5257e15 100644
--- a/win_app/peers_view.py
+++ b/win_app/peers_view.py
@@ -10,8 +10,10 @@ from __future__ import annotations
from dataclasses import dataclass
from core import peerlist, protocol
+from core.i18n import matches_translation, N_, tr
-PLATFORM_NAMES = {"macos": "Mac", "windows": "Windows", "linux": "Linux", "ios": "iPhone", "android": "Android"}
+PLATFORM_NAMES = {"macos": N_("Mac"), "windows": N_("Windows"), "linux": N_("Linux"),
+ "ios": N_("iPhone"), "android": N_("Android")}
REFUSED_KINDS = ("unauthenticated", "wrong_id", "different", "unreadable", "forgotten")
VERSION_KINDS = ("older", "newer", "not_beamer")
@@ -27,14 +29,14 @@ class PeerState:
def platform_name(entry: dict) -> str:
- return PLATFORM_NAMES.get(entry.get("platform"), "Other")
+ return tr(PLATFORM_NAMES.get(entry.get("platform"), N_("Other")))
def address_line(entry: dict, hide: bool) -> str:
host, port = entry.get("host") or "", entry.get("port")
if not host or not isinstance(port, int) or isinstance(port, bool) or port <= 0:
- return "No address"
- return f"{'•••' if hide else host} · port {port}"
+ return tr("No address")
+ return tr("{address} · port {port}").format(address="•••" if hide else host, port=port)
def describe(entry: dict, label: str, *, up: bool, driving: bool, input_there: bool, kind: str, status: str,
@@ -44,32 +46,34 @@ def describe(entry: dict, label: str, *, up: bool, driving: bool, input_there: b
last reported."""
reason = peerlist.dormant_reason(entry)
if reason:
- return PeerState("amber", "Needs re-pair", reason)
+ return PeerState("amber", tr("Needs re-pair"), reason)
if entry.get("in_use", True) is not True:
- return PeerState("amber", "NOT IN USE", f"{label} is not in use on this PC.")
+ return PeerState("amber", tr("NOT IN USE"), tr("{name} is not in use on this PC.").format(name=label))
if driving:
- return PeerState("signal", "Driving this PC",
- f"{label}'s keyboard and pointer are on this PC. Push the pointer back through the edge it arrived by to send them home.")
+ return PeerState("signal", tr("Driving this PC"),
+ tr("{name}'s keyboard and pointer are on this PC. Push the pointer back through the edge it arrived by to send them home.").format(name=label))
if input_there:
- return PeerState("signal", "Input here",
- f"This PC's keyboard and pointer are on {label}. Do the same again to bring them home.")
+ return PeerState("signal", tr("Input here"),
+ tr("This PC's keyboard and pointer are on {name}. Do the same again to bring them home.").format(name=label))
if not protocol.linkable(entry):
- return PeerState("amber", "Pair again",
- f"{label} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.")
+ return PeerState("amber", tr("Pair again"),
+ tr("{name} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.").format(name=label))
if up:
- return PeerState("signal", "Linked", f"Connected to {label}.")
+ return PeerState("signal", tr("Linked"), tr("Connected to {name}.").format(name=label))
if waking:
- return PeerState("amber", "Waiting", f"Waking {label}…")
+ return PeerState("amber", tr("Waiting"), tr("Waking {name}…").format(name=label))
if not entry.get("send"):
- return PeerState("amber", "Waiting", f"Waiting for {label} to connect.")
+ return PeerState("amber", tr("Waiting"), tr("Waiting for {name} to connect.").format(name=label))
if not status or kind in QUIET_KINDS:
- return PeerState("amber", "Waiting", f"Looking for {label}. It connects on its own once Beamer is open there.")
+ return PeerState("amber", tr("Waiting"), tr("Looking for {name}. It connects on its own once Beamer is open there.").format(name=label))
if kind in REFUSED_KINDS:
- return PeerState("fault", "Refused", status)
- if kind in VERSION_KINDS or (kind == "closed" and status.startswith("Update Beamer on")):
- return PeerState("fault", "Version", status)
+ return PeerState("fault", tr("Refused"), status)
+ if kind in VERSION_KINDS or (kind == "closed" and matches_translation(
+ status, "Update Beamer on {name} to 1.5.0; if it is up to date, pair the two again",
+ "Update Beamer on {name}: it is older than this one")):
+ return PeerState("fault", tr("Version"), status)
if kind in UNREACHABLE_KINDS:
- return PeerState("fault", "Unreachable", status)
+ return PeerState("fault", tr("Unreachable"), status)
if kind == "refused":
- return PeerState("fault", "Not listening", status)
- return PeerState("fault", "Dropped", f"{status.rstrip('.')}. Beamer keeps trying to reconnect.")
+ return PeerState("fault", tr("Not listening"), status)
+ return PeerState("fault", tr("Dropped"), tr("{status}. Beamer keeps trying to reconnect.").format(status=status.rstrip(".")))
diff --git a/win_app/portal.py b/win_app/portal.py
index 4813e12..c5d4445 100644
--- a/win_app/portal.py
+++ b/win_app/portal.py
@@ -33,6 +33,9 @@ PROPERTIES = "org.freedesktop.DBus.Properties"
NOTIFICATION = "org.freedesktop.portal.Notification"
CALL_SECONDS = 10.0
TICK_SECONDS = 0.1
+# A request still unanswered after this long is said in the log once, and still waited for: the
+# user may be taking their time over the dialog, or the desktop may have lost it.
+SLOW_ANSWER_SECONDS = 60.0
class Refused(Exception):
@@ -127,7 +130,9 @@ class Portal:
token = self.token()
path = f"/org/freedesktop/portal/desktop/request/{self._sender}/{token}"
self.call(interface, method, signature, make_body(token))
- deadline = None if timeout is None else time.monotonic() + timeout
+ started = time.monotonic()
+ deadline = None if timeout is None else started + timeout
+ warned = False
while True:
for item in list(self._waiting):
_kind, at, iface, member, body = item
@@ -141,6 +146,10 @@ class Portal:
raise PortalError(f"{method} ended without an answer ({code})")
if self._stopping():
raise PortalError(f"{method} was abandoned: Beamer is stopping")
+ if not warned and time.monotonic() - started >= SLOW_ANSWER_SECONDS:
+ warned = True
+ LOGGER.warning("Still waiting for the desktop's answer to %s.%s after %d s",
+ interface.rsplit(".", 1)[-1], method, SLOW_ANSWER_SECONDS)
wait = TICK_SECONDS
if deadline is not None:
wait = min(wait, deadline - time.monotonic())
diff --git a/win_app/quit_signals.py b/win_app/quit_signals.py
new file mode 100644
index 0000000..aed6e8c
--- /dev/null
+++ b/win_app/quit_signals.py
@@ -0,0 +1,57 @@
+"""SIGTERM and SIGINT quit the Qt app through its own quit(), so a restart from outside (a session
+over ssh, the desktop's logout, `kill`) still restores the pointer and stops the portals and the
+injector, instead of dying mid-capture (14-10-2026, Fedora 1.5.3 to 1.5.4).
+
+Python runs a signal handler only between bytecodes on the main thread, and that thread sits in
+Qt's event loop, in C, until something wakes it. So the signal's byte goes to a socket that
+Python's set_wakeup_fd writes, a QSocketNotifier on its other end wakes the loop, and the handler
+then runs and asks for quit() on the next turn of the loop."""
+
+import logging
+import signal
+import socket
+from typing import Callable, Optional
+
+from PySide6.QtCore import QObject, QSocketNotifier, QTimer
+
+LOGGER = logging.getLogger(__name__)
+
+SIGNALS = tuple(getattr(signal, name) for name in ("SIGTERM", "SIGINT") if hasattr(signal, name))
+
+
+class QuitSignals(QObject):
+ def __init__(self, on_quit: Callable[[], None], parent: Optional[QObject] = None) -> None:
+ super().__init__(parent)
+ self._on_quit = on_quit
+ self._quitting = False
+ self._reader, self._writer = socket.socketpair()
+ for end in (self._reader, self._writer):
+ end.setblocking(False)
+ self._previous_fd = signal.set_wakeup_fd(self._writer.fileno())
+ self._previous = {number: signal.signal(number, self._handle) for number in SIGNALS}
+ self._notifier = QSocketNotifier(self._reader.fileno(), QSocketNotifier.Type.Read, self)
+ self._notifier.activated.connect(self._drain)
+
+ def _drain(self, *_args) -> None:
+ try:
+ while self._reader.recv(64):
+ pass
+ except (BlockingIOError, InterruptedError):
+ pass
+
+ def _handle(self, number, _frame) -> None:
+ if self._quitting:
+ return
+ self._quitting = True
+ LOGGER.info("%s received; quitting", signal.Signals(number).name)
+ QTimer.singleShot(0, self._on_quit)
+
+ def close(self) -> None:
+ if self._reader.fileno() == -1:
+ return
+ self._notifier.setEnabled(False)
+ for number, previous in self._previous.items():
+ signal.signal(number, previous)
+ signal.set_wakeup_fd(self._previous_fd)
+ self._reader.close()
+ self._writer.close()
diff --git a/win_app/sender.py b/win_app/sender.py
index 417d42c..0fa72f3 100644
--- a/win_app/sender.py
+++ b/win_app/sender.py
@@ -35,8 +35,10 @@ from core import protocol
from core import special_keys
from core import receiver
from core import return_edge
+from core.shake import HomeHold, ShakeDetector
from core import ways
from core import wol
+from core.i18n import N_, tr
LOGGER = logging.getLogger(__name__)
@@ -48,9 +50,9 @@ WAKE_POLL_SECONDS = 0.5
# How long a machine that is being driven waits for its driver to let go before it gives up on
# the move it was asked for: the responder's own forced end is one second.
LET_GO_WAIT_SECONDS = 1.5
-WAKING_STATUS = "Waking {name}…"
-NOT_WOKEN_STATUS = "{name} did not wake"
-NOT_CONNECTED_STATUS = "Not connected"
+WAKING_STATUS = N_("Waking {name}…")
+NOT_WOKEN_STATUS = N_("{name} did not wake")
+NOT_CONNECTED_STATUS = N_("Not connected")
# The capture names this PC's Ctrl "cmd" and its Windows key "ctrl", the Semantic style; the key
# table takes the physical key, so the two are swapped back here.
@@ -65,12 +67,12 @@ INPUT_TYPES = protocol.INPUT_TYPES
# What the owner's reasons for bringing input home say, naming the machine (WIRE.md section 5).
HOME_REASONS = {
- "not_allowed": "{name} does not accept input from this one",
- "sent_home": "{name} sent the input back",
- "link_lost": "Lost the link to {name}",
- "no_answer": "{name} did not answer",
- "refused": "{name} would not take the input",
- "malformed": "{name} would not take the input",
+ "not_allowed": N_("{name} does not accept input from this one"),
+ "sent_home": N_("{name} sent the input back"),
+ "link_lost": N_("Lost the link to {name}"),
+ "no_answer": N_("{name} did not answer"),
+ "refused": N_("{name} would not take the input"),
+ "malformed": N_("{name} would not take the input"),
}
@@ -175,12 +177,17 @@ class LinkSender:
# The name a key went down under, by virtual key, so its release matches even when Shift or
# the style changes while it is held.
self._keys_down: dict = {}
+ self._input_method_tap_releases: set = set()
self._pending_windows_key: Optional[int] = None
self._intent_keys_up: set = set()
self._intent_windows_up: set = set()
self._accepts: dict = {} # peer id: whether it lets this PC drive it
self._sent_names: dict = {} # (peer, physical key): the name its press went out under
self._buttons_held = set()
+ self._shake_detector = None
+ self._shake_callback = None
+ self._home_hold = None
+ self._shake_home_pending = False
self._pin_point = None
self._monitors = None
self._display_map = {}
@@ -222,6 +229,7 @@ class LinkSender:
# capture it (Wayland), which it does at an edge barrier: there the shortcut and the tray
# cannot send input away, only an edge push can.
self.input_held: Callable[[], bool] = lambda: True
+ self.push_out: Optional[Callable[[bytes, Callable[[], None], Callable[[], None]], bool]] = None
# The responder's: whether a peer's input is on this PC, and sending it home.
self.driven: Callable[[], bool] = lambda: False
self.send_peer_home: Callable[[], bool] = lambda: False
@@ -316,7 +324,8 @@ class LinkSender:
def _announce_shortcut_skips(self, skipped):
for ident in skipped:
- self._alert(f"Skipped {peerlist.label_for(self._entries, peer_id=ident) or 'Other machine'}: not connected.")
+ name = peerlist.label_for(self._entries, peer_id=ident)
+ self._alert(tr("Skipped {name}: not connected.").format(name=name or tr("Other machine")))
def toggle_shortcut(self) -> None:
if self._setting("shortcut_goes_to", "last") == "last":
@@ -325,6 +334,13 @@ class LinkSender:
target = self._cycle_target()
self.set_redirecting(target is not None, peer=target)
+ def models_toward(self, peer: bytes) -> list:
+ """The active zone models that lead to `peer`, or none while edges are held."""
+ with self._lock:
+ if self.edges_held:
+ return []
+ return [model for target, model in self._models if target == peer]
+
def hold_shortcut(self, down: bool) -> None:
if not down:
self.set_redirecting(False)
@@ -505,12 +521,37 @@ class LinkSender:
owner = self._owner
if owner is None:
return False
+ if name in ("hangul", "hanja"):
+ # A tap goes whole on the press; only the release of a press that went is swallowed.
+ held = vk if vk is not None else name
+ if not down:
+ if held in self._input_method_tap_releases:
+ self._input_method_tap_releases.discard(held)
+ return True
+ return False
+ if not owner.away:
+ return False
+ if not self._live():
+ self._lost()
+ return False
+ if vk is not None:
+ entry = ignored.key(vk)
+ kept = self._ignore_gate.keeps(entry, True)
+ self._ignore_gate.keeps(entry, False)
+ if kept:
+ return False
+ if not self._input_tap(name):
+ return False
+ self._input_method_tap_releases.add(held)
+ return True
held = vk if vk is not None else name
if down:
data = self._keys_down.get(held) or self._key_data(name, us)
self._keys_down[held] = data
else:
data = self._keys_down.pop(held, None) or self._key_data(name, us)
+ if self._shake_detector is not None:
+ self._shake_detector.held(self._clock(), bool(self._keys_down or self._buttons_held))
if owner.away:
if not self._live():
self._lost()
@@ -634,6 +675,8 @@ class LinkSender:
self._buttons_held.add(name)
else:
self._buttons_held.discard(name)
+ if self._shake_detector is not None:
+ self._shake_detector.held(self._clock(), bool(self._buttons_held or self._keys_down))
owner = self._owner
if owner is None:
return False
@@ -657,6 +700,8 @@ class LinkSender:
if not self._live():
self._lost()
return False
+ if self._shake_detector is not None:
+ self._shake_detector.scroll(self._clock())
self._send_pending_windows_key()
return self._input(protocol.scroll_msg(dy, -dx, "line"))
@@ -680,10 +725,48 @@ class LinkSender:
if not self._live():
self._lost()
return
+ now = self._clock()
+ detector = self._shake_detector
+ if detector is not None and detector.motion(now, dx, dy):
+ peer = self.owner
+ self._shake_home_pending = True
+ self._home_hold = HomeHold()
+ self._home_hold.motion(now)
+ detector.disarm()
+ self.set_redirecting(False)
+ if self._shake_callback is not None and peer is not None:
+ self._call(self._shake_callback, peer)
+ return
self._input({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": int(dx), "dy": int(dy)}})
return
+ now = self._clock()
+ if self._home_hold is not None:
+ if self._home_hold.blocks(now):
+ self._home_hold.motion(now)
+ return
+ self._home_hold = None
self._press_edge(int(dx), int(dy))
+ def set_shake(self, enabled: bool, stroke: float, on_shake=None) -> None:
+ """Configure the local raw-motion return gesture; disabled until the app opts in."""
+ if enabled and self._shake_detector is not None:
+ self._shake_detector.set_stroke(stroke)
+ self._shake_callback = on_shake
+ return
+ self._shake_detector = ShakeDetector(stroke) if enabled else None
+ self._shake_callback = on_shake
+ self._home_hold = None
+ self._shake_home_pending = False
+ if self._shake_detector is not None and self.redirecting:
+ now = self._clock()
+ self._shake_detector.arm(now)
+ self._shake_detector.held(now, bool(self._buttons_held or self._keys_down))
+
+ def _consume_shake_home(self) -> bool:
+ """One-shot reason flag used by Wayland's capture release after a shake."""
+ pending, self._shake_home_pending = self._shake_home_pending, False
+ return pending
+
def _input(self, message: dict) -> bool:
"""Gives the owner one input event and carries out what it answers; True when this PC
must not act on the event."""
@@ -693,6 +776,19 @@ class LinkSender:
self._report(actions)
return not any(action is owner_module.LOCAL for action in actions)
+ def _input_tap(self, name: str) -> bool:
+ """Queue both halves under the owner lock, so a switch cannot release a half-tap as held."""
+ actions = []
+ with self._lock:
+ owner = self._owner
+ if owner is None:
+ return False
+ for message in keytable.tap_messages(name, True):
+ actions.extend(owner.input(message))
+ self._queue(actions)
+ self._report(actions)
+ return not any(action is owner_module.LOCAL for action in actions)
+
def _press_edge(self, dx, dy) -> None:
"""One raw movement while input is still this PC's. Feeds the zone models, the same ones
the responder uses for a driven pointer, so the border behaves identically whichever side
@@ -705,7 +801,8 @@ class LinkSender:
It runs while a peer is driving this PC too. Every move a peer makes here carries
INJECTED_MARK and never arrives, so what does is this PC's own mouse, and its push out
means the pointer is going on with this mouse behind it."""
- if not self._models or self.edges_held or self._owner is None:
+ if ((self._home_hold is not None and self._home_hold.blocks(self._clock()))
+ or not self._models or self.edges_held or self._owner is None):
return
if self._buttons_held and self._setting("block_while_dragging", True) and self._still_dragging():
# A drag that reaches the edge is dragging, not leaving: the push so far is dropped,
@@ -802,7 +899,7 @@ class LinkSender:
return self.go(peer) if peer is not None and peer != self.owner else False
peer = peer or self.shortcut_target()
if peer is None:
- self._alert(f"Cannot switch — {self.status}")
+ self._alert(tr("Cannot switch — {status}").format(status=self.status))
return False
return self._go(peer)
if not self.redirecting:
@@ -827,8 +924,17 @@ class LinkSender:
if owner is None:
return False
if not self.input_held():
- self._alert("Cannot switch — on this desktop input goes to another machine only by pushing the pointer "
- "through an edge")
+ if self.push_out is not None:
+ if self.push_out(
+ peer,
+ on_captured=lambda: self._go(peer, edge, offset, display, side),
+ on_failed=lambda: self._alert(tr(
+ "Cannot switch — the desktop did not let Beamer send input to {name}"
+ ).format(name=self._name(peer))),
+ ):
+ return True
+ self._alert(tr("Cannot switch — on this desktop input goes to another machine only by pushing the pointer "
+ "through an edge"))
return False
if self.driven():
# A machine that is driven does not drive (section 4): its driver goes home first, then
@@ -851,7 +957,7 @@ class LinkSender:
def _after_let_go(self, peer, edge, offset, display=None, side=None) -> None:
if not self.send_peer_home() and self.driven():
- self._alert(f"Cannot switch — {self._name(peer)} could not be reached while this PC is being driven")
+ self._alert(tr("Cannot switch — {name} could not be reached while this PC is being driven").format(name=self._name(peer)))
return
deadline = self._clock() + LET_GO_WAIT_SECONDS
while self.driven() and self._clock() < deadline and not self._stop_event.is_set():
@@ -1281,9 +1387,11 @@ class LinkSender:
other = peerlist.label_for(self._entries, peer_id=protocol.id_text(moved.other))
reason = peerlist.refusal_text(moved.why, self._name(moved.left), other)
if moved.why == "taken_over":
- reason = f"{other or 'Another machine'} took over {self._name(moved.left)}"
+ reason = tr("{other} took over {name}").format(
+ other=other or tr("Another machine"), name=self._name(moved.left))
if reason is None:
- reason = HOME_REASONS.get(moved.why, "{name} returned the input").format(name=self._name(moved.left))
+ reason = tr(HOME_REASONS.get(moved.why, N_("{name} returned the input"))).format(
+ name=self._name(moved.left))
self._alert(reason)
def _land(self, edge: str, offset: float, display=None, side=None) -> None:
@@ -1314,6 +1422,14 @@ class LinkSender:
if value == self._reported_redirecting:
return
self._reported_redirecting = value
+ detector = self._shake_detector
+ if detector is not None:
+ if value:
+ now = self._clock()
+ detector.arm(now)
+ detector.held(now, bool(self._buttons_held or self._keys_down))
+ else:
+ detector.disarm()
if self._redirect_callback is not None:
self._call(self._redirect_callback, value)
@@ -1321,17 +1437,17 @@ class LinkSender:
name = self._name(action.peer)
if action.why == "unreachable" and not self.links.up(action.peer):
if not self.wake(action.peer):
- self._alert(f"Cannot switch — {self._status_of(action.peer)}")
+ self._alert(tr("Cannot switch — {status}").format(status=self._status_of(action.peer)))
return
if action.why == "unreachable" and self._accepts.get(action.peer) is False:
- self._alert("Cannot switch — " + HOME_REASONS["not_allowed"].format(name=name))
+ self._alert(tr("Cannot switch — {reason}").format(reason=tr(HOME_REASONS["not_allowed"]).format(name=name)))
return
other = ""
if isinstance(action.other, bytes) and action.other != self._own_id:
other = peerlist.label_for(self._entries, peer_id=protocol.id_text(action.other))
reason = peerlist.refusal_text(action.why, name, other)
if reason is None:
- reason = f"Cannot switch — {name} could not be reached"
+ reason = tr("Cannot switch — {name} could not be reached").format(name=name)
self._alert(reason)
def _learn_hardware(self, peer: bytes) -> None:
@@ -1376,20 +1492,20 @@ class LinkSender:
self._wake_sender(address, entry.get("host") or None)
except (OSError, ValueError) as exc:
LOGGER.warning("wake-on-LAN packet not sent: %s", exc)
- self._alert("Could not send the wake-up packet")
+ self._alert(tr("Could not send the wake-up packet"))
return
LOGGER.info("sent wake-on-LAN to %s", name)
- self._alert(WAKING_STATUS.format(name=name))
+ self._alert(tr(WAKING_STATUS).format(name=name))
while not self._stop_event.wait(WAKE_POLL_SECONDS):
if self.links.up(peer):
LOGGER.info("%s woke and connected", name)
- self._alert(f"{name} is awake — switch again to send input")
+ self._alert(tr("{name} is awake — switch again to send input").format(name=name))
return
if self._clock() - started >= wol.WAKE_WINDOW_SECONDS:
break
if not self._stop_event.is_set():
LOGGER.warning("%s did not answer within %.0fs of the wake-on-LAN packet", name, wol.WAKE_WINDOW_SECONDS)
- self._alert(NOT_WOKEN_STATUS.format(name=name))
+ self._alert(tr(NOT_WOKEN_STATUS).format(name=name))
finally:
with self._wake_lock:
self._waking.discard(peer)
@@ -1445,7 +1561,7 @@ class LinkSender:
def _name(self, peer) -> str:
"""What this PC's statuses and alerts call a machine: its label, so two of one name are told apart."""
- return peerlist.label_for(self._entries, peer_id=protocol.id_text(peer)) or "The other machine"
+ return peerlist.label_for(self._entries, peer_id=protocol.id_text(peer)) or tr("The other machine")
def _alert(self, message: str) -> None:
if self.on_alert is None:
diff --git a/win_app/shake_stroke.py b/win_app/shake_stroke.py
new file mode 100644
index 0000000..e8fcfe9
--- /dev/null
+++ b/win_app/shake_stroke.py
@@ -0,0 +1,16 @@
+"""The detector's first stroke length for each PC capture back end."""
+
+from core.shake import STROKE_WINDOWS, STROKE_WAYLAND, STROKE_X11, stroke_at_sensitivity
+
+
+def shake_stroke(backend, sensitivity=100):
+ name = getattr(backend, "__name__", backend)
+ lengths = {
+ "capture_win": STROKE_WINDOWS,
+ "capture_x11": STROKE_X11,
+ "capture_portal": STROKE_WAYLAND,
+ }
+ try:
+ return stroke_at_sensitivity(lengths[name], sensitivity)
+ except KeyError as exc:
+ raise ValueError(f"unknown capture back end: {name}") from exc
diff --git a/win_app/tests/portal_fakes.py b/win_app/tests/portal_fakes.py
index 0dc8407..67e3b05 100644
--- a/win_app/tests/portal_fakes.py
+++ b/win_app/tests/portal_fakes.py
@@ -23,7 +23,7 @@ class FakeBus:
Response, or a callable taking the body and returning one; `returns[method]` is the body a
plain call returns. Every call is recorded in `calls` as (interface, method, body)."""
- REQUESTS = {"CreateSession", "SelectDevices", "Start", "GetZones", "SetPointerBarriers"}
+ REQUESTS = {"CreateSession", "SelectDevices", "Start", "GetZones", "SetPointerBarriers", "BindShortcuts"}
def __init__(self, versions=None) -> None:
self.unique_name = ":1.42"
@@ -32,6 +32,7 @@ class FakeBus:
self.answers = {}
self.returns = {}
self.calls = []
+ self.signatures = []
self.closed = False
self.aborted = False
self._signals = []
@@ -43,6 +44,7 @@ class FakeBus:
raise portal.PortalError("the connection is closed")
with self._lock:
self.calls.append((interface, method, body))
+ self.signatures.append((method, signature))
if method in self.failures:
raise self.failures[method]
if interface == portal.PROPERTIES and method == "Get":
diff --git a/win_app/tests/test_app_config.py b/win_app/tests/test_app_config.py
index 60dd052..1728162 100644
--- a/win_app/tests/test_app_config.py
+++ b/win_app/tests/test_app_config.py
@@ -31,6 +31,18 @@ class EdgeGlowConfigTests(unittest.TestCase):
config_from_dict({**BASE, "edge_glow": "yes"})
+class HomeShortcutConfigTests(unittest.TestCase):
+ def test_off_by_default_since_turning_it_on_asks_the_desktop_and_round_trips(self):
+ self.assertFalse(config_from_dict(dict(BASE)).home_shortcut)
+ config = config_from_dict({**BASE, "home_shortcut": True})
+ self.assertTrue(config.home_shortcut)
+ self.assertIs(config_to_dict(config)["home_shortcut"], True)
+
+ def test_rejects_a_non_boolean(self):
+ with self.assertRaises(ConfigError):
+ config_from_dict({**BASE, "home_shortcut": "yes"})
+
+
class OverlappingZonesTests(unittest.TestCase):
def _legacy_contacts(self):
own, a, b = (protocol.id_text(peer) for peer in (h.HERE, h.B, h.C))
diff --git a/win_app/tests/test_capture_portal.py b/win_app/tests/test_capture_portal.py
index 2456133..d23fd58 100644
--- a/win_app/tests/test_capture_portal.py
+++ b/win_app/tests/test_capture_portal.py
@@ -24,6 +24,13 @@ ONE = [Rect(0, 0, 1920, 1080)]
SESSION = "/org/freedesktop/portal/desktop/session/1_42/beamer2"
+class CapturePortalNamesTests(unittest.TestCase):
+ def test_input_method_names_share_the_evdev_mapping_and_cannot_be_triggers(self):
+ self.assertEqual((capture_portal.VK_TO_NAME[122], capture_portal.VK_TO_NAME[123]), ("hangul", "hanja"))
+ self.assertEqual((capture_portal.VK_TITLES[122], capture_portal.VK_TITLES[123]), ("Han/Yeong", "Hanja"))
+ self.assertTrue({122, 123} <= capture_portal.NOT_TRIGGER_VKS)
+
+
class BarrierTest(unittest.TestCase):
def test_a_scoped_wayland_zone_does_not_create_barriers_on_another_display(self):
screens = [Rect(0, 0, 1920, 1080), Rect(1920, 0, 1920, 1080)]
@@ -323,7 +330,7 @@ class Harness:
`push_to_cross` pushes, as the zone model does. `gnome` makes the portal GNOME's, on the zone
the laptop reports."""
- def __init__(self, version=1, models=None, push_to_cross=2, tokens=None, gnome=False, kde=False):
+ def __init__(self, version=1, models=None, push_to_cross=2, tokens=None, gnome=False, kde=False, clock=time.monotonic):
if gnome:
self.bus = GnomeBus(LAPTOP, versions={capture_portal.INTERFACE: version})
else:
@@ -340,7 +347,7 @@ class Harness:
self.push_to_cross = push_to_cross
self.tokens = tokens or MemoryTokens()
self.hooks = capture_portal.Hooks(self._key, self._mouse, self._motion, connect=lambda: self.bus,
- ei=lambda fd: self.ei, tokens=self.tokens)
+ ei=lambda fd: self.ei, tokens=self.tokens, clock=clock)
self.hooks.grab_while(lambda: self.away)
self.hooks.barriers_from(lambda: self.models)
self.hooks.on_home = lambda: self.homes.append(True) or setattr(self, "away", False)
@@ -485,6 +492,120 @@ class HooksTest(unittest.TestCase):
self.assertEqual(h.bus.made("SetPointerBarriers")[0][3], 7)
self.assertEqual(desktop_portal.monitors(), ONE)
+ def test_the_session_says_once_that_it_is_ready(self):
+ with self.assertLogs(capture_portal.LOGGER, level="INFO") as said:
+ h = self.make()
+ h.start()
+ h.hooks._key = None
+ h.hooks._place_barriers(h.hooks._session)
+ ready = [line for line in said.output if "Input capture is ready" in line]
+ self.assertEqual(ready, ["INFO:capture_portal:Input capture is ready: 1 of 1 edge barriers placed"])
+
+ def test_push_through_moves_to_a_barrier_then_steps_outward_and_captures_once(self):
+ h = self.make()
+ h.start()
+ captured, failed, moves = [], [], []
+ with mock.patch.object(capture_portal, "inject_portal", create=True) as injection:
+ injection.push.side_effect = lambda x, y, deltas, wanted: (
+ moves.append(("to", (x, y))) if wanted() else None,
+ moves.extend(("by", delta) for delta in deltas) if wanted() else None,
+ )
+ self.assertTrue(h.hooks.push_through(h.models, lambda: captured.append(True), lambda: failed.append(True)))
+ self.assertEqual(moves, [("to", (1916, 539))] + [("by", (24, 0))] * 6)
+ h.activate(x=1920.0, y=539.0)
+ self.assertEqual((captured, failed), ([True], []))
+
+ def test_a_queued_push_is_discarded_after_its_capture_deadline(self):
+ clock = Clock()
+ h = self.make(clock=clock)
+ h.start()
+ queued, moves, failed = [], [], []
+ with mock.patch.object(capture_portal, "inject_portal", create=True) as injection:
+ injection.push.side_effect = lambda x, y, deltas, wanted: queued.append((x, y, deltas, wanted))
+ self.assertTrue(h.hooks.push_through(h.models, lambda: None, lambda: failed.append(True)))
+ clock.now += capture_portal.PUSH_SECONDS + 0.01
+ h.hooks._tick()
+ x, y, deltas, wanted = queued[0]
+ if wanted():
+ moves.append(("to", (x, y)))
+ moves.extend(("by", delta) for delta in deltas)
+ self.assertEqual(failed, [True])
+ self.assertEqual(moves, [])
+
+ def test_a_queued_push_run_after_its_deadline_does_nothing_before_the_tick(self):
+ clock = Clock()
+ h = self.make(clock=clock)
+ h.start()
+ queued = []
+ with mock.patch.object(capture_portal, "inject_portal", create=True) as injection:
+ injection.push.side_effect = lambda x, y, deltas, wanted: queued.append(wanted)
+ self.assertTrue(h.hooks.push_through(h.models, lambda: None, lambda: None))
+ self.assertTrue(queued[0]())
+ clock.now += capture_portal.PUSH_SECONDS + 0.01
+ self.assertFalse(queued[0]())
+
+ def test_push_through_ignores_an_activation_at_another_wall(self):
+ h = self.make()
+ h.start()
+ captured, failed = [], []
+ with mock.patch.object(capture_portal, "inject_portal", create=True):
+ self.assertTrue(h.hooks.push_through(h.models, lambda: captured.append(True), lambda: failed.append(True)))
+ h.hooks._activated({"activation_id": 9, "cursor_position": (0, 500), "barrier_id": 2})
+ self.assertEqual((captured, failed), ([], []))
+
+ def test_push_through_deadline_calls_failure_from_tick_once(self):
+ clock = Clock()
+ h = self.make(clock=clock)
+ h.start()
+ failed = []
+ with mock.patch.object(capture_portal, "inject_portal", create=True):
+ self.assertTrue(h.hooks.push_through(h.models, lambda: None, lambda: failed.append(True)))
+ clock.now += capture_portal.PUSH_SECONDS + 0.01
+ h.hooks._tick()
+ h.hooks._tick()
+ self.assertEqual(failed, [True])
+
+ def test_push_through_refuses_when_there_is_no_session_or_no_barrier(self):
+ h = self.make()
+ with mock.patch.object(capture_portal, "inject_portal", create=True) as injection:
+ self.assertFalse(h.hooks.push_through([], lambda: None, lambda: None))
+ h.start()
+ self.assertFalse(h.hooks.push_through([], lambda: None, lambda: None))
+ injection.push.assert_not_called()
+
+ def test_push_through_refuses_while_input_is_captured(self):
+ h = self.make()
+ h.start()
+ h.hooks._activation = 3
+ with mock.patch.object(capture_portal, "inject_portal", create=True) as injection:
+ self.assertFalse(h.hooks.push_through(h.models, lambda: None, lambda: None))
+ injection.push.assert_not_called()
+
+ def test_push_through_refuses_a_second_request_while_one_is_pending(self):
+ h = self.make()
+ h.start()
+ with mock.patch.object(capture_portal, "inject_portal", create=True) as injection:
+ self.assertTrue(h.hooks.push_through(h.models, lambda: None, lambda: None))
+ self.assertFalse(h.hooks.push_through(h.models, lambda: None, lambda: None))
+ injection.push.assert_called_once()
+ x, y, moves, _wanted = injection.push.call_args.args
+ self.assertEqual((x, y), (1916, 539))
+ self.assertEqual(moves, [(24, 0)] * capture_portal.PUSH_STEPS)
+
+ def test_kde_push_starts_inside_the_last_pixel_column_barrier(self):
+ with mock.patch.dict(os.environ, {"XDG_CURRENT_DESKTOP": "KDE"}):
+ h = self.make(kde=True)
+ h.start()
+ moves = []
+ with mock.patch.object(capture_portal, "inject_portal", create=True) as injection:
+ injection.push.side_effect = lambda x, y, deltas, wanted: (
+ moves.append(("to", (x, y))) if wanted() else None,
+ moves.extend(("by", delta) for delta in deltas) if wanted() else None,
+ )
+ self.assertTrue(h.hooks.push_through(h.models, lambda: None, lambda: None))
+ self.assertEqual(h.hooks._selected[0], ("right", (1920, 0, 1920, 1079)))
+ self.assertEqual(moves[0], ("to", (1916, 539)))
+
def test_a_push_crosses_input_goes_away_and_comes_home_where_the_sender_lands_it(self):
h = self.make()
h.start()
diff --git a/win_app/tests/test_capture_win.py b/win_app/tests/test_capture_win.py
index ec7a9b7..7a25a01 100644
--- a/win_app/tests/test_capture_win.py
+++ b/win_app/tests/test_capture_win.py
@@ -27,6 +27,16 @@ class HookPoint(ctypes.Structure):
class NameTests(unittest.TestCase):
+ def test_input_method_keys_are_captured_and_not_offered_as_triggers(self):
+ state = KeyboardState()
+ self.assertEqual(key_name(0x15, 0, state, names_only), "hangul")
+ self.assertEqual(key_name(0x19, 0, state, names_only), "hanja")
+ self.assertTrue({0x15, 0x19} <= capture_win.NOT_TRIGGER_VKS)
+
+ def test_every_named_key_but_the_undifferentiated_modifiers_has_a_title(self):
+ # 1.4.3's loader, kept as a fixture, titles every named key but these three.
+ self.assertEqual(set(capture_win.VK_TO_NAME) - set(capture_win.VK_TITLES), {0x10, 0x11, 0x12})
+
def test_browser_search_and_app_launch_keys_are_captured(self):
state = KeyboardState()
self.assertEqual(key_name(0xAA, 0, state, names_only), "browser_search")
diff --git a/win_app/tests/test_capture_x11.py b/win_app/tests/test_capture_x11.py
index 0386811..d8d1b88 100644
--- a/win_app/tests/test_capture_x11.py
+++ b/win_app/tests/test_capture_x11.py
@@ -234,6 +234,10 @@ class NamesTest(unittest.TestCase):
self.assertEqual(capture_x11.VK_TITLES[125], "Left Super")
self.assertNotIn(163, set(capture_x11.VK_TO_NAME) - capture_x11.NOT_TRIGGER_VKS) # media keys are not triggers
self.assertIn(57, capture_x11.UNRECORDABLE_TRIGGER_VKS)
+ self.assertEqual((capture_x11.VK_TO_NAME[122], capture_x11.VK_TO_NAME[123]), ("hangul", "hanja"))
+ self.assertEqual((capture_x11.VK_TITLES[122], capture_x11.VK_TITLES[123]), ("Han/Yeong", "Hanja"))
+ self.assertTrue({122, 123} <= capture_x11.NOT_TRIGGER_VKS)
+ self.assertFalse({"hangul", "hanja"} & capture_x11.MODIFIER_NAMES)
def test_hook_vk_is_the_keycode_less_eight(self):
self.assertEqual(capture_x11.hook_vk(0xFFE4, 105), 97)
diff --git a/win_app/tests/test_crossing_ledger.py b/win_app/tests/test_crossing_ledger.py
index 0549a65..953851d 100644
--- a/win_app/tests/test_crossing_ledger.py
+++ b/win_app/tests/test_crossing_ledger.py
@@ -4,12 +4,13 @@ import copy
import unittest
from itertools import combinations
-from PySide6.QtCore import QPoint, Qt
-from PySide6.QtGui import QAccessible, QImage
+from PySide6.QtCore import QPoint, QRectF, Qt
+from PySide6.QtGui import QAccessible, QImage, QPainter
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QWidget
import app_config
+import diagram
from core import ways
import test_crossing_page_parity as parity
@@ -38,6 +39,20 @@ def band_point(canvas, third, side="right"):
return QPoint(round(rect.left() + rect.width() * fraction), round(rect.top() if side == "top" else rect.bottom()))
+def stroke_insets(image, left, top, right, bottom, reference):
+ """Device-pixel insets of every pixel that differs from the colour at `reference`, measured inside
+ the box (left, top, right, bottom), inclusive."""
+ base = image.pixelColor(*reference)
+ xs, ys = [], []
+ for y in range(top, bottom + 1):
+ for x in range(left, right + 1):
+ pixel = image.pixelColor(x, y)
+ if abs(pixel.red() - base.red()) + abs(pixel.green() - base.green()) + abs(pixel.blue() - base.blue()) > 60:
+ xs.append(x)
+ ys.append(y)
+ return min(xs) - left, min(ys) - top, right - max(xs), bottom - max(ys)
+
+
def paint(canvas):
image = QImage(canvas.size(), QImage.Format.Format_ARGB32)
image.fill(Qt.GlobalColor.transparent)
@@ -109,6 +124,42 @@ class CrossingLedgerTests(unittest.TestCase):
self._open_window()
self.assertEqual(row_of(self.window, peer).corner_grid.buttons[corner].isChecked(), on)
+ def test_corner_brackets_sit_centred_in_whole_squares(self):
+ # A style sheet's min-height replaced the minimum setFixedSize set, so the grid squashed
+ # each square to 28 x 19 and the bracket drawn for 28 x 28 was clipped off-centre.
+ self.window.resize(1280, 1392)
+ self.window.show()
+ QApplication.processEvents()
+ row = row_of(self.window, self.peers[0]["id"])
+ for kind, enabled in (("free", True), ("on", True), ("held", False), ("unavailable", False)):
+ for corner, button in row.corner_grid.buttons.items():
+ with self.subTest(kind=kind, corner=corner):
+ button.set_state(kind, "", "", enabled)
+ self.assertEqual(button.size().toTuple(), (28, 28))
+ image = button.grab().toImage()
+ w, h = image.width(), image.height()
+ insets = stroke_insets(image, 3, 3, w - 4, h - 4, (w // 2, h // 2))
+ self.assertLessEqual(max(insets) - min(insets), 1, insets)
+ self.assertGreaterEqual(min(insets), 3, insets)
+
+ def test_map_corner_pad_bracket_sits_centred_in_its_pad(self):
+ # Drawn at 4x so a half-pixel offset shows as two device pixels.
+ scale = 4
+ for corner in ways.CORNERS:
+ with self.subTest(corner=corner):
+ image = QImage(80 * scale, 80 * scale, QImage.Format.Format_ARGB32)
+ image.fill(Qt.GlobalColor.black)
+ painter = QPainter(image)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ painter.scale(scale, scale)
+ diagram.AtlasCanvas._paint_corner_pad(painter, QRectF(30, 30, 20, 20), corner, 1.0)
+ painter.end()
+ x = 30 if corner.endswith("left") else 50
+ y = 30 if corner.startswith("top") else 50
+ insets = stroke_insets(image, (x - 6) * scale, (y - 6) * scale, (x + 6) * scale - 1, (y + 6) * scale - 1,
+ ((x + 5) * scale + 2, (y + 5) * scale + 2))
+ self.assertLessEqual(max(insets) - min(insets), 1, insets)
+
def test_two_corners_at_once_a_held_one_and_an_unavailable_one_refuse_without_a_write(self):
first, second = [entry["id"] for entry in self.peers]
rows = self.window.crossing_ledger.rows
diff --git a/win_app/tests/test_crossing_matrix.py b/win_app/tests/test_crossing_matrix.py
index 22897f7..1743d3b 100644
--- a/win_app/tests/test_crossing_matrix.py
+++ b/win_app/tests/test_crossing_matrix.py
@@ -285,6 +285,8 @@ class ArrangementHeldByBothTests(unittest.TestCase):
server=types.SimpleNamespace(peers_changed=lambda: self.refreshed.append("server"),
rearm=lambda: self.refreshed.append("rearmed")),
_tell=lambda peer: self.refreshed.append("answered"),
+ _configure_shake=lambda settings=None: self.refreshed.append("shake"),
+ _carry_desk=lambda outcome, source=None: None,
_live=lambda peer: True,
_gone=lambda peer: False,
_design_peer_caps=lambda: {},
@@ -302,6 +304,7 @@ class ArrangementHeldByBothTests(unittest.TestCase):
self.page._carry_crossing = types.MethodType(kvm_bridge_win.WindowsApplication._carry_crossing, self.page)
self.page._reflect_ways = lambda: None
self.page._reflect_look = lambda: None
+ self.page._refresh_tray_profiles = lambda settings: None
def arrive(self, edge, stamp, by=None):
kvm_bridge_win.WindowsApplication._on_arrangement(self.page, self.peer, edge, stamp, by or self.peer)
@@ -312,7 +315,7 @@ class ArrangementHeldByBothTests(unittest.TestCase):
def test_a_newer_arrangement_is_applied_as_this_pcs_opposite_edge(self):
self.arrive("top", 200)
self.assertEqual(self.side(), "bottom")
- self.assertEqual(self.refreshed, ["updated", "sender", "server", "rearmed", "answered"])
+ self.assertEqual(self.refreshed, ["updated", "sender", "server", "rearmed", "shake", "answered"])
def test_an_older_arrangement_is_ignored(self):
self.arrive("top", 50)
diff --git a/win_app/tests/test_crossing_page_parity.py b/win_app/tests/test_crossing_page_parity.py
index b9999ed..6bcd28f 100644
--- a/win_app/tests/test_crossing_page_parity.py
+++ b/win_app/tests/test_crossing_page_parity.py
@@ -48,7 +48,10 @@ class CrossingPageParityTests(unittest.TestCase):
self.app = QApplication.instance() or QApplication([])
theme.init_fonts()
self.app.setFont(theme.font(theme.TYPE["body"]))
- self.patches = []
+ # The PC page as Windows and X11 draw it, whatever session runs the suite: Wayland hides the
+ # pointer module.
+ self.patches = [patch.object(kvm.platform_parts, "WAYLAND", False)]
+ self.patches[0].start()
for name, value in (("installed_exe", lambda: Path("Beamer.exe")),
("is_enabled", lambda: False),
("can_run_for_current_user", lambda: False)):
diff --git a/win_app/tests/test_effect_fires.py b/win_app/tests/test_effect_fires.py
index d84d4e4..e26f152 100644
--- a/win_app/tests/test_effect_fires.py
+++ b/win_app/tests/test_effect_fires.py
@@ -54,6 +54,12 @@ class PressureRoutingTest(unittest.TestCase):
edge) both end up on the same bridge.pressure signal and the same _on_pressure -- nothing
here tells the two apart, which is why one set of tests covers both directions."""
+ def setUp(self):
+ # X11 and Windows, whatever session runs the suite; the Wayland tests set it themselves.
+ wayland = mock.patch.object(kvm_bridge_win.platform_parts, "WAYLAND", False)
+ wayland.start()
+ self.addCleanup(wayland.stop)
+
def test_an_edge_push_reaches_the_effects_overlay_when_the_style_is_an_effect(self):
owner = _owner(glow_style="rupture")
overlay = mock.Mock()
@@ -203,6 +209,10 @@ class ArrivalRoutingTest(unittest.TestCase):
def setUp(self):
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
self.app = QApplication.instance() or QApplication([])
+ # X11 and Windows, whatever session runs the suite.
+ wayland = mock.patch.object(kvm_bridge_win.platform_parts, "WAYLAND", False)
+ wayland.start()
+ self.addCleanup(wayland.stop)
def test_an_edge_crossing_arrival_reaches_the_effects_overlay_when_wanted(self):
owner = _owner(glow_style="rupture")
diff --git a/win_app/tests/test_gameinput_foreground.py b/win_app/tests/test_gameinput_foreground.py
index edb79bd..524211a 100644
--- a/win_app/tests/test_gameinput_foreground.py
+++ b/win_app/tests/test_gameinput_foreground.py
@@ -118,6 +118,39 @@ class GameInputForegroundTests(unittest.TestCase):
self.assertEqual(len(self.restarts), 1)
self.assertEqual(self.user32.set_calls, [(1818, 2159), (1818, 2159)])
+ def test_placement_callback_waits_for_the_gameinput_retry(self):
+ self.user32.foreground = GAMEINPUT
+ self.user32.set_results = [0]
+ placed = mock.Mock()
+
+ desktop_win.set_cursor_position_with_callback(1818, 2159, placed)
+
+ placed.assert_called_once_with()
+ self.assertEqual(self.user32.set_calls, [(1818, 2159), (1818, 2159)])
+
+ def test_pending_arrival_does_not_warp_after_its_visit_ends(self):
+ self.user32.set_results = [0]
+ current = [True]
+ placed = mock.Mock()
+ with mock.patch.object(input_injector, "release_gameinput_foreground", return_value=True) as retry:
+ desktop_win.set_cursor_position_with_callback(
+ 1818, 2159, placed, place_if_current=lambda action: action() if current[0] else None)
+
+ placed.assert_not_called()
+ current[0] = False
+ retry.call_args.kwargs["after"]()
+
+ self.assertEqual(self.user32.set_calls, [(1818, 2159)])
+ placed.assert_not_called()
+
+ def test_failed_placement_does_not_claim_arrival_completed(self):
+ self.user32.foreground = EXPLORER
+ self.user32.set_results = [0]
+ placed = mock.Mock()
+ with self.assertLogs(desktop_win.LOGGER, "WARNING"):
+ desktop_win.set_cursor_position_with_callback(10, 20, placed)
+ placed.assert_not_called()
+
def test_a_refusal_under_anything_else_is_logged_once_per_blocker(self):
self.user32.foreground = EXPLORER
self.user32.set_results = [0, 0, 0, 1, 0]
diff --git a/win_app/tests/test_global_shortcut_portal.py b/win_app/tests/test_global_shortcut_portal.py
new file mode 100644
index 0000000..e1ed74c
--- /dev/null
+++ b/win_app/tests/test_global_shortcut_portal.py
@@ -0,0 +1,124 @@
+import os
+import sys
+import time
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+import global_shortcut_portal
+import portal
+from portal_fakes import FakeBus, wait_for
+
+
+SESSION = "/org/freedesktop/portal/desktop/session/1_42/beamer2"
+INTERFACE = global_shortcut_portal.INTERFACE
+
+
+class GlobalShortcutPortalTest(unittest.TestCase):
+ def start_shortcut(self, bus, callback=None, stopping=lambda: False):
+ bus.answers.setdefault("CreateSession", (0, {"session_handle": SESSION}))
+ bus.answers.setdefault("BindShortcuts", (0, {"shortcuts": [
+ (global_shortcut_portal.SHORTCUT_ID, {"trigger_description": "Super+Shift+B"})
+ ]}))
+ shortcut = global_shortcut_portal.GlobalShortcut(lambda: bus, callback or (lambda: None), stopping)
+ shortcut.start()
+ return shortcut
+
+ def test_binds_with_the_portal_signature_description_and_preferred_trigger(self):
+ bus = FakeBus(versions={INTERFACE: 1})
+ shortcut = self.start_shortcut(bus)
+ self.addCleanup(shortcut.stop)
+ wait_for(lambda: shortcut.trigger_description is not None, what="the bound trigger")
+
+ call = next(item for item in bus.calls if item[1] == "BindShortcuts")
+ self.assertEqual(call[0], INTERFACE)
+ self.assertEqual(dict(bus.signatures)["BindShortcuts"], "oa(sa{sv})sa{sv}")
+ self.assertEqual(call[2][0], SESSION)
+ self.assertEqual(call[2][1][0][0], global_shortcut_portal.SHORTCUT_ID)
+ self.assertEqual(call[2][1][0][1]["description"], ("s", "Send input to another machine"))
+ self.assertEqual(call[2][1][0][1]["preferred_trigger"], ("s", global_shortcut_portal.PREFERRED_TRIGGER))
+ self.assertEqual(bus.made("BindShortcuts")[0], (SESSION, [(global_shortcut_portal.SHORTCUT_ID, {
+ "description": ("s", "Send input to another machine"),
+ "preferred_trigger": ("s", global_shortcut_portal.PREFERRED_TRIGGER),
+ })], "", {"handle_token": ("s", "beamer3")}))
+ self.assertTrue(shortcut.available)
+ self.assertEqual(shortcut.trigger_description, "Super+Shift+B")
+
+ def test_activated_requires_our_session_and_shortcut_id(self):
+ bus = FakeBus(versions={INTERFACE: 1})
+ fired = []
+ shortcut = self.start_shortcut(bus, lambda: fired.append(True))
+ self.addCleanup(shortcut.stop)
+ wait_for(lambda: shortcut.trigger_description is not None, what="the bound trigger")
+ bus.emit(portal.OBJECT_PATH, INTERFACE, "Activated", (SESSION, "other", 1, {}))
+ bus.emit(portal.OBJECT_PATH, INTERFACE, "Activated", (SESSION + "-other", global_shortcut_portal.SHORTCUT_ID, 1, {}))
+ time.sleep(0.03)
+ self.assertEqual(fired, [])
+
+ bus.emit(portal.OBJECT_PATH, INTERFACE, "Activated", (SESSION, global_shortcut_portal.SHORTCUT_ID, 1, {}))
+ wait_for(lambda: len(fired) == 1, what="the activation callback")
+
+ def test_shortcuts_changed_updates_the_trigger_description(self):
+ bus = FakeBus(versions={INTERFACE: 1})
+ shortcut = self.start_shortcut(bus)
+ self.addCleanup(shortcut.stop)
+ wait_for(lambda: shortcut.trigger_description is not None, what="the bound trigger")
+ bus.emit(portal.OBJECT_PATH, INTERFACE, "ShortcutsChanged", (SESSION, [
+ (global_shortcut_portal.SHORTCUT_ID, {"trigger_description": "Ctrl+Alt+K"})
+ ]))
+ wait_for(lambda: shortcut.trigger_description == "Ctrl+Alt+K", what="the changed trigger")
+
+ def test_missing_interface_is_unavailable_without_creating_a_session(self):
+ bus = FakeBus(versions={INTERFACE: 0})
+ shortcut = self.start_shortcut(bus)
+ shortcut._thread.join(timeout=1)
+
+ self.assertFalse(shortcut.available)
+ self.assertEqual(bus.made("CreateSession"), [])
+ shortcut.stop()
+
+ def test_refused_binding_sets_refused_without_escaping(self):
+ bus = FakeBus(versions={INTERFACE: 1})
+ bus.answers["BindShortcuts"] = (1, {})
+ shortcut = self.start_shortcut(bus)
+ shortcut._thread.join(timeout=1)
+
+ self.assertTrue(shortcut.available)
+ self.assertTrue(shortcut.refused)
+ self.assertIsNone(shortcut.trigger_description)
+ shortcut.stop()
+
+ def test_callback_exception_does_not_end_the_signal_loop(self):
+ bus = FakeBus(versions={INTERFACE: 1})
+ fired = []
+
+ def callback():
+ fired.append(True)
+ if len(fired) == 1:
+ raise RuntimeError("callback failure")
+
+ shortcut = self.start_shortcut(bus, callback)
+ self.addCleanup(shortcut.stop)
+ wait_for(lambda: shortcut.trigger_description is not None, what="the bound trigger")
+ with self.assertLogs(global_shortcut_portal.LOGGER, level="ERROR"):
+ bus.emit(portal.OBJECT_PATH, INTERFACE, "Activated", (SESSION, global_shortcut_portal.SHORTCUT_ID, 1, {}))
+ wait_for(lambda: len(fired) == 1, what="the first callback")
+ bus.emit(portal.OBJECT_PATH, INTERFACE, "Activated", (SESSION, global_shortcut_portal.SHORTCUT_ID, 2, {}))
+ wait_for(lambda: len(fired) == 2, what="the second callback")
+
+ def test_stop_closes_session_and_bus_and_ends_the_thread(self):
+ bus = FakeBus(versions={INTERFACE: 1})
+ shortcut = self.start_shortcut(bus)
+ wait_for(lambda: shortcut.trigger_description is not None, what="the bound trigger")
+ thread = shortcut._thread
+
+ shortcut.stop()
+
+ self.assertTrue(bus.closed)
+ self.assertIn((portal.SESSION, "Close", ()), [(iface, method, body) for iface, method, body in bus.calls])
+ self.assertFalse(thread.is_alive())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_home_shortcut_setting.py b/win_app/tests/test_home_shortcut_setting.py
new file mode 100644
index 0000000..415ceb1
--- /dev/null
+++ b/win_app/tests/test_home_shortcut_setting.py
@@ -0,0 +1,68 @@
+"""The Linux-on-Wayland switch that turns on the key combination sending input out from home: shown
+only on Wayland, saved, and starting or stopping the GlobalShortcuts session it drives."""
+import json
+import os
+from pathlib import Path
+import tempfile
+import unittest
+from unittest import mock
+
+try:
+ from PySide6.QtWidgets import QApplication
+ import kvm_bridge_win
+ import theme
+ from core.tests import responder_harness as harness
+except ImportError: # PySide6 is only in the Windows venv
+ kvm_bridge_win = None
+
+
+class RecordingShortcut:
+ def __init__(self):
+ self.calls = []
+
+ def start(self):
+ self.calls.append("start")
+
+ def stop(self):
+ self.calls.append("stop")
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class HomeShortcutSettingTests(unittest.TestCase):
+ def window(self, wayland):
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ QApplication.instance() or QApplication([])
+ theme.init_fonts()
+ folder = Path(tempfile.mkdtemp())
+ self.config = folder / "settings.json"
+ raw = {"host": "192.0.2.20", "port": harness.free_port(), "auth_token": "synthetic", "paired_with": "MacBook Pro",
+ "mac_host": "192.0.2.10", "mac_return_edge": "left"}
+ (folder / "config.json").write_text(json.dumps(raw))
+ patch = mock.patch.object(kvm_bridge_win.platform_parts, "WAYLAND", wayland)
+ patch.start()
+ self.addCleanup(patch.stop)
+ window = kvm_bridge_win.WindowsApplication(self.config)
+ self.addCleanup(window.deleteLater)
+ self.addCleanup(window.server.stop)
+ return window
+
+ def test_off_by_default_and_hidden_off_wayland(self):
+ window = self.window(wayland=False)
+ self.assertFalse(window._config.home_shortcut)
+ self.assertFalse(window.home_shortcut_switch.isChecked())
+ self.assertTrue(window.home_shortcut_switch.isHidden())
+ self.assertTrue(window.home_shortcut_note.isHidden())
+
+ def test_on_wayland_turning_it_on_saves_and_starts_the_session_and_off_stops_it(self):
+ window = self.window(wayland=True)
+ self.assertFalse(window.home_shortcut_switch.isHidden())
+ window.global_shortcut = RecordingShortcut()
+ window.home_shortcut_switch.setChecked(True)
+ self.assertTrue(json.loads(self.config.read_text())["home_shortcut"])
+ window.home_shortcut_switch.setChecked(False)
+ self.assertFalse(json.loads(self.config.read_text())["home_shortcut"])
+ self.assertEqual(window.global_shortcut.calls, ["start", "stop"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_i18n_pages.py b/win_app/tests/test_i18n_pages.py
new file mode 100644
index 0000000..b26ac0f
--- /dev/null
+++ b/win_app/tests/test_i18n_pages.py
@@ -0,0 +1,172 @@
+from __future__ import annotations
+
+import os
+import re
+import socket
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "win_app"))
+
+from PySide6.QtCore import QCoreApplication, QEvent, Qt
+from PySide6.QtGui import QAction
+from PySide6.QtWidgets import QApplication, QAbstractButton, QComboBox, QGroupBox, QLabel, QLineEdit, QWidget
+
+import pages_win
+import theme
+import app_config
+from core import i18n
+from core import protocol
+from core.tests import responder_harness
+from win_app.tests.test_settings_layout_acceptance import SyntheticWindow
+
+
+# Language names stay self-named; the remaining text is test data, brand, glyphs, or units.
+# Key names are recorded values, the synthetic row supplies its peer name, and the machine running
+# the test shows its own name as this machine's.
+ALLOWED_TEXT = {
+ "Beamer",
+ "English", "Italiano",
+ "Synthetic workstation",
+ socket.gethostname(), socket.gethostname().split(".", 1)[0],
+ "Right Ctrl",
+ "https://kalkmancode.co.uk/beamer",
+ "⌘", "⌥", "⌃", "⇧", "⌫", "↵", "⎋", "←", "→", "↑", "↓",
+ "px", "ms", "s", "Hz", "DIP",
+}
+
+
+class LocalisedPages(unittest.TestCase):
+ maxDiff = None
+
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+ theme.init_fonts()
+ cls.app.setFont(theme.font(theme.TYPE["body"]))
+
+ def setUp(self):
+ os.environ["BEAMER_LANGUAGE"] = "qps"
+ i18n.install("auto")
+ self.folder = tempfile.TemporaryDirectory(prefix="beamer-i18n-")
+ settings = app_config.migrate(None, machine_id=protocol.id_text(responder_harness.HERE))
+ settings.update(port=49152, appearance="dark", check_updates=False)
+ settings["peers"] = [
+ responder_harness.entry(responder_harness.B, "Synthetic workstation", side="right"),
+ ]
+ settings["zones"] = [{"peer": protocol.id_text(responder_harness.B), "kind": "part", "parts": ["middle"]}]
+ config_path = Path(self.folder.name) / "settings.json"
+ app_config.write_settings(config_path, settings)
+ self.window = SyntheticWindow(config_path)
+ self.window.full_screen_timer.stop()
+ self.window.refresh_timer.stop()
+ self.window.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)
+ self.window.resize(320, 900)
+ self.window.show()
+ self.settle()
+
+ def tearDown(self):
+ self.window.server.stop()
+ self.window.close()
+ self.window.deleteLater()
+ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
+ self.app.processEvents()
+ self.folder.cleanup()
+ os.environ.pop("BEAMER_LANGUAGE", None)
+ i18n.install("en")
+
+ def settle(self):
+ for _ in range(5):
+ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)
+ self.app.processEvents()
+
+ def visible_text(self):
+ values = []
+ for widget in self.window.findChildren(QLabel) + self.window.findChildren(QAbstractButton):
+ if widget.isVisible() and widget.text().strip():
+ values.append((widget, "text", widget.text().strip()))
+ for widget in self.window.findChildren(QGroupBox):
+ if widget.isVisible() and widget.title().strip():
+ values.append((widget, "title", widget.title().strip()))
+ for widget in self.window.findChildren(QLineEdit):
+ if widget.isVisible() and widget.placeholderText().strip():
+ values.append((widget, "placeholder", widget.placeholderText().strip()))
+ for combo in self.window.findChildren(QComboBox):
+ if combo.isVisible():
+ values.extend((combo, "choice", combo.itemText(index).strip()) for index in range(combo.count()))
+ for action in self.window.findChildren(QAction):
+ if action.isVisible() and action.text().strip():
+ values.append((action, "action", action.text().strip()))
+ for widget in self.window.findChildren(QWidget):
+ if not widget.isVisible():
+ continue
+ for field in ("toolTip", "statusTip", "whatsThis", "accessibleName", "accessibleDescription"):
+ text = getattr(widget, field)().strip()
+ if text:
+ values.append((widget, field, text))
+ return values
+
+ def test_every_settings_page_and_pairing_sheet_use_pseudo_localised_text(self):
+ missing = []
+ for key in self.window._page_indexes:
+ with self.subTest(page=key):
+ self.window._select_page(key)
+ self.settle()
+ if key == "overview":
+ self.window._toggle_pairing_sheet()
+ self.settle()
+ for widget, field, text in self.visible_text():
+ full_text = getattr(widget, "full_text", "")
+ if full_text and full_text.startswith("⟦") and full_text.endswith("⟧"):
+ continue
+ if text in ALLOWED_TEXT or not any(char.isalpha() for char in text):
+ continue
+ remainder = text
+ for data in sorted(ALLOWED_TEXT, key=len, reverse=True):
+ remainder = remainder.replace(data, "")
+ remainder = re.sub(r"\d+(?:\.\d+)?\s*(?:px|ms|s|Hz|pt|DIP)?", "", remainder)
+ if remainder.strip(" ,.;:·()") and not (remainder.startswith("⟦") and remainder.endswith("⟧")):
+ missing.append(f"{key}: {type(widget).__name__}.{field}: {text}")
+ self.assertEqual(missing, [])
+
+ def test_no_page_text_is_translated_twice(self):
+ # A tr() over text already translated is one pseudo wrap round another and nothing else; in a
+ # real language it would look the translation up as an English msgid. A translated value
+ # filling a translated template has text of the template's own beside it.
+ twice = []
+ for key in pages_win.KEYS:
+ self.window._select_page(key)
+ self.settle()
+ twice.extend(f"{key}: {text}" for _widget, _field, text in self.visible_text()
+ if re.fullmatch(r"⟦⟦[^⟦⟧]*⟧·*⟧", text))
+ self.assertEqual(twice, [])
+
+ def test_crossing_design_and_pairing_labels_fit_at_narrow_width(self):
+ for key in ("crossing", "design", "overview"):
+ self.window._select_page(key)
+ self.settle()
+ if key == "overview":
+ self.window._toggle_pairing_sheet()
+ self.settle()
+ labels = [label for label in self.window.findChildren(QLabel)
+ if label.isVisible() and label.text().strip()]
+ for label in labels:
+ with self.subTest(page=key, text=label.text()):
+ if label.wordWrap():
+ self.assertGreaterEqual(label.height(), label.heightForWidth(label.width()))
+ else:
+ self.assertLessEqual(label.fontMetrics().horizontalAdvance(label.text()), label.width())
+ for index, first in enumerate(labels):
+ for second in labels[index + 1:]:
+ if first.parentWidget() is second.parentWidget():
+ with self.subTest(page=key, first=first.text(), second=second.text()):
+ self.assertFalse(first.geometry().intersects(second.geometry()))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_idle_refresh.py b/win_app/tests/test_idle_refresh.py
index 32adc66..7bc54b7 100644
--- a/win_app/tests/test_idle_refresh.py
+++ b/win_app/tests/test_idle_refresh.py
@@ -29,6 +29,10 @@ class IdleRefreshTest(unittest.TestCase):
theme.init_fonts()
def setUp(self):
+ # British spelling, whatever region the machine running the suite is set to.
+ us_region = patch("core.locale.is_us_region", return_value=False)
+ us_region.start()
+ self.addCleanup(us_region.stop)
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
self.path = Path(self.folder.name) / "idle-fixture.json"
diff --git a/win_app/tests/test_ignored_inputs.py b/win_app/tests/test_ignored_inputs.py
index 923fd36..7b825da 100644
--- a/win_app/tests/test_ignored_inputs.py
+++ b/win_app/tests/test_ignored_inputs.py
@@ -130,8 +130,9 @@ class CaptureTests(unittest.TestCase):
def test_every_trigger_key_has_its_virtual_key(self):
self.assertEqual(set(app_config.TRIGGER_VKS), set(app_config.TRIGGER_KEYS))
+ # Against the capture module app_config reads, the one this platform's hook names keys with.
for name, vk in app_config.TRIGGER_VKS.items():
- self.assertEqual(capture_win.VK_TO_NAME[vk], name)
+ self.assertEqual(app_config.capture_win.VK_TO_NAME[vk], name)
def test_a_windows_modifier_is_recorded_as_the_side_the_hook_reports(self):
self.assertEqual(capture_win.hook_vk(0x11, 0x1D), 0xA2)
diff --git a/win_app/tests/test_inject_portal.py b/win_app/tests/test_inject_portal.py
index 94e7891..45a47c1 100644
--- a/win_app/tests/test_inject_portal.py
+++ b/win_app/tests/test_inject_portal.py
@@ -48,6 +48,16 @@ class FakeKeymap:
class StepsTest(unittest.TestCase):
+ def test_input_method_names_press_and_release_evdev_122_and_123(self):
+ for name, code in (("hangul", 122), ("hanja", 123)):
+ with self.subTest(name=name):
+ state = inject_portal.KeyState()
+ layout = inject_portal.WaylandLayout(FakeKeymap())
+ down = inject_portal.plan_key(name, True, None, state, layout, 0, 0)
+ up = inject_portal.plan_key(name, False, None, state, layout, 0, 0)
+ self.assertEqual(inject_portal.wayland_steps(down), [(code, True)])
+ self.assertEqual(inject_portal.wayland_steps(up), [(code, False)])
+
def test_a_key_with_shift_worked_around_it_is_let_go_at_once_and_repeat_and_map_mean_nothing(self):
steps = [(NO_REPEAT, 38), (PRESS, 50), (PRESS, 38), (RELEASE, 50), (REPEAT, 38), (MAP, 200, 0x41, False)]
self.assertEqual(inject_portal.wayland_steps(steps), [(42, True), (30, True), (30, False), (42, False)])
@@ -165,6 +175,26 @@ class RemoteTest(unittest.TestCase):
self.assertEqual([item[2:] for item in self.ei.sends("absolute")], [(100.0, 100.0), (110.0, 95.0), (1919.0, 95.0)])
self.assertEqual(desktop_portal.cursor_position(), (1919, 95))
+ def test_a_push_places_then_moves_on_the_session_thread(self):
+ self.up()
+ inject_portal.push(200, 300, [(10, 0), (0, -5)], lambda: True)
+ wait_for(lambda: len(self.ei.sends("absolute")) == 3, what="the shortcut push")
+ self.assertEqual([item[2:] for item in self.ei.sends("absolute")],
+ [(200.0, 300.0), (210.0, 300.0), (210.0, 295.0)])
+
+ def test_a_queued_push_is_dropped_when_its_capture_deadline_passes(self):
+ checked = threading.Event()
+
+ def wanted():
+ checked.set()
+ return False
+
+ desktop_portal.set_cursor_position(100, 100)
+ inject_portal.push(200, 300, [(10, 0), (0, -5)], wanted)
+ self.up()
+ wait_for(checked.is_set, what="the queued push to be checked")
+ self.assertEqual(self.ei.sends("absolute"), [])
+
def test_leftward_arrival_at_the_right_edge_continues_inward(self):
from core.return_edge import Rect, arrival_position
diff --git a/win_app/tests/test_inject_x11.py b/win_app/tests/test_inject_x11.py
index d0d5841..76c1334 100644
--- a/win_app/tests/test_inject_x11.py
+++ b/win_app/tests/test_inject_x11.py
@@ -3,6 +3,7 @@ tools/x11_proof.sh types through the same module on a real X server and reads it
import sys
import unittest
+from unittest import mock
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
@@ -68,6 +69,8 @@ class NamedKeyTest(unittest.TestCase):
self.assertEqual(plan("alt_r"), [(PRESS, 108)])
self.assertEqual(plan("f24"), [(PRESS, 202)])
self.assertEqual(plan("media_play_pause"), [(PRESS, 172)])
+ self.assertEqual(plan("hangul"), [(PRESS, 130)])
+ self.assertEqual(plan("hanja"), [(PRESS, 131)])
def test_search_intents_open_the_gnome_activities_key(self):
self.assertEqual(plan("spotlight"), [(PRESS, 133)])
@@ -89,8 +92,11 @@ class NamedKeyTest(unittest.TestCase):
self.assertEqual(state.mods_down, {"shift_r"})
def test_an_unknown_name_is_dropped(self):
- with self.assertLogs(inject_x11.LOGGER, "WARNING"):
- self.assertEqual(plan("hyper_q"), [])
+ old_names = {name: code for name, code in inject_x11.NAME_TO_CODE.items() if name not in ("hangul", "hanja")}
+ with mock.patch.object(inject_x11, "NAME_TO_CODE", old_names):
+ for name in ("hangul", "hanja"):
+ with self.subTest(name=name), self.assertLogs(inject_x11.LOGGER, "WARNING"):
+ self.assertEqual(plan(name), [])
class CharacterTest(unittest.TestCase):
diff --git a/win_app/tests/test_input_injector.py b/win_app/tests/test_input_injector.py
index cc7da71..d396254 100644
--- a/win_app/tests/test_input_injector.py
+++ b/win_app/tests/test_input_injector.py
@@ -258,6 +258,13 @@ class PlanKeyInputsNamedKeyTests(unittest.TestCase):
plan = plan_key_inputs("enter", True, set(), {}, fake_vk_lookup, fake_scan_lookup)
self.assertEqual(plan, [(0x0D, 0x1C, 0)])
+ def test_input_method_keys_use_their_non_extended_virtual_keys(self):
+ self.assertFalse({"hangul", "hanja"} & input_injector.MODIFIER_KEYS)
+ for name, vk in (("hangul", 0x15), ("hanja", 0x19)):
+ with self.subTest(name=name):
+ plan = plan_key_inputs(name, True, set(), {}, fake_vk_lookup, fake_scan_lookup)
+ self.assertEqual(plan, [(vk, fake_scan_lookup(vk), 0)])
+
def test_extended_keys_carry_extended_flag(self):
for name, vk in (("up", 0x26), ("ctrl_r", 0xA3), ("cmd", 0x5B)):
with self.subTest(name=name):
@@ -280,8 +287,11 @@ class PlanKeyInputsNamedKeyTests(unittest.TestCase):
self.assertNotIn("ctrl", mods_down)
def test_unknown_key_name_is_dropped(self):
- plan = plan_key_inputs("not_a_real_key", True, set(), {}, fake_vk_lookup, fake_scan_lookup)
- self.assertEqual(plan, [])
+ old_names = {name: vk for name, vk in input_injector.VK_MAP.items() if name not in ("hangul", "hanja")}
+ with mock.patch.object(input_injector, "VK_MAP", old_names):
+ for name in ("hangul", "hanja"):
+ with self.subTest(name=name):
+ self.assertEqual(plan_key_inputs(name, True, set(), {}, fake_vk_lookup, fake_scan_lookup), [])
def test_release_all_releases_a_held_named_non_modifier_key(self):
sent = []
diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.py
index 940cdea..21c5395 100644
--- a/win_app/tests/test_links.py
+++ b/win_app/tests/test_links.py
@@ -5,6 +5,8 @@ import queue
import threading
import time
import unittest
+from types import SimpleNamespace
+from unittest import mock
from links_rig import B, C, CAPS, HERE, Rig, edge_zone, make_config
@@ -197,6 +199,29 @@ class TakingTests(unittest.TestCase):
self.assertEqual(kinds, ["focus", "clipboard", "keydown"])
self.assertEqual(self.rig.sent(B, "clipboard")[0]["data"]["text"], "here")
+ def test_input_method_keys_send_one_tap_and_never_enter_held_key_state(self):
+ self.sender.set_redirecting(True)
+ self.rig.accept_take()
+ self.rig.flush()
+ self.rig.links.sent.clear()
+ self.assertTrue(self.sender.on_key("hangul", True, 0x15))
+ self.assertTrue(self.sender.on_key("hangul", False, 0x15))
+ messages = self.rig.sent(B)
+ self.assertEqual([(item["type"], item["data"]["key"]) for item in messages],
+ [(protocol.MSG_KEYDOWN, "hangul"), (protocol.MSG_KEYUP, "hangul")])
+ self.assertNotIn(0x15, self.sender._keys_down)
+ self.assertNotIn((B, "hangul"), self.sender._sent_names)
+ self.assertNotIn(0x15, self.sender._input_method_tap_releases)
+
+ def test_input_method_key_pressed_at_home_is_released_at_home(self):
+ self.assertFalse(self.sender.on_key("hanja", True, 0x19))
+ self.sender.set_redirecting(True)
+ self.rig.accept_take()
+ self.rig.flush()
+ self.rig.links.sent.clear()
+ self.assertFalse(self.sender.on_key("hanja", False, 0x19))
+ self.assertEqual(self.rig.sent(B), [])
+
def test_noncomposable_dead_key_sequence_is_sent_as_text(self):
self.sender.set_redirecting(True)
self.assertTrue(self.sender.on_text("§a", 0x41))
@@ -532,6 +557,12 @@ class KeyTests(unittest.TestCase):
"""Keys leave as the key table names them for the peer's platform (WIRE.md section 7)."""
def setUp(self):
+ # These are Windows virtual keys, and the Windows key's shortcuts are this PC's own: the
+ # sender as Windows runs it, whichever machine runs the suite.
+ for name, value in (("sys", SimpleNamespace(platform="win32")), ("OWN_PLATFORM", "windows")):
+ patcher = mock.patch.object(sender, name, value)
+ patcher.start()
+ self.addCleanup(patcher.stop)
self.rig = Rig()
self.sender = self.rig.sender
self.sender.set_redirecting(True)
diff --git a/win_app/tests/test_linux_desktop.py b/win_app/tests/test_linux_desktop.py
index 2460a2c..d350b8b 100644
--- a/win_app/tests/test_linux_desktop.py
+++ b/win_app/tests/test_linux_desktop.py
@@ -43,7 +43,9 @@ class CrossingGuidanceTests(unittest.TestCase):
layout = QVBoxLayout(host)
view = SimpleNamespace(
_ways_module=lambda _: QWidget(), _pointer_module=lambda _: QWidget(), _resistance_module=lambda _: QWidget(),
- _shortcut_module=lambda _: QWidget(), _reflect_ways=lambda: None, _reflect_other_name=lambda: None,
+ _shortcut_module=lambda _: QWidget(), _profile_override_module=lambda: QWidget(),
+ _profile_ledger_module=lambda: QWidget(), _way_home_module=lambda: QWidget(),
+ _reflect_ways=lambda: None, _reflect_other_name=lambda: None,
)
bridge.WindowsApplication._crossing_page(view, layout, bridge.default_config())
self.assertEqual(not view.linux_tray_note.isHidden(), shown)
diff --git a/win_app/tests/test_linux_start.py b/win_app/tests/test_linux_start.py
index 680321a..a294c9e 100644
--- a/win_app/tests/test_linux_start.py
+++ b/win_app/tests/test_linux_start.py
@@ -166,6 +166,9 @@ def x11_child() -> None:
raise RuntimeError("no X server in this test")
desktop_x11._connect = no_server
+ # Start reads this PC's displays for the Crossing map (696d451f); the one X call answered here.
+ from core.return_edge import Rect
+ desktop_x11.monitors = lambda: [Rect(0, 0, 1920, 1080)]
import kvm_bridge_win
import platform_parts
diff --git a/win_app/tests/test_map_ticks.py b/win_app/tests/test_map_ticks.py
index 854ec32..0d2ed3a 100644
--- a/win_app/tests/test_map_ticks.py
+++ b/win_app/tests/test_map_ticks.py
@@ -163,7 +163,7 @@ class MapTicks(unittest.TestCase):
continue
box = canvas._cycle_box(rect)
self.assertEqual((box.width(), box.height()), (16, 16))
- self.assertAlmostEqual(box.left(), rect.right() - 24)
+ self.assertAlmostEqual(box.left(), rect.right() - (36 if rect.height() < 56 else 24))
self.assertFalse(box.intersects(title))
if band == "small":
self.assertGreaterEqual(title.width(), rect.width() - 16 - 1e-9)
diff --git a/win_app/tests/test_page_column_geometry.py b/win_app/tests/test_page_column_geometry.py
index 60ea0cf..348da29 100644
--- a/win_app/tests/test_page_column_geometry.py
+++ b/win_app/tests/test_page_column_geometry.py
@@ -60,6 +60,7 @@ class PageColumnGeometryTests(unittest.TestCase):
scope_labels={}, _host="localhost-live.example.lan",
_hide_addresses=lambda: False, _set_hide_addresses=lambda *_: None,
_shown=lambda text: text, save=lambda: None, _firewall_action=lambda: None,
+ _set_language=lambda *_: None, relaunch=lambda *_: None,
)
owner._firewall_module = MethodType(kvm.WindowsApplication._firewall_module, owner)
scroll, layout = kvm.WindowsApplication._page_shell(
diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.py
index f342faf..5ce9cc2 100644
--- a/win_app/tests/test_pages_win.py
+++ b/win_app/tests/test_pages_win.py
@@ -463,7 +463,7 @@ class CrossingPageTest(unittest.TestCase):
for _ in range(8):
QApplication.processEvents()
- self.assertEqual(self.page.atlas_canvas_hint.text(), "Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out")
+ self.assertEqual(self.page.atlas_canvas_hint.text(), "Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize")
self.assertIs(self.page.atlas_canvas_hint.parentWidget(), self.page.atlas_canvas.parentWidget())
self.assertGreaterEqual(self.page.atlas_canvas_hint.y(),
self.page.atlas_canvas.y() + self.page.atlas_canvas.height())
diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.py
index 452d86c..cc79b0f 100644
--- a/win_app/tests/test_pairing_window.py
+++ b/win_app/tests/test_pairing_window.py
@@ -16,6 +16,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from core import feature_flags, pairing, peerlist, protocol, ways
from core.tests import responder_harness as harness
+import qr_code
try:
from PySide6.QtCore import QCoreApplication, QEvent, Qt
@@ -455,6 +456,10 @@ class PairingSheetWindowTest(unittest.TestCase):
self.phone_pairing_flag = mock.patch.object(feature_flags, "PAIRING_QR_VISIBLE", True)
self.phone_pairing_flag.start()
self.addCleanup(self.phone_pairing_flag.stop)
+ # British spelling, whatever region the machine running the suite is set to.
+ us_region = mock.patch("core.locale.is_us_region", return_value=False)
+ us_region.start()
+ self.addCleanup(us_region.stop)
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
self.app = QApplication.instance() or QApplication([])
theme.init_fonts()
@@ -489,6 +494,8 @@ class PairingSheetWindowTest(unittest.TestCase):
self.assertTrue(self.window.sheet.code_showing)
self.assertTrue(self.window.sheet.count_label.text().startswith("Expires in "))
+ # segno is in the Windows build only until phone pairing ships, and Linux with it (todo.md).
+ @unittest.skipIf(qr_code.segno is None, "segno is not installed")
def test_pair_phone_button_opens_the_sheet_and_generates_a_qr_in_one_click(self):
self.window._toggle_pairing_sheet()
self.window._pairing_address = lambda: "192.0.2.20"
@@ -667,6 +674,8 @@ class PairingSheetWindowTest(unittest.TestCase):
self.assertEqual(self.window.sheet.pair_note.text(),
peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_REFUSED), "Studio"))
+ # segno is in the Windows build only until phone pairing ships, and Linux with it (todo.md).
+ @unittest.skipIf(qr_code.segno is None, "segno is not installed")
def test_the_code_shows_a_qr_unless_addresses_are_hidden(self):
from unittest import mock
from core import feature_flags
diff --git a/win_app/tests/test_parity.py b/win_app/tests/test_parity.py
index e9c4bf1..746bf52 100644
--- a/win_app/tests/test_parity.py
+++ b/win_app/tests/test_parity.py
@@ -48,13 +48,16 @@ class TriggerKeyTests(unittest.TestCase):
config_from_dict(raw(trigger_key=name))
def test_every_trigger_is_titled_in_windows_words(self):
+ # In this PC's own words: the key Windows calls Windows is Super on Linux.
self.assertEqual(app_config.TRIGGER_KEYS["cmd_r"], "Right Ctrl")
- self.assertEqual(app_config.TRIGGER_KEYS["ctrl"], "Left Windows")
+ self.assertEqual(app_config.TRIGGER_KEYS["ctrl"],
+ "Left Super" if sys.platform.startswith("linux") else "Left Windows")
self.assertEqual(app_config.TRIGGER_KEYS["f13"], "F13")
def test_a_recorded_trigger_is_what_the_hook_names_it(self):
+ # Against the capture module app_config reads, the one this platform's hook names keys with.
for name, vk in app_config.TRIGGER_VKS.items():
- self.assertEqual(capture_win.VK_TO_NAME[vk], name)
+ self.assertEqual(app_config.capture_win.VK_TO_NAME[vk], name)
trigger = capture_win.Trigger("f13", "double_tap", 300)
self.assertIsNone(trigger.feed("f13", True, 0.0))
self.assertIsNone(trigger.feed("f13", False, 0.05))
@@ -73,8 +76,12 @@ class ReviewFixTests(unittest.TestCase):
self.assertTrue(trigger.claims("alt_r", True, True))
def test_typing_keys_are_never_offered_as_the_trigger(self):
- for vk in (0x08, 0x09, 0x0D, 0x1B, 0x20, 0x2C):
- self.assertIn(vk, app_config.UNRECORDABLE_TRIGGER_VKS)
+ typing = ("backspace", "tab", "enter", "esc", "space", "print_screen")
+ names = app_config.capture_win.VK_TO_NAME
+ self.assertEqual({names[vk] for vk in app_config.UNRECORDABLE_TRIGGER_VKS} & set(typing), set(typing))
+ for vk, name in names.items():
+ if name in typing:
+ self.assertIn(vk, app_config.UNRECORDABLE_TRIGGER_VKS)
def test_the_subnet_broadcast_of_a_home_address(self):
from core import wol
diff --git a/win_app/tests/test_part_edge_corners_qt.py b/win_app/tests/test_part_edge_corners_qt.py
index 108bd06..54ab86a 100644
--- a/win_app/tests/test_part_edge_corners_qt.py
+++ b/win_app/tests/test_part_edge_corners_qt.py
@@ -126,6 +126,51 @@ class PartEdgeCornersTests(unittest.TestCase):
QTest.mouseClick(window.atlas_canvas, Qt.MouseButton.LeftButton, pos=band_point(window.atlas_canvas, third, side))
self.assertEqual(picked_row(window), list(ways.PARTS))
+ def test_a_grip_on_the_seam_leaves_the_end_band_to_its_third(self):
+ window, peer = self.window, self.peers[0]["id"]
+ window._ledger_edge(peer)
+ layout = copy.deepcopy(window.atlas_canvas.tiles)
+ own = window._config.machine_id
+ layout[own].update(x=0, y=0, w=160, h=120)
+ layout[peer].update(x=-160, y=0, w=160, h=120)
+ layout[self.peers[1]["id"]].update(x=500, y=300)
+ window._layout_dropped(layout, peer)
+ parity.settle(window)
+ canvas = window.atlas_canvas
+ band = band_point(canvas, "end", "left")
+ grip = canvas._resize_grip_rect(peer)
+ self.assertTrue(grip.contains(QPointF(band)))
+ self.assertIsNone(canvas._resize_at(QPointF(band)))
+ self.assertEqual(canvas._third_at(QPointF(band)), (peer, "end"))
+ inside = QPointF(grip.right() - 8, grip.bottom() - 4)
+ self.assertEqual(canvas._resize_at(inside), peer)
+ QTest.mousePress(canvas, Qt.MouseButton.LeftButton, pos=inside.toPoint())
+ self.assertTrue(canvas._resizing)
+ QTest.mouseRelease(canvas, Qt.MouseButton.LeftButton, pos=inside.toPoint())
+
+ def test_a_tile_inside_the_band_keeps_its_end_third_and_its_grip(self):
+ window, peer = self.window, self.peers[0]["id"]
+ window._ledger_edge(peer)
+ layout = copy.deepcopy(window.atlas_canvas.tiles)
+ own = window._config.machine_id
+ layout[own].update(x=0, y=0, w=160, h=120)
+ layout[peer].update(x=160, y=0, w=4, h=120)
+ layout[self.peers[1]["id"]].update(x=500, y=300)
+ window._layout_dropped(layout, peer)
+ parity.settle(window)
+ canvas = window.atlas_canvas
+ grip = canvas._resize_grip_rect(peer)
+ self.assertLessEqual(grip.width(), 5)
+ band = band_point(canvas, "end", "right")
+ self.assertEqual(canvas._third_at(QPointF(band)), (peer, "end"))
+ self.assertIsNone(canvas._resize_at(QPointF(band)))
+ outside = QPointF(grip.right() + 8, grip.bottom() + 4)
+ self.assertIsNone(canvas._third_at(outside))
+ self.assertEqual(canvas._resize_at(outside), peer)
+ QTest.mousePress(canvas, Qt.MouseButton.LeftButton, pos=outside.toPoint())
+ self.assertTrue(canvas._resizing)
+ QTest.mouseRelease(canvas, Qt.MouseButton.LeftButton, pos=outside.toPoint())
+
def test_band_is_five_pixels_wide_and_available_when_edge_is_off(self):
window, peer = self.window, self.peers[0]["id"]
canvas = window.atlas_canvas
diff --git a/win_app/tests/test_pc_three_machines.py b/win_app/tests/test_pc_three_machines.py
index bd2b6c1..71e6328 100644
--- a/win_app/tests/test_pc_three_machines.py
+++ b/win_app/tests/test_pc_three_machines.py
@@ -81,6 +81,65 @@ class ShortcutMachineTests(unittest.TestCase):
rig.sender.toggle_shortcut()
self.assertIsNone(rig.sender.owner)
+ def test_shortcut_at_home_asks_to_push_to_its_target_then_moves_when_captured(self):
+ rig = self.rig(up=(B, C))
+ rig.sender.input_held = lambda: False
+ requested = []
+
+ def push_out(peer, on_captured, on_failed):
+ requested.append((peer, on_captured, on_failed))
+ return True
+
+ rig.sender.push_out = push_out
+ rig.sender.toggle_shortcut()
+
+ self.assertEqual(len(requested), 1)
+ peer, captured, _failed = requested[0]
+ self.assertEqual(peer, rig.sender.shortcut_target())
+ self.assertEqual(rig.sender.owner, None)
+ self.assertEqual(rig.alerts, [])
+ rig.sender.input_held = lambda: True
+ captured()
+ self.assertEqual(rig.sender.owner, peer)
+
+ def test_failed_push_out_alerts_with_the_target_name(self):
+ rig = self.rig(up=(B, C))
+ rig.sender.input_held = lambda: False
+ requests = []
+ rig.sender.push_out = lambda peer, on_captured, on_failed: requests.append((peer, on_failed)) or True
+ rig.sender.toggle_shortcut()
+
+ requests[0][1]()
+
+ self.assertEqual(rig.alerts, ["Cannot switch — the desktop did not let Beamer send input to Bee"])
+
+ def test_no_push_out_keeps_the_existing_wayland_alert(self):
+ rig = self.rig(up=(B, C))
+ rig.sender.input_held = lambda: False
+
+ rig.sender.toggle_shortcut()
+
+ self.assertEqual(rig.alerts, ["Cannot switch — on this desktop input goes to another machine only by pushing the pointer through an edge"])
+
+ def test_push_out_refusal_falls_back_to_the_existing_wayland_alert(self):
+ rig = self.rig(up=(B, C))
+ rig.sender.input_held = lambda: False
+ rig.sender.push_out = lambda peer, on_captured, on_failed: False
+
+ rig.sender.toggle_shortcut()
+
+ self.assertEqual(rig.alerts, ["Cannot switch — on this desktop input goes to another machine only by pushing the pointer through an edge"])
+
+ def test_models_toward_returns_only_that_peers_models_and_none_while_edges_are_held(self):
+ rig = self.rig(up=(B, C))
+
+ models = rig.sender.models_toward(B)
+
+ self.assertTrue(models)
+ self.assertEqual(models, [model for peer, model in rig.sender._models if peer == B])
+ rig.sender.crossing_paused = True
+ self.assertEqual(rig.sender.models_toward(B), [])
+
def test_next_shortcut_passes_over_a_machine_that_just_refused_and_comes_home(self):
# The owner ignores a move to a machine it holds back, so choosing it left input where it was.
rig = self.rig(up=(B, C), shortcut_goes_to="next")
diff --git a/win_app/tests/test_portal.py b/win_app/tests/test_portal.py
index db1e84d..32c22bd 100644
--- a/win_app/tests/test_portal.py
+++ b/win_app/tests/test_portal.py
@@ -10,6 +10,7 @@ import tempfile
import threading
import time
import unittest
+import unittest.mock
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -34,6 +35,16 @@ class RequestTest(unittest.TestCase):
results = portal.Portal(bus).request("I", "CreateSession", "sa{sv}", lambda token: ("", {"handle_token": ("s", token)}))
self.assertEqual(results, {"session_handle": "/session/1", "capabilities": 3})
+ def test_a_request_unanswered_for_a_minute_is_logged_once_and_still_waited_for(self):
+ bus = FakeBus()
+ bus.answers["CreateSession"] = None
+ with unittest.mock.patch.object(portal, "SLOW_ANSWER_SECONDS", 0.05), \
+ self.assertLogs(portal.LOGGER, level="WARNING") as said, self.assertRaises(portal.PortalError):
+ portal.Portal(bus).request("org.freedesktop.portal.InputCapture", "CreateSession", "sa{sv}",
+ lambda token: ("", {"handle_token": ("s", token)}), timeout=0.4)
+ self.assertEqual(said.output, ["WARNING:portal:Still waiting for the desktop's answer to "
+ "InputCapture.CreateSession after 0 s"])
+
def test_a_refusal_and_another_ending_are_told_apart(self):
bus = FakeBus()
bus.answers["Start"] = (1, {})
diff --git a/win_app/tests/test_profiles_canvas_qt.py b/win_app/tests/test_profiles_canvas_qt.py
new file mode 100644
index 0000000..fc0d998
--- /dev/null
+++ b/win_app/tests/test_profiles_canvas_qt.py
@@ -0,0 +1,247 @@
+"""Profile map selection and remote ledger controls; run offscreen, one module per process."""
+
+import copy
+import os
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from PySide6.QtCore import QEvent, QPoint, QPointF, Qt
+from PySide6.QtGui import QColor, QImage, QMouseEvent
+from PySide6.QtTest import QTest
+from PySide6.QtWidgets import QApplication
+
+from core import ways
+from crossing_ledger import CrossingLedger
+from diagram import AtlasCanvas
+import theme
+
+
+class ProfilesCanvasTests(unittest.TestCase):
+ def setUp(self):
+ self.app = QApplication.instance() or QApplication([])
+ self.edited, self.chosen, self.dropped = [], [], []
+ self.canvas = AtlasCanvas(on_edit_machine=self.edited.append, on_select=self.chosen.append,
+ on_drop=lambda tiles, peer: self.dropped.append((tiles, peer)))
+ self.addCleanup(self.canvas.deleteLater)
+ self.canvas.resize(720, 268)
+ self.tiles = {"home": {"x": 0, "y": 0, "w": 160, "h": 100},
+ "peer": {"x": 160, "y": 0, "w": 160, "h": 100}}
+ self.canvas.profile_mode = True
+ self.reflect()
+
+ def reflect(self):
+ self.canvas.set_tiles(self.tiles, {"home": "This PC", "peer": "Studio Mac"},
+ {"home": {"profile_word": "Own"},
+ "peer": {"linked": False, "profile_word": "Offline"}},
+ "peer", cycle_mode="ticked", own_id="home")
+
+ def test_clicking_each_tile_edits_that_machine_without_selecting_a_destination_or_writing(self):
+ for peer in self.tiles:
+ QTest.mouseClick(self.canvas, Qt.MouseButton.LeftButton,
+ pos=self.canvas.tile_rect(peer).center().toPoint())
+ self.assertEqual(self.edited, ["home", "peer"])
+ self.assertEqual(self.chosen, [])
+ self.assertEqual(self.dropped, [])
+
+ def test_keyboard_can_focus_own_tile_and_activate_it_with_return_or_space(self):
+ self.canvas.selected = "peer"
+ self.assertTrue(self.canvas.focusNextPrevChild(False))
+ self.assertEqual(self.canvas.selected, "home")
+ self.assertEqual(self.edited, [])
+ for key in (Qt.Key.Key_Return, Qt.Key.Key_Space):
+ QTest.keyClick(self.canvas, key)
+ self.assertEqual(self.edited, ["home", "home"])
+ self.assertTrue(self.canvas.rename_edit.isHidden())
+ self.assertEqual(self.chosen, [])
+
+ def test_remote_map_keeps_geometry_drag_without_changing_edited_machine(self):
+ self.canvas.remote = True
+ start = self.canvas.tile_rect("peer").center()
+ end = start + QPointF(35, 20)
+ QTest.mousePress(self.canvas, Qt.MouseButton.LeftButton, pos=start.toPoint())
+ event = QMouseEvent(QEvent.Type.MouseMove, end, end, Qt.MouseButton.NoButton,
+ Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier)
+ self.canvas.mouseMoveEvent(event)
+ QTest.mouseRelease(self.canvas, Qt.MouseButton.LeftButton, pos=end.toPoint())
+ self.assertEqual(self.edited, [])
+ self.assertIsNone(self.canvas._drag)
+ self.assertNotEqual(self.canvas.tiles["peer"], self.tiles["peer"])
+
+ def test_read_only_map_can_pick_machine_but_cannot_drag_recentre_or_change_thirds(self):
+ self.canvas.read_only = True
+ self.reflect()
+ before = copy.deepcopy(self.canvas.tiles)
+ start = self.canvas.tile_rect("peer").center().toPoint()
+ QTest.mousePress(self.canvas, Qt.MouseButton.LeftButton, pos=start)
+ QTest.mouseMove(self.canvas, start + QPoint(30, 0))
+ QTest.mouseRelease(self.canvas, Qt.MouseButton.LeftButton, pos=start + QPoint(30, 0))
+ QTest.keyClick(self.canvas, Qt.Key.Key_Left)
+ self.canvas.recentre()
+ self.assertEqual(self.canvas.tiles, before)
+ self.assertEqual(self.dropped, [])
+ QTest.mouseClick(self.canvas, Qt.MouseButton.LeftButton, pos=start)
+ self.assertEqual(self.edited, ["peer"])
+ self.assertTrue(self.canvas.recentre_button.isHidden())
+
+ def test_remote_profile_hides_cycle_and_blocks_rename_and_leave_out(self):
+ self.canvas.remote = True
+ self.canvas.on_rename = Mock()
+ self.canvas.on_leave_out = Mock()
+ self.assertFalse(self.canvas._shows_cycle("peer"))
+ self.canvas.begin_rename("peer")
+ self.canvas.leave_out("peer")
+ self.canvas.put_back("peer")
+ self.assertTrue(self.canvas.rename_edit.isHidden())
+ self.canvas.on_rename.assert_not_called()
+ self.canvas.on_leave_out.assert_not_called()
+
+ def test_own_cycle_checkbox_does_not_switch_the_machine_being_edited(self):
+ cycled = []
+ self.canvas.on_cycle = lambda peer, on: cycled.append((peer, on))
+ QTest.mouseClick(self.canvas, Qt.MouseButton.LeftButton,
+ pos=self.canvas._cycle_box(self.canvas.tile_rect("peer")).center().toPoint())
+ self.assertEqual(cycled, [("peer", False)])
+ self.assertEqual(self.edited, [])
+
+ def test_profile_mode_does_not_force_remote_own_tile_online(self):
+ self.canvas.remote = True
+ self.canvas.set_tiles(self.tiles, {"home": "Studio PC", "peer": "Studio Mac"},
+ {"peer": {"linked": False, "detail": "macOS", "profile_word": "Offline"}},
+ "home", own_id="peer")
+ self.assertFalse(self.canvas.states["peer"]["linked"])
+ self.assertEqual(self.canvas.states["peer"]["detail"], "macOS")
+
+ def test_profile_word_is_drawn_on_own_and_older_tiles(self):
+ def draw(states):
+ self.canvas.set_tiles(self.tiles, {"home": "This PC", "peer": "Studio Mac"},
+ states, "peer", own_id="home")
+ image = QImage(self.canvas.size(), QImage.Format.Format_ARGB32)
+ image.fill(Qt.GlobalColor.transparent)
+ self.canvas.render(image)
+ return image
+
+ blank = draw({"home": {"profile_word": ""},
+ "peer": {"legacy": True, "profile_word": ""}})
+ for peer, word in (("home", "Own"), ("peer", "Older")):
+ with self.subTest(peer=peer):
+ states = {"home": {"profile_word": ""},
+ "peer": {"legacy": True, "profile_word": ""}}
+ states[peer]["profile_word"] = word
+ self.assertNotEqual(draw(states), blank)
+
+ def test_normal_map_click_still_selects_destination(self):
+ self.canvas.profile_mode = False
+ self.reflect()
+ QTest.mouseClick(self.canvas, Qt.MouseButton.LeftButton,
+ pos=self.canvas.tile_rect("peer").center().toPoint())
+ self.assertEqual(self.chosen, ["peer"])
+ self.assertEqual(self.edited, [])
+
+ def test_profile_word_dot_uses_the_word_even_when_an_older_machine_is_linked(self):
+ for word, colour in (("Desk", "signal"), ("Own", "signal"), ("Older", "ink_3"), ("Offline", "ink_3")):
+ with self.subTest(word=word):
+ self.canvas.set_tiles(self.tiles, {"home": "This PC", "peer": "Studio Mac"},
+ {"peer": {"linked": True, "profile_word": word}}, "home", own_id="home")
+ picture = QImage(self.canvas.size(), QImage.Format.Format_ARGB32)
+ picture.fill(Qt.GlobalColor.transparent)
+ self.canvas.render(picture)
+ rect = self.canvas.tile_rect("peer")
+ self.assertEqual(picture.pixelColor(round(rect.left() + 15), round(rect.top() + 39)),
+ QColor(theme.colour(colour)))
+
+ def test_remote_map_does_not_draw_amber_contacts_between_other_machines(self):
+ self.canvas.remote = True
+ tiles = {**self.tiles, "third": {"x": 0, "y": -100, "w": 160, "h": 100}}
+ self.canvas.set_tiles(tiles, {"home": "This PC", "peer": "Studio Mac", "third": "Laptop"},
+ {"home": {"state": "set-elsewhere"}, "third": {"state": "set-elsewhere"}},
+ "peer", own_id="peer")
+ paint_contact = Mock(wraps=self.canvas._paint_contact)
+ self.canvas._paint_contact = paint_contact
+ picture = QImage(self.canvas.size(), QImage.Format.Format_ARGB32)
+ picture.fill(Qt.GlobalColor.transparent)
+ self.canvas.render(picture)
+ for call in paint_contact.call_args_list:
+ self.assertNotIn("amber", call.args)
+
+
+class ProfilesLedgerTests(unittest.TestCase):
+ def setUp(self):
+ self.app = QApplication.instance() or QApplication([])
+ self.remote, self.read_only, self.platform = True, False, "pc"
+ self.settings = {"machine_id": "remote", "peers": [{"id": "home", "name": "Studio PC",
+ "ways": {"edge": True, "part": False, "parts": [], "edges": [],
+ "corner": False, "corners": [], "notch": False}}],
+ "layout": {"remote": {"x": 0, "y": 0, "w": 160, "h": 100},
+ "home": {"x": 160, "y": 0, "w": 160, "h": 100}}}
+ self.owner = SimpleNamespace(**{name: Mock() for name in (
+ "_ledger_third", "_ledger_edge", "_ledger_side", "_ledger_corner", "_ledger_jump",
+ "_set_shortcut_cycle", "_canvas_left_out", "_jump_arming", "_rename_canvas_peer",
+ "_choose_machine", "_write_ways")})
+ self.owner._profile_remote = lambda: self.remote
+ self.owner._profile_read_only = lambda: self.read_only
+ self.owner._crossing_view_settings = lambda: self.settings
+ self.owner._profile_settings = lambda: {"machine_id": "home", "peers": [], "crossing_desk": {
+ "status": {"remote": {"value": {"platform": self.platform}}}}}
+ self.owner._profile_machine = lambda: "remote"
+ self.ledger = CrossingLedger(self.owner)
+ self.addCleanup(self.ledger.deleteLater)
+
+ def reflect(self):
+ reach = {"home": ways.reach(self.settings, "home", platform=self.platform, capable={"home"},
+ live=lambda _peer: True)}
+ self.ledger.reflect(self.settings, self.settings["layout"], {"home": "Studio PC"},
+ "home", lambda _peer: True, "Ctrl Ctrl", reach=reach)
+ return self.ledger.rows["home"]
+
+ def test_remote_view_shows_local_machine_destination_but_no_local_controls(self):
+ row = self.reflect()
+ self.assertEqual(row.name.full_text, "Studio PC")
+ for widget in (row.keys, row.rename, row.leave):
+ self.assertTrue(widget.isHidden())
+ self.assertEqual(row.grid.columnMinimumWidth(3), 0)
+ self.assertTrue(row.edge_chips.isEnabled())
+ row.begin_rename()
+ self.assertTrue(row.edit.isHidden())
+
+ def test_read_only_remote_ledger_disables_ways_without_losing_the_displayed_state(self):
+ self.read_only = True
+ row = self.reflect()
+ self.assertFalse(row.edge_chips.isEnabled())
+ self.assertFalse(row.corner_grid.isEnabled())
+ self.assertEqual(row.name.full_text, "Studio PC")
+ self.read_only = False
+ self.assertTrue(self.reflect().edge_chips.isEnabled())
+
+ def test_returning_to_own_ways_restores_keys_and_machine_actions(self):
+ # The wide layout, as the window lays it out; an unsized offscreen ledger lays out narrow.
+ self.ledger.resize(900, 600)
+ row = self.reflect()
+ self.remote = False
+ self.reflect()
+ for widget in (row.keys, row.rename, row.leave):
+ self.assertFalse(widget.isHidden())
+ self.assertEqual(row.grid.columnMinimumWidth(3), 128)
+
+ def test_remote_mac_shows_notch_and_routes_both_flags_through_profile_write(self):
+ self.platform = "mac"
+ row = self.reflect()
+ self.assertFalse(row.notch_cell.isHidden())
+ self.assertTrue(row.keys.isHidden())
+ row.notch.click()
+ self.owner._write_ways.assert_called_with(peer="home", notch=True)
+ self.settings["peers"][0]["ways"]["notch"] = True
+ row = self.reflect()
+ self.assertTrue(row.notch.isChecked())
+ self.assertFalse(row.notch_return.isHidden())
+ row.notch_return.click()
+ self.owner._write_ways.assert_called_with(peer="home", notch_return=True)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_profiles_labels.py b/win_app/tests/test_profiles_labels.py
new file mode 100644
index 0000000..e9e9606
--- /dev/null
+++ b/win_app/tests/test_profiles_labels.py
@@ -0,0 +1,32 @@
+"""Pure archive labels, including author names and human dates."""
+
+import sys
+import time
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import pages_win
+
+
+class SavedWaysLabelsTests(unittest.TestCase):
+ def test_archive_reasons_and_day_first_date(self):
+ stamp = time.mktime((2026, 10, 14, 12, 0, 0, 0, 0, -1))
+ for reason, words in (("upgrade", "Before Beamer 1.5.5"),
+ ("older_version", "From an older Beamer"),
+ ("sync_off", "When Same ways went off"),
+ ("seeded", "When Same ways went on"),
+ ("edited", "Before you changed it"),
+ ("restored", "Before a restore")):
+ with self.subTest(reason=reason):
+ self.assertEqual(pages_win.saved_ways_label({"why": reason, "at": stamp}, {}),
+ "14-10-2026 · " + words)
+
+ def test_replaced_row_names_the_author(self):
+ result = pages_win.saved_ways_label({"why": "replaced_by", "by": "own"},
+ {"machine_id": "own", "name": "Studio PC"})
+ self.assertTrue(result.endswith("Before Studio PC changed it"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_profiles_page_qt.py b/win_app/tests/test_profiles_page_qt.py
new file mode 100644
index 0000000..18af5ce
--- /dev/null
+++ b/win_app/tests/test_profiles_page_qt.py
@@ -0,0 +1,234 @@
+"""Profiles page behaviour; run offscreen, one module per process."""
+
+import unittest
+import sys
+from unittest.mock import patch
+
+import test_crossing_page_parity as fixture
+from core import crossing_state, profiles, ways
+import app_config
+from PySide6.QtWidgets import QBoxLayout, QLabel
+
+
+class ProfilesPageTests(unittest.TestCase):
+ setUp = fixture.CrossingPageParityTests.setUp
+ tearDown = fixture.CrossingPageParityTests.tearDown
+ _open_window = fixture.CrossingPageParityTests._open_window
+ _close_window = fixture.CrossingPageParityTests._close_window
+ _stop_patches = fixture.CrossingPageParityTests._stop_patches
+
+ def enable(self):
+ self.window._design_peer_caps = lambda: {
+ entry["id"]: {"layout", "profiles"} for entry in self.peers}
+ self.window._profile_event(crossing_state.set_same_ways, True)
+ fixture.settle(self.window)
+
+ def test_off_keeps_tabs_hidden_and_home_available(self):
+ self.assertFalse(self.window.profile_tabs.isVisible())
+ self.assertFalse(self.window.same_ways_switch.isChecked())
+ self.assertTrue(self.window.shake_home_switch.isChecked())
+ self.assertTrue(self.window.profile_off_note.isVisible())
+ self.assertEqual(self.window.shake_sensitivity.value(), 100)
+
+ def test_way_home_sensitivity_is_saved_and_reflected(self):
+ self.window.shake_sensitivity.setValue(150)
+ settings = app_config.load_settings(self.path)
+ self.assertEqual(profiles.shake_sensitivity(settings), 150)
+ self.assertEqual(self.window.shake_sensitivity.value(), 150)
+ self.assertEqual(self.window.shake_sensitivity_figure.text(), "150 %")
+
+ def test_profile_tabs_and_read_only_overview_follow_switch(self):
+ self.enable()
+ window = self.window
+ self.assertTrue(window.profile_tabs.isVisible())
+ self.assertIn("On", window.same_ways_summary.text())
+ settings = app_config.load_settings(self.path)
+ before = profiles.view_row(settings, settings["machine_id"])
+ window._profile_event(crossing_state.new_profile, "Sofa")
+ settings = app_config.load_settings(self.path)
+ sofa = next(item["id"] for item in profiles.profile_list(settings) if item["name"] == "Sofa")
+ window._profile_event(crossing_state.switch_profile, sofa)
+ self.assertEqual(app_config.load_settings(self.path)["crossing_desk"]["active"]["value"], sofa)
+ self.assertEqual(profiles.view_row(app_config.load_settings(self.path), settings["machine_id"]), before)
+
+ def test_remote_view_edits_that_row_and_hides_local_controls(self):
+ self.enable()
+ window = self.window
+ machine, destination = (entry["id"] for entry in self.peers)
+ window._edit_profile_machine(machine)
+ fixture.settle(window)
+ self.assertEqual(window.atlas_canvas.own_id, machine)
+ self.assertEqual(window._crossing_view_settings()["machine_id"], machine)
+ self.assertIn("MacBook Pro", window.profile_editing.text())
+ self.assertFalse(window.pointer_module.isVisible())
+ window._write_ways(peer=destination, edge=False, corners=["top_left"])
+ settings = app_config.load_settings(self.path)
+ self.assertFalse(profiles.view_row(settings, machine)[destination]["ways"]["edge"])
+ self.assertTrue(window.profile_back.isVisible())
+ window.profile_back.click()
+ self.assertFalse(window._profile_remote())
+
+ def test_same_ways_shelves_left_out_machine_in_picker_and_remote_layout(self):
+ own = app_config.load_settings(self.path)["machine_id"]
+ viewed, shelved = (entry["id"] for entry in self.peers)
+ settings = app_config.load_settings(self.path)
+ next(peer for peer in settings["peers"] if peer["id"] == shelved).update(
+ left_out=True)
+ settings["layout"][shelved] = dict(settings["layout"][viewed])
+ app_config.write_settings(self.path, settings)
+
+ self.enable()
+ self.window._edit_profile_machine(shelved)
+ self.assertEqual(self.window._profile_machine(), own)
+ self.window._edit_profile_machine(viewed)
+ viewed_settings = self.window._crossing_view_settings()
+ self.assertEqual(viewed_settings["machine_id"], viewed)
+ states = ways.compile_layout(viewed_settings, viewed_settings["layout"], platform="pc")["tiles"]
+ self.assertEqual(states[shelved]["state"], "dormant")
+ self.assertNotEqual(states.get(own, {}).get("state"), "overlap")
+ self.assertNotEqual(states.get(viewed, {}).get("state"), "overlap")
+
+ def test_older_machine_is_read_only(self):
+ self.enable()
+ machine, destination = (entry["id"] for entry in self.peers)
+ self.window._design_peer_caps = lambda: {machine: {"layout"}, destination: {"layout", "profiles"}}
+ self.window._edit_profile_machine(machine)
+ before = app_config.load_settings(self.path)
+ self.assertTrue(self.window._profile_read_only())
+ self.assertFalse(self.window._write_ways(peer=destination, edge=False))
+ self.assertEqual(app_config.load_settings(self.path), before)
+ self.assertIn("Read only", self.window.profile_machine_status.text())
+
+ def test_profile_actions_create_rename_and_protect_active_profile(self):
+ self.enable()
+ window = self.window
+ self.assertTrue(window.profile_actions.isVisible())
+ self.assertFalse(window.profile_delete.isEnabled(), "the only profile cannot go")
+
+ window.profile_new.click()
+ window.profile_name.setText("Sofa")
+ window._save_profile_name()
+ settings = app_config.load_settings(self.path)
+ sofa = next(item["id"] for item in profiles.profile_list(settings) if item["name"] == "Sofa")
+ window._reflect_ways()
+ self.assertTrue(window.profile_delete.isEnabled())
+ # Rename names the active profile (Desk); a tab click would switch the desk.
+ window.profile_rename.click()
+ self.assertEqual(window.profile_name.text(), "Desk")
+ window.profile_name.setText("Studio desk")
+ window._save_profile_name()
+ names = {item["name"] for item in profiles.profile_list(app_config.load_settings(self.path))}
+ self.assertEqual(names, {"Studio desk", "Sofa"})
+ # Delete offers only the profiles that are not active.
+ menu = window._profile_delete_menu()
+ self.assertEqual([action.text() for action in menu.actions()], ["Sofa"])
+ menu.deleteLater()
+ window._profile_event(crossing_state.remove_profile, sofa)
+ self.assertEqual(len(profiles.profile_list(app_config.load_settings(self.path))), 1)
+ window._reflect_ways()
+ self.assertFalse(window.profile_delete.isEnabled())
+
+ def test_override_actions_share_a_plain_row_with_archive(self):
+ self.enable()
+ window = self.window
+ self.assertEqual(window.profile_keep_own.parentWidget(), window.profile_archive_toggle.parentWidget())
+ for widget in (window.profile_header, window.profile_tabs, window.profile_own_actions, window.profile_archive):
+ self.assertEqual(widget.property("vernier"), "plain")
+ window.profile_archive_toggle.click()
+ self.assertIn("▴", window.profile_archive_toggle.text())
+ window.profile_archive_toggle.click()
+ self.assertIn("▾", window.profile_archive_toggle.text())
+
+ def test_remote_header_order_and_shortcut_link_open_overview(self):
+ self.enable()
+ window = self.window
+ window._edit_profile_machine(self.peers[0]["id"])
+ fixture.settle(window)
+ self.assertEqual(window.profile_editing.parentWidget(), window.profile_back.parentWidget())
+ self.assertEqual(window.profile_editing.geometry().top(), window.profile_back.geometry().top())
+ body = window.profile_ledger_module.body
+ self.assertLess(body.indexOf(window.profile_editing_row), body.indexOf(window.profile_machine_status))
+ self.assertLess(body.indexOf(window.profile_machine_status), body.indexOf(window.profile_remote_note))
+ self.assertLess(body.indexOf(window.profile_remote_note), body.indexOf(window.profile_permissions_note))
+ self.assertIsInstance(window.profile_shortcut, QLabel)
+ self.assertIn("font-family", window.profile_shortcut.text())
+ with patch.object(window, "_select_page", wraps=window._select_page) as select:
+ window.profile_shortcut.linkActivated.emit("shortcut")
+ select.assert_called_with("overview")
+ self.assertEqual(window.focusWidget(), window.same_checks["shortcut"])
+
+ def test_remote_warning_uses_viewed_machine_and_preserves_platforms(self):
+ self.enable()
+ window = self.window
+ machine = self.peers[0]["id"]
+ window._edit_profile_machine(machine)
+ settings = app_config.load_settings(self.path)
+ with patch.object(profiles, "no_way_back", return_value=["Studio PC"]) as missing:
+ window._reflect_profiles(settings)
+ missing.assert_called_once_with(settings, machine)
+ self.assertIn("back to MacBook Pro", window.profile_no_return.text())
+ viewed = window._crossing_view_settings()
+ real = {entry["id"]: entry.get("platform") for entry in settings["peers"]}
+ for entry in viewed["peers"]:
+ local = "linux" if sys.platform.startswith("linux") else "windows"
+ self.assertEqual(entry.get("platform"), local if entry["id"] == settings["machine_id"] else real[entry["id"]])
+
+ def test_profile_hint_and_narrow_header_keep_controls_visible(self):
+ self.enable()
+ window = self.window
+ self.assertTrue(window.atlas_canvas_hint.isVisible())
+ self.assertIn("Tab and Return", window.atlas_canvas_hint.text())
+ for button in window.profile_buttons.values():
+ self.assertGreaterEqual(button.minimumWidth(), button.sizeHint().width())
+ window.profile_header.setFixedWidth(280)
+ fixture.settle(window)
+ self.assertEqual(window.profile_header.layout().direction(), QBoxLayout.Direction.TopToBottom)
+ self.assertGreater(window.same_ways_switch.geometry().top(), window.profile_tabs.geometry().bottom())
+ window.profile_header.setFixedWidth(600)
+ fixture.settle(window)
+ self.assertEqual(window.profile_header.layout().direction(), QBoxLayout.Direction.LeftToRight)
+
+ def test_own_override_archive_restore_and_shake(self):
+ self.enable()
+ window = self.window
+ window._profile_event(crossing_state.set_own_ways, True)
+ self.assertTrue(window.profile_use_desk.isVisible())
+ window.profile_use_desk.click()
+ self.assertFalse(app_config.load_settings(self.path)["crossing_own"]["use_own"])
+ saved = profiles.saved_list(app_config.load_settings(self.path))
+ self.assertTrue(saved)
+ window._profile_event(crossing_state.restore_saved, saved[0]["id"])
+ self.assertTrue(app_config.load_settings(self.path)["crossing_own"]["use_own"])
+ window.shake_home_switch.click()
+ self.assertFalse(profiles.shake_on(app_config.load_settings(self.path)))
+
+ def test_invalid_profile_name_and_full_desk_use_page_note(self):
+ self.enable()
+ self.window._profile_event(crossing_state.new_profile, " ")
+ self.assertTrue(self.window.profile_note.text())
+ for index in range(7):
+ self.window._profile_event(crossing_state.new_profile, str(index))
+ self.window._profile_event(crossing_state.new_profile, "Too many")
+ self.assertIn("full", self.window.profile_note.text())
+
+ def test_older_version_note_is_consumed_into_page_memory(self):
+ with patch.object(app_config, "load_notes", return_value=["older_version"]):
+ self.window._reflect_ways()
+ self.window._reflect_ways()
+ self.assertTrue(self.window.profile_load_note.isVisible())
+ self.assertIn("older Beamer", self.window.profile_load_note.text())
+
+ def test_unreadable_settings_leave_a_safe_profile_snapshot(self):
+ with patch.object(self.window, "_config", None), \
+ patch.object(self.window, "_window_settings", side_effect=app_config.SettingsFileError("unreadable")), \
+ patch.object(app_config, "write_settings") as write:
+ snapshot = self.window._profile_settings()
+ self.assertIn("crossing_own", snapshot)
+ self.assertIn("crossing_desk", snapshot)
+ self.assertFalse(profiles.same_ways_on(snapshot))
+ self.assertTrue(profiles.shake_on(snapshot))
+ write.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_profiles_sync_qt.py b/win_app/tests/test_profiles_sync_qt.py
new file mode 100644
index 0000000..25ec6fb
--- /dev/null
+++ b/win_app/tests/test_profiles_sync_qt.py
@@ -0,0 +1,190 @@
+"""Qt app wire paths with synthetic settings and links; no input capture or GUI is started."""
+
+import copy
+from pathlib import Path
+import sys
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import app_config
+from core import crossing_state, profiles, protocol, settings_sync
+from core.tests import responder_harness as h
+
+try:
+ import kvm_bridge_win as kvm
+except ImportError:
+ kvm = None
+
+
[email protected](kvm is None, "needs PySide6 and the Qt app dependencies")
+class ProfilesSyncQtTests(unittest.TestCase):
+ def setUp(self):
+ self.own, self.a, self.b, self.old = [protocol.id_text(peer) for peer in (h.HERE, h.B, h.C, bytes([4]) * 16)]
+ self.settings = app_config.migrate(None, machine_id=self.own)
+ self.settings["peers"] = [h.entry(h.B, "Studio", side="right"), h.entry(h.C, "Laptop", side="left")]
+ self.settings = crossing_state.migrate(self.settings, "pc")["settings"]
+ self.settings, _ = profiles.before_load(self.settings, now=100)
+ self.settings, _ = profiles.after_load(self.settings, platform="pc", now=100)
+ self.config = app_config.config_from_dict(app_config._flat_from_settings(self.settings))
+ self.envelope = dict(on=False, set_at=100, by=self.own, groups=[], values={"shortcut": True},
+ layout={"tiles": {}}, design_sync={"values": {}})
+ self.caps = {h.B: {"settings", "layout", "profiles"}, h.C: {"settings", "layout", "profiles"},
+ bytes([4]) * 16: {"settings", "layout"}}
+ self.app = SimpleNamespace(
+ config_path=Path("synthetic-settings.json"), _config=self.config,
+ _profile_last_heard={}, _peer_caps=lambda: self.caps, _same_state=lambda: self.envelope,
+ _send_to=mock.Mock(return_value=True), _live=lambda peer: True,
+ _own_displays=lambda: {}, _layout_capable=lambda: {self.own, self.a, self.b},
+ _crossing_event_args=lambda: dict(platform="pc", capable={self.own, self.a, self.b},
+ live=lambda peer: True, gone=lambda peer: False, now=101),
+ book=SimpleNamespace(peers=lambda: self.settings["peers"]),
+ )
+ self.app._desk_messages = lambda desk, caps: kvm.WindowsApplication._desk_messages(self.app, desk, caps)
+ self.app._publish_desk = lambda settings=None: kvm.WindowsApplication._publish_desk(self.app, settings)
+ # What linked peers were last told, as after the app's first publish at start.
+ self.app._desk_published = profiles.desk_message(self.settings)
+
+ def test_framed_desk_is_sent_only_to_profiles_peers_and_never_with_layout_or_design(self):
+ outcome = crossing_state.set_same_ways(self.settings, True, platform="pc", now=101)
+ with mock.patch.object(profiles, "MAX_DESK_BYTES", 200):
+ kvm.WindowsApplication._carry_desk(self.app, outcome)
+ calls = self.app._send_to.call_args_list
+ self.assertGreater(len(calls), 2)
+ self.assertEqual({call.args[0] for call in calls}, {h.B, h.C})
+ for call in calls:
+ data = call.args[1]["data"]
+ self.assertIn("desk", data)
+ self.assertNotIn("layout", data)
+ self.assertNotIn("design_sync", data)
+ self.assertNotIn("values", data)
+ self.assertEqual(data["set_at"], self.envelope["set_at"])
+
+ def test_a_change_made_outside_a_crossing_event_still_reaches_linked_peers(self):
+ # App review: a removal (or pairing) changed this machine's status and no event carried it.
+ changed = crossing_state.set_same_ways(self.settings, True, platform="pc", now=101)["settings"]
+ kvm.WindowsApplication._publish_desk(self.app, changed)
+ peers = {call.args[0] for call in self.app._send_to.call_args_list}
+ self.assertEqual(peers, {h.B, h.C}, "profiles peers only")
+ self.app._send_to.reset_mock()
+ kvm.WindowsApplication._publish_desk(self.app, changed)
+ self.app._send_to.assert_not_called()
+
+ def test_unchanged_outcome_forwards_away_from_source_and_answers_source_only(self):
+ full = profiles.desk_message(self.settings)
+ forward = {"on": full["on"]}
+ answer = {"active": full["active"]}
+ outcome = dict(settings=self.settings, send_desk=[], forward=forward, answer=answer)
+ kvm.WindowsApplication._carry_desk(self.app, outcome, source=self.a)
+ sent = {peer: message["data"]["desk"] for peer, message in (call.args for call in self.app._send_to.call_args_list)}
+ self.assertEqual(sent, {h.B: answer, h.C: forward})
+
+ def test_link_up_returns_whole_framed_desk(self):
+ self.app._carry_crossing = mock.Mock()
+ self.app._send_same = mock.Mock()
+ with mock.patch.object(app_config, "load_settings", return_value=copy.deepcopy(self.settings)), \
+ mock.patch.object(profiles, "MAX_DESK_BYTES", 200):
+ messages = kvm.WindowsApplication._announce(self.app, h.B)
+ held = self.app._carry_crossing.call_args.args[0]["settings"]
+ expected = profiles.frames(profiles.desk_message(held))
+ frames = [message["data"]["desk"] for message in messages if "desk" in message.get("data", {})]
+ self.assertEqual(frames, expected)
+ self.assertGreater(len(frames), 1)
+ paths = {path for frame in frames for path, register in profiles._paths(frame)}
+ self.assertEqual(paths, {path for path, register in profiles._paths(profiles.desk_message(held))})
+ self.assertIsInstance(self.app._profile_last_heard[self.a], (int, float))
+
+ def test_received_desk_uses_crossing_event_path_and_marks_current_link_heard(self):
+ self.app._carry_crossing = mock.Mock()
+ self.app._design_states = {}
+ self.app._profile_last_heard[self.a] = 100
+ incoming = settings_sync.desk_message_data(self.envelope, profiles.desk_message(self.settings))
+ outcome = crossing_state.desk_arrived(self.settings, incoming["desk"], source=self.a,
+ platform="pc", linked=True, now=101)
+ with mock.patch.object(app_config, "load_settings", return_value=copy.deepcopy(self.settings)), \
+ mock.patch.object(settings_sync, "arrived", return_value=None), \
+ mock.patch.object(settings_sync, "names_arrived", return_value=({}, None)), \
+ mock.patch.object(settings_sync, "merge", return_value=None), \
+ mock.patch.object(crossing_state, "desk_arrived", return_value=outcome) as arrived:
+ kvm.WindowsApplication._on_settings(self.app, self.a, incoming)
+ self.assertEqual(arrived.call_args.kwargs["source"], self.a)
+ self.assertTrue(arrived.call_args.kwargs["linked"])
+ # What arrives is read first: read_desk_state keeps only stamped registers, so an unset
+ # tombstone ("removed": None) is not passed on.
+ self.assertEqual(arrived.call_args.args[1], profiles.read_desk_state(incoming))
+ self.app._carry_crossing.assert_called_once_with(outcome, source=self.a)
+ self.assertIsNone(self.app._profile_last_heard[self.a])
+
+ def test_shake_notice_uses_local_count_and_stops_after_three(self):
+ settings = copy.deepcopy(self.settings)
+ self.app._label_of = lambda peer: "Studio"
+ self.app._on_alert = mock.Mock()
+ with mock.patch.object(app_config, "load_settings", side_effect=lambda path: copy.deepcopy(settings)), \
+ mock.patch.object(app_config, "write_settings", side_effect=lambda path, saved: settings.update(saved)):
+ for _ in range(5):
+ kvm.WindowsApplication._on_shake(self.app, h.B)
+ self.assertEqual(settings["shake_notices"], 3)
+ self.assertEqual(self.app._on_alert.call_count, 3)
+ self.assertIn("Shook home from Studio.", self.app._on_alert.call_args.args[1])
+
+ def test_startup_configures_shake_before_input_hooks_start(self):
+ events = []
+ self.app._any_send = lambda: True
+ self.app._configure_trigger = lambda config: events.append("trigger")
+ self.app._configure_shake = lambda: events.append("shake")
+ self.app.hooks = SimpleNamespace(start=lambda: events.append("hooks"))
+ self.app.sender = SimpleNamespace(start=lambda config: events.append("sender"))
+ kvm.WindowsApplication._start_sending(self.app, self.config)
+ self.assertEqual(events, ["trigger", "shake", "hooks", "sender"])
+
+ def test_rejected_desk_cannot_change_settings_or_forward_registers(self):
+ settings = copy.deepcopy(self.settings)
+ settings["peers"][0]["allow_drive"] = False
+ outcome = crossing_state.desk_arrived(settings, profiles.desk_message(self.settings),
+ source=self.a, platform="pc", linked=True, now=101)
+ self.assertFalse(outcome["accepted"])
+ self.assertEqual(outcome["reason"], "untrusted")
+ self.assertEqual(outcome["settings"], settings)
+ kvm.WindowsApplication._carry_desk(self.app, outcome, source=self.a)
+ self.app._send_to.assert_not_called()
+
+ def test_shake_settings_reach_sender_without_resetting_an_unchanged_detector(self):
+ self.app.sender = SimpleNamespace(set_shake=mock.Mock())
+ self.app.bridge = SimpleNamespace(shook_home=SimpleNamespace(emit=mock.Mock()))
+ self.app._shake_enabled = None
+ self.app._shake_sensitivity = None
+ kvm.WindowsApplication._configure_shake(self.app, self.settings)
+ kvm.WindowsApplication._configure_shake(self.app, self.settings)
+ self.assertEqual(self.app.sender.set_shake.call_count, 1)
+ self.assertTrue(self.app.sender.set_shake.call_args.args[0])
+ changed = crossing_state.set_shake(self.settings, False, platform="pc", now=102)["settings"]
+ kvm.WindowsApplication._configure_shake(self.app, changed)
+ self.assertEqual(self.app.sender.set_shake.call_count, 2)
+ self.assertFalse(self.app.sender.set_shake.call_args.args[0])
+ self.assertEqual(self.app.sender.set_shake.call_args.kwargs["on_shake"], self.app.bridge.shook_home.emit)
+
+
+class ProfilesLoadNotesTests(unittest.TestCase):
+ def test_older_version_notice_is_exposed_once_without_a_settings_flag(self):
+ with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[1]) as folder:
+ path = Path(folder) / "settings.json"
+ own, peer = protocol.id_text(h.HERE), protocol.id_text(h.B)
+ settings = app_config.migrate(None, machine_id=own)
+ settings["peers"] = [h.entry(h.B, "Studio", side="right")]
+ app_config.write_settings(path, settings)
+ settings = app_config.load_settings(path)
+ settings["peers"][0]["ways"]["edge"] = not settings["peers"][0]["ways"]["edge"]
+ app_config.write_settings(path, settings)
+ loaded = app_config.load_settings(path)
+ self.assertEqual(app_config.load_notes(path), ["older_version"])
+ self.assertEqual(app_config.load_notes(path), [])
+ app_config.load_settings(path)
+ self.assertEqual(app_config.load_notes(path), [])
+ self.assertNotIn("profile_load_notes", loaded)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_profiles_tray_qt.py b/win_app/tests/test_profiles_tray_qt.py
new file mode 100644
index 0000000..28e849c
--- /dev/null
+++ b/win_app/tests/test_profiles_tray_qt.py
@@ -0,0 +1,60 @@
+"""Profile choices in the real Qt tray; run offscreen, without capture or receivers."""
+
+from pathlib import Path
+import sys
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import app_config
+from core import crossing_state, profiles
+from win_app.tests import test_tray_icon as fixture
+
+
[email protected](fixture.kvm_bridge_win is None, "needs PySide6")
+class ProfilesTrayQtTests(unittest.TestCase):
+ setUp = fixture.TrayWindowTest.setUp
+ tearDown = fixture.TrayWindowTest.tearDown
+
+ def test_submenu_stays_hidden_when_settings_cannot_be_read(self):
+ with patch.object(app_config, "load_settings", side_effect=app_config.SettingsFileError("unreadable")):
+ self.window._refresh_tray_profiles()
+ self.assertFalse(self.window.profile_menu.menuAction().isVisible())
+ self.assertEqual(self.window.profile_menu.actions(), [])
+ with patch.object(self.window, "_config", None), patch.object(app_config, "load_settings") as load:
+ self.window._refresh_tray_profiles()
+ load.assert_not_called()
+ self.assertFalse(self.window.profile_menu.menuAction().isVisible())
+
+ def test_submenu_requires_same_ways_and_two_profiles_then_switches(self):
+ menu = self.window.profile_menu
+ self.assertFalse(menu.menuAction().isVisible())
+ settings = app_config.load_settings(self.config)
+ settings = crossing_state.set_same_ways(settings, True, platform="pc", now=100)["settings"]
+ app_config.write_settings(self.config, settings)
+ self.window._refresh_tray_profiles(settings)
+ self.assertFalse(menu.menuAction().isVisible())
+ settings = crossing_state.new_profile(settings, "Sofa", platform="pc", now=101)["settings"]
+ app_config.write_settings(self.config, settings)
+ self.window._refresh_tray_profiles(settings)
+ self.assertTrue(menu.menuAction().isVisible())
+ actions = {action.text(): action for action in menu.actions()}
+ self.assertEqual(set(actions), {"Desk", "Sofa"})
+ self.assertEqual(sum(action.isChecked() for action in actions.values()), 1)
+ target = next(item["id"] for item in profiles.profile_list(settings) if item["name"] == "Sofa")
+ if settings["crossing_desk"]["active"]["value"] == target:
+ target = profiles.DESK_ID
+ actions["Desk"].trigger()
+ else:
+ actions["Sofa"].trigger()
+ saved = app_config.load_settings(self.config)
+ self.assertEqual(saved["crossing_desk"]["active"]["value"], target)
+ self.assertEqual(sum(action.isChecked() for action in menu.actions()), 1)
+ saved = crossing_state.set_same_ways(saved, False, platform="pc", now=102)["settings"]
+ self.window._refresh_tray_profiles(saved)
+ self.assertFalse(menu.menuAction().isVisible())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_quit_signals.py b/win_app/tests/test_quit_signals.py
new file mode 100644
index 0000000..7c0d608
--- /dev/null
+++ b/win_app/tests/test_quit_signals.py
@@ -0,0 +1,47 @@
+"""SIGTERM and SIGINT reach the app's quit() through the Qt event loop, once, and closing puts the
+previous handlers back."""
+import os
+import signal
+import unittest
+
+try:
+ from PySide6.QtCore import QCoreApplication, QTimer
+ import quit_signals
+except ImportError: # PySide6 is only in the Windows venv and the Flatpak
+ quit_signals = None
+
+
[email protected](quit_signals is None, "needs PySide6")
+class QuitSignalsTests(unittest.TestCase):
+ def setUp(self):
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QCoreApplication.instance() or QCoreApplication([])
+ self.calls = []
+ self.handler = quit_signals.QuitSignals(lambda: (self.calls.append("quit"), self.app.quit()))
+ self.addCleanup(self.handler.close)
+
+ def run_loop_after(self, raise_it):
+ # raise_signal runs the handler in this process on every OS; os.kill on Windows would end it.
+ QTimer.singleShot(0, raise_it)
+ QTimer.singleShot(2000, self.app.quit)
+ self.app.exec()
+
+ def test_sigterm_quits_through_the_event_loop(self):
+ self.run_loop_after(lambda: signal.raise_signal(signal.SIGTERM))
+ self.assertEqual(self.calls, ["quit"])
+
+ def test_sigint_quits_and_a_second_signal_does_not_quit_twice(self):
+ def twice():
+ signal.raise_signal(signal.SIGINT)
+ signal.raise_signal(signal.SIGINT)
+ self.run_loop_after(twice)
+ self.assertEqual(self.calls, ["quit"])
+
+ def test_close_restores_the_previous_handlers(self):
+ self.handler.close()
+ self.handler.close()
+ self.assertIs(signal.getsignal(signal.SIGINT), signal.default_int_handler)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_sender_shake.py b/win_app/tests/test_sender_shake.py
new file mode 100644
index 0000000..3d6c695
--- /dev/null
+++ b/win_app/tests/test_sender_shake.py
@@ -0,0 +1,226 @@
+import unittest
+from unittest import mock
+from types import SimpleNamespace
+
+from core.tests.test_shake import qualifying_strokes, trace
+from core.shake import STROKE_WINDOWS, STROKE_X11, STROKE_WAYLAND
+from core.return_edge import Rect
+
+import sender
+import capture_portal
+import desktop_portal
+
+
+PEER = b"peer-peer-peer-01"
+
+
+def qualifying_windows_trace(start=0.31):
+ strokes = qualifying_strokes(length=STROKE_WINDOWS * 1.25)
+ strokes.append((1, STROKE_WINDOWS * 0.25 + 0.001, 0.02))
+ return trace(strokes, start=start)
+
+
+class Clock:
+ def __init__(self):
+ self.now = 0.0
+
+ def __call__(self):
+ return self.now
+
+
+class Owner:
+ def __init__(self):
+ self.away = True
+ self.on = PEER
+ self.homes = 0
+
+ def go(self, peer):
+ if peer is None and self.away:
+ self.away = False
+ self.on = None
+ self.homes += 1
+ return []
+
+
+class ShakeSenderTests(unittest.TestCase):
+ def setUp(self):
+ self.clock = Clock()
+ self.sender = sender.LinkSender.__new__(sender.LinkSender)
+ self.sender._clock = self.clock
+ self.sender._owner = Owner()
+ self.sender._reported_redirecting = False
+ self.sender._redirect_callback = None
+ self.sender._lock = __import__("threading").RLock()
+ self.sender._buttons_held = set()
+ self.sender._shake_home_pending = False
+ self.sender._shake_detector = None
+ self.sender._keys_down = {}
+ self.sender._peers = {}
+ self.sender._intent_windows_up = set()
+ self.sender._intent_keys_up = set()
+ self.sender._pending_windows_key = None
+ self.sender._ignore_gate = sender.ignored.Gate()
+ self.sender._config_lock = __import__("threading").RLock()
+ self.sender._config = None
+ self.sender._input_messages = []
+ self.sender._input = lambda message: self.sender._input_messages.append(message) or True
+ self.sender._queue = lambda actions: None
+ self.sender._report = lambda actions: None
+ self.sender.links = type("Links", (), {"live": lambda _self, _peer: True})()
+ self.edge_calls = []
+ self.sender._press_edge = lambda dx, dy: self.edge_calls.append((dx, dy))
+
+ def arm_away(self, on_shake=None):
+ self.sender.set_shake(True, STROKE_WINDOWS, on_shake)
+ self.sender._report_redirecting(True)
+
+ def test_sensitivity_change_preserves_existing_refractory_period(self):
+ self.arm_away()
+ self.feed(qualifying_windows_trace())
+ detector = self.sender._shake_detector
+ cooldown = detector._cooldown_until
+ self.sender.set_shake(True, STROKE_WINDOWS / 2)
+ self.assertIs(self.sender._shake_detector, detector)
+ self.assertEqual(detector._cooldown_until, cooldown)
+
+ def feed(self, events):
+ for t, dx, dy in events:
+ self.clock.now = t
+ self.sender.on_motion(dx, dy)
+
+ def test_qualifying_shake_returns_home_once_notifies_peer_and_drops_triggering_motion(self):
+ notices = []
+ self.arm_away(notices.append)
+ events = qualifying_windows_trace()
+
+ self.feed(events)
+
+ self.assertEqual(self.sender._owner.homes, 1)
+ self.assertEqual(notices, [PEER])
+ self.assertEqual(len(self.sender._input_messages), len(events) - 1)
+ self.assertEqual(self.sender._input_messages[-1]["data"],
+ {"dx": int(events[-2][1]), "dy": int(events[-2][2])})
+
+ def test_disabled_shake_never_returns_home(self):
+ self.sender.set_shake(False, STROKE_WINDOWS)
+ self.sender._report_redirecting(True)
+
+ self.feed(qualifying_windows_trace())
+
+ self.assertEqual(self.sender._owner.homes, 0)
+
+ def test_enabling_shake_while_away_arms_it(self):
+ notices = []
+ self.sender.set_shake(True, STROKE_WINDOWS, notices.append)
+
+ self.feed(qualifying_windows_trace())
+
+ self.assertEqual(self.sender._owner.homes, 1)
+ self.assertEqual(notices, [PEER])
+
+ def test_arm_respects_a_button_already_held_when_input_leaves(self):
+ self.sender._buttons_held.add("left")
+ self.arm_away()
+
+ self.feed(qualifying_windows_trace())
+
+ self.assertEqual(self.sender._owner.homes, 0)
+
+ def test_button_or_key_held_and_recent_scroll_reset_the_shake(self):
+ for kind in ("button", "key", "scroll"):
+ with self.subTest(kind=kind):
+ self.setUp()
+ self.arm_away()
+ events = qualifying_windows_trace()
+ if kind == "button":
+ self.sender.on_button("left", True)
+ elif kind == "key":
+ self.sender.on_key("a", True, 0x41)
+ else:
+ self.clock.now = 0.30
+ self.sender.on_wheel(1, 0)
+ self.feed(events)
+ self.assertEqual(self.sender._owner.homes, 0)
+
+ def test_motion_in_the_first_300_ms_after_leaving_does_not_count(self):
+ self.arm_away()
+ events = qualifying_windows_trace(start=0.20)
+
+ self.feed(events)
+
+ self.assertEqual(self.sender._owner.homes, 0)
+
+ def test_home_edge_is_held_for_200_ms_after_shake_motion_then_resumes(self):
+ self.arm_away()
+ events = qualifying_windows_trace()
+ self.feed(events)
+ self.assertEqual(self.sender._owner.homes, 1)
+
+ self.clock.now = events[-1][0] + 0.199
+ self.sender.on_motion(4, 0)
+ self.assertEqual(self.edge_calls, [])
+ self.clock.now += 0.201
+ self.sender.on_motion(4, 0)
+ self.assertEqual(self.edge_calls, [(4, 0)])
+
+ def test_home_edge_is_not_held_without_a_shake(self):
+ self.sender.set_shake(True, STROKE_WINDOWS)
+ self.sender._report_redirecting(False)
+ self.sender._owner.away = False
+
+ self.sender.on_motion(4, 0)
+
+ self.assertEqual(self.edge_calls, [(4, 0)])
+
+ def test_capture_backend_selects_its_stroke_length(self):
+ self.sender.set_shake(False, STROKE_WINDOWS)
+ from shake_stroke import shake_stroke
+
+ self.assertEqual(shake_stroke("capture_win"), STROKE_WINDOWS)
+ self.assertEqual(shake_stroke("capture_x11"), STROKE_X11)
+ self.assertEqual(shake_stroke("capture_portal"), STROKE_WAYLAND)
+ self.assertEqual(shake_stroke("capture_win", 200), STROKE_WINDOWS / 2)
+
+ def test_wayland_shake_release_moves_inward_and_skips_landing_wait(self):
+ hooks = capture_portal.Hooks(None, None, self.sender.on_motion, clock=self.clock)
+ hooks._activation = 7
+ hooks._session = SimpleNamespace()
+ hooks._predicate = lambda: False
+ hooks._zones = [Rect(0, 0, 1920, 1080)]
+ hooks._placed = [("right", (1920, 0, 1920, 1079))]
+ hooks._last_wall = "right"
+ released = []
+ hooks._let_go = released.append
+ self.sender._shake_home_pending = True
+
+ with mock.patch.object(desktop_portal, "cursor_position", return_value=(1920, 500)):
+ hooks._tick()
+
+ self.assertEqual(released, [(1896, 500)])
+ self.assertFalse(self.sender._shake_home_pending)
+
+ def test_wayland_non_shake_release_keeps_landing_wait_and_original_point(self):
+ hooks = capture_portal.Hooks(None, None, self.sender.on_motion, clock=self.clock)
+ hooks._activation = 7
+ hooks._session = SimpleNamespace()
+ hooks._predicate = lambda: False
+ hooks._zones = [Rect(0, 0, 1920, 1080)]
+ hooks._placed = [("right", (1920, 0, 1920, 1079))]
+ hooks._last_wall = "right"
+ released = []
+ hooks._let_go = released.append
+ self.clock.now = 1.0
+
+ with mock.patch.object(desktop_portal, "cursor_position", return_value=(1920, 500)):
+ hooks._tick()
+ self.clock.now += capture_portal.LANDING_SECONDS - 0.001
+ hooks._tick()
+ self.assertEqual(released, [])
+ self.clock.now += 0.002
+ hooks._tick()
+
+ self.assertEqual(released, [(1920, 500)])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_single_instance.py b/win_app/tests/test_single_instance.py
index 793330c..1c7c72b 100644
--- a/win_app/tests/test_single_instance.py
+++ b/win_app/tests/test_single_instance.py
@@ -23,6 +23,58 @@ class SingleInstanceTests(unittest.TestCase):
self.assertFalse(kvm_bridge_win.activate_existing_instance(hidden=True))
activate.assert_not_called()
+ def test_relaunched_instance_waits_until_the_holder_releases_the_lock(self):
+ now = [0.0]
+ holder = [True]
+
+ def claim():
+ return None if holder[0] else lambda: None
+
+ def sleep(duration):
+ now[0] += duration
+ if now[0] >= 0.2:
+ holder[0] = False
+
+ release = kvm_bridge_win._claim_instance_waiting(
+ 1, claim=claim, sleep=sleep, clock=lambda: now[0]
+ )
+ self.assertIsNotNone(release)
+
+ def test_relaunched_instance_gives_up_after_the_wait_window(self):
+ now = [0.0]
+ claims = []
+
+ def claim():
+ claims.append(now[0])
+ return None
+
+ def sleep(duration):
+ now[0] += duration
+
+ release = kvm_bridge_win._claim_instance_waiting(
+ 0.25, claim=claim, sleep=sleep, clock=lambda: now[0]
+ )
+ self.assertIsNone(release)
+ self.assertAlmostEqual(now[0], 0.25)
+ self.assertEqual(len(claims), 4)
+
+ def test_relaunch_marks_replacement_and_quits_through_application(self):
+ class SettingsPage:
+ relaunch = kvm_bridge_win.WindowsApplication.relaunch
+
+ def __init__(self):
+ self.quit = mock.Mock()
+
+ page = SettingsPage()
+ with mock.patch.object(sys, "argv", ["beamer.exe", "--hidden", "--relaunched"]), \
+ mock.patch.object(sys, "frozen", True, create=True), \
+ mock.patch.object(kvm_bridge_win.QProcess, "startDetached", return_value=(True, 123)) as start, \
+ mock.patch.object(kvm_bridge_win.QApplication, "quit") as app_quit:
+ page.relaunch()
+ start.assert_called_once_with(sys.executable, ["--hidden", "--relaunched"])
+ page.quit.assert_called_once_with()
+ app_quit.assert_not_called()
+
@unittest.skipUnless(sys.platform == 'win32', 'Windows receiver mutex')
def test_two_logon_tasks_cannot_claim_two_receivers(self):
import ctypes
@@ -61,7 +113,7 @@ class SingleInstanceTests(unittest.TestCase):
def test_startup_migrates_the_legacy_task_before_single_instance_handling(self):
order = []
- with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True})()), \
+ with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True, "relaunched": False})()), \
mock.patch.object(kvm_bridge_win, "prepare_windows_startup", side_effect=lambda: order.append("migrate")), \
mock.patch.object(kvm_bridge_win, "_claim_instance", side_effect=lambda: order.append("claim") or None), \
mock.patch.object(kvm_bridge_win, "activate_existing_instance") as activate:
@@ -70,7 +122,7 @@ class SingleInstanceTests(unittest.TestCase):
activate.assert_called_once_with(True, mock.ANY)
def test_failed_migration_still_reaches_instance_handling(self):
- with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True})()), \
+ with mock.patch.object(kvm_bridge_win, "parse_args", return_value=type("Args", (), {"hidden": True, "relaunched": False})()), \
mock.patch.object(kvm_bridge_win, "prepare_windows_startup", side_effect=OSError("Access is denied")), \
mock.patch.object(kvm_bridge_win, "_claim_instance", return_value=None) as claim, \
mock.patch.object(kvm_bridge_win, "activate_existing_instance"), \
diff --git a/win_app/tests/test_tile_resize_qt.py b/win_app/tests/test_tile_resize_qt.py
new file mode 100644
index 0000000..d0051f4
--- /dev/null
+++ b/win_app/tests/test_tile_resize_qt.py
@@ -0,0 +1,300 @@
+"""Manual tile resize gestures; written for Qt, never run by the edits-only task."""
+
+import copy
+import os
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+
+class TileResizeQtTests(unittest.TestCase):
+ def setUp(self):
+ from PySide6.QtWidgets import QApplication
+ from diagram import AtlasCanvas
+
+ self.app = QApplication.instance() or QApplication([])
+ self.drops = mock.Mock(return_value=True)
+ self.canvas = AtlasCanvas(on_drop=self.drops)
+ self.addCleanup(self.canvas.deleteLater)
+ self.canvas.resize(240, 268)
+ self.canvas.on_announce = mock.Mock()
+ self.canvas.on_leave_out = mock.Mock()
+ self.canvas.set_tiles(
+ {"home": {"x": 0, "y": 0, "w": 160, "h": 100},
+ "peer": {"x": 160, "y": 0, "w": 160, "h": 100}},
+ {"home": "This PC", "peer": "Studio PC with a very long name"},
+ {}, "peer", own_id="home")
+
+ def mouse_event(self, kind, point):
+ from PySide6.QtCore import QEvent, Qt
+ from PySide6.QtGui import QMouseEvent
+
+ return QMouseEvent(getattr(QEvent.Type, kind), point, point,
+ Qt.MouseButton.NoButton if kind == "MouseMove" else Qt.MouseButton.LeftButton,
+ Qt.MouseButton.LeftButton if kind != "MouseButtonRelease" else Qt.MouseButton.NoButton,
+ Qt.KeyboardModifier.NoModifier)
+
+ def drag(self, dx, dy, peer="peer"):
+ from PySide6.QtCore import QPointF
+
+ canvas = self.canvas
+ start = canvas._resize_grip_rect(peer).center()
+ end = start + QPointF(dx, dy)
+ canvas.mousePressEvent(self.mouse_event("MouseButtonPress", start))
+ canvas.mouseMoveEvent(self.mouse_event("MouseMove", end))
+ self.drops.assert_not_called()
+ canvas.mouseReleaseEvent(self.mouse_event("MouseButtonRelease", end))
+
+ def test_grip_drag_uses_map_scale_keeps_aspect_and_commits_one_drop(self):
+ from PySide6.QtCore import Qt
+ from core import ways
+
+ canvas = self.canvas
+ before = copy.deepcopy(canvas.tiles)
+ scale = canvas._scale
+ self.assertLess(scale, 1)
+ with mock.patch.object(ways, "resize_from_drag", wraps=ways.resize_from_drag) as resize:
+ self.drag(32 * scale, 20 * scale)
+ resize.assert_called_once()
+ source, dx, dy = resize.call_args.args
+ self.assertEqual(source, before["peer"])
+ self.assertAlmostEqual(dx, 32)
+ self.assertAlmostEqual(dy, 20)
+ self.drops.assert_called_once()
+ tiles, peer = self.drops.call_args.args
+ self.assertEqual(peer, "peer")
+ self.assertEqual(tiles[peer], {"x": 160, "y": 0, "w": 192, "h": 120})
+ self.assertEqual(tiles["home"], before["home"])
+ self.assertEqual(tiles[peer]["w"] / tiles[peer]["h"], 1.6)
+ canvas.on_announce.assert_called_once_with("Studio PC with a very long name resized.")
+ self.assertEqual(canvas.cursor().shape(), Qt.CursorShape.ArrowCursor)
+
+ def test_drag_clamps_at_both_limits(self):
+ from core import ways
+
+ for delta, limit in ((-10000, ways.RESIZE_MIN), (10000, ways.RESIZE_MAX)):
+ with self.subTest(limit=limit):
+ self.drops.reset_mock()
+ self.drag(delta, delta)
+ self.drops.assert_called_once()
+ tile = self.drops.call_args.args[0]["peer"]
+ self.assertEqual(max(tile["w"], tile["h"]), limit)
+ self.assertEqual(tile["w"] / tile["h"], 1.6)
+ self.canvas.on_leave_out.assert_not_called()
+
+ def test_drag_resizes_display_offsets_without_mutating_the_start_tile(self):
+ canvas = self.canvas
+ canvas.tiles["peer"].update(
+ displays={"main": {"x": 0, "y": 0, "w": 160, "h": 100}},
+ display_offsets={"main": {"x": -16, "y": -8}})
+ canvas._geometry()
+ before = copy.deepcopy(canvas.tiles["peer"])
+ self.drag(80 * canvas._scale, 50 * canvas._scale)
+ tile = self.drops.call_args.args[0]["peer"]
+ self.assertEqual((tile["w"], tile["h"]), (240, 150))
+ self.assertEqual(tile["display_offsets"], {"main": {"x": -24, "y": -12}})
+ self.assertEqual(tile["displays"], before["displays"])
+ self.assertEqual(canvas._tile_start, before)
+
+ def test_resize_freezes_geometry_and_does_not_show_a_move_snap_preview(self):
+ from PySide6.QtCore import QPointF, Qt
+
+ canvas = self.canvas
+ start = canvas._resize_grip_rect("peer").center()
+ geometry = (canvas._scale, canvas.tile_rect("home"))
+ canvas.mousePressEvent(self.mouse_event("MouseButtonPress", start))
+ canvas.mouseMoveEvent(self.mouse_event("MouseMove", start + QPointF(10, 10)))
+ self.assertEqual((canvas._scale, canvas.tile_rect("home")), geometry)
+ self.assertIsNone(canvas.snap_preview())
+ self.assertEqual(canvas.cursor().shape(), Qt.CursorShape.SizeFDiagCursor)
+ self.drops.assert_not_called()
+
+ def test_grip_is_visible_for_selection_or_hover_and_clears_on_leave(self):
+ from PySide6.QtCore import QEvent, Qt
+
+ canvas = self.canvas
+ canvas.selected = "home"
+ self.assertIsNone(canvas._resize_grip_rect("peer"))
+ event = self.mouse_event("MouseMove", canvas.tile_rect("peer").center())
+ canvas.mouseMoveEvent(event)
+ grip = canvas._resize_grip_rect("peer")
+ self.assertIsNotNone(grip)
+ canvas.mouseMoveEvent(self.mouse_event("MouseMove", grip.center()))
+ self.assertEqual(canvas.cursor().shape(), Qt.CursorShape.SizeFDiagCursor)
+ canvas.leaveEvent(QEvent(QEvent.Type.Leave))
+ self.assertIsNone(canvas._resize_grip_rect("peer"))
+
+ def test_no_grip_or_keyboard_resize_when_read_only_or_shelved(self):
+ canvas = self.canvas
+ for restriction in ("read_only", "left_out", "not_in_use", "dormant"):
+ with self.subTest(restriction=restriction):
+ canvas.read_only = restriction == "read_only"
+ canvas.set_left_out({"peer"} if restriction == "left_out" else set(),
+ {"peer": False} if restriction == "not_in_use" else {},
+ {"peer"} if restriction == "dormant" else set())
+ before = copy.deepcopy(canvas.tiles)
+ self.assertIsNone(canvas._resize_grip_rect("peer"))
+ self.key("Right")
+ self.assertEqual(canvas.tiles, before)
+ self.drops.assert_not_called()
+
+ def test_machine_grip_does_not_cover_another_machines_split_display(self):
+ canvas = self.canvas
+ canvas.tiles["home"].update(
+ displays={"main": {"x": 0, "y": 0, "w": 160, "h": 100}},
+ display_offsets={"main": {"x": 160, "y": 0}})
+ canvas._geometry()
+ self.assertIsNone(canvas._resize_grip_rect("peer"))
+ split = canvas.display_rect("home", "main")
+ self.assertIsNone(canvas._resize_at(split.bottomRight()))
+
+ def key(self, direction, alt=True):
+ from PySide6.QtCore import QEvent, Qt
+ from PySide6.QtGui import QKeyEvent
+
+ self.canvas.keyPressEvent(QKeyEvent(
+ QEvent.Type.KeyPress, getattr(Qt.Key, "Key_" + direction),
+ Qt.KeyboardModifier.AltModifier if alt else Qt.KeyboardModifier.NoModifier))
+
+ def test_alt_arrows_resize_by_an_eighth_and_leave_position_unchanged(self):
+ from core import ways
+
+ for direction, sign in (("Right", 1), ("Down", 1), ("Left", -1), ("Up", -1)):
+ with self.subTest(direction=direction):
+ before = copy.deepcopy(self.canvas.tiles["peer"])
+ long_side = max(before["w"], before["h"])
+ self.drops.reset_mock()
+ with mock.patch.object(ways, "resize_tile", wraps=ways.resize_tile) as resize:
+ self.key(direction)
+ resize.assert_called_once_with(before, long_side + sign * long_side / 8)
+ self.drops.assert_called_once()
+ tile = self.drops.call_args.args[0]["peer"]
+ self.assertEqual((tile["x"], tile["y"]), (before["x"], before["y"]))
+ self.assertEqual(tile, ways.resize_tile(before, long_side + sign * long_side / 8))
+
+ def test_own_tile_can_resize_but_plain_arrows_do_not_move_it(self):
+ self.canvas.selected = "home"
+ self.key("Left")
+ self.drops.assert_called_once()
+ self.assertEqual(self.drops.call_args.args[0]["home"], {"x": 0, "y": 0, "w": 140, "h": 88})
+ self.drops.reset_mock()
+ self.key("Right", alt=False)
+ self.drops.assert_not_called()
+ self.drag(14 * self.canvas._scale, 0, peer="home")
+ self.drops.assert_called_once()
+
+ def test_profile_resize_is_not_a_profile_click_even_with_a_short_drag(self):
+ self.canvas.profile_mode = True
+ self.canvas.on_edit_machine = mock.Mock()
+ self.drag(1, 1)
+ self.drops.assert_called_once()
+ self.canvas.on_edit_machine.assert_not_called()
+
+ def test_small_tile_resize_grip_does_not_steal_the_cycle_tick(self):
+ canvas = self.canvas
+ canvas.cycle_mode = "ticked"
+ canvas.on_cycle = mock.Mock()
+ canvas.resize(480, 268)
+ for height in (44, 50, 40):
+ with self.subTest(height=height):
+ canvas.tiles["peer"].update(w=100, h=height)
+ canvas._geometry()
+ rect = canvas.tile_rect("peer")
+ grip = canvas._resize_grip_rect("peer")
+ box = canvas._cycle_box(rect)
+ self.assertFalse(grip.intersects(box))
+ point = box.center()
+ canvas.mousePressEvent(self.mouse_event("MouseButtonPress", point))
+ self.assertIsNone(canvas._drag)
+ self.assertFalse(canvas._resizing)
+ self.assertEqual(canvas.on_cycle.call_count, 3)
+ self.drops.assert_not_called()
+
+ def test_rejected_resize_is_not_announced_as_success(self):
+ self.drops.return_value = False
+ self.key("Right")
+ self.drops.assert_called_once()
+ self.canvas.on_announce.assert_not_called()
+
+ def test_small_tile_keeps_full_name_in_tooltip_and_accessible_description(self):
+ from PySide6.QtGui import QFontMetrics
+ import theme
+ import tokens
+
+ self.drag(-10000, -10000)
+ canvas = self.canvas
+ name = canvas.labels["peer"]
+ title = canvas._title_rect("peer", canvas.tile_rect("peer"))
+ self.assertLess(title.width(), QFontMetrics(theme.font(tokens.TYPE["body"], 650)).horizontalAdvance(name))
+ canvas.mouseMoveEvent(self.mouse_event("MouseMove", canvas.tile_rect("peer").center()))
+ self.assertEqual(canvas.toolTip(), name)
+ self.assertIn(name, canvas.accessibleDescription())
+ self.assertIn("size can be changed", canvas.accessibleDescription())
+
+
+class TileResizePageQtTests(unittest.TestCase):
+ def setUp(self):
+ import test_crossing_page_parity as fixture
+
+ fixture.CrossingPageParityTests.setUp(self)
+
+ def _open_window(self):
+ import test_crossing_page_parity as fixture
+
+ fixture.CrossingPageParityTests._open_window(self)
+
+ def tearDown(self):
+ import test_crossing_page_parity as fixture
+
+ fixture.CrossingPageParityTests._close_window(self)
+
+ def _stop_patches(self):
+ import test_crossing_page_parity as fixture
+
+ fixture.CrossingPageParityTests._stop_patches(self)
+
+ def test_off_hint_adds_resize_and_profiles_on_hint_stays_the_same(self):
+ from core import crossing_state
+
+ window = self.window
+ self.assertEqual(window.atlas_canvas_hint.text(),
+ "Alt-click a display to split or group · drag to move · click a third of a lit edge to leave it out · drag a corner to resize")
+ window._design_peer_caps = lambda: {entry["id"]: {"layout", "profiles"} for entry in self.peers}
+ window._profile_event(crossing_state.set_same_ways, True)
+ self.assertEqual(window.atlas_canvas_hint.text(),
+ "Click a machine to set its ways · Tab and Return pick one from the keyboard")
+
+ def test_own_resize_reaches_the_existing_crossing_drop_handler(self):
+ import app_config
+ from core import crossing_state, ways
+
+ window = self.window
+ own = window._config.machine_id
+ tiles = copy.deepcopy(window.atlas_canvas.tiles)
+ tiles[own] = ways.resize_tile(tiles[own], max(tiles[own]["w"], tiles[own]["h"]) * 7 / 8)
+ with mock.patch.object(crossing_state, "drop", wraps=crossing_state.drop) as drop:
+ self.assertTrue(window._layout_dropped(tiles, own))
+ drop.assert_called_once()
+ self.assertEqual(drop.call_args.args[1][own], tiles[own])
+ self.assertEqual(app_config.load_settings(self.path)["layout"][own], tiles[own])
+
+ def test_own_move_is_still_rejected_by_the_existing_drop_handler(self):
+ import app_config
+ from core import crossing_state
+
+ before = app_config.load_settings(self.path)
+ own = self.window._config.machine_id
+ tiles = copy.deepcopy(self.window.atlas_canvas.tiles)
+ tiles[own]["x"] += 20
+ with mock.patch.object(crossing_state, "drop", wraps=crossing_state.drop) as drop:
+ self.assertFalse(self.window._layout_dropped(tiles, own))
+ drop.assert_not_called()
+ self.assertEqual(app_config.load_settings(self.path), before)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/theme.py b/win_app/theme.py
index 45e33d9..a7a37e7 100644
--- a/win_app/theme.py
+++ b/win_app/theme.py
@@ -228,6 +228,8 @@ QLabel[vernier="note-amber"] {{ color: {amber}; font-size: {note}px; }}
QLabel[vernier="note-fault"] {{ color: {fault}; font-size: {note}px; }}
QLabel[vernier="note-live"] {{ color: {signal}; font-size: {note}px; }}
QLabel[vernier="note-quiet"] {{ color: {ink_3}; font-size: {note}px; }}
+QLabel[profile_warning="true"] {{ border: 1px solid {rule}; padding: 8px; }}
+QLabel[profile_heading="true"] {{ font-weight: 600; }}
QLabel[vernier="key"] {{ color: {ink_2}; font-size: {note}px; }}
QLabel[vernier="mono"] {{ color: {ink_2}; font-family: "{mono}"; font-size: {note}px; }}
QLabel[vernier="readout"] {{ color: {ink}; font-family: "{sans}"; font-size: {note}px; font-weight: 700; }}
@@ -257,6 +259,9 @@ QPushButton[vernier="live"] {{ background: {signal}; border-color: {signal}; col
QPushButton[vernier="live"][keyboard_ring="true"]:focus {{ border: 2px solid {ink}; }}
QPushButton[vernier="small"] {{ font-size: {small}px; padding: 4px 10px; }}
QPushButton[vernier="small"][keyboard_ring="true"]:focus {{ padding: 3px 9px; }}
+QPushButton[flat="true"][vernier="small"] {{ background: transparent; border: 0; padding: 4px 2px; min-width: 0; color: {ink_2}; font-weight: 400; }}
+QPushButton[flat="true"][vernier="small"]:disabled {{ color: {ink_3}; }}
+QPushButton[flat="true"][vernier="small"][keyboard_ring="true"]:focus {{ border: 1px solid {signal}; padding: 3px 1px; }}
QPushButton[vernier="choice"] {{ color: {ink_2}; font-size: {small}px; font-weight: 400; padding: 4px 8px; }}
QPushButton[vernier="choice"]:checked {{ background: {selected_bg}; border-color: {selected_bg}; color: {selected_ink}; font-weight: 600; }}
QPushButton[vernier="choice"][keyboard_ring="true"]:focus {{ padding: 3px 7px; }}
diff --git a/win_app/widgets.py b/win_app/widgets.py
index f69f814..cdd0a57 100644
--- a/win_app/widgets.py
+++ b/win_app/widgets.py
@@ -39,6 +39,7 @@ import motion
import theme
import tokens
from core.locale import americanise
+from core.i18n import N_, tr
from core import ways as core_ways
LEFT_CTRL_VK = 0xA2
@@ -418,6 +419,10 @@ class ActionButton(QPushButton):
"""An intrinsic action whose full label remains readable in a narrow column."""
def __init__(self, text="", parent=None):
+ if isinstance(text, QWidget) and parent is None:
+ parent, text = text, ""
+ if text is None:
+ text = ""
super().__init__(text, parent)
self.setMaximumWidth(240)
self.setMinimumHeight(30)
@@ -724,7 +729,9 @@ class Choice:
exclusive=True) -> None:
self.view = _SegmentedView(parent)
self._buttons: dict = {}
+ self._names: dict = {}
for index, (value, text) in enumerate(items):
+ self._names[value] = text
button = ActionButton(text, self.view)
button.setMaximumWidth(16777215)
button.setProperty("vernier", "choice")
@@ -766,8 +773,9 @@ class Choice:
def set_names(self, prefix: str) -> None:
"""Each cell's accessible name leads with what the row chooses: "Where your Mac is, Left"."""
- for button in self._buttons.values():
- button.setAccessibleName(f"{prefix}, {button.text()}")
+ for value, button in self._buttons.items():
+ button.setAccessibleName(tr("{name}, {choice}").format(
+ name=prefix, choice=button.text()))
class _TileOutline(QWidget):
@@ -941,7 +949,7 @@ class ChoiceTiles:
tile.name_label.setIndent(_TileOutline.CHECK_ROOM if candidate == value else 0)
tile.outline.update()
title = self._titles[candidate]
- tile.setAccessibleName(f"{title}, selected" if candidate == value else title)
+ tile.setAccessibleName(tr("{name}, selected").format(name=title) if candidate == value else title)
def tile(self, value):
return self._tiles.get(value)
@@ -1242,8 +1250,8 @@ class InputRecorder(ActionButton):
("key", virtual key) or ("button", name) pair, and a left click anywhere disarms it. The key is
read as the low-level hook will report it, so what is recorded is what the hook matches."""
- HINT = "Click, then press it"
- RECORDING_HINT = "Click again to cancel"
+ HINT = N_("Click, then press it")
+ RECORDING_HINT = N_("Click again to cancel")
BUTTONS = {
Qt.MouseButton.RightButton: "right",
Qt.MouseButton.MiddleButton: "middle",
@@ -1252,7 +1260,8 @@ class InputRecorder(ActionButton):
}
def __init__(self, title: str, on_record, hook_vk, parent: QWidget | None = None, keys_only: bool = False,
- name: str = "", mono: bool = True) -> None:
+ name: str = "", mono: bool = True, hint: str = HINT,
+ recording_hint: str = RECORDING_HINT) -> None:
super().__init__(parent)
# What the recorder is, before what it shows: "Shortcut key, Right Ctrl".
self.name = name
@@ -1277,7 +1286,9 @@ class InputRecorder(ActionButton):
row.setSpacing(10)
self.key = label(title, "keycap", wrap=True)
self.key.setFont(theme.mono_font(tokens.TYPE["field_mono"]) if mono else theme.font(tokens.TYPE["body"]))
- self.hint = label(self.HINT, "small", wrap=True)
+ self.hint = label(hint, "small", wrap=True)
+ self.hint_text = hint
+ self.recording_hint = recording_hint
for part in (self.key, self.hint):
part.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
row.addWidget(self.key, 1)
@@ -1303,7 +1314,7 @@ class InputRecorder(ActionButton):
self.key.setText(title)
def _spoken(self, title: str) -> str:
- return f"{self.name}, {title}" if self.name else title
+ return tr("{name}, {key}").format(name=self.name, key=title) if self.name else title
def cancel(self) -> None:
self.left_ctrl_held = False
@@ -1313,7 +1324,7 @@ class InputRecorder(ActionButton):
QApplication.instance().removeEventFilter(self)
self.key.setText(self.title)
set_role(self.key, "keycap")
- self.hint.setText(self.HINT)
+ self.hint.setText(self.hint_text)
set_role(self, "keycap")
def _toggle(self) -> None:
@@ -1321,9 +1332,9 @@ class InputRecorder(ActionButton):
self.cancel()
return
self.armed = True
- self.key.setText("Press a key or button…")
+ self.key.setText(tr("Press a key or button…"))
set_role(self.key, "keycap-live")
- self.hint.setText(self.RECORDING_HINT)
+ self.hint.setText(self.recording_hint)
set_role(self, "keycap-live")
QApplication.instance().installEventFilter(self)
@@ -1381,8 +1392,8 @@ class JumpKeyRecorder(ActionButton):
row = QVBoxLayout(self)
row.setContentsMargins(12, 5, 12, 5)
row.setSpacing(2)
- self.key = label("Choose a key combination", "body", wrap=True)
- self.hint = label("Click, then press a key combination", "small", wrap=True)
+ self.key = label(tr("Choose a key combination"), "body", wrap=True)
+ self.hint = label(tr("Click, then press a key combination"), "small", wrap=True)
self.key.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.hint.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
row.addWidget(self.key)
@@ -1400,8 +1411,8 @@ class JumpKeyRecorder(ActionButton):
def set_value(self, value: str) -> None:
self.value = value or ""
shown = " ".join(self._names.get(part, part.upper() if len(part) == 1 else part.replace("_", " ").title())
- for part in self.value.split("+")) if self.value else "Choose a key combination"
- name = f"Jump straight here key, {shown}"
+ for part in self.value.split("+")) if self.value else tr("Choose a key combination")
+ name = tr("Jump straight here key, {key}").format(key=shown)
if self.accessibleName() != name:
self.setAccessibleName(name)
if not self.armed:
@@ -1418,7 +1429,7 @@ class JumpKeyRecorder(ActionButton):
self.on_arm(False)
self.set_value(self.value)
set_role(self.key, "keycap" if self.value else "body")
- self.hint.setText("Click, then press a key combination")
+ self.hint.setText(tr("Click, then press a key combination"))
set_role(self, "keycap")
def _toggle(self) -> None:
@@ -1426,9 +1437,9 @@ class JumpKeyRecorder(ActionButton):
self.cancel()
return
self.armed = True
- self.key.setText("Press a key combination…")
+ self.key.setText(tr("Press a key combination…"))
set_role(self.key, "keycap-live")
- self.hint.setText("Click again to cancel")
+ self.hint.setText(tr("Click again to cancel"))
set_role(self, "keycap-live")
QApplication.instance().installEventFilter(self)
if self.on_arm is not None:
@@ -1614,7 +1625,7 @@ class Sidebar(QWidget):
details_layout.addWidget(self.link_peer)
self._link_layout.addWidget(self._link_details, 1)
self.response_time = label("", "note")
- self.response_time.setAccessibleName("Response time: no fresh measurement")
+ self.response_time.setAccessibleName(tr("Response time: no fresh measurement"))
self.response_time.hide()
outer.addWidget(link)
response_row = QHBoxLayout()
@@ -1630,10 +1641,11 @@ class Sidebar(QWidget):
list_layout.setSpacing(2)
self._buttons: dict = {}
for key, name, _purpose in pages:
- button = PageButton(name)
+ shown_name = tr(name)
+ button = PageButton(shown_name)
button._sidebar = self
button._page_key = key
- button.setToolTip(name)
+ button.setToolTip(shown_name)
button.clicked.connect(lambda _checked=False, k=key: self._pointer_select(k))
list_layout.addWidget(button)
self._buttons[key] = button
@@ -1789,7 +1801,7 @@ class Sidebar(QWidget):
self.response_time.setVisible(connected)
if not connected:
self.response_time.setText("")
- self.response_time.setAccessibleName("Response time: disconnected")
+ self.response_time.setAccessibleName(tr("Response time: disconnected"))
self.response_time.setToolTip("")
return
target = f" to {self._response_peer}" if getattr(self, "_response_peer", "") else ""