Skip to content

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

Beamer 1.5.0-beta.5

Toby Kalkman2b750bfbf2b4
diff --git a/VERSION b/VERSION
index 6dea063..76daa65 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.5.0-beta.4
+1.5.0-beta.5
diff --git a/WIRE.md b/WIRE.md
index b66d72f..29404a6 100644
--- a/WIRE.md
+++ b/WIRE.md
@@ -120,6 +120,7 @@ A peer entry:
| `linked` | boolean | a version 6 link with this peer has authenticated at least once |
| `from_1_4` | boolean | this entry was migrated from a 1.4.x pairing, and never links |
| `way_back` | boolean, optional | what the peer last said in `arrangement`'s `way_back` (section 8): whether one of its zones leads here; absent until it says |
+| `way_back_by` | `b64`, optional | what the peer last said in `arrangement`'s `way_back_by` (section 8): the machine whose zone holds the side it has for this one; absent when it named none |
Rules:
@@ -319,7 +320,8 @@ The responder:
is not a valid `hello` (a plaintext that is not JSON or not an object, another `type`, a
malformed field) is answered with `welcome` carrying only `version` 6 and
`error: "invalid_hello"`, and the link is closed. This is the one place a plaintext that is
- not a JSON object is answered rather than ending the link at once.
+ not a JSON object is answered rather than ending the link at once. A paired peer with `in_use`
+ set to `false` receives this same refusal after its authenticated `hello`.
8. Checks the `id` in `hello`. When it is this machine's own, or is not the entry's, it answers
`welcome` carrying only `version` 6 and `error: "wrong_id"`, and closes. Only a holder of the
token can read that answer, so it tells nobody else anything. Otherwise it sets `linked`, and
@@ -688,6 +690,15 @@ one of `"owned"`, `"not_allowed"`, `"busy"`, `"sent_home"` and `"malformed"`. A
all a `refuse` needs: one whose `why` is missing, not a string, or another string is not
malformed, and the initiator acts on it at once as a refusal it cannot name.
+A `refuse` may also carry **`other`**, a machine id: with `owned`, the owner that holds the
+responder; with `busy`, the machine the responder's own input is on. The responder includes it
+whenever it knows that machine's id, and never with any other `why`. It is there so the initiator
+can say which machine is in the way ("Can't cross to Bee: it is being driven from Sea"); the
+initiator names it by its own peer entry for that id, and as another machine when it has none, or
+when `other` is not a valid id or is the initiator's own, in which case it is ignored and the
+refusal still stands. A version 6 machine from before 1.5.0-beta.5 ignores it, as it ignores any
+unknown key (Encodings).
+
`switch`, responder to its owner only:
| Field | |
@@ -1152,6 +1163,9 @@ only for the entry migrated from 1.4.x, which never links. A zone never names a
- **Every machine starts with its whole edge.** Pairing gives the new machine an `edge` zone,
and so does an `arrangement` for a machine that has no zone yet, and so does reading a
settings file in which a paired desktop has none (pairing made no zones before 1.5.0-beta.5).
+ On a Mac with one desktop machine paired and no side for it, Beamer holds `right` unstamped and
+ with no author, as the Crossing page shows, so the edge crosses from pairing and a side either
+ machine chooses wins over it.
An `edge` zone whose side another zone in use already covers is written `off`, so the file
stays one the settings accept. A machine with a side and no way in, because another machine
holds that side, is named on the Crossing page with the machine that holds it.
@@ -1182,6 +1196,17 @@ having no way back while it is `false`. An answer is sent only after an `arrange
something here, so two machines never answer each other in turn. A version 6 machine from before
1.5.0-beta.5 ignores it, as it ignores any unknown key (Encodings).
+With `way_back` false, `arrangement` may also carry **`way_back_by`**, a machine id: the machine
+whose zone in use already covers the sender's side for the receiver, which is why the sender's own
+zone there was turned `off` (Every machine starts with its whole edge, and Order and overlap). The
+sender includes it whenever one such machine holds that side, the first in its zone list when
+several do, and never with `way_back` true or absent. The receiver keeps it as `way_back_by` on the
+sender's entry beside `way_back`, and drops it whenever an `arrangement` from the sender carries
+`way_back` without it; one that is not a valid id, or is the receiver's own, is ignored as if
+absent. With it, the receiver's Crossing page says which machine is in the way ("Bee has Sea on its
+left too"), naming it by its own entry for that id and as another machine when it has none. A
+version 6 machine from before 1.5.0-beta.5 ignores it, as it ignores any unknown key (Encodings).
+
**From 1.4.x's settings.** The migration turns the one pair's ways across into zones for its one
peer, one of each kind, with `off` set for each method that was not on: an `edge` zone; a `part`
zone with the saved thirds, `off` as well when the edge is on; a `corner` zone with the saved
diff --git a/core/link.py b/core/link.py
index 2784095..ca4a1ef 100644
--- a/core/link.py
+++ b/core/link.py
@@ -225,7 +225,8 @@ class OutboundLink:
"""Where to dial the entry, or None when it is not dialled: send off, no address, or not
made by pairing (a typed token, or any token migrated from 1.4.x)."""
host, port = entry.get("host"), entry.get("port")
- if not protocol.linkable(entry) or entry.get("send") is not True or not host or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
+ if (not protocol.linkable(entry) or entry.get("in_use", True) is not True or entry.get("send") is not True
+ or not host or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535):
return None
return host, port
diff --git a/core/owner.py b/core/owner.py
index 522fee0..94157b1 100644
--- a/core/owner.py
+++ b/core/owner.py
@@ -67,12 +67,14 @@ class Moved:
why: str # "asked", "switch", a refusal's `why`, "refused", "no_answer", "link_lost"
edge: Optional[str] = None # where to land the pointer, when the move says
offset: Optional[float] = None
+ other: Optional[object] = None
@dataclass(frozen=True)
class Unreachable:
peer: str
why: str # a refusal's `why`, "refused", "no_answer", "link_lost", "unreachable"
+ other: Optional[object] = None
@dataclass(frozen=True)
@@ -257,12 +259,12 @@ class Owner:
wait = self._wait
if wait is not None and wait.chain:
if peer == wait.peer and route == wait.route:
- return self._not_taken(peer, why)
+ return self._not_taken(peer, why, data.get("other"))
return []
# The take's own route too: a re-arm sent before its answer came raised the route past it.
if peer == self.on and (route == self.route or (wait is not None and route == wait.route)):
self._hold_back(peer, why)
- return self._come_home(why)
+ return self._come_home(why, other=data.get("other"))
return []
def tick(self):
@@ -386,7 +388,7 @@ class Owner:
def _forget_pressed(self, peer):
self._swallow.update(self._pressed.pop(peer, {}))
- def _come_home(self, why, edge=None, offset=None):
+ def _come_home(self, why, edge=None, offset=None, other=None):
left = self.on
if self._wait is not None and not self._wait.chain:
# Never taken: a clipboard sent after the take was dropped there.
@@ -399,7 +401,7 @@ class Owner:
self._forget_pressed(left)
self.on = None
self.reach_sent = []
- actions.append(Moved(None, left, why, edge, offset))
+ actions.append(Moved(None, left, why, edge, offset, other))
return actions + self._replay_held()
def _abandon(self, unless=None):
@@ -415,12 +417,12 @@ class Owner:
self._clipboard_at.discard(wait.peer)
return [Drop(wait.peer)]
- def _not_taken(self, peer, why):
+ def _not_taken(self, peer, why, other=None):
"""A hand-over from the machine the input is on did not happen: re-arm it without `peer`."""
self._wait = None
if peer is not None:
self._hold_back(peer, why)
- return self._stay() + [Unreachable(peer, why)] + self._replay_held()
+ return self._stay() + [Unreachable(peer, why, other)] + self._replay_held()
def held_back(self, peer):
"""Whether `peer` refused, or did not take, a move a moment ago and is not asked again yet."""
diff --git a/core/pairing.py b/core/pairing.py
index c392a0c..59330af 100644
--- a/core/pairing.py
+++ b/core/pairing.py
@@ -330,6 +330,7 @@ def peer_entry(identity: bytes, name: str, platform: str, port: int, token: str,
return {
"id": _b64(identity), "name": name, "platform": platform, "token": token,
"host": "" if phone else host, "port": port, "hw": "", "send": not phone, "allow_drive": True,
+ "in_use": True,
"side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": int(paired_at),
"linked": False, "from_1_4": False,
}
diff --git a/core/peerlist.py b/core/peerlist.py
index 8fb9e19..de3286c 100644
--- a/core/peerlist.py
+++ b/core/peerlist.py
@@ -146,6 +146,17 @@ def pairing_error_text(error: Exception, name: str) -> str:
return f"Pairing failed: {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.")
+ 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 None
+
+
def host_outcome_text(outcome: Optional[str], entry: Optional[dict]) -> str:
"""How the code on screen ended, said to the person at this machine (`PairingService.outcome`,
with `entry` the machine that paired or, for `known`, the entry it was found to be); "" while
diff --git a/core/protocol.py b/core/protocol.py
index a924b1e..3c8d7f7 100644
--- a/core/protocol.py
+++ b/core/protocol.py
@@ -983,10 +983,15 @@ def accept_msg(route: int) -> dict:
return {"type": MSG_ACCEPT, "data": {"route": route}}
-def refuse_msg(route: int, why: str) -> dict:
+def refuse_msg(route: int, why: str, other=None) -> dict:
if why not in REFUSE_REASONS:
raise ValueError(f"not a refusal: {why!r}")
- return {"type": MSG_REFUSE, "data": {"route": route, "why": why}}
+ data = {"route": route, "why": why}
+ if why in ("owned", "busy") and isinstance(other, bytes):
+ text = id_text(other)
+ if read_id(text) is not None:
+ data["other"] = text
+ return {"type": MSG_REFUSE, "data": data}
def accepts_msg(accepts: bool) -> dict:
@@ -1009,7 +1014,11 @@ def read_refuse(message):
route, why = parsed[1].get("route"), parsed[1].get("why")
if not _int(route, 1, MAX_SAFE_INTEGER):
return None
- return {"route": route, "why": why if isinstance(why, str) else None}
+ result = {"route": route, "why": why if isinstance(why, str) else None}
+ other = read_id(parsed[1].get("other")) if why in ("owned", "busy") else None
+ if other is not None:
+ result["other"] = other
+ return result
def read_accepts(message):
@@ -1146,18 +1155,23 @@ def read_clipboard(message):
return {"text": text, "image": clipboard_image(data)}
-def arrangement_v6(edge: str, set_at: int, by: bytes, way_back=None) -> dict:
- """`way_back`, when a boolean, says whether one of the sender's zones leads to the receiver (WIRE.md section 8)."""
+def arrangement_v6(edge: str, set_at: int, by: bytes, way_back=None, way_back_by=None) -> dict:
+ """`way_back` says whether a sender's zone leads here; `way_back_by` names a holder when it does not."""
data = {"edge": edge, "set_at": int(set_at), "by": id_text(by)}
if isinstance(way_back, bool):
data["way_back"] = way_back
+ if way_back is False and isinstance(way_back_by, bytes):
+ text = id_text(way_back_by)
+ if read_id(text) is not None:
+ data["way_back_by"] = text
return {"type": MSG_ARRANGEMENT, "data": data}
def read_arrangement_v6(message, now: float):
- """{edge, set_at, by} from an `arrangement`, with `way_back` when it carried a boolean one, or
- None: malformed, or stamped more than a day ahead of `now` or above 2^53 - 2, which the
- receiver ignores. A `way_back` that is not a boolean is left out, and the side still stands."""
+ """{edge, set_at, by} from an `arrangement`, with `way_back` when it carried a boolean one and,
+ beside a `way_back` of false, `way_back_by` when it is a valid id; or None: malformed, or stamped
+ more than a day ahead of `now` or above 2^53 - 2, which the receiver ignores. A `way_back` that is
+ not a boolean is left out, and the side still stands."""
parsed = read_message(message)
if parsed is None or parsed[0] != MSG_ARRANGEMENT:
return None
@@ -1169,6 +1183,10 @@ def read_arrangement_v6(message, now: float):
read = {"edge": data["edge"], "set_at": set_at, "by": by}
if isinstance(data.get("way_back"), bool):
read["way_back"] = data["way_back"]
+ if data["way_back"] is False:
+ way_back_by = read_id(data.get("way_back_by"))
+ if way_back_by is not None:
+ read["way_back_by"] = way_back_by
return read
diff --git a/core/receiver.py b/core/receiver.py
index a31f0ff..3ce4742 100644
--- a/core/receiver.py
+++ b/core/receiver.py
@@ -119,6 +119,7 @@ OUTBOX_LIMIT = 512
ADMITTED = "admitted"
WRONG_ID = "wrong_id"
GONE = "gone"
+IN_USE_OFF = "in_use_off"
_DROPPED_TEXT = frozenset(chr(code) for code in list(range(0x00, 0x20)) + list(range(0x7F, 0xA0))) - {"\n", "\t"}
_TEXT_KEYS = {"\n": "enter", "\t": "tab"}
@@ -179,7 +180,7 @@ def zone_models(zones, peers, allowed, resistance_px: int, notch_span=None) -> l
sides = {}
for peer in peers or ():
ident = protocol.read_id(peer.get("id")) if isinstance(peer, dict) else None
- if ident is not None:
+ if ident is not None and peer.get("in_use", True) is True:
sides[ident] = peer.get("side")
found = {"corner": [], "edge": [], "part": [], "notch": []}
for zone in zones or ():
@@ -310,6 +311,8 @@ class PeerBook:
return GONE, None
if peer_id == own_id or entry.get("id") != protocol.id_text(peer_id):
return WRONG_ID, None
+ if entry.get("in_use", True) is not True:
+ return IN_USE_OFF, None
before = copy.deepcopy(entry)
entry.update(changes)
entry["linked"] = True
@@ -504,6 +507,11 @@ class LinkResponder:
with self._lock:
return self._requested_running and self._thread is not None and self._thread.is_alive()
+ @property
+ def listening_port(self) -> Optional[int]:
+ with self._lock:
+ return self._port if self._listener is not None else None
+
@property
def owner(self) -> Optional[bytes]:
link = self._owner
@@ -572,7 +580,8 @@ class LinkResponder:
listener.settimeout(0.1)
with self._lock:
self._listener = listener
- LOGGER.info("Listening for version 6 links on 0.0.0.0:%s", port)
+ self._port = listener.getsockname()[1]
+ LOGGER.info("Listening for version 6 links on 0.0.0.0:%s", self._port)
self._report()
while not stop_event.is_set():
try:
@@ -694,6 +703,9 @@ class LinkResponder:
LOGGER.warning("%s holds a pairing of this machine's under another machine's id", host)
self._answer(connection, host, session.seal(protocol.wrong_id_v6()))
return None
+ if outcome == IN_USE_OFF:
+ self._answer(connection, host, session.seal(protocol.invalid_hello_v6()))
+ return None
allow_drive = entry.get("allow_drive") is True
welcome = protocol.welcome_v6(
own_id, identity["name"], identity["platform"], identity["app"], identity["caps"], allow_drive, self._hardware_towards(host, identity)
@@ -1094,7 +1106,8 @@ class LinkResponder:
else:
why = self._refusal_locked(link, focus)
if why is not None:
- link.post(protocol.refuse_msg(focus["route"], why))
+ reason, other = why
+ link.post(protocol.refuse_msg(focus["route"], reason, other=other))
return
link.route = focus["route"]
# The answer goes before the pointer is placed or anything plays.
@@ -1105,33 +1118,39 @@ class LinkResponder:
if stale:
self._rearm_fresh()
- def _refusal_locked(self, link: _Link, focus: dict) -> Optional[str]:
+ def _refusal_locked(self, link: _Link, focus: dict):
"""Section 4's decision order, after the stale route (steps 2 to 7). The take is made
visible (`driven`) before `away()` is read, and stays so until it is refused or becomes
the ownership; `away()` is called under the lock, so it must be a plain read."""
if focus["malformed"]:
- return "malformed"
+ return "malformed", None
if not link.allow_drive:
- return "not_allowed"
+ return "not_allowed", None
self._claiming = link
try:
- busy = bool(self._away())
+ away = self._away()
+ busy = bool(away)
except Exception:
LOGGER.exception("Could not tell whether this machine's input is elsewhere")
busy = False
+ away = None
why = None
+ other = None
sent_home_at = self._sent_home_at.get(link.peer_id)
if busy:
why = "busy"
+ if isinstance(away, bytes) and len(away) == protocol.MACHINE_ID_SIZE:
+ other = away
elif sent_home_at is not None and time.monotonic() - sent_home_at < SENT_HOME_SECONDS:
why = "sent_home"
elif self._owner is not None and self._owner is not link:
why = "owned"
+ other = self._owner.peer_id
elif focus["stay"] and self._owner is not link:
why = "malformed"
if why is not None:
self._claiming = None
- return why
+ return (why, other) if why is not None else None
def _own_locked(self, link: _Link, focus: dict, peers, zones) -> list:
began = self._owner is not link
@@ -1235,6 +1254,11 @@ class LinkResponder:
LOGGER.info("%s was removed; its link is closed", link.name)
link.close()
continue
+ if peer.get("in_use", True) is not True:
+ after += self._end_locked(link)
+ link.close()
+ LOGGER.info("%s is not in use; its link is closed", link.name)
+ continue
allow_drive = peer.get("allow_drive") is True
if allow_drive != link.allow_drive:
link.allow_drive = allow_drive
diff --git a/core/tests/responder_harness.py b/core/tests/responder_harness.py
index 2da3e5a..ad9de8e 100644
--- a/core/tests/responder_harness.py
+++ b/core/tests/responder_harness.py
@@ -229,20 +229,11 @@ class Machine:
self.port = None
def start(self):
- with socket.socket() as probe:
- probe.bind(("127.0.0.1", 0))
- self.port = probe.getsockname()[1]
- self.responder.start(self.port)
- assert wait_for(lambda: self.responder.listening and self._accepting()), "the responder did not listen"
+ self.responder.start(0)
+ assert wait_for(lambda: self.responder.listening_port is not None), "the responder did not listen"
+ self.port = self.responder.listening_port
return self
- def _accepting(self):
- try:
- with socket.create_connection(("127.0.0.1", self.port), timeout=0.2):
- return True
- except OSError:
- return False
-
def stop(self):
self.responder.stop()
diff --git a/core/tests/test_link.py b/core/tests/test_link.py
index 6a30342..56f2b37 100644
--- a/core/tests/test_link.py
+++ b/core/tests/test_link.py
@@ -174,6 +174,7 @@ class LinkHandshakeTests(unittest.TestCase):
time.sleep(0.3)
self.assertEqual(self.machine.links, [])
+
def test_a_peer_that_does_not_know_the_key_id_closes_and_the_text_follows_linked(self):
for linked, expected in ((False, "Update Beamer on Far to 1.5.0"), (True, "closed the connection")):
side = Side(self.machine, token=other_token(), linked=linked)
@@ -556,6 +557,11 @@ class LinkFollowTests(unittest.TestCase):
self.addCleanup(link.stop)
return side, link
+ def test_a_peer_not_in_use_has_no_dial_target(self):
+ side, _link = self.link(FakeClock(), [])
+ side.peer()["in_use"] = False
+ self.assertIsNone(OutboundLink._target(side.peer()))
+
def test_a_beacon_with_the_exact_name_is_tried_once_the_link_has_been_down_ten_seconds(self):
clock, tried = FakeClock(), []
side, link = self.link(clock, tried)
diff --git a/core/tests/test_owner.py b/core/tests/test_owner.py
index 9099c38..50c2be9 100644
--- a/core/tests/test_owner.py
+++ b/core/tests/test_owner.py
@@ -132,6 +132,13 @@ class TakeFromHomeTests(OwnerCase):
self.assertFalse(self.o.away)
self.clock.now += owner.SENT_HOME_FOR
+ def test_a_refusal_naming_the_machine_in_the_way_says_it_when_the_input_comes_home(self):
+ self.o.go("B")
+ self.assertEqual(moved(self.o.refuse("B", {"route": self.o.route, "why": "owned", "other": "C"})).other, "C")
+ self.clock.now += owner.SENT_HOME_FOR
+ self.o.go("B")
+ self.assertIsNone(moved(self.o.refuse("B", {"route": self.o.route, "why": "owned"})).other)
+
def test_a_machine_that_refused_a_take_is_not_taken_again_for_a_while(self):
# The live check, 01-10-2026: every push at the laptop's edge took the rig again while the
# Mac drove it, about 30 refusals and 30 notices in 20 seconds.
@@ -315,6 +322,13 @@ class SwitchTests(OwnerCase):
self.assertEqual(self.o.on, "C")
self.assertEqual(self.o.reach_sent, ["B", "D"])
+ def test_a_hand_over_refused_names_the_machine_in_the_way(self):
+ # Opus review: an onward hand-over refused as owned came back as Unreachable without `other`.
+ self.take("B")
+ self.switch("B", "C")
+ actions = self.o.refuse("C", {"route": 2, "why": "owned", "other": "D"})
+ self.assertIn(Unreachable("C", "owned", "D"), actions)
+
def test_a_refusal_from_the_next_machine_re_arms_the_one_left_leaving_it_out_for_three_seconds(self):
self.take("B")
self.switch("B", "C")
diff --git a/core/tests/test_pairing_v3.py b/core/tests/test_pairing_v3.py
index a6d96b1..b501625 100644
--- a/core/tests/test_pairing_v3.py
+++ b/core/tests/test_pairing_v3.py
@@ -482,7 +482,7 @@ class StoreTests(unittest.TestCase):
host_entry = rig.host_book.entries[0]
self.assertEqual(host_entry, {
"id": b64(REQUESTER_ID), "name": "Requester Mac", "platform": "macos", "token": token,
- "host": "192.168.77.5", "port": 24820, "hw": "", "send": True, "allow_drive": True,
+ "host": "192.168.77.5", "port": 24820, "hw": "", "send": True, "allow_drive": True, "in_use": True,
"side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": 1_790_000_000,
"linked": False, "from_1_4": False,
})
diff --git a/core/tests/test_peerlist.py b/core/tests/test_peerlist.py
index c4332e3..f50d0d8 100644
--- a/core/tests/test_peerlist.py
+++ b/core/tests/test_peerlist.py
@@ -214,5 +214,26 @@ class SharingANameTests(unittest.TestCase):
self.assertEqual(peerlist.sharing_a_name([]), [])
+class RefusalTextTests(unittest.TestCase):
+ """What a refused crossing says on either desktop, naming the machine in the way when the
+ refusal's `other` named one this machine knows (WIRE.md section 5)."""
+
+ def test_owned_and_busy_name_the_machine_in_the_way(self):
+ self.assertEqual(peerlist.refusal_text("owned", "Laptop-PC", "Desk-PC"),
+ "Can't cross to Laptop-PC: it is being driven from Desk-PC.")
+ self.assertEqual(peerlist.refusal_text("busy", "Desk-PC", "Laptop-PC"),
+ "Can't cross to Desk-PC: it is driving Laptop-PC.")
+
+ def test_with_no_machine_named_it_is_another_machine(self):
+ self.assertEqual(peerlist.refusal_text("owned", "Laptop-PC", ""),
+ "Can't cross to Laptop-PC: another machine is driving it.")
+ self.assertEqual(peerlist.refusal_text("busy", "Desk-PC", None),
+ "Can't cross to Desk-PC: it is driving another machine.")
+
+ def test_other_reasons_are_left_to_the_apps_own_words(self):
+ for why in ("not_allowed", "sent_home", "malformed", "refused", "no_answer", "link_lost"):
+ self.assertIsNone(peerlist.refusal_text(why, "Bee", "Sea"))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/core/tests/test_protocol_v6.py b/core/tests/test_protocol_v6.py
index 3291191..789d668 100644
--- a/core/tests/test_protocol_v6.py
+++ b/core/tests/test_protocol_v6.py
@@ -631,6 +631,22 @@ class Answers(unittest.TestCase):
with self.assertRaises(ValueError):
protocol.refuse_msg(5, "because")
+ def test_a_refuse_names_the_machine_in_the_way_only_when_owned_or_busy(self):
+ for why in ("owned", "busy"):
+ with self.subTest(why=why):
+ message = protocol.refuse_msg(5, why, other=ID_B)
+ self.assertEqual(message["data"], {"route": 5, "why": why, "other": protocol.id_text(ID_B)})
+ self.assertEqual(protocol.read_refuse(message), {"route": 5, "why": why, "other": ID_B})
+ for why in ("not_allowed", "sent_home", "malformed"):
+ with self.subTest(why=why):
+ self.assertNotIn("other", protocol.refuse_msg(5, why, other=ID_B)["data"])
+ self.assertNotIn("other", protocol.refuse_msg(5, "owned")["data"])
+ # One that is not an id is left out, and the refusal still stands.
+ for odd in ("x", 7, None, protocol.id_text(bytes(16))):
+ data = {"route": 5, "why": "owned", "other": odd}
+ with self.subTest(other=odd):
+ self.assertEqual(protocol.read_refuse({"type": "refuse", "data": data}), {"route": 5, "why": "owned"})
+
def test_switch(self):
read = protocol.read_switch(protocol.switch_v6(3, ID_A, edge="right", offset=0.5))
self.assertEqual(read, {"route": 3, "next": ID_A, "edge": "right", "offset": 0.5})
@@ -818,6 +834,23 @@ class Others(unittest.TestCase):
self.assertEqual(protocol.read_arrangement_v6({"type": "arrangement", "data": data}, now),
{"edge": "left", "set_at": now, "by": ID_A})
+ def test_arrangement_way_back_by_names_the_machine_holding_the_side_only_with_way_back_false(self):
+ now = 1_790_000_000
+ message = protocol.arrangement_v6("left", now, ID_A, way_back=False, way_back_by=ID_C)
+ self.assertEqual(message["data"]["way_back_by"], protocol.id_text(ID_C))
+ self.assertEqual(protocol.read_arrangement_v6(message, now),
+ {"edge": "left", "set_at": now, "by": ID_A, "way_back": False, "way_back_by": ID_C})
+ for way_back in (True, None):
+ with self.subTest(way_back=way_back):
+ self.assertNotIn("way_back_by", protocol.arrangement_v6("left", now, ID_A, way_back=way_back,
+ way_back_by=ID_C)["data"])
+ for data in ({"way_back": True, "way_back_by": protocol.id_text(ID_C)},
+ {"way_back_by": protocol.id_text(ID_C)},
+ {"way_back": False, "way_back_by": "x"}):
+ data = {"edge": "left", "set_at": now, "by": protocol.id_text(ID_A), **data}
+ with self.subTest(data=data):
+ self.assertNotIn("way_back_by", protocol.read_arrangement_v6({"type": "arrangement", "data": data}, now))
+
def test_paired(self):
self.assertEqual(protocol.read_paired(protocol.paired_msg([ID_A, ID_C])), [ID_A, ID_C])
self.assertEqual(protocol.read_paired(protocol.paired_msg([])), [])
diff --git a/core/tests/test_responder_accessors.py b/core/tests/test_responder_accessors.py
index 2e20dc1..671414e 100644
--- a/core/tests/test_responder_accessors.py
+++ b/core/tests/test_responder_accessors.py
@@ -3,7 +3,7 @@ them, and the capabilities a linked peer announced."""
import unittest
-from core import protocol
+from core import protocol, receiver
from core.tests.responder_harness import B, Initiator, Machine, entry, wait_for
@@ -25,6 +25,14 @@ class AccessorTests(unittest.TestCase):
machine.book.store_paired("nobody", ids)
self.assertEqual(machine.settings.saves, saves)
+ def test_the_book_does_not_admit_a_peer_that_is_not_in_use(self):
+ machine = Machine([entry(B, "Peer", in_use=False, linked=False)])
+ outcome, found = machine.book.admit(
+ protocol.key_id(machine.settings.peer(protocol.id_text(B))["token"]), machine.own, B, {"name": "Changed"}
+ )
+ self.assertEqual((outcome, found), (receiver.IN_USE_OFF, None))
+ self.assertFalse(machine.settings.peer(protocol.id_text(B))["linked"])
+
def test_the_responder_gives_a_linked_peers_capabilities(self):
machine = Machine([entry(B, "Peer")]).start()
self.addCleanup(machine.stop)
diff --git a/core/tests/test_responder_handshake.py b/core/tests/test_responder_handshake.py
index d313a57..ba37839 100644
--- a/core/tests/test_responder_handshake.py
+++ b/core/tests/test_responder_handshake.py
@@ -90,6 +90,17 @@ class TheLookup(Case):
self.machine.settings.peer(TOKENS[B])["allow_drive"] = False
self.assertFalse(self.initiator().handshake()["accepts"])
+ def test_in_use_off_refuses_the_handshake_and_on_accepts_it(self):
+ self.machine.settings.peer(TOKENS[B])["in_use"] = False
+ link = self.initiator()
+ with self.assertRaises(protocol.HelloRefused) as caught:
+ link.handshake()
+ self.assertEqual(caught.exception.error, protocol.ERROR_INVALID_HELLO)
+ self.assertTrue(wait_for(lambda: self.machine.responder.links() == set()))
+
+ self.machine.settings.peer(TOKENS[B])["in_use"] = True
+ self.assertEqual(self.initiator().handshake()["id"], HERE)
+
def test_a_typed_token_is_never_matched_or_given_a_key_id(self):
typed = "hunter2"
self.machine.settings.data["peers"].append(entry("", "Typed", token=typed, from_1_4=True, linked=False))
@@ -414,7 +425,7 @@ class TheThreadCap(Case):
self.assertTrue(wait_for(lambda: len(self.machine.responder._slots) == 1))
second = self.raw()
self.assertTrue(silent_close(second))
- first.sendall(b"MY\x07" + os.urandom(56))
+ first.sendall(b"MY\x07")
self.assertEqual(protocol._recv_exact(first, protocol.SHORT_REPLY_SIZE, time.monotonic() + 3)[:6], b"BEAMY\x06")
diff --git a/core/tests/test_responder_ownership.py b/core/tests/test_responder_ownership.py
index 4e7b20a..47a28d4 100644
--- a/core/tests/test_responder_ownership.py
+++ b/core/tests/test_responder_ownership.py
@@ -39,9 +39,16 @@ class Case(unittest.TestCase):
self.assertTrue(wait_for(lambda: self.machine.responder.owner == link.peer))
return route
- def refused(self, link, why, **fields):
+ def refused(self, link, why, other=None, **fields):
+ """`other`, when given, is the machine the refusal must name; the rest of the time it is not
+ checked, so the decision-order tests stay about the order."""
route = link.take(**fields)
- self.assertEqual(link.answer(route), (REFUSE, {"route": route, "why": why}))
+ kind, data = link.answer(route)
+ if other is not None:
+ self.assertEqual(data.get("other"), protocol.id_text(other))
+ self.assertEqual((kind, {key: value for key, value in data.items() if key != "other"}),
+ (REFUSE, {"route": route, "why": why}))
+ return data
def injected_from(self, count=None):
return self.machine.injected()
@@ -104,6 +111,22 @@ class Taking(Case):
self.refused(self.link(B), "busy")
self.assertIsNone(self.machine.responder.owner)
+ def test_an_owned_refusal_names_the_owner_and_a_busy_one_the_machine_input_is_on(self):
+ b, c = self.link(B), self.link(C)
+ self.own(b)
+ self.refused(c, "owned", other=B)
+ b.let_go()
+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))
+ # away() may say which machine this one's input is on; then busy names it.
+ self.machine.away = D
+ self.refused(c, "busy", other=D)
+ # Only a yes or no: busy, naming nothing.
+ self.machine.away = True
+ self.assertNotIn("other", self.refused(c, "busy"))
+ self.peer_entry(C)["allow_drive"] = False
+ self.machine.responder.peers_changed()
+ self.assertNotIn("other", self.refused(c, "not_allowed"))
+
def test_the_answer_comes_before_the_pointer_is_placed(self):
self.machine.desktop.slow = 1.0
b = self.link(B)
@@ -302,6 +325,17 @@ class Ending(Case):
self.assertEqual(b.expect(protocol.MSG_ACCEPTS), {"accepts": True})
self.own(b)
+ def test_turning_in_use_off_releases_the_owner_and_closes_the_link(self):
+ b = self.link(B)
+ self.own(b)
+ self.hold(b)
+ self.peer_entry(B)["in_use"] = False
+ self.machine.responder.peers_changed()
+ self.assertTrue(wait_for(self.released))
+ self.assertTrue(b.closed.wait(2))
+ self.assertIsNone(self.machine.responder.owner)
+ self.assertTrue(wait_for(lambda: B not in self.machine.responder.links()))
+
def test_the_forced_end_after_a_send_home(self):
with mock.patch.object(receiver, "FORCED_END_SECONDS", 0.3), mock.patch.object(receiver, "SENT_HOME_SECONDS", 1.0):
b = self.link(B)
@@ -496,6 +530,11 @@ class ZoneModels(unittest.TestCase):
self.assertEqual([peer for peer, _ in self.models(zones, allowed=(B, D))], [])
self.assertEqual([peer for peer, _ in self.models(zones)], [C])
+ def test_a_peers_zones_are_not_armed_when_it_is_not_in_use(self):
+ peers = [entry(B, "Bee", side="left", in_use=False)]
+ zones = [{"peer": protocol.id_text(B), "kind": "edge"}]
+ self.assertEqual(receiver.zone_models(zones, peers, {B}, 120), [])
+
def test_a_corner_lands_at_the_end_nearest_it(self):
self.assertEqual(receiver.corner_offset("top_right", "right"), 0.0)
self.assertEqual(receiver.corner_offset("top_right", "top"), 1.0)
diff --git a/core/tests/test_responder_ported.py b/core/tests/test_responder_ported.py
index 42e1f79..82747e9 100644
--- a/core/tests/test_responder_ported.py
+++ b/core/tests/test_responder_ported.py
@@ -262,7 +262,8 @@ class Unlock:
def finish_unlock():
for thread in threading.enumerate():
if thread.name == "Beamer-v6-unlock":
- thread.join(3)
+ if wait_for(lambda: thread.ident is not None):
+ thread.join(3)
class LockScreen(Case):
diff --git a/core/tests/test_settings_sync.py b/core/tests/test_settings_sync.py
index d55eba7..77fd0d1 100644
--- a/core/tests/test_settings_sync.py
+++ b/core/tests/test_settings_sync.py
@@ -54,6 +54,11 @@ class MessageTests(unittest.TestCase):
"methods", "edge_parts", "corner"):
self.assertNotIn(own, flat)
+ def test_jump_keys_are_not_sent_by_same_on_all_machines(self):
+ values = settings_sync.mac_values(mac_raw())
+ values["jump_key"] = "ctrl+alt+2"
+ self.assertNotIn("jump_key", settings_sync.message_data(True, 50, values)["crossing"])
+
def test_a_round_trip_reads_back_what_was_sent(self):
values = settings_sync.mac_values(mac_raw())
on, set_at, read = settings_sync.read(settings_sync.message_data(True, 7, values), KEYS)
diff --git a/core/tests/test_ways.py b/core/tests/test_ways.py
index 9bd9531..3e09d1a 100644
--- a/core/tests/test_ways.py
+++ b/core/tests/test_ways.py
@@ -56,6 +56,64 @@ class ReadingOnePeer(unittest.TestCase):
self.assertEqual(ways.ways(settings(), A)["methods"], [])
+class JumpKeys(unittest.TestCase):
+ def test_missing_jump_key_is_none(self):
+ self.assertIsNone(ways.jump_key(peer(A, "Ay")))
+
+ def test_trigger_key_cannot_be_recorded_as_a_jump_key(self):
+ held = settings(peer(A, "Ay"))
+ with self.assertRaisesRegex(ValueError, "trigger"):
+ ways.check_jump_key(held, A, "ctrl+f9", "f9")
+
+ def test_a_chord_with_the_trigger_key_or_its_modifier_is_refused(self):
+ # A chord holding the trigger's modifier would start its double-tap or hold, and leave the
+ # modifier held here once input had jumped away.
+ held = settings(peer(A, "Ay"))
+ for value, trigger in (("ctrl+f9", "f9"), ("ctrl+alt+2", "alt_r"), ("alt+2", "alt_r")):
+ with self.subTest(value=value), self.assertRaisesRegex(ValueError, "trigger"):
+ ways.check_jump_key(held, A, value, trigger)
+ self.assertEqual(ways.check_jump_key(held, A, "ctrl+cmd+2", "alt_r"), "ctrl+cmd+2")
+
+ def test_space_is_recorded_by_its_name_not_as_a_blank(self):
+ self.assertFalse(ways.valid_jump_key("cmd+ "))
+ self.assertEqual(ways.jump_chord(["cmd"], "space"), "cmd+space")
+
+ def test_shift_alone_is_not_enough_because_it_would_swallow_typing(self):
+ for value in ("shift+a", "shift+2"):
+ with self.subTest(value=value), self.assertRaises(ValueError):
+ ways.check_jump_key(settings(peer(A, "Ay")), A, value, "alt_r")
+ self.assertEqual(ways.jump_chord(["shift"], "a"), None)
+
+ def test_bare_modifiers_and_unrecognised_words_are_not_jump_chords(self):
+ for value in ("ctrl", "nonsense+2", "shift+ctrl+2"):
+ with self.subTest(value=value), self.assertRaises(ValueError):
+ ways.check_jump_key(settings(peer(A, "Ay")), A, value, "alt_r")
+ with self.assertRaises(ValueError):
+ ways.check_jump_key(settings(peer(A, "Ay")), A, 2, "alt_r")
+
+ def test_shifted_printable_keys_and_plus_have_stable_chords(self):
+ self.assertEqual(ways.jump_chord(["ctrl", "shift"], "@"), "ctrl+shift+@")
+ self.assertEqual(ways.jump_chord(["ctrl"], "+"), "ctrl+plus")
+ self.assertEqual(ways.jump_chord(["ctrl_r"], "2"), "ctrl+2")
+
+ def test_another_peers_jump_key_cannot_be_reused(self):
+ held = settings(peer(A, "Ay", jump_key="ctrl+shift+2"), peer(B, "Bee"))
+ with self.assertRaisesRegex(ValueError, "already"):
+ ways.check_jump_key(held, B, "ctrl+shift+2", "alt_r")
+
+ def test_clearing_a_jump_key_removes_it(self):
+ entry = peer(A, "Ay", jump_key="ctrl+shift+2")
+ self.assertIsNone(ways.check_jump_key(settings(entry), A, "", "alt_r"))
+
+ def test_a_chord_finds_its_in_use_machine(self):
+ held = settings(peer(A, "Ay", jump_key="ctrl+shift+2"), peer(B, "Bee", jump_key="ctrl+shift+3"))
+ self.assertEqual(ways.jump_peer(held["peers"], "ctrl+shift+3"), B)
+
+ def test_a_not_in_use_machines_jump_key_is_ignored(self):
+ held = settings(peer(A, "Ay", jump_key="ctrl+shift+2", in_use=False))
+ self.assertIsNone(ways.jump_peer(held["peers"], "ctrl+shift+2"))
+
+
class WritingOnePeer(unittest.TestCase):
def test_one_zone_of_each_kind_is_written_for_that_peer_and_the_others_are_left_alone(self):
other = {"peer": B, "kind": "edge"}
@@ -243,6 +301,55 @@ class WayBack(unittest.TestCase):
self.assertEqual(ways.no_way_back_sentence(held, C), "")
+ def test_with_no_way_back_the_sender_names_the_machine_whose_zone_holds_that_side(self):
+ # The laptop on 02-10-2026: the Mac and the rig both on its left, the rig's edge in use.
+ held = settings(peer(A, "Mac", side="left"), peer(B, "Rig", side="left"),
+ zones=[{"peer": A, "kind": "edge", "off": True}, {"peer": B, "kind": "edge"}])
+ self.assertEqual(ways.way_back_by(held, A), B)
+ self.assertIsNone(ways.way_back_by(held, B))
+ held["zones"][0].pop("off")
+ held["zones"][1]["off"] = True
+ self.assertIsNone(ways.way_back_by(held, A))
+ # Off by choice, with nobody else on that side: no way back, and nobody in the way.
+ held["zones"][0]["off"] = True
+ self.assertIsNone(ways.way_back_by(held, A))
+
+ def test_what_each_machine_is_told_of_its_way_back_so_a_change_reaches_every_machine_it_touches(self):
+ # Moving one machine can open or close another's way back: Sol's review, 02-10-2026.
+ held = settings(peer(A, "Mac", side="left"), peer(B, "Rig", side="left"),
+ zones=[{"peer": A, "kind": "edge", "off": True}, {"peer": B, "kind": "edge"}])
+ before = ways.way_back_state(held)
+ self.assertEqual(before, {A: (False, B), B: (True, None)})
+ held["peers"][1]["side"] = "right"
+ held["zones"][0].pop("off")
+ after = ways.way_back_state(held)
+ self.assertEqual(sorted(peer for peer in after if after[peer] != before.get(peer)), [A])
+
+ def test_an_arrangement_keeps_who_is_in_the_way_only_beside_a_way_back_of_false(self):
+ held = settings(peer(A, "Ay", side="left", side_set_at=50, side_by=A))
+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False, way_back_by=C), (True, []))
+ self.assertEqual(held["peers"][0]["way_back_by"], C)
+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False)
+ self.assertNotIn("way_back_by", held["peers"][0])
+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False, way_back_by=C)
+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=True, way_back_by=C)
+ self.assertNotIn("way_back_by", held["peers"][0])
+ # This machine's own id, or one that is not an id, is ignored as if absent.
+ for odd in (HERE, "x"):
+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False, way_back_by=odd)
+ self.assertNotIn("way_back_by", held["peers"][0])
+
+ def test_the_sentence_names_the_machine_in_the_way_and_where_to_change_it(self):
+ held = settings(peer(A, "Laptop-PC", side="right", way_back=False, way_back_by=B), peer(B, "Desk-PC"))
+ self.assertEqual(ways.no_way_back_sentence(held, A),
+ "Laptop-PC has Desk-PC on its left too, so none of its edges leads back here. On "
+ "Laptop-PC's Crossing page, share that side by thirds or move one of them.")
+ held["peers"][0]["way_back_by"] = C
+ self.assertEqual(ways.no_way_back_sentence(held, A),
+ "Laptop-PC has another machine on its left too, so none of its edges leads back here. On "
+ "Laptop-PC's Crossing page, share that side by thirds or move one of them.")
+
+
class Arrangement(unittest.TestCase):
def test_a_newer_arrangement_sets_the_opposite_side_for_that_peer_only(self):
held = settings(peer(A, "Ay", side="left", side_set_at=10, side_by=HERE), peer(B, "Bee", side="right"))
@@ -297,6 +404,10 @@ class TheShortcutsMachine(unittest.TestCase):
peers = [peer(A, "Ay", send=False)]
self.assertIsNone(ways.shortcut_peer(peers, A, lambda ident: True))
+ def test_a_machine_not_in_use_is_never_picked(self):
+ peers = [peer(A, "Ay", in_use=False), peer(B, "Bee")]
+ self.assertEqual(ways.shortcut_peer(peers, A, lambda ident: True), B)
+
def test_a_phone_or_an_entry_without_an_id_is_never_picked(self):
peers = [peer(PHONE, "Phone", port=0, host="", send=False), peer("", "Old", from_1_4=True)]
self.assertIsNone(ways.shortcut_peer(peers, None, lambda ident: True))
@@ -315,6 +426,10 @@ class MissingPairings(unittest.TestCase):
held = settings(peer(A, "Ay"), peer(B, "Bee", allow_drive=False))
self.assertEqual(ways.missing_pairings(held, A), [])
+ def test_a_machine_not_in_use_needs_no_pairing(self):
+ held = settings(peer(A, "Ay"), peer(B, "Bee", in_use=False))
+ self.assertEqual(ways.missing_pairings(held, A), [])
+
def test_a_machine_that_has_never_linked_is_not_judged(self):
held = settings(peer(A, "Ay"), peer(B, "Bee", linked=False))
self.assertEqual(ways.missing_pairings(held, A), [])
@@ -337,23 +452,47 @@ class MissingPairings(unittest.TestCase):
class TheShownDefault(unittest.TestCase):
- """The Mac's page shows Right for its one machine before a side is set, and a save writes it."""
+ """The Mac's page shows Right for its one machine before a side is set, so the settings hold it
+ from the moment that machine is paired, not from the first save (beta.4: Edge did nothing until
+ a save of another way wrote it)."""
- def test_a_side_written_as_the_pages_default_is_unstamped_so_the_peers_own_wins(self):
+ def test_the_one_machine_not_placed_holds_right_unstamped_so_its_edge_fires(self):
held = settings(peer(A, "Ay"), zones=[{"peer": A, "kind": "edge"}])
- self.assertTrue(ways.edit(held, A, side="right", methods=["edge"], parts=["middle"], corner="top_left",
- kinds=MAC, corner_edge=mac_corner_edge, now=1_900_000_000, default=True))
+ self.assertFalse(ways.has_way(held, A))
+ self.assertTrue(ways.default_side(held))
entry = held["peers"][0]
self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("right", 0, ""))
+ self.assertTrue(ways.has_way(held, A))
+ self.assertFalse(ways.default_side(held))
+
+ def test_the_held_default_loses_to_a_side_the_peer_chooses(self):
+ held = settings(peer(A, "Ay"), zones=[{"peer": A, "kind": "edge"}])
+ ways.default_side(held)
self.assertEqual(ways.arrangement(held, A, "bottom", 1_899_999_000, A, "this Mac"), (True, []))
self.assertEqual(held["peers"][0]["side"], "top")
def test_a_default_never_moves_a_side_already_set(self):
held = settings(peer(A, "Ay", side="left", side_set_at=5, side_by=A), zones=[{"peer": A, "kind": "edge"}])
- self.assertFalse(ways.edit(held, A, side="right", methods=["edge"], parts=["middle"], corner="top_left",
- kinds=MAC, corner_edge=mac_corner_edge, now=1_900_000_000, default=True))
+ self.assertFalse(ways.default_side(held))
self.assertEqual(held["peers"][0]["side"], "left")
+ def test_with_several_machines_none_is_given_a_side_nobody_chose(self):
+ held = settings(peer(A, "Ay"), peer(B, "Bee"),
+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])
+ self.assertFalse(ways.default_side(held))
+ self.assertEqual([entry["side"] for entry in held["peers"]], ["", ""])
+
+ def test_a_machine_paired_beside_the_one_migrated_from_1_4_is_given_no_side(self):
+ # The migrated entry has no id and holds the 1.4 side: Right as well would clash with it.
+ held = settings(peer("", "Studio", side="right", from_1_4=True), peer(A, "Ay"),
+ zones=[{"peer": "", "kind": "edge"}, {"peer": A, "kind": "edge"}])
+ self.assertFalse(ways.default_side(held))
+ self.assertEqual(held["peers"][1]["side"], "")
+
+ def test_a_phone_alone_is_given_no_side(self):
+ held = settings(peer(PHONE, "Phone", port=0, host="", send=False))
+ self.assertFalse(ways.default_side(held))
+
class TheCornerFollowsAnArrivingSide(unittest.TestCase):
def test_a_corner_that_crosses_the_side_is_rewritten_for_the_side_that_arrives(self):
@@ -363,5 +502,79 @@ class TheCornerFollowsAnArrivingSide(unittest.TestCase):
self.assertEqual((held["peers"][0]["side"], held["zones"][0]["edge"]), ("right", "right"))
+
+class SharingASide(unittest.TestCase):
+ """A machine put on a side another machine already crosses from is offered that side by thirds
+ on the spot, rather than refused (beta.4, 02-10-2026: "it rejects the option and hides it")."""
+
+ def two_on_the_right(self, rig_zone=None):
+ return settings(peer(A, "Desk-PC", side="right"), peer(B, "Laptop-PC", side="right"),
+ zones=[rig_zone or {"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])
+
+ def test_a_machine_whose_side_another_holds_whole_is_offered_the_end_third(self):
+ held = self.two_on_the_right()
+ self.assertEqual(ways.share_offer(held, B),
+ {"side": "right", "holders": [A], "thirds": {"start": A, "middle": A, "end": B}})
+
+ def test_free_thirds_go_to_the_machine_asking(self):
+ held = self.two_on_the_right({"peer": A, "kind": "part", "parts": ["end"]})
+ self.assertEqual(ways.share_offer(held, B)["thirds"], {"start": B, "middle": B, "end": A})
+
+ def test_nothing_is_offered_where_nothing_is_in_the_way(self):
+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"),
+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])
+ self.assertIsNone(ways.share_offer(held, B))
+ self.assertIsNone(ways.share_offer(self.two_on_the_right(), A))
+
+ def test_sharing_writes_each_machines_thirds_and_turns_their_whole_edges_off(self):
+ held = self.two_on_the_right()
+ changed = ways.share(held, "right", {"start": A, "middle": A, "end": B}, kinds=MAC)
+ self.assertEqual(sorted(changed), sorted([A, B]))
+ mine = {(zone["peer"], zone["kind"]): zone for zone in held["zones"]}
+ self.assertTrue(mine[(A, "edge")].get("off"))
+ self.assertTrue(mine[(B, "edge")].get("off"))
+ self.assertEqual((mine[(A, "part")]["parts"], mine[(A, "part")].get("off")), (["start", "middle"], None))
+ self.assertEqual((mine[(B, "part")]["parts"], mine[(B, "part")].get("off")), (["end"], None))
+ self.assertIsNone(ways.clash(held, "this Mac"))
+ self.assertTrue(ways.has_way(held, A) and ways.has_way(held, B))
+
+ def test_a_machine_on_that_side_left_with_no_third_crosses_there_no_more(self):
+ held = self.two_on_the_right()
+ ways.share(held, "right", {"start": B, "middle": B, "end": B}, kinds=MAC)
+ self.assertFalse(ways.has_way(held, A))
+ self.assertIsNone(ways.clash(held, "this Mac"))
+
+ def test_a_machine_left_with_no_third_keeps_a_part_zone_the_settings_accept(self):
+ # Sol's review: an empty `parts` made the Mac's store refuse the whole share.
+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"), peer(C, "Sea", side="right"),
+ zones=[{"peer": A, "kind": "part", "parts": ["start", "middle"]},
+ {"peer": C, "kind": "part", "parts": ["end"]},
+ {"peer": B, "kind": "edge", "off": True}])
+ ways.share(held, "right", {"start": A, "middle": A, "end": B}, kinds=MAC)
+ sea = next(zone for zone in held["zones"] if zone["peer"] == C and zone["kind"] == "part")
+ self.assertTrue(sea.get("off"))
+ self.assertTrue(sea["parts"])
+ self.assertIsNone(ways.clash(held, "this Mac"))
+
+ def test_sharing_reports_every_machine_whose_way_back_it_changed_not_only_whose_zones(self):
+ # Sol's review: Sea's blocker moved from Ay to Bee, and only Ay and Bee were told.
+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"), peer(C, "Sea", side="right"),
+ zones=[{"peer": B, "kind": "part", "parts": ["middle"], "off": True},
+ {"peer": A, "kind": "edge"},
+ {"peer": B, "kind": "edge", "off": True},
+ {"peer": C, "kind": "edge", "off": True}])
+ before = ways.way_back_state(held)
+ changed = ways.share(held, "right", {"start": A, "middle": A, "end": B}, kinds=MAC)
+ after = ways.way_back_state(held)
+ self.assertTrue({peer for peer in after if after[peer] != before.get(peer)} <= set(changed), changed)
+
+ def test_a_split_naming_a_machine_not_on_that_side_or_leaving_a_third_out_is_refused(self):
+ held = self.two_on_the_right()
+ held["peers"].append(peer(C, "Sea", side="left"))
+ for thirds in ({"start": A, "middle": A, "end": C}, {"start": A, "middle": B}):
+ with self.subTest(thirds=thirds), self.assertRaises(ValueError):
+ ways.share(held, "right", thirds, kinds=MAC)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/core/ways.py b/core/ways.py
index 5fbfec4..0ab0978 100644
--- a/core/ways.py
+++ b/core/ways.py
@@ -8,6 +8,7 @@ app calls these on its settings under its own lock and writes the file itself.
import base64
import binascii
+import re
from typing import Callable, Optional
from core import peerlist
@@ -21,6 +22,71 @@ DEFAULT_PARTS = ["middle"]
DEFAULT_CORNER = "top_left"
# 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"}
+_JUMP_KEYS = {"backspace", "caps_lock", "delete", "down", "end", "enter", "esc", "home", "insert",
+ "left", "page_down", "page_up", "pause", "print_screen", "right", "space", "tab", "up",
+ "menu", "num_lock", "scroll_lock", "browser_back", "browser_forward", "volume_mute",
+ "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"}
+
+
+def valid_jump_key(value) -> bool:
+ """Whether a recorded jump key is one modifier chord with a single non-modifier key."""
+ if not isinstance(value, str) or not value or value != value.lower():
+ return False
+ parts = value.split("+")
+ if len(parts) < 2 or any(not part for part in parts) or len(set(parts)) != len(parts):
+ return False
+ modifiers = [part for part in parts if part in _JUMP_MODIFIERS]
+ keys = [part for part in parts if part not in _JUMP_MODIFIERS]
+ if not set(modifiers) - {"shift"} or len(keys) != 1:
+ return False
+ if parts[:-1] != [name for name in ("ctrl", "alt", "shift", "cmd") if name in modifiers]:
+ return False
+ key = keys[0]
+ return (key in _JUMP_KEYS or key == "plus" or re.fullmatch(r"[a-z0-9]", key) is not None
+ or re.fullmatch(r"f(?:[1-9]|1[0-9]|2[0-4])", key) is not None
+ or (len(key) == 1 and key.isprintable() and key not in "+ "))
+
+
+def jump_chord(modifiers, key) -> Optional[str]:
+ """The stable spelling shared by both capture hooks and the key recorders."""
+ modifiers = {name[:-2] if name in {"alt_r", "cmd_r", "ctrl_r", "shift_r"} else name for name in modifiers}
+ modifiers &= _JUMP_MODIFIERS
+ key = key.lower() if isinstance(key, str) else ""
+ if key == "+":
+ key = "plus"
+ value = "+".join([name for name in ("ctrl", "ctrl_r", "alt", "alt_r", "shift", "shift_r", "cmd", "cmd_r")
+ if name in modifiers] + [key])
+ return value if valid_jump_key(value) else None
+
+
+def jump_key(peer: dict) -> Optional[str]:
+ """The peer's optional local jump chord, or None when absent or empty."""
+ value = peer.get("jump_key")
+ return value if isinstance(value, str) and value else None
+
+
+def check_jump_key(settings: dict, peer: str, value, trigger_key: str) -> Optional[str]:
+ """Validate and clash-check a peer's jump chord before it is stored; empty clears it."""
+ if value in (None, ""):
+ return None
+ if not isinstance(value, str):
+ raise ValueError("choose a modifier and one non-modifier key")
+ if not valid_jump_key(value):
+ raise ValueError("choose a modifier and one non-modifier key")
+ parts = value.split("+")
+ if parts[-1] == trigger_key or (isinstance(trigger_key, str) and trigger_key.removesuffix("_r") in parts):
+ raise ValueError("that key is the trigger shortcut's: pick a chord without it")
+ for entry in settings.get("peers", []):
+ if entry.get("id") != peer and entry.get("jump_key") == value:
+ raise ValueError("that key is already assigned to another machine")
+ return value
+
+
+def jump_peer(peers: list, chord: str) -> Optional[str]:
+ """The in-use machine assigned this jump chord, or None."""
+ return next((entry.get("id") for entry in peers
+ if entry.get("in_use", True) is True and entry.get("id") and entry.get("jump_key") == chord), None)
def _entry(settings: dict, peer: str) -> Optional[dict]:
@@ -52,25 +118,19 @@ def ways(settings: dict, peer: str) -> dict:
def edit(settings: dict, peer: str, *, side: str, methods, parts, corner: str, kinds,
- corner_edge: Callable[[str, str], str], now: float, default: bool = False) -> bool:
+ corner_edge: Callable[[str, str], str], now: float) -> bool:
"""Writes one peer's ways: its `side`, and one zone of each of `kinds` (the kinds this app
offers), in use when named in `methods` and `off` otherwise. The whole edge covers its thirds,
so with both chosen the thirds are written `off` (section 8). `corner_edge(corner, side)` is
the edge this app's corner crosses. A changed side is stamped by this machine, never below the
- stamp held plus one. `default` says `side` is only what the page shows for a machine not placed
- yet, which nobody chose: it is written only while no side is held, unstamped and with no author,
- so a side either machine does choose wins over it. Returns whether the side changed, which the
- caller sends as `arrangement`. KeyError when no entry has `peer`."""
+ stamp held plus one. Returns whether the side changed, which the caller sends as `arrangement`.
+ KeyError when no entry has `peer`."""
entry = _entry(settings, peer)
if entry is None:
raise KeyError(peer)
side = side if side in EDGES else ""
- if default and entry.get("side") in EDGES:
- side = entry["side"]
moved = bool(side) and side != entry.get("side")
- if moved and default:
- entry.update(side=side, side_set_at=0, side_by="")
- elif moved:
+ if moved:
entry.update(side=side, side_set_at=next_stamp(entry.get("side_set_at"), now), side_by=settings["machine_id"])
methods = set(methods)
if "edge" in methods:
@@ -109,6 +169,83 @@ def _stretch(zone: dict, sides: dict) -> set:
return set()
+def share_offer(settings: dict, peer: str) -> Optional[dict]:
+ """Propose thirds for `peer` when another machine already uses part of its side."""
+ entry = _entry(settings, peer)
+ side = entry.get("side") if entry else ""
+ if side not in EDGES:
+ return None
+ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}
+ holders = _side_holders(settings, peer)
+ if not holders:
+ return None
+ holder_set = set(holders)
+ assigned = {}
+ for zone in settings["zones"]:
+ owner = zone.get("peer")
+ if owner not in holder_set or zone.get("off") is True or sides.get(owner) != side:
+ continue
+ if zone.get("kind") not in ("edge", "part"):
+ continue
+ covered = {part for stretch_side, part in _stretch(zone, sides) if stretch_side == side}
+ if not covered:
+ continue
+ for part in PARTS:
+ if part in covered:
+ assigned.setdefault(part, owner)
+ thirds = {part: assigned.get(part, peer) for part in PARTS}
+ if peer not in thirds.values():
+ thirds["end"] = peer
+ return {"side": side, "holders": holders, "thirds": thirds}
+
+
+def share(settings: dict, side: str, thirds: dict, *, kinds) -> list:
+ """Writes a side split by thirds (`thirds`: part -> machine id) after checking every third and its
+ machine, before anything changes: each machine on that side gets its thirds as a part zone in use
+ and its whole edge off; one left with none keeps its part zone off. Returns every machine to tell:
+ those whose zones changed and those whose way back or way_back_by did (section 8)."""
+ if side not in EDGES or not isinstance(thirds, dict) or set(thirds) != set(PARTS):
+ raise ValueError("a split needs every third of a known side")
+ peers = {entry.get("id"): entry for entry in settings["peers"]}
+ if any(not isinstance(peer, str) or peers.get(peer, {}).get("side") != side for peer in thirds.values()):
+ raise ValueError("every third must belong to a machine on that side")
+ if "part" not in kinds:
+ raise ValueError("this app does not offer parts of an edge")
+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}
+ owners = set(thirds.values())
+ told = way_back_state(settings)
+ changed = []
+ for entry in settings["peers"]:
+ peer = entry.get("id")
+ mine = _mine(settings, peer)
+ zones = [zone for zone in mine.values() if zone.get("off") is not True and
+ any(stretch[0] == side for stretch in _stretch(zone, sides))]
+ if entry.get("side") != side or (not zones and peer not in owners):
+ continue
+ edge = mine.get("edge")
+ part = mine.get("part")
+ expected = [name for name in PARTS if thirds[name] == peer]
+ before = (dict(edge) if edge else None, dict(part) if part else None)
+ if edge is not None:
+ edge["off"] = True
+ if part is None:
+ part = {"peer": peer, "kind": "part"}
+ settings["zones"].append(part)
+ if expected:
+ part["parts"] = expected
+ part.pop("off", None)
+ else:
+ # Off, never empty: the settings refuse a part zone that names no third.
+ if not (isinstance(part.get("parts"), list) and part["parts"]):
+ part["parts"] = list(DEFAULT_PARTS)
+ part["off"] = True
+ if before != (dict(edge) if edge else None, dict(part)):
+ changed.append(peer)
+ # A machine whose zones did not change can still be told something new: who holds its side.
+ changed += [peer for peer, state in way_back_state(settings).items() if told.get(peer) != state and peer not in changed]
+ return changed
+
+
def _clashing(settings: dict):
"""The first two zones in use that cover one stretch, and that stretch; None when none do."""
sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}
@@ -149,17 +286,17 @@ def _id_bytes(text) -> Optional[bytes]:
data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
except (binascii.Error, ValueError):
return None
- return data if len(data) == 16 and base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") == text else None
+ return data if len(data) == 16 and any(data) and base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") == text else None
def arrangement(settings: dict, peer: str, edge: str, set_at: int, by: str, here: str, way_back=None,
- corner_edge: Optional[Callable[[str, str], str]] = None):
+ way_back_by=None, corner_edge: Optional[Callable[[str, str], str]] = None):
"""A peer's `arrangement` (section 8): `edge` is the peer's edge that faces this machine, so this
machine's side for it is the opposite. Taken when newer than the side held: a higher stamp, or the
same stamp and the larger `by` as bytes. A machine with no zone yet gets its whole edge for that
side, and a side that would put two zones in use over one stretch is applied and turns this peer's
- clashing zones off. `way_back`, when the message carried it, is kept on the entry whether or not
- the side was newer. `corner_edge(corner, side)`, the app's own, rewrites the edge its corner zones
+ clashing zones off. `way_back` and `way_back_by`, when carried, are kept on the entry whether or
+ not the side was newer. `corner_edge(corner, side)`, the app's own, rewrites the edge its corner zones
for the peer cross, as `edit` does, since a PC's corner crosses the side. Returns (changed,
notices), a sentence for each zone turned off; `here` is "this Mac" or "this PC"."""
entry = _entry(settings, peer)
@@ -169,6 +306,17 @@ def arrangement(settings: dict, peer: str, edge: str, set_at: int, by: str, here
told = isinstance(way_back, bool) and entry.get("way_back") is not way_back
if told:
entry["way_back"] = way_back
+ if isinstance(way_back, bool):
+ holder = _id_bytes(way_back_by)
+ valid_holder = holder is not None and way_back is False and holder != _id_bytes(settings.get("machine_id"))
+ if valid_holder:
+ valid_text = way_back_by
+ if entry.get("way_back_by") != valid_text:
+ entry["way_back_by"] = valid_text
+ told = True
+ elif "way_back_by" in entry:
+ del entry["way_back_by"]
+ told = True
held = (int(entry.get("side_set_at") or 0), _id_bytes(entry.get("side_by")) or b"")
if (int(set_at), by_bytes) <= held:
return told, []
@@ -187,6 +335,20 @@ def _zoned(entry: dict) -> bool:
return bool(entry.get("id")) and entry.get("port") != 0
+def default_side(settings: dict) -> bool:
+ """The Mac's one paired machine with no side holds Right, the side its Crossing page shows, so
+ its edge crosses from pairing rather than from the first save. Unstamped and with no author, so a
+ side either machine chooses wins over it. Only with one entry in all, as the page counts them: a
+ second, even the one migrated from 1.4.x, may hold Right already. True when it wrote the side."""
+ if len(settings["peers"]) != 1:
+ return False
+ entry = settings["peers"][0]
+ if not _zoned(entry) or entry.get("side") in EDGES:
+ return False
+ entry.update(side="right", side_set_at=0, side_by="")
+ return True
+
+
def ensure_zones(settings: dict) -> bool:
"""Gives every machine with no zone at all its whole edge, `off` when its side is another machine's
already, so the settings stay readable (section 8, overlap). Pairing never made zones before
@@ -227,10 +389,7 @@ def blocked_sentence(settings: dict, peer: str, here: str) -> str:
side = entry.get("side")
if side not in EDGES or has_way(settings, peer):
return ""
- sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}
- holder = next((zone.get("peer") for zone in settings["zones"]
- if zone.get("peer") != peer and zone.get("off") is not True and zone.get("kind") in ("edge", "part")
- and _stretch(zone, sides) & {(side, part) for part in PARTS}), None)
+ holder = _side_holder(settings, peer)
if holder is None:
return ""
peers = settings["peers"]
@@ -247,9 +406,52 @@ def no_way_back_sentence(settings: dict, peer: str) -> str:
if entry.get("way_back") is not False:
return ""
name = peerlist.label_for(settings["peers"], peer_id=peer) or peerlist.UNNAMED
+ 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"
+ 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."
+def way_back_by(settings: dict, peer: str) -> Optional[str]:
+ """The machine whose active edge or part zone holds `peer`'s side here, when no way leads to it."""
+ return _side_holder(settings, peer) if not has_way(settings, peer) else None
+
+
+def way_back_state(settings: dict) -> dict:
+ """What this machine tells every zoned peer about its way back, keyed by peer id."""
+ return {entry["id"]: (has_way(settings, entry["id"]), way_back_by(settings, entry["id"]))
+ for entry in settings["peers"] if _zoned(entry)}
+
+
+def _side_holder(settings: dict, peer: str) -> Optional[str]:
+ """The first active edge or part zone holding `peer`'s side, in zone order."""
+ holders = _side_holders(settings, peer)
+ return holders[0] if holders else None
+
+
+def _side_holders(settings: dict, peer: str) -> list:
+ """Every machine with an active edge or part zone over `peer`'s side, in zone order."""
+ entry = _entry(settings, peer) or {}
+ side = entry.get("side")
+ if side not in EDGES:
+ return []
+ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}
+ stretches = {(side, part) for part in PARTS}
+ holders = []
+ for zone in settings["zones"]:
+ owner = zone.get("peer")
+ if (owner != peer and owner not in holders and zone.get("off") is not True
+ and zone.get("kind") in ("edge", "part") and _stretch(zone, sides) & stretches):
+ holders.append(owner)
+ return holders
+
+
def settle(settings: dict, peer: str, here: str) -> list:
"""After a machine's side moved here: its zones that now clash with another machine's are turned
off, as when the side arrives from that machine, and a sentence for each is returned."""
@@ -287,7 +489,7 @@ def _turn_off_clashes(settings: dict, entry: dict, here: str) -> list:
def _sendable(entry: dict) -> bool:
- return bool(entry.get("id")) and entry.get("send") is True and entry.get("port") != 0
+ return bool(entry.get("id")) and entry.get("in_use", True) is True and entry.get("send") is True and entry.get("port") != 0
def shortcut_peer(peers: list, last: Optional[str], ready: Callable[[str], bool]) -> Optional[str]:
@@ -306,7 +508,7 @@ def missing_pairings(settings: dict, peer: str) -> list:
they are not paired with `peer` (section 5, "What the Crossing page may offer"). A machine is
judged only once it has linked, since its `paired` list arrives on a link."""
return [entry for entry in settings["peers"]
- if entry.get("id") != peer and entry.get("allow_drive") is True and entry.get("linked") is True
+ if entry.get("id") != peer and entry.get("in_use", True) is True and entry.get("allow_drive") is True and entry.get("linked") is True
and peer not in (entry.get("paired_with") or [])]
diff --git a/mac_app/bridge.py b/mac_app/bridge.py
index 59c2625..c54dd92 100644
--- a/mac_app/bridge.py
+++ b/mac_app/bridge.py
@@ -5,8 +5,10 @@ import logging
import platform
import queue
import socket
+import sys
import threading
import time
+import traceback
import types
import dataclasses
from dataclasses import dataclass
@@ -68,9 +70,7 @@ MEDIA_KEY_NAMES = frozenset({"volume_mute", "volume_down", "volume_up", "media_n
# Why input came home, in words, for the alert. A why that is not here comes home quietly.
WHY_TEXT = {
- "owned": "{name} is being driven from another machine",
"not_allowed": "{name} does not accept input from this Mac",
- "busy": "{name} is driving another machine",
"malformed": "{name} could not read the request to take it",
"refused": "{name} refused the input",
"no_answer": "{name} did not answer",
@@ -474,7 +474,10 @@ class KVMController:
@redirecting.setter
def redirecting(self, value):
+ old = self._redirecting
self._redirecting = bool(value)
+ if old != self._redirecting:
+ self.logger.info("redirecting %s -> %s (thread %s)", old, self._redirecting, threading.current_thread().name)
if not self._redirecting:
self.pointer.show()
@@ -523,6 +526,11 @@ class KVMController:
self.pointer = PointerHider(quartz, logger=self.logger)
self._cursor_assoc_status_logged = False
self._cursor_warp_error_logged = False
+ self._redirecting = False
+ self._repair_lock = threading.Lock()
+ self._repair_running = False
+ self._repair_again = False
+ self._repair_disagreement_seen = False
self.redirecting = False
# True while another machine is driving this Mac over a link it opened. The tap passes
# everything through while it is, except this Mac's own trigger key, so the two directions
@@ -558,6 +566,8 @@ class KVMController:
self.tap_callback_ref = self._event_tap_callback
self.translator = QuartzEventTranslator(quartz)
self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]
+ self._jump_swallowed = set()
+ self.jump_recording = False
self.last_trigger_down = 0.0
self.trigger_suppressed = False
self.redirect_started_at = 0.0
@@ -643,7 +653,8 @@ class KVMController:
return crossing.CrossingEngine(resistance_px=self.cfg.crossing["resistance_px"],
block_while_dragging=self.cfg.crossing["block_while_dragging"], ways=[])
return crossing.CrossingEngine.from_config(self.cfg.crossing)
- peers = [entry for entry in self.book.peers() if entry.get("send") is True]
+ peers = [entry for entry in self.book.peers()
+ if entry.get("in_use", True) is True and entry.get("send") is True]
return crossing.CrossingEngine.from_zones(self.cfg.crossing, self.book.zones(), peers)
def zones_changed(self):
@@ -674,7 +685,8 @@ class KVMController:
its link goes only at the next sync."""
if self._memory is not None:
return bool(self.cfg.send_to_windows)
- return any(entry.get("id") == peer and entry.get("send") is True for entry in self.book.peers())
+ return any(entry.get("id") == peer and entry.get("in_use", True) is True and entry.get("send") is True
+ for entry in self.book.peers())
def _zone_peer(self, step):
"""The machine a push through a zone goes to; a Config-built controller's one machine has no id in its zones."""
@@ -1258,6 +1270,8 @@ class KVMController:
if self.event_tap is not None:
self.quartz.CGEventTapEnable(self.event_tap, True)
return event
+ if not self._was_injected(event) and self._handle_jump_key(event_type, event):
+ return None
if self.receiving:
# The PC is driving this Mac over the other link. Everything
# passes through untouched: crossing must not read a pointer
@@ -1286,9 +1300,25 @@ class KVMController:
return self._handle_local_mouse(event_type, event)
return event
if self.gesture_translator.wants(event_type):
- return self._handle_gesture_event(event_type, event)
+ if self.redirecting and not self.owner.away:
+ self._repair_redirecting_disagreement()
+ return event
+ handled = self._handle_gesture_event(event_type, event)
+ if handled is None and self.redirecting and not self.owner.away:
+ # Input came home while it was converted: this one is the user's.
+ self._repair_redirecting_disagreement()
+ return event
+ return handled
if event_type == media_keys.NX_SYSDEFINED_EVENT_TYPE:
- return self._handle_system_event(event)
+ if self.redirecting and not self.owner.away:
+ self._repair_redirecting_disagreement()
+ return event
+ handled = self._handle_system_event(event)
+ if handled is None and self.redirecting and not self.owner.away:
+ # Input came home while it was converted: this one is the user's.
+ self._repair_redirecting_disagreement()
+ return event
+ return handled
if self._was_injected(event):
# One Beamer itself posted for the PC, on its way to an app
# here. Only keys and pointer events are ever injected, which
@@ -1307,6 +1337,9 @@ class KVMController:
)
if result.is_trigger:
return self._handle_trigger(result, event)
+ if self.redirecting and not self.owner.away:
+ self._repair_redirecting_disagreement()
+ return event
had = len(result.messages)
result.messages = self._after_home_presses(result.messages)
if self.redirecting:
@@ -1325,6 +1358,9 @@ class KVMController:
# The release of a key pressed here, while the input was home, stays here.
return event
else:
+ if self.redirecting and not self.owner.away:
+ self._repair_redirecting_disagreement()
+ return event
button = self.translator.button_of(event_type, event)
if not self.redirecting:
if button is not None:
@@ -1361,6 +1397,9 @@ class KVMController:
self._warp_cursor_to_pin()
if not self.redirecting:
return event
+ if not self.owner.away:
+ self._repair_redirecting_disagreement()
+ return event
return None
except BaseException:
self._return_local()
@@ -1482,6 +1521,47 @@ class KVMController:
self._notify_crossing("tick" if step.tick else "pressure", step)
return event
+ def _handle_jump_key(self, event_type, event):
+ """Moves input to the peer named by a local jump chord and consumes its key press."""
+ quartz = self.quartz
+ if event_type not in (quartz.kCGEventKeyDown, quartz.kCGEventKeyUp):
+ return False
+ keycode = int(quartz.CGEventGetIntegerValueField(event, quartz.kCGKeyboardEventKeycode))
+ if event_type == quartz.kCGEventKeyUp and keycode in self._jump_swallowed:
+ self._jump_swallowed.discard(keycode)
+ return True
+ if event_type == quartz.kCGEventKeyDown and keycode in self._jump_swallowed:
+ return True
+ if event_type != quartz.kCGEventKeyDown or self.jump_recording:
+ return False
+ # A key already down when its modifiers arrive repeats; it is not a press of the chord.
+ if quartz.CGEventGetIntegerValueField(event, quartz.kCGKeyboardEventAutorepeat):
+ return False
+ key = SPECIAL_KEY_NAMES.get(keycode) or PRINTABLE_KEY_FALLBACKS.get(keycode)
+ if key is None:
+ character = self.translator._unicode_character(event, keycode)
+ key = character.lower() if character and len(character) == 1 else None
+ if key is None or key in ("shift", "shift_r", "alt", "alt_r", "ctrl", "ctrl_r", "cmd", "cmd_r"):
+ return False
+ flags = quartz.CGEventGetFlags(event)
+ modifiers = []
+ for name, mask in (("ctrl", quartz.kCGEventFlagMaskControl), ("alt", quartz.kCGEventFlagMaskAlternate),
+ ("shift", quartz.kCGEventFlagMaskShift), ("cmd", quartz.kCGEventFlagMaskCommand)):
+ if flags & mask:
+ modifiers.append(name)
+ chord = ways.jump_chord(modifiers, key)
+ if chord is None:
+ return False
+ peer = ways.jump_peer(self.book.peers(), chord)
+ if peer is None:
+ return False
+ self._jump_swallowed.add(keycode)
+ if self.owner.on == peer:
+ self.set_redirecting(False)
+ else:
+ self.set_redirecting(True, peer=peer)
+ return True
+
def _current_desktop_bounds(self):
now = self.clock()
if self._bounds_cache is None or now - self._bounds_at > DESKTOP_BOUNDS_MAX_AGE_SECONDS:
@@ -1700,8 +1780,10 @@ class KVMController:
"""One link per peer with `send` on, made and ended to match the peers as the book has them
now. Cheap, and called every couple of seconds as well as when the settings change."""
peers = self.book.peers()
- wanted = {peer["token"] for peer in peers if peer.get("token") and peer.get("send") is True}
- first = peers[0].get("token") if peers else None
+ wanted = {peer["token"] for peer in peers if peer.get("token") and peer.get("in_use", True) is True
+ and peer.get("send") is True}
+ first = next((peer["token"] for peer in peers
+ if peer.get("token") and peer.get("in_use", True) is True and peer.get("send") is True), None)
with self._links_lock:
gone = [self.links.pop(token) for token in [token for token in self.links if token not in wanted]]
if not self.stop_event.is_set():
@@ -1847,8 +1929,10 @@ class KVMController:
own = bytes(self.identity()["id"])
if entry.get("side") in crossing.EDGES:
by = protocol.read_id(entry.get("side_by")) or own
- link.post(protocol.arrangement_v6(entry["side"], entry.get("side_set_at", 0), by,
- way_back=self.way_back(link.peer_id)))
+ link.post(protocol.arrangement_v6(
+ entry["side"], entry.get("side_set_at", 0), by, way_back=self.way_back(link.peer_id),
+ way_back_by=protocol.read_id(self.way_back_by(link.peer_id)),
+ ))
if "settings" in link.caps:
try:
announcements = list(self.announce())
@@ -1861,10 +1945,12 @@ class KVMController:
self._announce_paired(link)
def _pairing_ids(self):
- return tuple(peer.get("id") for peer in self.book.peers() if protocol.read_id(peer.get("id")) is not None)
+ return tuple(peer.get("id") for peer in self.book.peers()
+ if peer.get("in_use", True) is True and protocol.read_id(peer.get("id")) is not None)
def _announce_paired(self, link):
- ids = [protocol.read_id(peer.get("id")) for peer in self.book.peers() if peer.get("id") != link.peer_id]
+ ids = [protocol.read_id(peer.get("id")) for peer in self.book.peers()
+ if peer.get("in_use", True) is True and peer.get("id") != link.peer_id]
ids = [ident for ident in ids if ident is not None][:protocol.MAX_PEERS]
link.post(protocol.paired_msg(ids))
@@ -1933,7 +2019,10 @@ class KVMController:
read = protocol.read_arrangement_v6(message, time.time())
if read is None or self.on_arrangement is None or not peer:
return
- self.on_arrangement(peer, read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"))
+ args = (peer, read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"))
+ if read.get("way_back_by"):
+ args += (protocol.id_text(read["way_back_by"]),)
+ self.on_arrangement(*args)
def way_back(self, peer):
"""Whether one of this Mac's zones in use leads to `peer` and can fire: what every `arrangement`
@@ -1941,6 +2030,11 @@ class KVMController:
with self.book.lock:
return ways.has_way({"peers": self.book.peers(), "zones": self.book.zones()}, peer)
+ def way_back_by(self, peer):
+ with self.book.lock:
+ return ways.way_back_by({"machine_id": protocol.id_text(self.identity()["id"]),
+ "peers": self.book.peers(), "zones": self.book.zones()}, peer)
+
def send_arrangement(self, peer, mac_edge, set_at, by=None):
"""Tell `peer` which edge of this Mac faces it, stamped `set_at` by `by` (a b64 id, this Mac when
None), with whether a way leads there, over this Mac's own link to it. Sent straight out: it is
@@ -1950,7 +2044,10 @@ class KVMController:
if link is None or not link.live():
return False
author = protocol.read_id(by) or bytes(self.identity()["id"])
- return link.post(protocol.arrangement_v6(mac_edge, int(set_at), author, way_back=self.way_back(peer)))
+ return link.post(protocol.arrangement_v6(
+ mac_edge, int(set_at), author, way_back=self.way_back(peer),
+ way_back_by=protocol.read_id(self.way_back_by(peer)),
+ ))
def send_settings(self, data, source=None):
"""Tell every peer that keeps Same on all machines this Mac's state, but `source` (the peer
@@ -2127,7 +2224,16 @@ class KVMController:
return {"type": message["type"], "data": data}
def _on_moved(self, moved):
+ self.logger.info(
+ "move applied: to %s from %s why %s (thread %s)",
+ self._name_of(moved.to) if moved.to is not None else "home",
+ self._name_of(moved.left) if moved.left is not None else "home",
+ moved.why,
+ threading.current_thread().name,
+ )
if moved.to is not None:
+ with self._repair_lock:
+ self._repair_disagreement_seen = False
if not self.redirecting:
self.redirect_started_at = self.clock()
self.redirecting = True
@@ -2138,9 +2244,14 @@ class KVMController:
self.logger.info("redirecting input to %s", self._name_of(moved.to))
return
self._local_cleanup()
- why = WHY_TEXT.get(moved.why)
- if why is not None:
- text = why.format(name=self._name_of(moved.left))
+ other = ""
+ if isinstance(moved.other, bytes) and moved.other != bytes(self.identity()["id"]):
+ other = peerlist.label_for(self.book.peers(), peer_id=protocol.id_text(moved.other))
+ name = self._name_of(moved.left)
+ text = peerlist.refusal_text(moved.why, name, other)
+ if text is None and moved.why in WHY_TEXT:
+ text = 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)
if moved.why == "switch":
@@ -2168,7 +2279,12 @@ class KVMController:
why = unreachable.why
if why == "unreachable" and self._accepts.get(unreachable.peer) is False:
why = "not_allowed"
- text = WHY_TEXT.get(why, "{name} could not be reached").format(name=name)
+ other = ""
+ if isinstance(unreachable.other, bytes) and unreachable.other != bytes(self.identity()["id"]):
+ 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)
self.logger.warning("%s", text)
self._alert("Beamer", text)
@@ -2264,7 +2380,64 @@ class KVMController:
return
if not self.redirecting:
return
- self._step(lambda owner: owner.input(message) if owner.away else [])
+ def route(owner):
+ if owner.away:
+ return owner.input(message)
+ self._repair_redirecting_disagreement()
+ return []
+
+ self._step(route)
+
+ def _repair_redirecting_disagreement(self):
+ """The tap is about to swallow input as redirected while the owner says it is home. Starts
+ one repair and nothing else: the tap thread never logs, formats a stack or takes the owner's
+ or the effects lock, since anything that stalls it holds the user's keyboard."""
+ with self._repair_lock:
+ if self._repair_running:
+ # Asked again while one runs: it looks once more before it ends.
+ self._repair_again = True
+ return
+ self._repair_running = True
+ self._repair_again = False
+ try:
+ threading.Thread(target=self._repair, name="Beamer-repair", daemon=True).start()
+ except BaseException:
+ with self._repair_lock:
+ self._repair_running = False
+
+ def _repair(self):
+ """Puts redirecting right if the two views still disagree once every move in flight has
+ been applied: checked under the owner's and the effects lock, so the gap of an ordinary
+ return, or a take that landed since, is left alone. The first disagreement of an episode is
+ logged with every thread's stack, so the next one names its cause."""
+ while True:
+ self._repair_once()
+ with self._repair_lock:
+ if not self._repair_again:
+ self._repair_running = False
+ return
+ self._repair_again = False
+
+ def _repair_once(self):
+ try:
+ # Both held through the check, as _step holds them between deciding a move and
+ # applying it, so a return in flight is never read as a disagreement.
+ with self._owner_lock, self._effects_lock:
+ diverged = self.redirecting and not self.owner.away
+ if diverged:
+ self._local_cleanup()
+ with self._repair_lock:
+ log = diverged and not self._repair_disagreement_seen
+ if diverged:
+ self._repair_disagreement_seen = True
+ if log:
+ frames = sys._current_frames()
+ stacks = ["Thread %s:\n%s" % (thread.name, "".join(traceback.format_stack(frames[thread.ident])))
+ for thread in threading.enumerate() if thread.ident in frames]
+ self.logger.error("redirecting while the owner says input is home; input forced local\n%s",
+ "\n".join(stacks))
+ except Exception:
+ self.logger.exception("putting redirecting right failed")
def _force_local(self, reason):
self._return_local()
diff --git a/mac_app/crossing.py b/mac_app/crossing.py
index 9f8f3ae..27c4a5a 100644
--- a/mac_app/crossing.py
+++ b/mac_app/crossing.py
@@ -144,7 +144,8 @@ class CrossingEngine:
"""An engine for every zone in use that leads to one of `peers` (settings entries, each with
its `id` and `side`): the machines this Mac can send to now. A machine with no side keeps its
corner and the notch, which do not need one."""
- sides = {entry.get("id"): entry.get("side") for entry in peers if entry.get("id")}
+ sides = {entry.get("id"): entry.get("side") for entry in peers
+ if entry.get("id") and entry.get("in_use", True) is True}
found = {}
for zone in zones:
peer = zone.get("peer")
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index c9869b5..6ab2dac 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -44,6 +44,7 @@ from key_codes import KEY_NAME_TO_CODE
import link_state
import machines_panel
import login_item
+import notices
import pages
from core import updates
from core import protocol
@@ -1123,6 +1124,7 @@ class ControlWindow(AppKit.NSObject):
# another page.
if key != "crossing":
self.key_recorder.cancel()
+ self.jump_recorder.cancel()
if key != "keyboard":
self.ignored_recorder.cancel()
self._run_previews()
@@ -1330,12 +1332,13 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _load_ways(self, flat=None):
"""The chosen machine's ways into the page's controls, from the settings (core/ways.py);
- with nothing paired, from `flat`, the crossing settings as 1.4.x kept them. A chosen machine
- no longer paired gives way to the first."""
+ with nothing active, from `flat`, the crossing settings as 1.4.x kept them. A chosen machine
+ no longer paired or in use gives way to the first active machine."""
settings = self.settings_store.current()
peers = settings["peers"]
- if self.chosen_peer not in {entry["id"] for entry in peers}:
- self.chosen_peer = peers[0]["id"] if peers else None
+ available = [entry for entry in peers if entry.get("in_use", True) is True]
+ if self.chosen_peer not in {entry["id"] for entry in available}:
+ self.chosen_peer = available[0]["id"] if available else None
if self.chosen_peer is None:
flat = flat or self.controller.cfg.crossing
held = {"side": flat["edge"], "methods": flat["methods"], "parts": flat["edge_parts"], "corner": flat["corner"]}
@@ -1355,12 +1358,14 @@ class ControlWindow(AppKit.NSObject):
machines or their names change, and the words on the page that name the chosen one."""
settings = self.settings_store.current()
peers = settings["peers"]
- if self.chosen_peer not in {entry["id"] for entry in peers} and (peers or self.chosen_peer is not None):
+ available = [entry for entry in peers if entry.get("in_use", True) is True]
+ if self.chosen_peer not in {entry["id"] for entry in available} and (available or self.chosen_peer is not None):
self._load_ways()
self._reflect()
return
labels = peerlist.labels(peers)
- choices = [(entry["id"], self._shown(labels[entry["token"]])) for entry in peers]
+ choices = [(entry["id"], self._shown(labels[entry["token"]])) for entry in peers
+ if entry.get("in_use", True) is True]
several = len(choices) > 1
if choices != self._picker_choices:
self._picker_choices = choices
@@ -1381,13 +1386,60 @@ class ControlWindow(AppKit.NSObject):
self.edge_select.view.setAccessibilityLabel_(caption)
self.edge_note.set(pages.notch_or_corner_note(label))
chosen = self.chosen_peer
+ offer = core_ways.share_offer(settings, chosen) if chosen else None
+ holders = [self._shown(peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED)
+ for peer in offer["holders"]] if offer else []
+ identity = (offer["side"], tuple(offer["holders"]), tuple(offer["thirds"].items())) if offer else None
+ if identity != getattr(self, "_share_identity", None):
+ self._share_identity = identity
+ self.share_thirds = dict(offer["thirds"]) if offer else {}
+ motion.set_hidden(self.share_box, offer is None)
+ if offer:
+ side = offer["side"]
+ self.share_title.set(f"Share the {side} edge")
+ self.share_sentence.set(pages.share_sentence(holders, side, self._chosen_label()))
+ self.share_button.set_title(f"Share the {side} edge")
+ self.share_recipients = [chosen, *offer["holders"]]
+ for part, tile in self.share_tiles.items():
+ tile.name.set(pages.part_names(side)[part])
+ owner = self.share_thirds[part]
+ tile.set_detail(self._shown(peerlist.label_for(peers, peer_id=owner) or peerlist.UNNAMED))
+ tile.value = owner == chosen
+ self.share_button.set_enabled(chosen in self.share_thirds.values())
for note, sentence in (
- (self.blocked_note, core_ways.blocked_sentence(settings, chosen, "this Mac") if chosen else ""),
+ (self.blocked_note, core_ways.blocked_sentence(settings, chosen, "this Mac") if chosen and not offer else ""),
(self.missing_note, core_ways.missing_sentence(settings, chosen, "this Mac") if chosen else ""),
(self.no_way_back_note, core_ways.no_way_back_sentence(settings, chosen) if chosen else "")):
note.set(self._shown(sentence))
motion.set_hidden(note.view, not sentence)
+ self._show_jump_key()
+
+ @objc.python_method
+ def _share_third(self, part):
+ """Move one offered third to the next machine without writing until Share is pressed."""
+ recipients = self.share_recipients
+ current = recipients.index(self.share_thirds[part])
+ self.share_thirds[part] = recipients[(current + 1) % len(recipients)]
+ self._show_machines()
+
+ @objc.python_method
+ def _share_side(self):
+ """Apply the proposed split, rebuild the live zones and tell every affected machine."""
+ side, thirds = self._share_identity[0], dict(self.share_thirds)
+ try:
+ changed = self.settings_store.share_side(side, thirds)
+ cfg = self.settings_store.load()
+ except (SettingsError, ValueError):
+ self.logger.exception("The shared side could not be saved")
+ return
+ self.controller.cfg = cfg
+ self.controller.zones_changed()
+ for peer in changed:
+ self._tell(peer)
+ self._load_ways()
+ self._reflect()
+
@objc.python_method
def _machine_picked(self, peer):
# A change still waiting out the pause belongs to the machine being left.
@@ -1592,6 +1644,7 @@ class ControlWindow(AppKit.NSObject):
def windowWillClose_(self, _notification):
self.key_recorder.cancel()
+ self.jump_recorder.cancel()
self.ignored_recorder.cancel()
# A code that stays up with nobody watching would still accept a pairing.
self.panel.stop_showing()
@@ -2104,6 +2157,24 @@ class ControlWindow(AppKit.NSObject):
)
self.edge_row, self.edge_caption = widgets.field_row(pages.where_caption(None), self.edge_select.view)
module.add(self.edge_row)
+ # A group within Ways, never a panel of its own: a panel inside a panel also forced the
+ # window's layout and squeezed the pairing sheet's code boxes to 28 pt.
+ self.share_box = widgets.stack(spacing=8)
+ self.share_title = widgets.Label("Share the edge", theme.TYPE["eyebrow"], 700, "ink_3",
+ tracking=theme.TRACKING["eyebrow"], upper=True)
+ widgets.add(self.share_box, self.share_title.view)
+ self.share_sentence = widgets.note()
+ widgets.add(self.share_box, self.share_sentence.view)
+ self.share_thirds = {}
+ self.share_tiles = {
+ part: widgets.WayTile(pages.part_names("right")[part], on_change=lambda _on, part=part:
+ self._share_third(part)) for part in return_edge.PARTS
+ }
+ widgets.add(self.share_box, widgets.grid([tile.view for tile in self.share_tiles.values()], 3))
+ self.share_button = widgets.action_button("Share the right edge", self._share_side, style="primary")
+ self.share_box.addArrangedSubview_(self.share_button.view)
+ self.share_box.setHidden_(True)
+ module.add(self.share_box)
self.edge_note = widgets.note(pages.notch_or_corner_note(None))
self.edge_note.view.setHidden_(True)
module.add(self.edge_note.view)
@@ -2136,8 +2207,56 @@ class ControlWindow(AppKit.NSObject):
module.add(note.view)
self.dragging_box = widgets.Switch("Don't cross while dragging", on_change=self._changed)
module.add(self.dragging_box.view)
+ self.jump_box = widgets.stack(spacing=8)
+ widgets.add(self.jump_box, widgets.eyebrow("Jump straight here"))
+ self.jump_recorder = widgets.JumpKeyRecorder(on_change=self._record_jump_key, on_arm=self._jump_arming)
+ jump_controls = widgets.stack(vertical=False, spacing=8)
+ jump_controls.addArrangedSubview_(self.jump_recorder.view)
+ self.jump_clear = widgets.Button("Clear", self, "clearJumpKey:", scale="small")
+ jump_controls.addArrangedSubview_(self.jump_clear.view)
+ widgets.add(self.jump_box, jump_controls)
+ self.jump_note = widgets.note()
+ widgets.add(self.jump_box, self.jump_note.view)
+ module.add(self.jump_box)
+ module.body.setCustomSpacing_afterView_(18, self.dragging_box.view)
return module
+ @objc.python_method
+ def _show_jump_key(self):
+ peers = self.settings_store.current()["peers"]
+ entry = next((peer for peer in peers if peer.get("id") == self.chosen_peer), None)
+ self.jump_box.setHidden_(entry is None)
+ if entry is None:
+ self.jump_recorder.cancel()
+ return
+ self.jump_recorder.set_value(entry.get("jump_key", ""))
+ name = self._shown(peerlist.label_for(peers, peer_id=self.chosen_peer) or "this machine")
+ self.jump_note.set(f"sends input to {name}")
+ self.jump_clear.view.setAccessibilityLabel_(f"Clear jump key for {name}")
+
+ @objc.python_method
+ def _jump_arming(self, armed):
+ self.controller.jump_recording = armed
+
+ @objc.python_method
+ def _record_jump_key(self, value):
+ self._save_jump_key(value)
+
+ @objc.python_method
+ def _save_jump_key(self, value):
+ try:
+ self.settings_store.set_jump_key(self.chosen_peer, value, self.controller.cfg.trigger_key)
+ except SettingsError as exc:
+ peer = next((peer for peer in self.settings_store.current()["peers"] if peer.get("id") == self.chosen_peer), None)
+ if peer is not None:
+ self.jump_recorder.set_value(peer.get("jump_key", ""))
+ self.jump_note.set(str(exc), ink="amber")
+ return
+ self._show_jump_key()
+
+ def clearJumpKey_(self, _sender):
+ self._save_jump_key("")
+
@objc.python_method
def _way_toggled(self, way, on):
methods = pages.toggle_way([name for name, tile in self.method_boxes.items() if tile.value], way, on)
@@ -2732,24 +2851,31 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _write_ways(self):
"""The chosen machine's side and zones from the page's controls (core/ways.py), the engine
- built again from them, and a side that moved, or a way there that opened or closed, sent to
- that machine (`_tell`). False, with the store's sentence said and the controls back at what is
- saved, when the store refuses them."""
+ built again from them, and every machine whose way back changed told, along with the chosen
+ machine when its side or way changed. False, with the store's sentence said and the controls
+ back at what is saved, when the store refuses them."""
peer = self.chosen_peer
current = self.settings_store.current()
if peer not in {entry["id"] for entry in current["peers"]}:
# None chosen, or one removed while its change waited: nothing of its to write.
return True
side = self.edge_select.value or ""
+ methods = [name for name in core_ways.KIND_WORDS if self.method_boxes[name].value]
+ parts = [name for name, tile in self.part_boxes.items() if tile.value] or ["middle"]
+ offer = core_ways.share_offer(current, peer)
+ occupied = {part for part, owner in offer["thirds"].items() if owner in offer["holders"]} if offer else set()
+ if offer and side == offer["side"] and (
+ "edge" in methods or "part" in methods and occupied.intersection(parts)):
+ self._load_ways()
+ self._reflect()
+ self.window.makeFirstResponder_(self.share_button.view)
+ return False
+ before = core_ways.way_back_state(current)
had_way = core_ways.has_way(current, peer)
- # Right is shown for one machine not placed yet, and cannot be picked again while shown: written
- # unstamped, so it crosses here and a side either machine does choose wins over it.
- default = not core_ways.ways(current, peer)["side"] and side == pages.shown_side("", len(current["peers"]))
try:
moved = self.settings_store.set_ways(
- peer, side=side, default=default, corner=self.corner_select.value,
- methods=[name for name in core_ways.KIND_WORDS if self.method_boxes[name].value],
- parts=[name for name, tile in self.part_boxes.items() if tile.value] or ["middle"])
+ peer, side=side, corner=self.corner_select.value,
+ methods=methods, parts=parts)
cfg = self.settings_store.load()
except SettingsError as exc:
self._say(str(exc), "fault")
@@ -2764,8 +2890,13 @@ class ControlWindow(AppKit.NSObject):
# A side moved onto another machine's turns this machine's ways there off: show what was kept.
self._load_ways()
self._reflect()
- if moved or core_ways.has_way(self.settings_store.current(), peer) != had_way:
- self._tell(peer)
+ updated = self.settings_store.current()
+ changed_peers = [target for target, state in core_ways.way_back_state(updated).items()
+ if before.get(target) != state]
+ if moved or core_ways.has_way(updated, peer) != had_way:
+ changed_peers.append(peer)
+ for target in dict.fromkeys(changed_peers):
+ self._tell(target)
return True
@objc.python_method
@@ -2780,7 +2911,7 @@ class ControlWindow(AppKit.NSObject):
self.windows_input.send_arrangement(peer, side, at, by)
@objc.python_method
- def apply_arrangement(self, peer, edge, set_at, by, way_back=None):
+ def apply_arrangement(self, peer, edge, set_at, by, way_back=None, way_back_by=None):
"""A machine changed which of its edges faces this Mac (`edge` is its own). Applied here
rather than at either link, because this is the side that owns the settings file; kept only
when newer than the side held for that machine, a tie going to the larger `by` (WIRE.md
@@ -2791,8 +2922,9 @@ class ControlWindow(AppKit.NSObject):
# A change still waiting out the pause is written first: the page reloads from the
# settings below, which would otherwise drop it.
self._flush()
+ before = core_ways.way_back_state(self.settings_store.current())
try:
- changed, notices = self.settings_store.arrangement(peer, edge, set_at, by, way_back)
+ changed, notices = self.settings_store.arrangement(peer, edge, set_at, by, way_back, way_back_by)
cfg = self.settings_store.load() if changed else None
except (SettingsError, TypeError, ValueError):
self.logger.exception("could not save the arrangement %s sent", peer)
@@ -2806,7 +2938,10 @@ class ControlWindow(AppKit.NSObject):
self.logger.info("%s's arrangement: this Mac's %s edge", peer, crossing.OPPOSITE[edge])
self._load(config_to_raw(cfg))
self.refresh()
- self._tell(peer)
+ changed_peers = [target for target, state in core_ways.way_back_state(self.settings_store.current()).items()
+ if before.get(target) != state]
+ for target in dict.fromkeys([*changed_peers, peer]):
+ self._tell(target)
def quitApp_(self, _sender):
self.quit_handler()
@@ -3047,6 +3182,7 @@ class _LaunchWatch(AppKit.NSObject):
return self
def launched_(self, note):
+ self.tray.notices.ask()
info = note.userInfo() or {}
default = info.get("NSApplicationLaunchIsDefaultLaunchKey")
if default is not None and not bool(default):
@@ -3056,6 +3192,7 @@ class _LaunchWatch(AppKit.NSObject):
class TrayApp(rumps.App):
def __init__(self, controller, settings_store, logger, hidden=False):
self.hidden = hidden
+ self.notices = notices.Notices(logger)
self.launch_watch = _LaunchWatch.alloc().initWithTray_(self)
self.controller = controller
self.settings_store = settings_store
@@ -3186,10 +3323,10 @@ class TrayApp(rumps.App):
def _settings(self, data, peer=None):
AppHelper.callAfter(self.control_window.apply_same, data, peer)
- def _arrangement(self, peer, edge, set_at, by, way_back=None):
+ def _arrangement(self, peer, edge, set_at, by, way_back=None, way_back_by=None):
"""An arrangement from a machine, over either link, applied on the main
thread -- it writes the settings file and redraws the window."""
- AppHelper.callAfter(self.control_window.apply_arrangement, peer, edge, set_at, by, way_back)
+ AppHelper.callAfter(self.control_window.apply_arrangement, peer, edge, set_at, by, way_back, way_back_by)
def show_on_startup(self, _timer):
self.startup_timer.stop()
@@ -3318,7 +3455,7 @@ class TrayApp(rumps.App):
self._switch([peer["token"] for peer in peers], allow_drive=not all(peer.get("allow_drive") is True for peer in peers))
def _set_direction(self, token, **change):
- """One machine's switch from its row on Overview: `send=` or `allow_drive=`."""
+ """One machine's switch from its row on Overview."""
self._switch([token], **change)
def _switch(self, tokens, **change):
@@ -3337,7 +3474,8 @@ class TrayApp(rumps.App):
self.control_window.panel.invalidate()
self.control_window.peers_changed()
return
- if change.get("send") is False and any(entry.get("id") == controller.owner.on for entry in entries):
+ if ((change.get("send") is False or change.get("in_use") is False)
+ and any(entry.get("id") == controller.owner.on for entry in entries)):
# Input comes home by this switch, and shows where the pointer is as any switch does.
controller.set_redirecting(False)
self.control_window.peers_changed()
@@ -3494,7 +3632,7 @@ class TrayApp(rumps.App):
except Exception:
self.logger.exception("failed to beep for a user alert")
try:
- rumps.notification("Beamer", title, pages.redact(message, self.controller.cfg.hide_addresses))
+ self.notices.post(title, pages.redact(message, self.controller.cfg.hide_addresses))
except Exception:
self.logger.exception("failed to show a user notification")
diff --git a/mac_app/machines.py b/mac_app/machines.py
index 337acb5..07e4f65 100644
--- a/mac_app/machines.py
+++ b/mac_app/machines.py
@@ -24,6 +24,7 @@ class Row:
platform: str
address: str
state: LinkState
+ in_use: bool
drives: bool
driven: bool
@@ -41,12 +42,14 @@ def row(entry: dict, label: str, live: bool, kind: str, status: str, here: bool,
address = f"{host} · port {port}" if host and port else "No address"
return Row(
entry["token"], label, platform_name(entry.get("platform", "")), address,
- _state(entry, label, live, kind, status, here, driving, inbound, has_link),
+ _state(entry, label, live, kind, status, here, driving, inbound, has_link), entry.get("in_use", True) is True,
entry.get("send") is True, entry.get("allow_drive") is True,
)
def _state(entry, label, live, kind, status, here, driving, inbound, has_link) -> LinkState:
+ 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)
if not protocol.linkable(entry):
return LinkState(
"pair_again", AMBER, "Pair again", "Pair again",
diff --git a/mac_app/machines_panel.py b/mac_app/machines_panel.py
index 7a657ba..7e3d03c 100644
--- a/mac_app/machines_panel.py
+++ b/mac_app/machines_panel.py
@@ -22,7 +22,7 @@ import motion
import qr
import theme
import widgets
-from core import pairing, peerlist, protocol
+from core import pairing, peerlist, protocol, ways as core_ways
QR_SIDE = 176
CODE_GROUP = 3
@@ -53,6 +53,7 @@ class MachinesPanel:
self.wide = True
self._targets = []
self._rows_key = None
+ self.directions_open = set()
self._heard_key = None
self._heard = []
self._showing = False
@@ -207,8 +208,10 @@ class MachinesPanel:
# Not the sentence under each state: a link that is still trying changes it every attempt,
# and a rebuild takes keyboard and VoiceOver focus off whatever it was on.
key = (hide, self.removing, self.wide, tuple(
- (r.token, r.label, r.platform, r.address, r.state.key, r.state.word, r.state.tone, r.state.led, r.drives, r.driven)
+ (r.token, r.label, r.platform, r.address, r.state.key, r.state.word, r.state.tone, r.state.led,
+ r.in_use, r.drives, r.driven)
for r in rows))
+ key += (tuple(sorted(self.directions_open)),)
if key != self._rows_key:
self._rows_key = key
self._build_rows(rows)
@@ -277,13 +280,20 @@ class MachinesPanel:
place.addArrangedSubview_(remove)
widgets.add(body, place)
widgets.add(body, widgets.note(self._shown(state.detail)).view)
+ in_use = widgets.Switch("In use", on_change=lambda on, t=row.token: self._direction(t, in_use=on))
+ in_use.value = row.in_use
+ in_use.view.focus_id = (row.token, "in_use")
drives = widgets.Switch("This Mac drives it", on_change=lambda on, t=row.token: self._direction(t, send=on))
drives.value = row.drives
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.value = row.driven
driven.view.focus_id = (row.token, "driven")
- widgets.add(body, self._controls(row, drives, driven, remove))
+ 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}",
+ (row.token, "directions"))
+ widgets.add(body, self._controls(row, in_use, disclosure, drives, driven, remove))
frame.addSubview_(body)
widgets.pin(body, frame, (10, 12, 10, 12))
return frame
@@ -297,21 +307,35 @@ class MachinesPanel:
widgets.pin(word.view, chip, (6, 12, 6, 12))
return chip
- def _controls(self, row, drives, driven, remove):
- """The two switches, and the way to remove them on the same line while there is room."""
+ def _controls(self, row, in_use, disclosure, drives, driven, remove):
+ """The machine switch leads; its two direction switches stay under their disclosure."""
if self.removing == row.token:
column = widgets.stack(spacing=6)
- for view in (drives.view, driven.view, remove):
+ for view in (remove,):
widgets.add(column, view)
return column
- line = widgets.stack(vertical=False, spacing=24)
- for view in (drives.view, driven.view):
- line.addArrangedSubview_(view)
- widgets.hug(view, AppKit.NSLayoutPriorityRequired)
+ line = widgets.stack(vertical=False, spacing=16)
+ line.addArrangedSubview_(widgets.hug(in_use.view, AppKit.NSLayoutPriorityRequired))
line.addArrangedSubview_(widgets.hug(widgets.box(), AppKit.NSLayoutPriorityDefaultLow))
+ line.addArrangedSubview_(disclosure)
if self.wide:
line.addArrangedSubview_(remove)
- return line
+ column = widgets.stack(spacing=4)
+ column.addArrangedSubview_(line)
+ if row.token in self.directions_open:
+ directions = widgets.stack(vertical=False, spacing=24)
+ for view in (drives.view, driven.view):
+ directions.addArrangedSubview_(view)
+ widgets.hug(view, AppKit.NSLayoutPriorityRequired)
+ column.addArrangedSubview_(directions)
+ return column
+
+ def _toggle_directions(self, token):
+ if token in self.directions_open:
+ self.directions_open.remove(token)
+ else:
+ self.directions_open.add(token)
+ self.refresh()
def _removal(self, row):
label = self._shown(row.label)
@@ -337,6 +361,7 @@ class MachinesPanel:
def _remove(self, token):
self.removing = None
+ before = core_ways.way_back_state(self.settings_store.current())
try:
removed = self.settings_store.remove_peer(token)
except Exception as exc:
@@ -347,6 +372,10 @@ class MachinesPanel:
if removed is not None:
self.logger.info("removed %s", removed.get("name") or "a machine")
self.owner.peers_changed()
+ after = core_ways.way_back_state(self.settings_store.current())
+ changed_peers = [peer for peer, state in after.items() if before.get(peer) != state]
+ for peer in changed_peers:
+ self.owner._tell(peer)
def _direction(self, token, **change):
handler = self.owner.direction_handler
diff --git a/mac_app/notices.py b/mac_app/notices.py
new file mode 100644
index 0000000..a17edd5
--- /dev/null
+++ b/mac_app/notices.py
@@ -0,0 +1,82 @@
+"""Post user alerts through macOS notifications, including source runs outside an app bundle."""
+
+import secrets
+
+
+def user_notifications():
+ """Load the framework only when a notification is requested."""
+ import UserNotifications
+
+ return UserNotifications
+
+
+_PRESENTER = None
+
+
+def _presenter_class():
+ """The centre's delegate class, made once: macOS keeps a notice from the app in front out of
+ sight unless its delegate asks to show it, and Beamer's window is often in front when a crossing
+ from its own page is refused."""
+ global _PRESENTER
+ if _PRESENTER is None:
+ import objc
+ from Foundation import NSObject
+
+ try:
+ protocols = [objc.protocolNamed("UNUserNotificationCenterDelegate")]
+ except Exception:
+ protocols = []
+
+ class BeamerNoticePresenter(NSObject, protocols=protocols):
+ def userNotificationCenter_willPresentNotification_withCompletionHandler_(self, _centre, _note, handler):
+ handler(self.options)
+
+ _PRESENTER = BeamerNoticePresenter
+ return _PRESENTER
+
+
+class Notices:
+ def __init__(self, logger, framework=user_notifications):
+ self.logger = logger
+ self.framework = framework
+ self._asked = False
+ # The centre holds its delegate weakly.
+ self._presenter = None
+
+ def _module(self):
+ return self.framework() if callable(self.framework) else self.framework
+
+ def ask(self):
+ if self._asked:
+ return
+ self._asked = True
+ try:
+ framework = self._module()
+ centre = framework.UNUserNotificationCenter.currentNotificationCenter()
+ self._presenter = _presenter_class().alloc().init()
+ self._presenter.options = (framework.UNNotificationPresentationOptionBanner
+ | framework.UNNotificationPresentationOptionList
+ | framework.UNNotificationPresentationOptionSound)
+ centre.setDelegate_(self._presenter)
+ options = framework.UNAuthorizationOptionAlert | framework.UNAuthorizationOptionSound
+ centre.requestAuthorizationWithOptions_completionHandler_(options, lambda *_args: None)
+ except Exception:
+ self.logger.info("Could not request notification authorisation", exc_info=True)
+
+ def post(self, title, body) -> bool:
+ self.ask()
+ try:
+ framework = self._module()
+ centre = framework.UNUserNotificationCenter.currentNotificationCenter()
+ content = framework.UNMutableNotificationContent.alloc().init()
+ content.setTitle_(title)
+ content.setBody_(body)
+ content.setSound_(framework.UNNotificationSound.defaultSound())
+ request = framework.UNNotificationRequest.requestWithIdentifier_content_trigger_(
+ secrets.token_urlsafe(24), content, None
+ )
+ centre.addNotificationRequest_withCompletionHandler_(request, None)
+ return True
+ except Exception:
+ self.logger.info("Could not show notification %r: %r", title, body, exc_info=True)
+ return False
diff --git a/mac_app/pages.py b/mac_app/pages.py
index e2ed9db..efd844a 100644
--- a/mac_app/pages.py
+++ b/mac_app/pages.py
@@ -151,6 +151,16 @@ def parts_phrase(edge, parts):
return f"the {joined} of the {edge} edge"
+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}.")
+
+
# The ways in, in the Crossing page's order.
WAYS = ("shortcut", "edge", "part", "corner", "notch")
_EXCLUSIVE = {"edge": "part", "part": "edge"}
@@ -304,7 +314,8 @@ def send_items(peers, on, hide):
for each machine this Mac sends to, "Bring input back" on the one input is on (`on`). [] with
one or none, where the one Send input item stands as it always has."""
labels = peerlist.labels(peers)
- targets = [entry for entry in peers if entry.get("id") and entry.get("send") is True and entry.get("port") != 0]
+ targets = [entry for entry in peers if entry.get("id") and entry.get("in_use", True) is True
+ and entry.get("send") is True and entry.get("port") != 0]
if len(targets) < 2:
return []
return [(entry["id"], "Bring input back" if entry["id"] == on else redact(f"Send input to {labels[entry['token']]}", hide))
diff --git a/mac_app/requirements-mac.txt b/mac_app/requirements-mac.txt
index 684fee9..455e62c 100644
--- a/mac_app/requirements-mac.txt
+++ b/mac_app/requirements-mac.txt
@@ -1,6 +1,7 @@
setuptools>=68,<81
pyobjc-framework-Quartz==12.2.2
pyobjc-framework-ApplicationServices==12.2.2
+pyobjc-framework-UserNotifications==12.2.2
rumps==0.4.0
py2app==0.28.10
PyNaCl>=1.6
diff --git a/mac_app/settings_store.py b/mac_app/settings_store.py
index 26f80d6..8ee8e3a 100644
--- a/mac_app/settings_store.py
+++ b/mac_app/settings_store.py
@@ -45,8 +45,8 @@ ZONE_KINDS = tuple(method for method in METHODS if method != "shortcut")
SETTINGS_ONLY = ("schema", "machine_id", "name", "port", "shortcut", "migrated_token_sha256", "peers", "zones", "crossing")
PEER_DEFAULTS = {
"id": "", "name": "", "platform": "", "token": "", "host": "", "port": 0, "hw": "", "send": True,
- "allow_drive": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": 0,
- "linked": False, "from_1_4": False,
+ "allow_drive": True, "in_use": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": 0,
+ "linked": False, "from_1_4": False, "jump_key": "",
}
@@ -331,10 +331,10 @@ class SettingsStore:
self.save_settings(settings)
def set_peer(self, token, **switches):
- """Turns `send` (this Mac drives the machine) and `allow_drive` (it may drive this Mac) on
- or off for the machine holding `token`; returns its entry, None when no machine holds it."""
- if not switches or any(name not in ("send", "allow_drive") or not isinstance(value, bool) for name, value in switches.items()):
- raise SettingsError("only send and allow_drive can be switched, each on or off")
+ """Turns `send`, `allow_drive` and `in_use` on or off for the machine holding `token`; returns
+ its entry, None when no machine holds it."""
+ if not switches or any(name not in ("send", "allow_drive", "in_use") or not isinstance(value, bool) for name, value in switches.items()):
+ raise SettingsError("only send, allow_drive and in_use can be switched, each on or off")
with self.lock:
settings = copy.deepcopy(self.current())
entry = next((peer for peer in settings["peers"] if peer["token"] == token), None)
@@ -343,6 +343,19 @@ class SettingsStore:
entry.update(switches)
return copy.deepcopy(next(peer for peer in self.save_settings(settings)["peers"] if peer["token"] == token))
+ def set_jump_key(self, peer_id, value, trigger_key):
+ """Sets or clears one peer's local jump chord after the shared clash checks."""
+ with self.lock:
+ settings = copy.deepcopy(self.current())
+ entry = next((peer for peer in settings["peers"] if peer["id"] == peer_id), None)
+ if entry is None:
+ raise SettingsError("that machine is no longer paired with this Mac")
+ try:
+ entry["jump_key"] = ways.check_jump_key(settings, peer_id, value, trigger_key) or ""
+ except ValueError as exc:
+ raise SettingsError(str(exc)) from exc
+ return copy.deepcopy(next(peer for peer in self.save_settings(settings)["peers"] if peer["id"] == peer_id))
+
def remove_peer(self, token):
"""Removes the machine holding `token`, with its zones, and returns its entry; None when
no machine holds it."""
@@ -353,17 +366,15 @@ class SettingsStore:
self.save_settings(settings)
return removed
- def set_ways(self, peer, *, side, methods, parts, corner, default=False):
- """Writes one machine's side and zones, as the Crossing page shows them for it (core/ways.py);
- `default` when the side is only the one the page shows for a machine not placed yet. Returns
- whether its side moved, which the caller sends it as `arrangement`; SettingsError, writing
+ def set_ways(self, peer, *, side, methods, parts, corner):
+ """Writes one machine's side and zones, as the Crossing page shows them for it (core/ways.py).
+ Returns whether its side moved, which the caller sends it as `arrangement`; SettingsError, writing
nothing, for a machine not in the list or zones that would clash with another's."""
with self.lock:
settings = copy.deepcopy(self.current())
try:
moved = ways.edit(settings, peer, side=side, methods=methods, parts=parts, corner=corner,
- kinds=ZONE_KINDS, corner_edge=lambda corner, _side: _corner_edge(corner), now=time.time(),
- default=default)
+ kinds=ZONE_KINDS, corner_edge=lambda corner, _side: _corner_edge(corner), now=time.time())
except KeyError:
raise SettingsError("that machine is no longer paired with this Mac") from None
if moved:
@@ -373,6 +384,14 @@ class SettingsStore:
self.save_settings(settings)
return moved
+ def share_side(self, side, thirds):
+ """Split one side's zones under the store lock, returning every machine whose zones changed."""
+ with self.lock:
+ settings = copy.deepcopy(self.current())
+ changed = ways.share(settings, side, thirds, kinds=ZONE_KINDS)
+ self.save_settings(settings)
+ return changed
+
def set_hardware(self, peer, address):
"""Writes the hardware address learnt for a machine (wake-on-LAN); True when it changed."""
address = parse_mac(address)
@@ -387,13 +406,14 @@ class SettingsStore:
self.save_settings(settings)
return True
- def arrangement(self, peer, edge, set_at, by, way_back=None):
+ def arrangement(self, peer, edge, set_at, by, way_back=None, way_back_by=None):
"""A machine's `arrangement`, kept when it is newer than the side held for that machine, and
its `way_back` whatever the side (core/ways.py). Returns (changed, notices), a sentence for each
zone it turned off."""
with self.lock:
settings = copy.deepcopy(self.current())
- changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this Mac", way_back)
+ changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this Mac", way_back,
+ way_back_by=way_back_by)
if changed:
self.save_settings(settings)
return changed, notices
@@ -516,11 +536,11 @@ class SettingsStore:
@staticmethod
def _ensure_zones(settings):
- """A machine paired before beta.5 has no zone at all (pairing made none): it gets its edge.
- Run after a learnt id has renamed the migrated machine's zones, or that machine would look
- bare and get a second edge."""
+ """Give old pairs their edge and the one unplaced desktop its shown side on every read and save.
+ Run after a learnt id has renamed migrated zones, or that machine would get a second edge."""
if isinstance(settings["zones"], list) and all(isinstance(item, dict) for item in settings["peers"] + settings["zones"]):
ways.ensure_zones(settings)
+ ways.default_side(settings)
def _check(self, settings):
if not is_machine_id(settings["machine_id"]):
@@ -552,6 +572,10 @@ class SettingsStore:
value = peer[name]
if isinstance(default, bool) != isinstance(value, bool) or not isinstance(value, type(default)):
raise SettingsError(f"peer {name} must be {type(default).__name__}")
+ if "way_back_by" in peer and not isinstance(peer["way_back_by"], str):
+ raise SettingsError("peer way_back_by must be str")
+ if not isinstance(peer["jump_key"], str) or (peer["jump_key"] and not ways.valid_jump_key(peer["jump_key"])):
+ raise SettingsError("peer jump_key must be an empty string or a recorded modifier chord")
if peer["id"] == "":
empty += 1
if not peer["from_1_4"] or empty > 1:
diff --git a/mac_app/setup.py b/mac_app/setup.py
index 06f3c5b..6443cdb 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -39,6 +39,7 @@ setup(
"machines_panel",
"media_keys",
"motion",
+ "notices",
"notch_beam",
"notch_island",
"pages",
@@ -75,7 +76,7 @@ setup(
# The rest of core/ is named too, through the repo root put on sys.path above, so a module
# the scan misses cannot drop out; naming the package whole would ship its tests too.
"includes": [
- "objc", "AppKit", "ApplicationServices", "Quartz",
+ "objc", "AppKit", "ApplicationServices", "Quartz", "UserNotifications",
"core.effects", "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",
diff --git a/mac_app/tests/bridge_fakes.py b/mac_app/tests/bridge_fakes.py
index 742d8b6..bf3d80c 100644
--- a/mac_app/tests/bridge_fakes.py
+++ b/mac_app/tests/bridge_fakes.py
@@ -6,6 +6,7 @@ import logging
import time
import config
+from core import protocol
from core.tests import pngs
class FakeQuartz:
@@ -134,6 +135,14 @@ def make_config(token="synthetic-token"):
)
+def redirect_to(controller, peer=None):
+ """Put both views of where input is on the other machine."""
+ if peer is None:
+ peer = controller._primary_link.peer_id or protocol.id_text(bytes(range(1, 17)))
+ controller.owner.on = peer
+ controller.redirecting = True
+
+
def crossing_config(token="synthetic-token", **overrides):
cfg = make_config(token)
cfg.crossing = dict(config.DEFAULT_CROSSING, **overrides)
@@ -192,4 +201,3 @@ class FakeClipboard:
self.stamp += 1
return True
-
diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.py
index 576e514..6038c2c 100644
--- a/mac_app/tests/test_bridge.py
+++ b/mac_app/tests/test_bridge.py
@@ -35,6 +35,7 @@ from bridge_fakes import ( # noqa: F401 (re-exported)
crossing_config,
make_config,
quiet_logger,
+ redirect_to,
settle,
)
from fake_link import OTHER_ID, PEER_ID, FakeLink, bring_up
@@ -323,7 +324,7 @@ class ControllerTests(unittest.TestCase):
FakeQuartz.kCGKeyboardEventAutorepeat: 0,
"unicode": "a",
}
- self.controller.redirecting = True
+ redirect_to(self.controller)
returned = self._tap(FakeQuartz.kCGEventKeyDown, event)
self.assertIsNone(returned)
self.assertEqual(
@@ -353,7 +354,7 @@ class ControllerTests(unittest.TestCase):
}
self.controller.outbound = queue.Queue(maxsize=1)
self.controller.outbound.put_nowait({"full": True})
- self.controller.redirecting = True
+ redirect_to(self.controller)
returned = self._tap(FakeQuartz.kCGEventKeyDown, event)
self.assertIs(returned, event)
self.assertFalse(self.controller.redirecting)
@@ -389,6 +390,40 @@ class ControllerTests(unittest.TestCase):
self.assertEqual(self.controller.connection_status, "Windows stopped responding")
self.assertEqual(self.alerts, [("Beamer", "Input returned to this Mac")])
+ def test_jump_chord_for_the_current_peer_returns_input_home_and_is_swallowed(self):
+ link = bring_up(self.controller)
+ self.controller.book.data["peers"][0]["id"] = protocol.id_text(PEER_ID)
+ self.controller.book.data["peers"][0]["jump_key"] = "ctrl+shift+2"
+ self.assertTrue(self.controller.set_redirecting(True))
+ flags = FakeQuartz.kCGEventFlagMaskControl | FakeQuartz.kCGEventFlagMaskShift
+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x13, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "flags": flags,
+ "unicode": "2"}
+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x13, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "flags": flags,
+ "unicode": "2"}
+ self.assertIsNone(self._tap(FakeQuartz.kCGEventKeyDown, down))
+ self.assertFalse(self.controller.redirecting)
+ repeat = {**down, FakeQuartz.kCGKeyboardEventAutorepeat: 1}
+ self.assertIsNone(self._tap(FakeQuartz.kCGEventKeyDown, repeat))
+ self.assertFalse(self.controller.redirecting)
+ self.assertIsNone(self._tap(FakeQuartz.kCGEventKeyUp, up))
+ self.assertEqual(link.sent, [])
+
+ def test_a_key_repeating_when_its_modifiers_arrive_is_not_a_jump_and_nothing_jumps_while_recording(self):
+ bring_up(self.controller)
+ self.controller.book.data["peers"][0]["id"] = protocol.id_text(PEER_ID)
+ self.controller.book.data["peers"][0]["jump_key"] = "ctrl+shift+2"
+ flags = FakeQuartz.kCGEventFlagMaskControl | FakeQuartz.kCGEventFlagMaskShift
+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x13, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "flags": flags,
+ "unicode": "2"}
+ self._tap(FakeQuartz.kCGEventKeyDown, {**down, FakeQuartz.kCGKeyboardEventAutorepeat: 1})
+ self.assertFalse(self.controller.redirecting)
+ self.controller.jump_recording = True
+ self._tap(FakeQuartz.kCGEventKeyDown, down)
+ self.assertFalse(self.controller.redirecting)
+ self.controller.jump_recording = False
+ self._tap(FakeQuartz.kCGEventKeyDown, down)
+ self.assertTrue(self.controller.redirecting)
+
def test_a_failed_connection_while_idle_drops_the_link_without_an_alert(self):
link = bring_up(self.controller)
self.controller._connection_failed("Windows stopped responding")
@@ -510,7 +545,7 @@ class ControllerTests(unittest.TestCase):
self.assertTrue(self.controller.redirecting)
def test_worker_exception_forces_local(self):
- self.controller.redirecting = True
+ redirect_to(self.controller)
def fail():
raise RuntimeError("synthetic failure")
@@ -603,7 +638,7 @@ class ControllerTests(unittest.TestCase):
def test_set_redirecting_off_resets_mouse_accumulators(self):
bring_up(self.controller)
- self.controller.redirecting = True
+ redirect_to(self.controller)
self.controller.translator._move_accum_x = 0.4
self.controller.translator._move_accum_y = -0.4
self.controller.set_redirecting(False)
@@ -851,7 +886,7 @@ class OverlayGestureTests(unittest.TestCase):
self.assertTrue(self.controller.outbound.empty())
def test_overlay_gesture_translator_exception_does_not_raise(self):
- self.controller.redirecting = True
+ redirect_to(self.controller)
def boom(event_type, ns_event):
raise RuntimeError("synthetic overlay translation failure")
@@ -865,7 +900,7 @@ class OverlayGestureTests(unittest.TestCase):
logger = logging.getLogger("kvm-bridge-tests.overlay-gesture-capture")
logger.setLevel(logging.INFO)
controller = make_controller(self.clock, logger=logger)
- controller.redirecting = True
+ redirect_to(controller)
with self.assertLogs(logger, level="INFO") as captured:
controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.01))
controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.01))
@@ -875,7 +910,7 @@ class OverlayGestureTests(unittest.TestCase):
self.assertEqual(len(overlay_logs), 1)
def test_overlay_gesture_swipe_translated_while_redirecting(self):
- self.controller.redirecting = True
+ redirect_to(self.controller)
self.controller.handle_overlay_gesture(SWIPE_TYPE, FakeGestureEvent(deltaX=1.0))
drained = []
while not self.controller.outbound.empty():
@@ -899,7 +934,7 @@ class MediaKeyWiringTests(unittest.TestCase):
def test_play_pause_is_forwarded_and_swallowed(self):
controller = self._controller(lambda event: (8, self._data1(16)))
- controller.redirecting = True
+ redirect_to(controller)
self.assertIsNone(
controller._event_tap_callback(None, self.SYSDEFINED, object(), None)
)
@@ -910,7 +945,7 @@ class MediaKeyWiringTests(unittest.TestCase):
def test_volume_key_up_sends_keyup(self):
controller = self._controller(lambda event: (8, self._data1(0, down=False)))
- controller.redirecting = True
+ redirect_to(controller)
controller._event_tap_callback(None, self.SYSDEFINED, object(), None)
self.assertEqual(
controller.outbound.get_nowait(),
@@ -920,7 +955,7 @@ class MediaKeyWiringTests(unittest.TestCase):
def test_non_media_system_event_passes_through(self):
# NX code 3 is brightness-up, which Windows has no equivalent for.
controller = self._controller(lambda event: (8, self._data1(3)))
- controller.redirecting = True
+ redirect_to(controller)
raw_event = object()
self.assertIs(
controller._event_tap_callback(None, self.SYSDEFINED, raw_event, None),
@@ -949,7 +984,7 @@ class MediaKeyWiringTests(unittest.TestCase):
raise RuntimeError("boom")
controller = self._controller(converter)
- controller.redirecting = True
+ redirect_to(controller)
raw_event = object()
self.assertIs(
controller._event_tap_callback(None, self.SYSDEFINED, raw_event, None),
@@ -1011,7 +1046,7 @@ class GestureWiringTests(unittest.TestCase):
raise RuntimeError("synthetic AppKit failure")
controller = self._controller(converter)
- controller.redirecting = True
+ redirect_to(controller)
raw_event = object()
returned = controller._event_tap_callback(None, SWIPE_TYPE, raw_event, None)
self.assertIs(returned, raw_event)
@@ -1036,7 +1071,7 @@ class GestureWiringTests(unittest.TestCase):
def test_swipe_while_redirecting_is_translated_and_swallowed(self):
controller = self._controller(lambda event: FakeGestureEvent(deltaX=1.0))
- controller.redirecting = True
+ redirect_to(controller)
returned = controller._event_tap_callback(None, SWIPE_TYPE, object(), None)
self.assertIsNone(returned)
drained = []
@@ -1051,7 +1086,7 @@ class GestureWiringTests(unittest.TestCase):
self.clock, logger=logger,
gesture_event_converter=lambda event: FakeGestureEvent(magnification=0.01),
)
- controller.redirecting = True
+ redirect_to(controller)
with self.assertLogs(logger, level="INFO") as captured:
# 0.01 stays below the 0.05 zoom step both times, so no
# keydown/scroll/keyup messages are emitted at all -- the log
@@ -1080,7 +1115,7 @@ class DockControlWiringTests(unittest.TestCase):
def test_swipe_up_while_redirecting_becomes_one_gesture_message_and_is_swallowed(self):
controller = self._controller(lambda event: self._ended(motion=2, progress=-0.4))
- controller.redirecting = True
+ redirect_to(controller)
returned = controller._event_tap_callback(None, DOCK_CONTROL_TYPE, object(), None)
self.assertIsNone(returned)
self.assertEqual(controller.outbound.get_nowait(), protocol.gesture_msg("swipe_up"))
@@ -1105,7 +1140,7 @@ class DockControlWiringTests(unittest.TestCase):
raise RuntimeError("synthetic field failure")
controller = self._controller(reader)
- controller.redirecting = True
+ redirect_to(controller)
self.assertIsNone(controller._event_tap_callback(None, DOCK_CONTROL_TYPE, object(), None))
self.assertTrue(controller.outbound.empty())
self.assertTrue(controller.redirecting)
diff --git a/mac_app/tests/test_crossing_matrix.py b/mac_app/tests/test_crossing_matrix.py
index beb9d10..2768348 100644
--- a/mac_app/tests/test_crossing_matrix.py
+++ b/mac_app/tests/test_crossing_matrix.py
@@ -268,13 +268,14 @@ class ArrangementOverTheLinksTests(unittest.TestCase):
peer, read = duo.pc_responder.arrangements[0]
self.assertEqual((read["edge"], read["set_at"], read["by"]), ("top", 300, HERE))
- def test_a_side_never_learnt_is_announced_as_nothing(self):
+ def test_the_one_machine_never_placed_is_announced_on_the_right_unstamped_as_the_page_shows_it(self):
duo = self.duo(side="")
duo.link_mac_to_pc()
# What a link announces goes before anything sent after it, so this one is the fence.
self.assertTrue(duo.mac.send_arrangement(protocol.id_text(HERE), "left", 9))
self.assertTrue(wait_for(lambda: self.heard(duo, 9)))
- self.assertEqual([read["set_at"] for _, read in duo.pc_responder.arrangements], [9])
+ self.assertEqual([(read["edge"], read["set_at"]) for _, read in duo.pc_responder.arrangements],
+ [("right", 0), ("left", 9)])
class WhatIsSharedTests(unittest.TestCase):
@@ -484,14 +485,16 @@ class MacDrivenTests(unittest.TestCase):
self.assertIsNotNone(duo.pc_switch(), "this Mac's left edge never led home")
duo.close()
- def test_a_mac_that_has_learned_no_side_for_the_pc_has_no_way_home_however_it_is_pushed(self):
+ def test_a_mac_whose_one_machine_was_never_placed_leads_home_through_the_right_it_shows(self):
duo = self.duo(side="")
duo.link_pc_to_mac()
duo.pc_drives("left", 0.5)
- for edge in EDGES:
+ for edge in [edge for edge in EDGES if edge != "right"]:
duo.pc_leans(MAC_EDGE_POINT[edge], *outward(edge), times=3)
self.assertIsNone(duo.pc_switch(0.2), edge)
self.assertTrue(duo.mac.receiving)
+ duo.pc_leans(MAC_EDGE_POINT["right"], *outward("right"), times=3)
+ self.assertIsNotNone(duo.pc_switch(), "the right edge the page shows never led home")
def test_a_pc_this_mac_does_not_allow_to_drive_it_is_refused(self):
duo = self.duo(allow_drive=False)
@@ -545,7 +548,9 @@ class MacDrivenTests(unittest.TestCase):
self.assertTrue(wait_for(lambda: duo.pc_responder.responder.owner == duo.mac_id))
# And while it drives, the PC cannot take it: one machine never drives and is driven at once.
route = duo.pc_takes()
- self.assertEqual(duo.pc.answer(route), (protocol.MSG_REFUSE, {"route": route, "why": "busy"}))
+ # The refusal names the machine this Mac drives, which is the PC itself here.
+ self.assertEqual(duo.pc.answer(route), (protocol.MSG_REFUSE, {"route": route, "why": "busy",
+ "other": protocol.id_text(HERE)}))
self.assertTrue(duo.mac.redirecting)
diff --git a/mac_app/tests/test_crossing_page_machines.py b/mac_app/tests/test_crossing_page_machines.py
index a90fa94..c8c9943 100644
--- a/mac_app/tests/test_crossing_page_machines.py
+++ b/mac_app/tests/test_crossing_page_machines.py
@@ -114,15 +114,83 @@ class OneOrNoMachine(Page):
window = self.build([(BEE, token(100), "Bee")])
self.assertEqual(window.edge_select.value, "right")
- def test_a_save_with_one_machine_not_placed_writes_the_shown_right_unstamped_so_its_own_side_wins(self):
+ def test_one_machine_not_placed_holds_the_shown_right_unstamped_before_any_save_so_its_own_side_wins(self):
window = self.build([(BEE, token(100), "Bee")], [{"peer": BEE, "kind": "edge"}])
- window._apply_settings()
held = self.store.current()["peers"][0]
self.assertEqual((held["side"], held["side_set_at"], held["side_by"]), ("right", 0, ""))
- self.assertEqual(self.sent, [(BEE, "right", 0)])
+ window._apply_settings()
+ self.assertEqual(self.sent, [])
window.apply_arrangement(BEE, "bottom", 1_790_000_000, BEE, True)
self.assertEqual(self.ways_of(BEE)["side"], "top")
+
+class SharingSide(Page):
+ def build_blocked(self):
+ window = self.build(
+ [(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],
+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])
+ window._machine_picked(SEA)
+ return window
+
+ def test_the_panel_offers_thirds_under_the_side_picker_and_replaces_the_blocked_sentence(self):
+ window = self.build_blocked()
+ self.assertFalse(window.share_box.isHidden())
+ self.assertEqual([window.share_tiles[p].name.text for p in ("start", "middle", "end")],
+ ["Top", "Middle", "Bottom"])
+ self.assertEqual([window.share_tiles[p].detail.text for p in ("start", "middle", "end")],
+ ["Bee", "Bee", "Sea"])
+ self.assertTrue(window.blocked_note.view.isHidden())
+
+ def test_a_tile_moves_to_the_next_machine_and_share_writes_and_tells_both(self):
+ window = self.build_blocked()
+ window.share_tiles["start"]._toggle()
+ self.assertEqual(window.share_tiles["start"].detail.text, "Sea")
+ window._share_side()
+ zones = {(z["peer"], z["kind"]): z for z in self.store.current()["zones"]}
+ self.assertEqual(zones[(BEE, "part")]["parts"], ["middle"])
+ self.assertEqual(zones[(SEA, "part")]["parts"], ["start", "end"])
+ self.assertTrue(zones[(BEE, "edge")].get("off"))
+ self.assertTrue(zones[(SEA, "edge")].get("off"))
+ self.assertEqual({peer for peer, _edge, _stamp in self.sent}, {BEE, SEA})
+
+ def test_turning_on_edge_keeps_it_off_and_focuses_the_share_panel(self):
+ window = self.build_blocked()
+ self.toggle("edge")
+ window._flush()
+ self.assertFalse(window.method_boxes["edge"].value)
+ self.assertFalse(window.share_box.isHidden())
+ self.assertTrue(window.blocked_note.view.isHidden())
+ self.assertIs(window.window.firstResponder(), window.share_button.view)
+
+ def test_turning_on_an_overlapping_part_keeps_it_off_and_focuses_the_share_panel(self):
+ window = self.build_blocked()
+ self.toggle("part")
+ window._flush()
+ self.assertFalse(window.method_boxes["part"].value)
+ self.assertFalse(window.share_box.isHidden())
+ self.assertTrue(window.blocked_note.view.isHidden())
+ self.assertIs(window.window.firstResponder(), window.share_button.view)
+
+ def test_the_first_machine_paired_crosses_at_the_right_edge_the_page_shows_with_nothing_saved(self):
+ # beta.4 on three machines: Edge showed on, the pointer did not cross until a Notch save wrote the side.
+ window = self.build([])
+ self.store.add_peer(entry(BEE, token(100), "Bee", linked=False))
+ window.peers_changed()
+ self.controller.cfg = self.store.load()
+ self.controller.zones_changed()
+ self.assertEqual(window.edge_select.value, "right")
+ self.assertIn("edge", self.ways_of(BEE)["methods"])
+ found = [(way.peer, way.edge, "edge" in way.methods) for way in self.controller.crossing.ways]
+ self.assertEqual(found, [(BEE, "right", True)])
+ self.assertEqual(self.sent, [])
+
+ def test_a_second_machine_paired_is_given_no_side_and_the_first_keeps_its_right(self):
+ window = self.build([(BEE, token(100), "Bee")], [{"peer": BEE, "kind": "edge"}])
+ self.store.add_peer(entry(SEA, token(150), "Sea", linked=False))
+ window.peers_changed()
+ self.assertEqual([(peer["side"], peer["side_set_at"]) for peer in self.store.current()["peers"]],
+ [("right", 0), ("", 0)])
+
def test_with_one_machine_a_change_writes_its_ways_and_sends_it_the_side(self):
window = self.build([(BEE, token(100), "Bee", {"side": "left"})], [{"peer": BEE, "kind": "edge"}])
window.edge_select._choose("top")
@@ -147,6 +215,23 @@ class ChoosingAMachine(Page):
self.assertEqual(window.edge_caption.text, "Where Bee is")
self.assertEqual((window.edge_select.value, self.methods()), ("right", ["edge", "shortcut"]))
+ def test_the_picker_omits_machines_not_in_use_and_keeps_their_zones(self):
+ window = self.two()
+ zones = list(self.store.current()["zones"])
+ self.store.set_peer(token(150), in_use=False)
+ window._show_machines()
+ self.assertEqual(window._picker_choices, [(BEE, "Bee")])
+ self.assertTrue(window.machine_row.isHidden())
+ self.assertEqual(self.store.current()["zones"], zones)
+
+ def test_turning_off_the_chosen_machine_selects_an_active_machine(self):
+ window = self.two()
+ window._machine_picked(SEA)
+ self.store.set_peer(token(150), in_use=False)
+ window._show_machines()
+ self.assertEqual(window.chosen_peer, BEE)
+ self.assertTrue(window.machine_row.isHidden())
+
def test_choosing_a_machine_shows_its_ways(self):
window = self.two()
self.pick(SEA)
@@ -189,23 +274,35 @@ class ChoosingAMachine(Page):
window._apply_settings()
rebuilt.assert_called()
- def test_a_clash_is_said_naming_both_and_the_controls_go_back_to_what_is_saved(self):
+ def test_a_way_that_overlaps_an_existing_side_shows_the_share_panel_without_writing(self):
window = self.two()
self.pick(SEA)
# Moved onto Bee's side, Sea keeps the side and its ways there go off (core/ways.py settle).
window.edge_select._choose("right")
window._apply_settings()
- sea = next(entry for entry in self.store.current()["peers"] if entry["id"] == SEA)
- self.assertEqual(sea["side"], "right")
before = copy.deepcopy(self.store.current())
- methods = self.methods()
self.toggle("edge")
window._apply_settings()
+ self.assertFalse(window.method_boxes["edge"].value)
+ self.assertFalse(window.share_box.isHidden())
+ self.assertIn("Bee already crosses from the right edge", window.share_sentence.text)
+ self.assertTrue(window.blocked_note.view.isHidden())
+ self.assertEqual(window.edge_select.value, "right")
+ self.assertEqual(self.store.current()["zones"], before["zones"])
+
+ def test_a_corner_clash_keeps_its_refusal_naming_both_and_the_controls_go_back(self):
+ window = self.build(
+ [(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],
+ [{"peer": BEE, "kind": "corner", "corner": "top_right", "edge": "right"},
+ {"peer": SEA, "kind": "corner", "corner": "top_right", "edge": "right", "off": True}])
+ self.pick(SEA)
+ before = copy.deepcopy(self.store.current())
+ self.toggle("corner")
+ window._apply_settings()
self.assertEqual(window.message_label.ink, "fault")
self.assertIn("Bee", window.message_label.text)
self.assertIn("Sea", window.message_label.text)
- self.assertEqual(window.edge_select.value, "right")
- self.assertEqual(self.methods(), methods)
+ self.assertFalse(window.method_boxes["corner"].value)
self.assertEqual(self.store.current()["zones"], before["zones"])
def test_switching_machines_saves_a_change_still_waiting_first(self):
@@ -330,6 +427,26 @@ class WayBack(Page):
window._apply_settings()
self.assertEqual(len(self.sent), 2)
+ def test_moving_one_machine_tells_every_machine_whose_way_back_it_changed(self):
+ # Sol's review, 02-10-2026: Sea was told Bee holds its side, and moving Bee told Bee alone,
+ # so Sea's page kept naming Bee as in the way.
+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],
+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])
+ self.assertEqual(ways.way_back_by(self.store.current(), SEA), BEE)
+ self.pick(BEE)
+ window.edge_select._choose("top")
+ window._apply_settings()
+ self.assertEqual(sorted(peer for peer, _edge, _at in self.sent), sorted([BEE, SEA]))
+ self.assertIsNone(ways.way_back_by(self.store.current(), SEA))
+
+ def test_removing_the_machine_in_the_way_tells_the_one_it_blocked(self):
+ # Opus review: unpairing Sea left Bee told Sea held its side until Bee's link next came up.
+ window = self.build([(BEE, token(100), "Bee", {"side": "left"}), (SEA, token(150), "Sea", {"side": "left"})],
+ [{"peer": BEE, "kind": "edge", "off": True}, {"peer": SEA, "kind": "edge"}])
+ self.assertEqual(ways.way_back_by(self.store.current(), BEE), SEA)
+ window.panel._remove(token(150))
+ self.assertIn(BEE, [peer for peer, _edge, _at in self.sent])
+
def test_an_arrangement_that_changed_something_is_answered_with_this_macs_own(self):
window = self.two()
window.apply_arrangement(SEA, "top", 5000, SEA, True)
@@ -352,16 +469,15 @@ class WayBack(Page):
class TheNotes(Page):
"""What the page says under the ways about a machine it cannot reach, or that cannot reach back."""
- def test_a_machine_whose_side_another_holds_is_named_with_the_one_that_holds_it(self):
+ def test_a_machine_whose_side_another_holds_is_named_in_the_share_panel(self):
window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],
[{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])
self.pick(SEA)
- expected = ways.blocked_sentence(self.store.current(), SEA, "this Mac")
- self.assertIn("Sea has no way in: Bee already leads from the right edge", expected)
- self.assertFalse(window.blocked_note.view.isHidden())
- self.assertEqual(window.blocked_note.text, expected)
- self.pick(BEE)
+ self.assertFalse(window.share_box.isHidden())
+ self.assertIn("Bee already crosses from the right edge", window.share_sentence.text)
self.assertTrue(window.blocked_note.view.isHidden())
+ self.pick(BEE)
+ self.assertTrue(window.share_box.isHidden())
def test_a_machine_that_said_no_way_leads_back_is_named_until_it_says_one_does(self):
window = self.build([(BEE, token(100), "Bee", {"side": "right"}),
@@ -374,6 +490,16 @@ class TheNotes(Page):
window.apply_arrangement(SEA, "right", 5000, SEA, True)
self.assertTrue(window.no_way_back_note.view.isHidden())
+ def test_an_arrangement_names_the_machine_holding_the_way_back_side(self):
+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}),
+ (SEA, token(150), "Sea", {"side": "left"})],
+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])
+ self.pick(SEA)
+ window.apply_arrangement(SEA, "right", 5000, SEA, False, BEE)
+ entry = next(item for item in self.store.current()["peers"] if item["id"] == SEA)
+ self.assertEqual(entry["way_back_by"], BEE)
+ self.assertIn("Bee on its right too", window.no_way_back_note.text)
+
class TheOverview(Page):
def test_the_address_shown_is_the_machine_the_status_speaks_of(self):
diff --git a/mac_app/tests/test_crossing_zones.py b/mac_app/tests/test_crossing_zones.py
index 5b6a8f7..44b1aa4 100644
--- a/mac_app/tests/test_crossing_zones.py
+++ b/mac_app/tests/test_crossing_zones.py
@@ -83,6 +83,13 @@ class EachZoneSaysItsMachine(unittest.TestCase):
self.assertTrue(machine.armed)
self.assertEqual(machine.peers, {B})
+ def test_a_machine_not_in_use_keeps_its_zones_but_does_not_arm_them(self):
+ machine = engine([peer(A, "right"), {**peer(B, "left"), "in_use": False}], [
+ {"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"},
+ ])
+ self.assertEqual(machine.peers, {A})
+ self.assertEqual(push(machine, LEFT_X, 500.0, -20, 0).crossed, False)
+
def test_nothing_in_use_is_not_armed(self):
machine = engine([peer(A, "right")], [{"peer": A, "kind": "edge", "off": True}])
self.assertFalse(machine.armed)
diff --git a/mac_app/tests/test_hide_addresses_window.py b/mac_app/tests/test_hide_addresses_window.py
index 494a91c..b219f20 100644
--- a/mac_app/tests/test_hide_addresses_window.py
+++ b/mac_app/tests/test_hide_addresses_window.py
@@ -112,10 +112,9 @@ class NotificationTests(unittest.TestCase):
def test_a_notification_hides_the_pcs_address(self):
tray = mock.Mock()
tray.controller.cfg.hide_addresses = True
- with mock.patch.object(kvm_bridge_app.rumps, "notification") as notification, \
- mock.patch.object(kvm_bridge_app.AppKit, "NSBeep"):
+ with mock.patch.object(kvm_bridge_app.AppKit, "NSBeep"):
kvm_bridge_app.TrayApp._notify_user_main(tray, "Cannot switch", "Connecting to 192.0.2.20:24820")
- self.assertNotIn("192.0.2.20", notification.call_args.args[2])
+ self.assertNotIn("192.0.2.20", tray.notices.post.call_args.args[1])
if __name__ == "__main__":
diff --git a/mac_app/tests/test_ignored_inputs.py b/mac_app/tests/test_ignored_inputs.py
index 99d92e4..1e12aaa 100644
--- a/mac_app/tests/test_ignored_inputs.py
+++ b/mac_app/tests/test_ignored_inputs.py
@@ -15,7 +15,7 @@ from core import ignored
from core import protocol
import settings_store
from bridge import KVMController
-from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, make_config, quiet_logger
+from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, make_config, quiet_logger, redirect_to
from fake_link import FakeLink
KEY_F13 = 0x69
@@ -40,7 +40,7 @@ class TapTests(unittest.TestCase):
link_factory=FakeLink,
system_event_converter=lambda event: event,
)
- self.controller.redirecting = True
+ redirect_to(self.controller)
def tap(self, event_type, event):
return self.controller._event_tap_callback(None, event_type, event, None)
@@ -120,7 +120,7 @@ class TapTests(unittest.TestCase):
self.tap(FakeQuartz.kCGEventKeyDown, key_event(KEY_F13))
self.configure([ignored.key(KEY_F13)])
self.controller._return_local()
- self.controller.redirecting = True
+ redirect_to(self.controller)
up = key_event(KEY_F13)
self.assertIs(self.tap(FakeQuartz.kCGEventKeyUp, up), up)
diff --git a/mac_app/tests/test_mac_links.py b/mac_app/tests/test_mac_links.py
index 65fa0b6..db7265d 100644
--- a/mac_app/tests/test_mac_links.py
+++ b/mac_app/tests/test_mac_links.py
@@ -3,6 +3,7 @@ goes, what is sent to the machine it leaves and the one it takes, the pointer an
way home, the key table on the way out, and the clipboard. The links themselves are
core/tests/test_link.py's; the two ends together are test_mac_loopback.py's."""
+import logging
import os
import sys
import threading
@@ -74,6 +75,13 @@ class RemovedLinksTests(Base):
self.assertTrue(self.link.stopped)
self.assertFalse(self.link.stop_waited)
+ def test_the_primary_link_moves_to_the_first_machine_still_in_use(self):
+ self.controller.book.data["peers"][0]["in_use"] = False
+ self.controller.book.data["peers"].append({**self.controller.book.peers()[0], "token": "second", "in_use": True})
+ self.controller._sync_links()
+ self.assertEqual(self.controller._primary_token, "second")
+ self.assertIsNotNone(self.controller._primary_link)
+
def test_a_link_that_goes_down_after_its_machine_went_cannot_bring_input_back_or_report_up(self):
self.up()
self.controller.book.data["peers"][0]["send"] = False
@@ -458,7 +466,14 @@ class ComingHomeTests(Base):
def test_a_refusal_for_the_current_route_sends_input_home_with_the_reason(self):
self.arrives(protocol.refuse_msg(1, "owned"))
self.assertFalse(self.controller.redirecting)
- self.assertEqual(self.alerts, ["Office PC is being driven from another machine"])
+ self.assertEqual(self.alerts, ["Can't cross to Office PC: another machine is driving it."])
+
+ def test_a_refusal_names_the_other_machine_that_owns_the_responder(self):
+ peer = dict(self.controller.book.data["peers"][0], id=protocol.id_text(OTHER_ID),
+ token="second-peer", name="Desk-PC")
+ self.controller.book.data["peers"].append(peer)
+ self.arrives(protocol.refuse_msg(1, "owned", other=OTHER_ID))
+ self.assertEqual(self.alerts, ["Can't cross to Office PC: it is being driven from Desk-PC."])
def test_a_refusal_for_an_old_route_is_ignored(self):
self.arrives(protocol.accept_msg(1))
@@ -582,6 +597,8 @@ class AnnouncementTests(Base):
with self.controller.book.lock:
self.controller.book.data["peers"][0].update(side="left", side_set_at=7, id=self.peer)
self.controller.book.data["peers"].append({**entry, "id": protocol.id_text(OTHER_ID), "token": "other", "send": False})
+ inactive_id = bytes([33]) * 16
+ self.controller.book.data["peers"].append({**entry, "id": protocol.id_text(inactive_id), "token": "inactive", "in_use": False})
self.controller.announce = lambda: [protocol.settings_msg({"on": False, "set_at": 3, "by": ""})]
self.up()
types = self.link.types()
@@ -592,6 +609,13 @@ class AnnouncementTests(Base):
arrangement = next(m for m in self.link.posted if m["type"] == protocol.MSG_ARRANGEMENT)
self.assertEqual((arrangement["data"]["edge"], arrangement["data"]["set_at"]), ("left", 7))
+ def test_the_available_pairing_ids_skip_machines_not_in_use(self):
+ entry = self.controller.book.peers()[0]
+ self.controller.book.data["peers"][0]["id"] = self.peer
+ inactive_id = protocol.id_text(bytes([33]) * 16)
+ self.controller.book.data["peers"].append({**entry, "id": inactive_id, "token": "inactive", "in_use": False})
+ self.assertEqual(self.controller._pairing_ids(), (self.peer,))
+
def test_settings_are_not_announced_to_a_peer_that_does_not_keep_them(self):
self.controller.announce = lambda: [protocol.settings_msg({"on": False, "set_at": 3, "by": ""})]
self.up(caps=("clipboard",))
@@ -772,5 +796,135 @@ class GestureNamesTests(Base):
self.assertEqual(keys, ["ctrl", "ctrl"])
+
+
+class UnreachableWordsTests(Base):
+ def test_a_hand_over_refused_as_owned_says_so_rather_than_could_not_be_reached(self):
+ # Opus review: owned and busy left WHY_TEXT, so an onward refusal fell back to "could not be reached".
+ from core.owner import Unreachable
+ self.up()
+ self.controller._on_unreachable(Unreachable(self.peer, "owned", OTHER_ID))
+ self.assertEqual(self.alerts, ["Can't cross to Office PC: another machine is driving it."])
+
+
+class ItsOwnKeyboardTests(Base):
+ """beta.4 on 02-10-2026: the Mac's tap kept swallowing every key for nine minutes while its owner
+ said input was home, and the outbound worker dropped each one without a word. A Mac that thinks
+ it is redirecting never keeps its keyboard while its input is home."""
+
+ def tap(self, kind, keycode=0x00, character="a"):
+ event = {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "unicode": character}
+ return event, self.controller._event_tap_callback(None, kind, event, None)
+
+ def diverge(self):
+ """The state the Mac was found in: redirecting, with the owner at home."""
+ self.up()
+ self.controller._redirecting = True
+ self.assertFalse(self.controller.owner.away)
+
+ def test_a_key_while_the_owner_is_home_reaches_this_mac_and_the_state_is_put_right(self):
+ self.diverge()
+ event, returned = self.tap(FakeQuartz.kCGEventKeyDown)
+ self.assertIs(returned, event)
+ self.assertTrue(_wait(lambda: not self.controller.redirecting), "redirecting was never put right")
+ self.assertTrue(self.controller.outbound.empty())
+ # And the keyboard is this Mac's from then on.
+ event, returned = self.tap(FakeQuartz.kCGEventKeyUp)
+ self.assertIs(returned, event)
+
+ def test_the_tap_never_takes_a_lock_to_put_it_right(self):
+ self.diverge()
+ self.assertTrue(self.controller._owner_lock.acquire(timeout=1))
+ try:
+ started = time.monotonic()
+ event, returned = self.tap(FakeQuartz.kCGEventKeyDown)
+ self.assertIs(returned, event)
+ self.assertLess(time.monotonic() - started, 0.2, "the tap waited on the owner's lock")
+ finally:
+ self.controller._owner_lock.release()
+ self.assertTrue(_wait(lambda: not self.controller.redirecting))
+
+ def test_a_repair_that_finds_a_new_take_by_the_time_it_runs_leaves_it_alone(self):
+ # Sol's review: a repair queued in the gap of an ordinary return must not send a later take home.
+ self.diverge()
+ self.assertTrue(self.controller._owner_lock.acquire(timeout=1))
+ try:
+ self.tap(FakeQuartz.kCGEventKeyDown)
+ # The take that lands before the repair gets the lock.
+ self.controller.owner.on = self.peer
+ finally:
+ self.controller._owner_lock.release()
+ time.sleep(0.2)
+ self.assertTrue(self.controller.redirecting)
+ self.assertEqual(self.controller.owner.on, self.peer)
+
+ def test_the_tap_returns_the_key_even_while_logging_is_stuck(self):
+ self.diverge()
+ stuck = threading.Event()
+
+ class Stuck(logging.Handler):
+ def emit(self, record):
+ stuck.wait(3)
+
+ handler = Stuck()
+ self.controller.logger.addHandler(handler)
+ try:
+ started = time.monotonic()
+ event, returned = self.tap(FakeQuartz.kCGEventKeyDown)
+ self.assertIs(returned, event)
+ self.assertLess(time.monotonic() - started, 0.2, "the tap waited on the log")
+ finally:
+ stuck.set()
+ self.controller.logger.removeHandler(handler)
+ self.assertTrue(_wait(lambda: not self.controller.redirecting))
+
+ def test_input_that_reaches_the_worker_after_the_owner_came_home_puts_it_right_rather_than_vanishing(self):
+ self.diverge()
+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})
+ self.assertTrue(_wait(lambda: not self.controller.redirecting), "the worker dropped the key and left the tap swallowing")
+
+ def test_the_disagreement_is_logged_once_with_every_threads_stack(self):
+ self.diverge()
+ with self.assertLogs(self.controller.logger, level="ERROR") as said:
+ self.tap(FakeQuartz.kCGEventKeyDown)
+ self.controller._redirecting = True
+ self.tap(FakeQuartz.kCGEventKeyDown)
+ self.assertTrue(_wait(lambda: not self.controller.redirecting))
+ disagreements = [line for line in said.output if "redirecting while the owner says input is home" in line]
+ self.assertEqual(len(disagreements), 1, said.output)
+ self.assertIn("Thread", disagreements[0])
+
+ def test_every_change_of_redirecting_and_every_move_applied_is_logged_with_its_thread(self):
+ self.up()
+ with self.assertLogs(self.controller.logger, level="INFO") as said:
+ self.controller.set_redirecting(True)
+ self.controller.set_redirecting(False)
+ here = threading.current_thread().name
+ changes = [line for line in said.output if "redirecting False -> True" in line or "redirecting True -> False" in line]
+ moves = [line for line in said.output if "move applied:" in line]
+ self.assertEqual(len(changes), 2, said.output)
+ self.assertGreaterEqual(len(moves), 2, said.output)
+ self.assertTrue(all(here in line for line in changes + moves), said.output)
+
+ def test_a_take_racing_a_hand_over_from_the_link_never_leaves_the_two_views_apart(self):
+ # The 12:29:36 to 12:29:38 race: input moved on by the peer's switch on a link thread while
+ # this Mac's tap took the same peer again.
+ self.up()
+ for _ in range(200):
+ self.controller.set_redirecting(True)
+ route = self.controller.owner.route
+ switch = threading.Thread(target=self.link.arrives, daemon=True, args=(
+ self.controller, protocol.switch_v6(route, protocol.read_id(self.own), "right", 0.5)))
+ take = threading.Thread(target=self.controller.set_redirecting, args=(True,), daemon=True)
+ switch.start()
+ take.start()
+ switch.join(2)
+ take.join(2)
+ settle(self.controller)
+ self.assertEqual(self.controller.redirecting, self.controller.owner.away)
+ self.controller.set_redirecting(False)
+ self.assertFalse(self.controller.redirecting or self.controller.owner.away)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_mac_listener_port.py b/mac_app/tests/test_mac_listener_port.py
index 454ce04..d04527f 100644
--- a/mac_app/tests/test_mac_listener_port.py
+++ b/mac_app/tests/test_mac_listener_port.py
@@ -51,6 +51,18 @@ class OwnPortTests(unittest.TestCase):
wire.sync(self.cfg)
wire.server.start.assert_called_once_with(24820)
+ def test_switching_a_machine_out_of_use_rearms_the_listener(self):
+ wire = WindowsInput(self.controller)
+ self.addCleanup(wire.server.stop)
+ wire.server = mock.Mock(input_scale=None, listening=True)
+ wire._running_for = self.controller.own_port
+ wire._armed_for = wire._held()
+ settings = self.store.current()
+ settings["peers"][0]["in_use"] = False
+ self.store.save_settings(settings)
+ wire.sync(self.cfg)
+ wire.server.peers_changed.assert_called_once_with()
+
def test_a_controller_built_from_a_config_alone_still_listens_where_it_dials(self):
controller = WakingController(self.cfg, logger=logging.getLogger("t"), link_factory=FakeLink)
self.assertEqual(controller.own_port, self.cfg.port)
diff --git a/mac_app/tests/test_machines.py b/mac_app/tests/test_machines.py
index 8a69821..832fd72 100644
--- a/mac_app/tests/test_machines.py
+++ b/mac_app/tests/test_machines.py
@@ -26,6 +26,10 @@ def row(**kwargs):
class StateTests(unittest.TestCase):
+ def test_a_machine_not_in_use_shows_its_own_status(self):
+ state = row(entry=entry(in_use=False), live=True).state
+ self.assertEqual((state.key, state.word), ("not_in_use", "NOT IN USE"))
+
def test_a_machine_driving_this_mac_beats_the_rest(self):
state = row(driving=True, live=True, here=True).state
self.assertEqual((state.key, state.tone, state.word), ("driving", "signal", "Driving this Mac"))
diff --git a/mac_app/tests/test_machines_panel.py b/mac_app/tests/test_machines_panel.py
index eab55f0..310f9dc 100644
--- a/mac_app/tests/test_machines_panel.py
+++ b/mac_app/tests/test_machines_panel.py
@@ -198,10 +198,14 @@ class DirectionAndRemovalTests(Base):
def test_each_switch_hands_the_handler_its_machine_and_one_change(self):
self.panel.refresh()
row = self.rows()[0]
+ self.assertEqual(len([view for view in self.descend(row)
+ if view.accessibilityRole() == AppKit.NSAccessibilityCheckBoxRole]), 1)
+ self.panel._toggle_directions(PAIRED_TOKEN)
+ row = self.rows()[0]
switches = [view for view in self.descend(row) if view.accessibilityRole() == AppKit.NSAccessibilityCheckBoxRole]
- self.assertEqual(len(switches), 2)
- switches[0].callback()
+ self.assertEqual(len(switches), 3)
switches[1].callback()
+ switches[2].callback()
token = PAIRED_TOKEN
self.assertEqual([call[0] for call in self.directions], [token, token])
self.assertEqual({tuple(call[1]) for call in self.directions}, {("send",), ("allow_drive",)})
@@ -274,6 +278,7 @@ class FocusTests(Base):
def test_a_rebuild_keeps_focus_on_the_same_switch(self):
self.panel.refresh()
+ self.panel._toggle_directions(PAIRED_TOKEN)
self.focus((PAIRED_TOKEN, "drives"))
self.panel.invalidate()
self.panel.refresh()
@@ -281,6 +286,7 @@ class FocusTests(Base):
def test_asking_to_remove_puts_focus_on_keep_and_keeping_puts_it_back_on_remove(self):
self.panel.refresh()
+ self.panel._toggle_directions(PAIRED_TOKEN)
self.focus((PAIRED_TOKEN, "remove"))
self.panel._ask_to_remove(PAIRED_TOKEN)
self.assertEqual(self.focused(), (PAIRED_TOKEN, "keep"))
@@ -297,6 +303,7 @@ class FocusTests(Base):
def test_a_removed_machines_focus_is_not_chased(self):
self.pair(FIRST, SECOND_TOKEN, "Laptop")
self.panel.refresh()
+ self.panel._toggle_directions(SECOND_TOKEN)
self.focus((SECOND_TOKEN, "drives"))
self.panel._remove(SECOND_TOKEN)
self.panel.refresh()
@@ -563,6 +570,50 @@ class EnteringACodeTests(Base):
self.assertIn("cannot look for machines: address already in use", self.panel.heard_empty.text)
+class CodeBoxCentringTests(Base):
+ """beta.4 on Toby's Mac: each typed digit sat left of the middle of its box. Measured on the real
+ window's boxes, drawn offscreen at the 773-point width it had, never put on screen."""
+
+ def ink_offsets(self):
+ window = self.window.window
+ window.setContentSize_((773, window.frame().size.height))
+ boxes = self.panel.code_boxes
+ boxes.focus(window)
+ for digit in "408819":
+ window.firstResponder().insertText_(digit)
+ self.assertEqual(boxes.value, "408819")
+ window.contentView().layoutSubtreeIfNeeded()
+ view = boxes.view
+ bounds = view.bounds()
+ picture = view.bitmapImageRepForCachingDisplayInRect_(bounds)
+ view.cacheDisplayInRect_toBitmapImageRep_(bounds, picture)
+ scale = picture.pixelsWide() / bounds.size.width
+
+ def level(x, y):
+ colour = picture.colorAtX_y_(x, y).colorUsingColorSpace_(AppKit.NSColorSpace.sRGBColorSpace())
+ return colour.redComponent() + colour.greenComponent() + colour.blueComponent()
+
+ offsets = []
+ rows = range(int(4 * scale), int((bounds.size.height - 4) * scale), 2)
+ for control in boxes.fields:
+ box = control.superview()
+ frame = box.convertRect_toView_(box.bounds(), view)
+ # Inside the box's border and corner, on its own ground.
+ first, last = int((frame.origin.x + 4) * scale), int((frame.origin.x + frame.size.width - 4) * scale)
+ ground = level(first, int(bounds.size.height * scale / 2))
+ inked = [x for x in range(first, last) if any(abs(level(x, y) - ground) > 0.6 for y in rows)]
+ self.assertTrue(inked, "no digit drawn in a box")
+ ink = (inked[0] + inked[-1] + 1) / 2 / scale
+ offsets.append(round(ink - (frame.origin.x + frame.size.width / 2), 2))
+ return offsets
+
+ def test_each_typed_digit_sits_in_the_middle_of_its_box(self):
+ self.panel._toggle_sheet()
+ self.panel.refresh()
+ for offset in self.ink_offsets():
+ self.assertLessEqual(abs(offset), 0.3, f"digits sit off the middle of their boxes: {self.ink_offsets()}")
+
+
class TrayTests(Base):
"""The menu bar's side: one machine's switch, every machine's tick, a pairing this Mac hosted."""
diff --git a/mac_app/tests/test_notices_mac.py b/mac_app/tests/test_notices_mac.py
new file mode 100644
index 0000000..13faad9
--- /dev/null
+++ b/mac_app/tests/test_notices_mac.py
@@ -0,0 +1,168 @@
+"""The Mac's notices go through UNUserNotificationCenter (beta.4 on three machines: a refused crossing
+raised one through rumps' NSUserNotificationCenter, deprecated since macOS 11, and nothing showed;
+Beamer was never in Notifications settings). Driven against a stand-in framework, so no test asks
+this Mac for anything or puts a notification on screen."""
+
+import logging
+import unittest
+from unittest import mock
+
+import rumps
+
+import notices
+from kvm_bridge_app import TrayApp
+
+
+class FakeContent:
+ def __init__(self):
+ self.title = self.body = None
+ self.sound = None
+
+ @classmethod
+ def alloc(cls):
+ return cls()
+
+ def init(self):
+ return self
+
+ def setTitle_(self, text):
+ self.title = text
+
+ def setBody_(self, text):
+ self.body = text
+
+ def setSound_(self, sound):
+ self.sound = sound
+
+
+class FakeRequest:
+ @classmethod
+ def requestWithIdentifier_content_trigger_(cls, ident, content, trigger):
+ request = cls()
+ request.ident, request.content, request.trigger = ident, content, trigger
+ return request
+
+
+class FakeCenter:
+ def __init__(self):
+ self.asked = []
+ self.added = []
+ self.delegate = None
+
+ def setDelegate_(self, delegate):
+ self.delegate = delegate
+
+ def requestAuthorizationWithOptions_completionHandler_(self, options, handler):
+ self.asked.append(options)
+ handler(True, None)
+
+ def addNotificationRequest_withCompletionHandler_(self, request, handler):
+ self.added.append(request)
+ if handler is not None:
+ handler(None)
+
+
+class FakeFramework:
+ UNAuthorizationOptionAlert = 1 << 2
+ UNAuthorizationOptionSound = 1 << 1
+ UNNotificationPresentationOptionBanner = 16
+ UNNotificationPresentationOptionList = 8
+ UNNotificationPresentationOptionSound = 2
+ UNMutableNotificationContent = FakeContent
+ UNNotificationRequest = FakeRequest
+
+ def __init__(self, center=None, fails=False):
+ self.center = center or FakeCenter()
+ self.fails = fails
+
+ class Sound:
+ @staticmethod
+ def defaultSound():
+ return "default"
+
+ self.UNNotificationSound = Sound
+ framework = self
+
+ class Center:
+ @staticmethod
+ def currentNotificationCenter():
+ if framework.fails:
+ # What the real call raises in a process that is not an app bundle (run from source).
+ raise RuntimeError("bundleProxyForCurrentProcess is nil")
+ return framework.center
+
+ self.UNUserNotificationCenter = Center
+
+
+class NoticesTest(unittest.TestCase):
+ def setUp(self):
+ self.framework = FakeFramework()
+ self.notices = notices.Notices(logging.getLogger("test-notices"), framework=lambda: self.framework)
+
+ def test_asking_requests_alerts_and_sound_once(self):
+ self.notices.ask()
+ self.notices.ask()
+ self.assertEqual(self.framework.center.asked,
+ [FakeFramework.UNAuthorizationOptionAlert | FakeFramework.UNAuthorizationOptionSound])
+
+ def test_a_notice_shows_while_beamer_is_in_front_too(self):
+ # macOS keeps a notice from the app in front out of sight unless its delegate asks to show it,
+ # and Beamer's window is usually in front when a crossing is refused from its own page.
+ self.notices.ask()
+ shown = []
+ self.framework.center.delegate.userNotificationCenter_willPresentNotification_withCompletionHandler_(
+ self.framework.center, None, shown.append)
+ self.assertEqual(shown, [FakeFramework.UNNotificationPresentationOptionBanner
+ | FakeFramework.UNNotificationPresentationOptionList
+ | FakeFramework.UNNotificationPresentationOptionSound])
+
+ def test_a_notice_is_one_request_with_its_title_body_and_the_default_sound_and_no_trigger(self):
+ self.assertTrue(self.notices.post("Can't cross to Laptop-PC", "It is being driven from Desk-PC."))
+ self.assertTrue(self.notices.post("Second", "Another."))
+ first, second = self.framework.center.added
+ self.assertEqual((first.content.title, first.content.body, first.content.sound, first.trigger),
+ ("Can't cross to Laptop-PC", "It is being driven from Desk-PC.", "default", None))
+ self.assertNotEqual(first.ident, second.ident)
+
+ def test_posting_asks_first_when_nothing_has_asked_yet(self):
+ self.notices.post("Title", "Body")
+ self.assertEqual(len(self.framework.center.asked), 1)
+
+ def test_run_from_source_with_no_bundle_a_notice_is_logged_and_never_raises(self):
+ framework = FakeFramework(fails=True)
+ quiet = notices.Notices(logging.getLogger("test-notices"), framework=lambda: framework)
+ with self.assertLogs("test-notices", level="INFO") as said:
+ self.assertFalse(quiet.post("Title", "Body"))
+ quiet.ask()
+ self.assertTrue(any("Title" in line for line in said.output))
+
+ def test_the_real_framework_is_the_default_and_names_what_the_notices_use(self):
+ framework = notices.user_notifications()
+ for name in ("UNUserNotificationCenter", "UNMutableNotificationContent", "UNNotificationRequest",
+ "UNNotificationSound", "UNAuthorizationOptionAlert", "UNAuthorizationOptionSound"):
+ self.assertTrue(hasattr(framework, name), name)
+
+
+class _FakeTrayApp:
+ _notify_user_main = TrayApp._notify_user_main
+
+ def __init__(self):
+ self.logger = logging.getLogger("test-notices-tray")
+ self.controller = mock.Mock()
+ self.controller.cfg.hide_addresses = True
+ self.notices = mock.Mock()
+
+
+class TrayNoticeTest(unittest.TestCase):
+ def test_the_tray_app_posts_through_the_notices_not_rumps_with_addresses_hidden_as_set(self):
+ fake = _FakeTrayApp()
+ with mock.patch.object(rumps, "notification") as old, mock.patch("AppKit.NSBeep"):
+ fake._notify_user_main("Can't cross to Bee", "Bee at 192.0.2.30 refused.")
+ old.assert_not_called()
+ title, body = fake.notices.post.call_args.args
+ self.assertEqual(title, "Can't cross to Bee")
+ self.assertNotIn("192.0.2.30", body)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_notify_user_thread.py b/mac_app/tests/test_notify_user_thread.py
index 992579f..cf2c823 100644
--- a/mac_app/tests/test_notify_user_thread.py
+++ b/mac_app/tests/test_notify_user_thread.py
@@ -4,7 +4,6 @@ import unittest
from unittest import mock
import AppKit
-import rumps
from PyObjCTools import AppHelper
from kvm_bridge_app import TrayApp
@@ -17,6 +16,7 @@ class _FakeTrayApp:
def __init__(self):
self.logger = logging.getLogger("test-notify-user")
+ self.notices = mock.Mock()
class NotifyUserMainThreadTest(unittest.TestCase):
@@ -27,7 +27,7 @@ class NotifyUserMainThreadTest(unittest.TestCase):
straight to controller.on_user_alert, which bridge.py's _alert()
invokes from the event-tap thread (see set_redirecting calls in
_handle_trigger and the crossing-feed path) -- so it must do the
- same hop instead of calling AppKit.NSBeep()/rumps.notification
+ same hop instead of calling AppKit.NSBeep()/Notices.post
directly on the calling thread.
"""
calling_threads = []
@@ -52,7 +52,7 @@ class NotifyUserMainThreadTest(unittest.TestCase):
)
with mock.patch.object(AppKit, "NSBeep", side_effect=record_and_beep), mock.patch.object(
- rumps, "notification", side_effect=record_and_notify
+ fake_self.notices, "post", side_effect=record_and_notify
), mock.patch.object(AppHelper, "callAfter", side_effect=tracking_call_after):
background.start()
background.join(timeout=2)
@@ -67,7 +67,7 @@ class NotifyUserMainThreadTest(unittest.TestCase):
self.assertEqual(
calling_threads,
[],
- "AppKit.NSBeep/rumps.notification ran synchronously on the calling "
+ "AppKit.NSBeep/Notices.post ran synchronously on the calling "
"(background) thread instead of being marshalled onto the main thread "
"via AppHelper.callAfter",
)
diff --git a/mac_app/tests/test_pages.py b/mac_app/tests/test_pages.py
index e1f6f9e..05de160 100644
--- a/mac_app/tests/test_pages.py
+++ b/mac_app/tests/test_pages.py
@@ -174,6 +174,14 @@ class CrossingPageRulesTests(unittest.TestCase):
self.assertEqual(pages.parts_phrase("top", []), "the middle of the top edge")
self.assertEqual(pages.parts_phrase("top", ["sideways"]), "the middle of the top edge")
+ def test_a_shared_side_names_its_holder_and_uses_plural_when_needed(self):
+ self.assertEqual(pages.share_sentence(["Bee"], "right", "Oak"),
+ "Bee already crosses from the right edge of this Mac. The thirds you pick go to Oak; "
+ "the rest stay with Bee.")
+ self.assertEqual(pages.share_sentence(["Bee", "Sea"], "top", "Oak"),
+ "Bee and Sea already cross from the top edge of this Mac. The thirds you pick go to Oak; "
+ "the rest stay where they are.")
+
def test_the_crossing_line_gives_the_first_reason_nothing_can_cross(self):
line = pages.crossing_state_sentence
self.assertTrue(line(False, False, False, True, False, None).startswith("Not paired yet"))
@@ -357,6 +365,10 @@ class SendItemsTest(unittest.TestCase):
self.assertEqual(pages.send_items(peers, None, False), [("A", "Send input to Bee"), ("B", "Send input to Sea")])
self.assertEqual(pages.send_items(peers, "B", False), [("A", "Send input to Bee"), ("B", "Bring input back")])
+ def test_a_machine_not_in_use_has_no_send_item(self):
+ peers = [self.entry("A", "Bee"), self.entry("B", "Sea"), self.entry("C", "Oak", in_use=False)]
+ self.assertEqual(pages.send_items(peers, None, False), [("A", "Send input to Bee"), ("B", "Send input to Sea")])
+
def test_a_nameless_machines_address_is_hidden_when_asked(self):
peers = [self.entry("A", ""), self.entry("B", "Sea")]
self.assertEqual(pages.send_items(peers, None, True)[0][1], "Send input to •••")
diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.py
index d16d18f..ac830b1 100644
--- a/mac_app/tests/test_settings_store.py
+++ b/mac_app/tests/test_settings_store.py
@@ -50,6 +50,48 @@ class SettingsStoreTests(unittest.TestCase):
self.assertTrue(loaded.allow_windows_to_drive)
self.assertFalse(store.load().send_to_windows)
+ def test_in_use_defaults_on_round_trips_and_rejects_non_booleans(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store = SettingsStore(Path(directory) / "settings.json")
+ store.save(self.valid_raw())
+ entry = store.current()["peers"][0]
+ self.assertTrue(entry["in_use"])
+ store.set_peer(entry["token"], in_use=False)
+ self.assertFalse(store.current()["peers"][0]["in_use"])
+ with self.assertRaises(SettingsError):
+ store.set_peer(entry["token"], in_use="no")
+
+ def test_jump_key_round_trips_and_rejects_non_strings(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "settings.json"
+ store = SettingsStore(path)
+ store.save(self.valid_raw())
+ settings = store.current()
+ settings["peers"][0]["jump_key"] = "ctrl+shift+2"
+ store.save_settings(settings)
+ self.assertEqual(SettingsStore(path).current()["peers"][0]["jump_key"], "ctrl+shift+2")
+ settings["peers"][0]["jump_key"] = []
+ with self.assertRaises(SettingsError):
+ store.save_settings(settings)
+
+ def test_an_old_peer_without_a_jump_key_defaults_to_none(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store = SettingsStore(Path(directory) / "settings.json")
+ store.save(self.valid_raw())
+ self.assertIsNone(store.current()["peers"][0].get("jump_key") or None)
+
+ def test_trigger_clash_is_refused_without_changing_the_saved_value_and_can_be_cleared(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store = SettingsStore(Path(directory) / "settings.json")
+ store.save(self.valid_raw())
+ peer = store.current()["peers"][0]
+ store.set_jump_key(peer["id"], "ctrl+shift+2", "alt_r")
+ with self.assertRaises(SettingsError):
+ store.set_jump_key(peer["id"], "ctrl+f9", "f9")
+ self.assertEqual(store.current()["peers"][0]["jump_key"], "ctrl+shift+2")
+ store.set_jump_key(peer["id"], "", "alt_r")
+ self.assertEqual(store.current()["peers"][0]["jump_key"], "")
+
def test_the_full_screen_hold_defaults_on_and_round_trips(self):
with tempfile.TemporaryDirectory() as directory:
store = SettingsStore(Path(directory) / "settings.json")
@@ -316,4 +358,3 @@ class LegacyPortTests(unittest.TestCase):
def test_both_ports_are_below_the_range_the_system_hands_out(self):
self.assertLess(protocol.DEFAULT_PORT, 49152)
self.assertLess(protocol.PAIRING_PORT, 49152)
-
diff --git a/mac_app/tests/test_settings_v6.py b/mac_app/tests/test_settings_v6.py
index f23fd61..68f0083 100644
--- a/mac_app/tests/test_settings_v6.py
+++ b/mac_app/tests/test_settings_v6.py
@@ -132,6 +132,7 @@ class MigrationTests(Base):
"hw": "02:1a:2b:3c:0d:4e",
"send": True,
"allow_drive": False,
+ "in_use": True,
"side": "left",
"side_set_at": 1790000000,
"side_by": machine_id,
@@ -139,6 +140,7 @@ class MigrationTests(Base):
"paired_at": 0,
"linked": False,
"from_1_4": True,
+ "jump_key": "",
}])
self.assertEqual(cfg.host, "192.0.2.20")
self.assertEqual(cfg.port, 24820)
diff --git a/mac_app/widgets.py b/mac_app/widgets.py
index df2d348..70358f0 100644
--- a/mac_app/widgets.py
+++ b/mac_app/widgets.py
@@ -18,7 +18,8 @@ import media_keys
import motion
import theme
from ignored_titles import is_modifier_release, recorded_entry
-from key_codes import KEY_NAME_TO_CODE, SPECIAL_KEY_NAMES, key_cap, key_title
+from key_codes import KEY_NAME_TO_CODE, PRINTABLE_KEY_FALLBACKS, SPECIAL_KEY_NAMES, key_cap, key_title
+from core import ways as core_ways
def _autolayout(view):
@@ -1134,6 +1135,89 @@ class KeyRecorder:
paint(self.view, "edge")
+class JumpKeyRecorder:
+ """Records a modifier chord for a peer-specific local jump key."""
+
+ HINT = "Click, then press a key combination"
+
+ def __init__(self, value="", on_change=None, on_arm=None):
+ self.value = value or ""
+ self.on_change = on_change
+ self.on_arm = on_arm
+ self.monitor = None
+ self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])
+ self.view.setAccessibilityLabel_("Jump straight here key, " + self._title())
+ face = box("ground", radius=theme.RADIUS["keycap"] - 1)
+ self.view.addSubview_(face)
+ pin(face, self.view, (1, 1, 3, 1))
+ self.key = Label(self._title(), theme.TYPE["keycap"], mono=True, tracking=-0.02)
+ squeeze(self.key.view)
+ self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight)
+ line = stack(vertical=False, spacing=10)
+ line.addArrangedSubview_(self.key.view)
+ line.addArrangedSubview_(self.hint.view)
+ hug(self.key.view, AppKit.NSLayoutPriorityDefaultLow)
+ face.addSubview_(line)
+ pin(line, face, (9, 12, 8, 12))
+
+ def _title(self):
+ if not self.value:
+ return "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.key.set(self._title())
+ self.view.setAccessibilityLabel_("Jump straight here key, " + self._title())
+
+ def _clicked(self):
+ if self.monitor is not None:
+ self._stop()
+ return
+ self.key.set("Press a key combination…", ink="signal")
+ self.hint.set("Click again to cancel")
+ paint(self.view, "signal")
+ self.monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(
+ AppKit.NSEventMaskKeyDown | AppKit.NSEventMaskFlagsChanged, self._recorded
+ )
+ if self.on_arm is not None:
+ self.on_arm(True)
+
+ def _recorded(self, event):
+ if event.type() != AppKit.NSEventTypeKeyDown:
+ return event
+ flags = int(event.modifierFlags())
+ modifiers = []
+ for name, flag in (("ctrl", AppKit.NSEventModifierFlagControl), ("alt", AppKit.NSEventModifierFlagOption),
+ ("shift", AppKit.NSEventModifierFlagShift), ("cmd", AppKit.NSEventModifierFlagCommand)):
+ if flags & flag:
+ modifiers.append(name)
+ keycode = int(event.keyCode())
+ key = SPECIAL_KEY_NAMES.get(keycode) or PRINTABLE_KEY_FALLBACKS.get(keycode)
+ chord = core_ways.jump_chord(modifiers, key)
+ if chord is None:
+ return None
+ self._stop()
+ self.set_value(chord)
+ if self.on_change is not None:
+ self.on_change(chord)
+ return None
+
+ def cancel(self):
+ self._stop()
+
+ def _stop(self):
+ if self.monitor is not None:
+ AppKit.NSEvent.removeMonitor_(self.monitor)
+ self.monitor = None
+ if self.on_arm is not None:
+ self.on_arm(False)
+ self.key.set(self._title(), ink="ink")
+ self.hint.set(self.HINT)
+ paint(self.view, "edge")
+
+
class IgnoredRecorder:
"""A keycap that records the next key, mouse button or media key as an entry to keep on this
Mac while its input is on Windows. Clicking arms it; the left mouse button is never recorded,
@@ -1245,6 +1329,7 @@ class CodeBoxes:
self.fields = []
for index in range(digits):
container, control = field(cls=_CentredField)
+ control.cell().setScrollable_(False)
control.setFont_(theme.mono_font(theme.TYPE["keycap"]))
control.setAlignment_(AppKit.NSTextAlignmentCenter)
# A fixed box the digit centres in, rather than one that hugs the line and leaves the
diff --git a/mac_app/windows_input.py b/mac_app/windows_input.py
index 6c65c24..522627d 100644
--- a/mac_app/windows_input.py
+++ b/mac_app/windows_input.py
@@ -38,7 +38,7 @@ class WindowsInput:
self._logger = logger or LOGGER
# A peer can change the arrangement too, and it reaches this Mac over whichever of the two
# links is up: this one, or the Mac's own, which bridge.py handles. Both end at the same
- # handler in the app, called with (peer, edge, set_at, by, way_back).
+ # handler in the app, called with (peer, edge, set_at, by, way_back, way_back_by).
self._arrangement_callback = arrangement_callback
self._lock = threading.RLock()
self._running_for = None
@@ -57,7 +57,8 @@ class WindowsInput:
clipboard=clipboard_mac,
unlock=no_unlock,
hardware=hardware_mac.hardware_address_towards,
- away=lambda: controller.owner.away,
+ # The machine this Mac's input is on, as bytes, so a `busy` refusal can name it.
+ away=lambda: controller.owner.on and (protocol.read_id(controller.owner.on) or True),
zones=controller.book.zones,
notch_span=lambda: controller.notch_range,
owner_callback=self._on_owner,
@@ -118,7 +119,7 @@ class WindowsInput:
def _held(self):
"""What the responder arms and answers from: the peers' ids, tokens, sides and switches, and the zones."""
book = self._controller.book
- peers = tuple((p.get("id"), p.get("token"), p.get("side"), p.get("allow_drive")) for p in book.peers())
+ peers = tuple((p.get("id"), p.get("token"), p.get("side"), p.get("allow_drive"), p.get("in_use", True)) for p in book.peers())
return peers, json.dumps(book.zones(), sort_keys=True)
def stop(self) -> None:
@@ -144,7 +145,8 @@ class WindowsInput:
return False
author = protocol.read_id(by) or bytes(self._controller.identity()["id"])
return self.server.send(ident, protocol.arrangement_v6(mac_edge, int(set_at), author,
- way_back=self._controller.way_back(peer)))
+ way_back=self._controller.way_back(peer),
+ way_back_by=protocol.read_id(self._controller.way_back_by(peer))))
def send_settings(self, data, source=None) -> bool:
"""This Mac's settings state to every machine linked to it that keeps it and that this Mac
@@ -171,7 +173,8 @@ class WindowsInput:
if entry.get("side") in crossing.EDGES:
by = protocol.read_id(entry.get("side_by")) or bytes(self._controller.identity()["id"])
messages.append(protocol.arrangement_v6(entry["side"], entry.get("side_set_at", 0), by,
- way_back=self._controller.way_back(text)))
+ way_back=self._controller.way_back(text),
+ way_back_by=protocol.read_id(self._controller.way_back_by(text))))
caps = self.server.caps_of(peer) or frozenset()
if "settings" in caps:
messages += [m for m in self._controller.announce() if m.get("type") == protocol.MSG_SETTINGS]
@@ -183,8 +186,11 @@ class WindowsInput:
def _on_arrangement(self, peer, read) -> None:
if self._arrangement_callback is None:
return
- self._arrangement_callback(protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]),
- read.get("way_back"))
+ args = (protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]),
+ read.get("way_back"))
+ if read.get("way_back_by"):
+ args += (protocol.id_text(read["way_back_by"]),)
+ self._arrangement_callback(*args)
def _on_settings(self, peer, data) -> None:
if self.settings_callback is not None:
diff --git a/win_app/app_config.py b/win_app/app_config.py
index 6f6ed6c..90dedc1 100644
--- a/win_app/app_config.py
+++ b/win_app/app_config.py
@@ -500,6 +500,7 @@ def _peer_entry(raw: dict, token: str, port: int, own_id: str) -> dict:
"id": "", "name": _text(raw.get("paired_with")), "platform": "macos", "token": token,
"host": _text(raw.get("mac_host")), "port": port, "hw": _text(raw.get("mac_hardware_address")),
"send": _flag(raw.get("send_to_mac"), True), "allow_drive": _flag(raw.get("allow_mac_to_drive"), True),
+ "in_use": True,
"side": side, "side_set_at": set_at, "side_by": own_id if set_at else "",
"paired_with": [], "paired_at": 0, "linked": False, "from_1_4": True,
}
@@ -640,6 +641,14 @@ 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")
+ 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"]):
+ raise SettingsFileError(f"{path} has a peer in_use that is not true or false, and is left as it is")
+ if any("jump_key" in entry and (not isinstance(entry["jump_key"], str)
+ or (entry["jump_key"] and not ways.valid_jump_key(entry["jump_key"])))
+ for entry in settings["peers"]):
+ raise SettingsFileError(f"{path} has a peer jump_key that is not a recorded modifier chord, and is left as it is")
if _overlapping_zones(settings):
raise SettingsFileError(f"{path} has two zones in use over the same stretch of the screen, and is left as it is")
settings.setdefault("name", "")
@@ -804,8 +813,29 @@ def save_config(path: Path, config: Config) -> None:
_write_json(path, settings)
+def set_jump_key(path: Path, peer_id: str, value, trigger_key: str) -> dict:
+ """Sets or clears one peer's local jump chord after the shared clash checks."""
+ with SETTINGS_LOCK:
+ settings = load_settings(path)
+ entry = next((peer for peer in settings["peers"] if peer["id"] == peer_id), None)
+ if entry is None:
+ raise ConfigError("that machine is no longer paired with this PC")
+ try:
+ entry["jump_key"] = ways.check_jump_key(settings, peer_id, value, trigger_key) or ""
+ except ValueError as exc:
+ raise ConfigError(str(exc)) from exc
+ write_settings(path, settings)
+ return copy.deepcopy(entry)
+
+
def write_settings(path: Path, settings: dict) -> None:
"""The settings as the link changed them (an id learnt, an address, `linked`), written atomically."""
+ if any("in_use" in entry and not isinstance(entry["in_use"], bool) for entry in settings.get("peers", []) if isinstance(entry, dict)):
+ raise SettingsFileError(f"{path} has a peer in_use that is not true or false")
+ if any("jump_key" in entry and (not isinstance(entry["jump_key"], str)
+ or (entry["jump_key"] and not ways.valid_jump_key(entry["jump_key"])))
+ for entry in settings.get("peers", []) if isinstance(entry, dict)):
+ raise SettingsFileError(f"{path} has a peer jump_key that is not a recorded modifier chord")
_write_json(path, settings)
@@ -872,14 +902,24 @@ def set_ways(path: Path, peer: str, *, side=None, methods, parts, corner) -> boo
return moved
-def apply_arrangement(path: Path, peer: str, edge: str, set_at: int, by: str, way_back=None):
+def share_side(path: Path, side: str, thirds: dict) -> list:
+ """Split one side's zones under the settings lock, returning every machine whose zones changed."""
+ with SETTINGS_LOCK:
+ settings = load_settings(path)
+ changed = ways.share(settings, side, thirds, kinds=KINDS)
+ _write_json(path, settings)
+ return changed
+
+
+def apply_arrangement(path: Path, peer: str, edge: str, set_at: int, by: str, way_back=None, way_back_by=None):
"""A peer's `arrangement` (WIRE.md section 8), as core.ways takes it: `edge` is the edge of the peer
that faces this PC, so this PC's side for it is the opposite, and `way_back` is kept whatever the
side. Returns (changed, notices): whether the file was written, and a sentence for each of that
peer's zones turned off by a clash."""
with SETTINGS_LOCK:
settings = load_settings(path)
- changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this PC", way_back, _corner_edge)
+ changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this PC", way_back,
+ way_back_by=way_back_by, corner_edge=_corner_edge)
if changed:
_write_json(path, settings)
return changed, notices
diff --git a/win_app/diagram.py b/win_app/diagram.py
index 1f9fecd..165cf0b 100644
--- a/win_app/diagram.py
+++ b/win_app/diagram.py
@@ -57,7 +57,8 @@ def _marks(machines, shortcut) -> dict:
alone = len(machines) == 1
marks = {("cap",): 1.0 if shortcut else 0.0}
for machine in machines:
- key, methods, edge = machine["key"], set(machine["methods"]), _drawn_side(machine, alone)
+ key, methods = machine["key"], set(machine["methods"])
+ edge = _drawn_side(machine, alone) if machine.get("side") else ""
for side in pages_win.SIDE_ANGLE:
marks[("edge", key, side)] = 1.0 if "edge" in methods and side == edge else 0.0
marks[("track", key, side)] = 1.0 if "part" in methods and side == edge else 0.0
@@ -132,7 +133,7 @@ class ArrangementDiagram(QWidget):
self._unplaced = "" if alone else pages_win.unplaced_line(
[machine["label"] for machine in machines if not machine.get("side")])
self.setAccessibleDescription(pages_win.diagram_description(
- [dict(machine, label=self._labels[machine["key"]], side=_drawn_side(machine, alone)) for machine in machines],
+ [dict(machine, label=self._labels[machine["key"]]) for machine in machines],
key_name, style, shortcut))
targets = _marks(machines, shortcut)
slots = pages_win.side_slots([dict(machine, side=_drawn_side(machine, alone)) for machine in machines])
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index f2f649d..ad6a946 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -227,9 +227,8 @@ class StatusBridge(QObject):
owner = Signal(str)
# A link learnt something about a peer and saved it, or came up or went down.
peers_changed = Signal()
- # Either link, telling us a peer's side of the arrangement changed at its end: (peer id, the
- # peer's edge that faces this PC, stamp, the machine that made the change, its way_back or None).
- arrangement = Signal(str, str, int, str, object)
+ # Either link, telling us a peer's side changed: peer, edge, stamp, author, way_back, way_back_by.
+ 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)
alert = Signal(str, str)
@@ -309,13 +308,14 @@ class WindowsApplication(QWidget):
),
owner_callback=lambda peer: self.bridge.owner.emit(protocol.id_text(peer) if peer else ""),
arrangement_callback=lambda peer, read: self.bridge.arrangement.emit(
- protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back")
+ protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"),
+ protocol.id_text(read["way_back_by"]) if read.get("way_back_by") else None
),
settings_callback=lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data),
paired_callback=self._store_paired,
link_callback=lambda peer, up: self.bridge.peers_changed.emit(),
announce=self._announce,
- away=lambda: self.sender.redirecting,
+ away=lambda: self.sender.owner,
zones=self._zones,
clipboard=platform_parts.clipboard,
unlock=platform_parts.unlock,
@@ -344,7 +344,8 @@ class WindowsApplication(QWidget):
# this PC's own arrangement the moment a link comes up.
self.sender.settings_callback = lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data)
self.sender.arrangement_callback = lambda peer, read: self.bridge.arrangement.emit(
- protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back")
+ protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"),
+ protocol.id_text(read["way_back_by"]) if read.get("way_back_by") else None
)
self.sender.link_callback = lambda peer, up: self.bridge.peers_changed.emit()
self.sender.paired_callback = self._store_paired
@@ -525,13 +526,14 @@ class WindowsApplication(QWidget):
self.ignored_recorder.cancel()
if key != "crossing":
self.trigger_recorder.cancel()
+ self.jump_recorder.cancel()
self._run_previews()
# -- Overview ---------------------------------------------------------------------------
def _overview_page(self, layout, current) -> None:
self.machines = machines_win.MachinesModule(
- self._set_peer_send, self._set_peer_allow, self._remove_peer, self._toggle_pairing_sheet
+ self._set_peer_send, self._set_peer_allow, self._set_peer_in_use, self._remove_peer, self._toggle_pairing_sheet
)
layout.addWidget(self.machines)
self.sheet = machines_win.PairingSheet(
@@ -673,7 +675,8 @@ class WindowsApplication(QWidget):
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]}"
- sendable = [entry for entry in self._peer_entries if entry.get("send")]
+ sendable = [entry for entry in 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"
@@ -803,10 +806,16 @@ class WindowsApplication(QWidget):
messages = []
author = protocol.read_id(entry.get("side_by")) or protocol.read_id(config.machine_id)
if entry.get("side") in return_edge.EDGES and entry.get("side_set_at") and author is not None:
- way_back = ways.has_way({"peers": peers, "zones": self.book.zones()}, entry["id"])
- messages.append(protocol.arrangement_v6(entry["side"], entry["side_set_at"], author, way_back=way_back))
- if entry.get("send"):
- others = [protocol.read_id(item.get("id")) for item in peers if protocol.read_id(item.get("id")) not in (None, peer)]
+ settings = {"machine_id": protocol.id_text(self._identity()["id"]), "peers": peers,
+ "zones": self.book.zones()}
+ way_back = ways.has_way(settings, entry["id"])
+ holder = protocol.read_id(ways.way_back_by(settings, entry["id"]))
+ messages.append(protocol.arrangement_v6(entry["side"], entry["side_set_at"], author,
+ way_back=way_back, way_back_by=holder))
+ if entry.get("in_use", True) is True and entry.get("send"):
+ others = [protocol.read_id(item.get("id")) for item in peers
+ if item.get("in_use", True) is True
+ and protocol.read_id(item.get("id")) not in (None, peer)]
messages.append(protocol.paired_msg(others[: protocol.MAX_PEERS]))
if "settings" in self._peer_caps().get(peer, ()):
messages.append(protocol.settings_msg(self._same_state()))
@@ -1001,6 +1010,32 @@ class WindowsApplication(QWidget):
self.crossing_rows = {
"edge": self._row(self.edge_heading, self.edge_note, self.edge_choice.view, self.edge_unlearned),
}
+ # A group within Ways, never a panel of its own: a panel inside a panel reads as a second page.
+ self.share_module = QWidget()
+ self.share_module.body = QVBoxLayout(self.share_module)
+ self.share_module.body.setContentsMargins(0, 0, 0, 0)
+ self.share_module.body.setSpacing(8)
+ self.share_module.eyebrow = widgets.Eyebrow("Share the edge")
+ self.share_module.body.addWidget(self.share_module.eyebrow)
+ self.share_sentence = widgets.label("", "note", wrap=True)
+ self.share_module.body.addWidget(self.share_sentence)
+ share_tiles = QHBoxLayout()
+ share_tiles.setSpacing(4)
+ self.share_tiles = {}
+ for part in return_edge.PARTS:
+ tile = QPushButton()
+ tile.setProperty("vernier", "choice")
+ tile.setCheckable(True)
+ tile.setMinimumHeight(48)
+ tile.clicked.connect(lambda _on=False, part=part: self._share_part(part))
+ share_tiles.addWidget(tile, 1)
+ self.share_tiles[part] = tile
+ self.share_module.body.addLayout(share_tiles)
+ self.share_button = QPushButton("Share the edge")
+ self.share_button.setProperty("vernier", "primary")
+ self.share_button.clicked.connect(self._share_side)
+ self.share_module.body.addWidget(self.share_button)
+ self.share_module.setVisible(False)
chips = QHBoxLayout()
chips.setSpacing(4)
@@ -1028,6 +1063,23 @@ class WindowsApplication(QWidget):
self.crossing_rows["dragging"] = self._row(self.dragging_switch)
for key in ("edge", "parts", "corner", "dragging"):
module.body.addWidget(self.crossing_rows[key])
+ if key == "edge":
+ module.body.addWidget(self.share_module)
+
+ self.jump_heading = widgets.Eyebrow("Jump straight here")
+ module.body.addWidget(self.jump_heading)
+ jump_row = QHBoxLayout()
+ jump_row.setSpacing(8)
+ self.jump_recorder = widgets.JumpKeyRecorder(self._record_jump_key, self._jump_arming)
+ jump_row.addWidget(self.jump_recorder, 1)
+ self.jump_clear = QPushButton("Clear")
+ self.jump_clear.setProperty("vernier", "plain")
+ self.jump_clear.setAccessibleName("Clear jump key")
+ self.jump_clear.clicked.connect(lambda: self._record_jump_key(""))
+ jump_row.addWidget(self.jump_clear)
+ module.body.addLayout(jump_row)
+ self.jump_note = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.jump_note)
return module
@@ -1060,6 +1112,29 @@ class WindowsApplication(QWidget):
found.update(ways.ways(settings, ident)["methods"])
return found
+ def _share_part(self, part: str) -> None:
+ """Move an offered third to the next machine without saving until Share is pressed."""
+ recipients = self._share_recipients
+ current = recipients.index(self._share_thirds[part])
+ self._share_thirds[part] = recipients[(current + 1) % len(recipients)]
+ self._reflect_ways()
+
+ def _share_side(self) -> None:
+ """Save the offered split, rebuild the live zones and tell every affected machine."""
+ side, thirds = self._share_identity[0], dict(self._share_thirds)
+ try:
+ changed = app_config.share_side(self.config_path, side, thirds)
+ except (ConfigError, OSError, ValueError):
+ LOGGER.exception("The shared side could not be saved")
+ return
+ self._read_crossing()
+ for peer in changed:
+ self._tell(peer)
+ self.server.peers_changed()
+ self.sender.refresh()
+ self._reflect_ways()
+ self._reflect_look()
+
def _choose_machine(self, peer: str) -> None:
self._chosen = peer
self._show_clash("")
@@ -1085,18 +1160,26 @@ class WindowsApplication(QWidget):
old.deleteLater()
def _write_ways(self, **changes) -> bool:
- """One change to the chosen machine's ways, written for that machine alone. A side that moved,
- or a way there that opened or closed, goes to it as `arrangement` (`_tell`); a change that would
- share a stretch of this screen with another machine's zone is refused, said, and every control
- goes back."""
+ """One change to the chosen machine's ways. Every machine whose way back changed is told,
+ along with the chosen machine when its side or way changed. An overlapping edge choice shows
+ the share offer; other clashes are refused, said, and every control goes back."""
peer = self._chosen_machine()
if self._config is None or peer is None:
self._reflect_ways()
return False
self._read_crossing()
+ before = ways.way_back_state(self._crossing_settings())
had_way = ways.has_way(self._crossing_settings(), peer)
held = ways.ways(self._crossing_settings(), peer)
held.update(changes)
+ offer = ways.share_offer(self._crossing_settings(), peer)
+ occupied = {part for part, owner in offer["thirds"].items() if owner in offer["holders"]} if offer else set()
+ if offer and ("edge" in held["methods"] or
+ "part" in held["methods"] and occupied.intersection(held["parts"])):
+ self._show_clash("")
+ self._reflect_ways()
+ self.share_button.setFocus(Qt.FocusReason.OtherFocusReason)
+ return False
try:
moved = app_config.set_ways(self.config_path, peer, side=changes.get("side"), methods=held["methods"],
parts=held["parts"], corner=held["corner"])
@@ -1110,9 +1193,14 @@ class WindowsApplication(QWidget):
return False
self._show_clash("")
self._read_crossing()
- if moved or ways.has_way(self._crossing_settings(), peer) != had_way:
+ settings = self._crossing_settings()
+ changed_peers = [target for target, state in ways.way_back_state(settings).items()
+ if before.get(target) != state]
+ if moved or ways.has_way(settings, peer) != had_way:
# One border, walked both ways: the machine on the other side of it moves its own side to match.
- self._tell(peer)
+ changed_peers.append(peer)
+ for target in dict.fromkeys(changed_peers):
+ self._tell(target)
# A change on the Crossing page reaches a peer's pointer while it is here, not at its next crossing.
self.server.peers_changed()
self.sender.refresh()
@@ -1193,8 +1281,29 @@ class WindowsApplication(QWidget):
self.ways_summary.setText(summary)
motion.fade_from(self.ways_summary, shot)
motion.set_shown(self.edge_unlearned, not side)
+ offer = ways.share_offer(settings, chosen) if chosen else None
+ identity = (offer["side"], tuple(offer["holders"]), tuple(offer["thirds"].items())) if offer else None
+ if identity != getattr(self, "_share_identity", None):
+ self._share_identity = identity
+ self._share_thirds = dict(offer["thirds"]) if offer else {}
+ self.share_module.eyebrow.setText(f"Share the {offer['side']} edge" if offer else "Share the edge")
+ self.share_button.setText(f"Share the {offer['side']} edge" if offer else "Share the edge")
+ self._share_recipients = [chosen, *offer["holders"]] if offer else []
+ labels = dict(machines)
+ if offer:
+ holder_names = [labels.get(peer, "another machine") for peer in offer["holders"]]
+ self.share_sentence.setText(pages_win.share_sentence(holder_names, offer["side"],
+ labels.get(chosen, "this machine")))
+ names = pages_win.part_names(offer["side"])
+ for part, tile in self.share_tiles.items():
+ owner = self._share_thirds[part]
+ tile.setText(f"{names[part]}\n{labels.get(owner, 'another machine')}")
+ tile.setAccessibleName(f"{names[part]} third: {labels.get(owner, 'another machine')}")
+ tile.setChecked(owner == chosen)
+ self.share_button.setEnabled(chosen in self._share_thirds.values())
+ motion.set_shown(self.share_module, offer is not None)
for note, sentence in (
- (self.blocked_note, ways.blocked_sentence(settings, chosen, "this PC") if chosen else ""),
+ (self.blocked_note, ways.blocked_sentence(settings, chosen, "this PC") if chosen and not offer else ""),
(self.missing_note, ways.missing_sentence(settings, chosen, "this PC") if chosen else ""),
(self.no_way_back_note, ways.no_way_back_sentence(settings, chosen) if chosen else "")):
sentence = self._shown(sentence)
@@ -1208,6 +1317,40 @@ class WindowsApplication(QWidget):
drawn.append(dict(found, key=ident, label=label, chosen=ident == chosen or not machines))
self.arrangement_diagram.set_machines(drawn, key_name, config.trigger_style, shortcut)
self.resistance_strip.set_edge(edge)
+ self._reflect_jump_key()
+
+ def _reflect_jump_key(self) -> None:
+ chosen = self._chosen_machine()
+ entry = next((peer for peer in self._peer_entries if peer.get("id") == chosen), None)
+ self.jump_heading.setVisible(entry is not None)
+ self.jump_recorder.setVisible(entry is not None)
+ self.jump_clear.setVisible(entry is not None)
+ self.jump_note.setVisible(entry is not None)
+ if entry is None:
+ self.jump_recorder.cancel()
+ return
+ name = self._shown(peerlist.label_for(self._peer_entries, peer_id=chosen) or "this machine")
+ self.jump_recorder.set_value(entry.get("jump_key", ""))
+ self.jump_clear.setAccessibleName(f"Clear jump key for {name}")
+ self.jump_note.setText(f"sends input to {name}")
+
+ def _jump_arming(self, armed: bool) -> None:
+ self.sender.jump_recording = armed
+
+ def _record_jump_key(self, value: str) -> None:
+ chosen = self._chosen_machine()
+ if chosen is None or self._config is None:
+ return
+ try:
+ app_config.set_jump_key(self.config_path, chosen, value, self._config.trigger_key)
+ except ConfigError as exc:
+ self._read_crossing()
+ self._reflect_jump_key()
+ self.jump_note.setText(self._shown(str(exc)))
+ return
+ self._read_crossing()
+ self.sender.refresh()
+ self._reflect_jump_key()
def _set_arrangement(self, pc_edge: str) -> None:
"""The edge of THIS PC that leads to the chosen machine -- one border, walked either way. Not
@@ -1245,10 +1388,12 @@ class WindowsApplication(QWidget):
target = protocol.read_id(peer)
if author is None or target is None:
return
- self._send_to(target, protocol.arrangement_v6(entry["side"], entry["side_set_at"], author,
- way_back=ways.has_way(settings, peer)))
+ self._send_to(target, protocol.arrangement_v6(
+ entry["side"], entry["side_set_at"], author, way_back=ways.has_way(settings, peer),
+ way_back_by=protocol.read_id(ways.way_back_by(settings, peer)),
+ ))
- def _on_arrangement(self, peer: str, edge: str, set_at: int, by: str, way_back=None) -> None:
+ def _on_arrangement(self, peer: str, edge: str, set_at: int, by: str, way_back=None, way_back_by=None) -> None:
"""A peer changed the arrangement, over either link. `edge` is the edge of the PEER that
faces this PC; one older than what this end holds, by stamp and then by id, is ignored. A
side that makes two zones cover one stretch turns the peer's clashing zones off. `way_back`
@@ -1256,8 +1401,11 @@ class WindowsApplication(QWidget):
own, and one that changed nothing is not, so two machines never answer in turn."""
if self._config is None:
return
+ self._read_crossing()
+ before = ways.way_back_state(self._crossing_settings())
try:
- changed, notices = app_config.apply_arrangement(self.config_path, peer, edge, set_at, by, way_back)
+ changed, notices = app_config.apply_arrangement(self.config_path, peer, edge, set_at, by, way_back,
+ way_back_by)
except (ConfigError, OSError):
LOGGER.exception("An arrangement could not be saved")
return
@@ -1268,7 +1416,11 @@ class WindowsApplication(QWidget):
self._pull_peer_fields()
self.sender.refresh()
self.server.peers_changed()
- self._tell(peer)
+ self._read_crossing()
+ changed_peers = [target for target, state in ways.way_back_state(self._crossing_settings()).items()
+ if before.get(target) != state]
+ for target in dict.fromkeys([*changed_peers, peer]):
+ self._tell(target)
def _pull_peer_fields(self) -> None:
"""What links wrote into the first peer, into the window's flat view, and every machine's side
@@ -1962,7 +2114,8 @@ class WindowsApplication(QWidget):
self.machines.set_peers(self._peer_items(self._peer_entries))
def _any_send(self) -> bool:
- return any(entry.get("send") and protocol.linkable(entry) for entry in self._peer_entries)
+ return any(entry.get("in_use", True) is True and entry.get("send") and protocol.linkable(entry)
+ for entry in self._peer_entries)
def _label_of(self, peer: Optional[bytes]) -> str:
return self._labels_by_id.get(peer, "another machine") if peer is not None else ""
@@ -2004,6 +2157,13 @@ class WindowsApplication(QWidget):
if self._edit_peer(token, allow_drive=bool(enabled)):
self._after_peers_edit()
+ def _set_peer_in_use(self, token: str, enabled: bool) -> None:
+ """Takes input home before closing this machine's links when it leaves use."""
+ if not enabled and self._input_is_on(token):
+ self.sender.set_redirecting(False)
+ if self._edit_peer(token, in_use=bool(enabled)):
+ self._after_peers_edit()
+
def _set_every_peer(self, field: str, enabled: bool) -> None:
"""The tray's two ticks: one direction for every paired machine at once."""
if field == "send" and not enabled and self.sender.owner is not None:
@@ -2041,7 +2201,8 @@ class WindowsApplication(QWidget):
is only there to bring input back; with one, the toggle names it, as it always did."""
labels = peerlist.labels(self._peer_entries)
sendable = [(entry["id"], f"Send input to {self._shown(labels[entry['token']])}") for entry in self._peer_entries
- if entry.get("send") and entry.get("port") and protocol.read_id(entry.get("id")) is not None]
+ if entry.get("in_use", True) is True and entry.get("send") and entry.get("port")
+ and protocol.read_id(entry.get("id")) is not None]
items = sendable if len(sendable) > 1 else []
if items != [(ident, action.text()) for ident, action in self.machine_actions.items()]:
for action in self.machine_actions.values():
@@ -2093,9 +2254,11 @@ class WindowsApplication(QWidget):
try:
with app_config.SETTINGS_LOCK:
settings = app_config.load_settings(self.config_path)
+ before = ways.way_back_state(settings)
removed = peerlist.remove_peer(settings, token)
if removed is None:
return
+ after = ways.way_back_state(settings)
app_config.write_settings(self.config_path, settings)
remaining = bool(settings["peers"])
except (ConfigError, OSError):
@@ -2105,6 +2268,9 @@ class WindowsApplication(QWidget):
LOGGER.info("Removed %s from the paired machines", removed.get("name") or "a machine")
if remaining:
self._after_peers_edit()
+ for peer, state in after.items():
+ if before.get(peer) != state:
+ self._tell(peer)
return
self.sender.set_redirecting(False)
self._stop_sending()
@@ -2715,6 +2881,8 @@ class WindowsApplication(QWidget):
"""Every key, on the hook thread. The trigger is swallowed as it
switches; everything else goes to the Mac only while the Mac has
input, and a key on the ignored list not even then."""
+ if self.sender.handle_jump_key(name, down, vk):
+ return True
action = self._trigger.feed(name, down, time.monotonic())
if action is not None:
if not self.sender.shortcut_armed:
@@ -2743,9 +2911,10 @@ class WindowsApplication(QWidget):
peers = self.book.peers()
except Exception:
return
- ids = [protocol.read_id(item.get("id")) for item in peers]
- for item, peer in zip(peers, ids):
- if peer is not None and item.get("send"):
+ available = [item for item in peers if item.get("in_use", True) is True]
+ ids = [protocol.read_id(item.get("id")) for item in available]
+ for item, peer in zip(available, ids):
+ if peer is not None and item.get("in_use", True) is True and item.get("send"):
self._send_to(peer, protocol.paired_msg([other for other in ids if other not in (None, peer)][: protocol.MAX_PEERS]))
def _learn_peer_hardware(self, peer: bytes, address: str) -> None:
@@ -2815,6 +2984,7 @@ class WindowsApplication(QWidget):
super().hideEvent(event)
self.ignored_recorder.cancel()
self.trigger_recorder.cancel()
+ self.jump_recorder.cancel()
self._run_previews()
def changeEvent(self, event) -> None:
diff --git a/win_app/machines_win.py b/win_app/machines_win.py
index fdff7c0..0790edf 100644
--- a/win_app/machines_win.py
+++ b/win_app/machines_win.py
@@ -45,9 +45,9 @@ def _button(text: str, role: str = "") -> QPushButton:
class PeerRow(QWidget):
- """One paired machine: its name and state, one sentence, the two direction switches and Remove."""
+ """One paired machine: its name and state, use switch, direction disclosure and Remove."""
- def __init__(self, token: str, on_send: Callable, on_allow: Callable, on_remove: Callable) -> None:
+ def __init__(self, token: str, on_send: Callable, on_allow: Callable, on_in_use: Callable, on_remove: Callable) -> None:
super().__init__()
self.setProperty("vernier", "plain")
self.token = token
@@ -71,6 +71,8 @@ class PeerRow(QWidget):
column.addWidget(self.where)
self.detail = widgets.label("", "note", wrap=True)
column.addWidget(self.detail)
+ self.in_use = widgets.Switch("In use")
+ self.in_use.toggled.connect(lambda on: on_in_use(self.token, on))
self.send = widgets.Switch("This PC drives it")
self.allow = widgets.Switch("It drives this PC")
for switch in (self.send, self.allow):
@@ -82,17 +84,26 @@ class PeerRow(QWidget):
self.remove_button.clicked.connect(lambda: self._ask(True))
controls = QHBoxLayout()
controls.setSpacing(16)
- switches = QVBoxLayout()
- switches.setSpacing(2)
- switches.addWidget(self.send)
- switches.addWidget(self.allow)
+ directions = QVBoxLayout()
+ directions.setSpacing(2)
+ directions.addWidget(self.send)
+ directions.addWidget(self.allow)
+ self.direction_group = QWidget()
+ self.direction_group.setLayout(directions)
+ self.direction_group.setVisible(False)
+ self.directions = _button("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"))
for switch in (self.send, self.allow):
switch.setMaximumWidth(300)
- controls.addLayout(switches)
+ controls.addWidget(self.in_use)
controls.addStretch(1)
+ controls.addWidget(self.directions)
controls.addWidget(self.remove_button, 0, Qt.AlignmentFlag.AlignBottom)
self.controls = controls
column.addLayout(controls)
+ column.addWidget(self.direction_group)
self.confirm = _plain()
sure = QVBoxLayout(self.confirm)
sure.setContentsMargins(0, 0, 0, 0)
@@ -117,8 +128,9 @@ class PeerRow(QWidget):
def _ask(self, asking: bool) -> None:
self.confirm.setVisible(asking)
self.remove_button.setVisible(not asking)
- self.send.setVisible(not asking)
- self.allow.setVisible(not asking)
+ self.in_use.setVisible(not asking)
+ self.directions.setVisible(not asking)
+ self.direction_group.setVisible(not asking and self.directions.isChecked())
def refresh(self, entry: dict, label: str, state, where: str) -> None:
self.led.set_tone(state.tone)
@@ -126,7 +138,8 @@ class PeerRow(QWidget):
(self.confirm_text, f"Remove {label}? {KEEP_NOTE}")):
if item.text() != text:
item.setText(text)
- for switch, value in ((self.send, bool(entry.get("send"))), (self.allow, bool(entry.get("allow_drive")))):
+ for switch, value in ((self.in_use, entry.get("in_use", True) is True),
+ (self.send, bool(entry.get("send"))), (self.allow, bool(entry.get("allow_drive")))):
if switch.isChecked() != value:
switch.blockSignals(True)
switch.setChecked(value)
@@ -138,9 +151,9 @@ class PeerRow(QWidget):
class MachinesModule(widgets.Module):
"""The paired machines, one row each, and the button that opens the pairing sheet."""
- def __init__(self, on_send: Callable, on_allow: Callable, on_remove: Callable, on_pair: Callable) -> None:
+ def __init__(self, on_send: Callable, on_allow: Callable, on_in_use: Callable, on_remove: Callable, on_pair: Callable) -> None:
super().__init__("Machines")
- self._callbacks = (on_send, on_allow, on_remove)
+ self._callbacks = (on_send, on_allow, on_in_use, on_remove)
self.rows: dict = {}
self.rows_layout = QVBoxLayout()
self.rows_layout.setContentsMargins(0, 0, 0, 0)
@@ -433,4 +446,3 @@ class PairingSheet(widgets.Module):
def clear_code(self) -> None:
self.code.clear()
self._refresh_pair_button()
-
diff --git a/win_app/pages_win.py b/win_app/pages_win.py
index 7db4599..3b1e7be 100644
--- a/win_app/pages_win.py
+++ b/win_app/pages_win.py
@@ -150,6 +150,16 @@ def parts_phrase(edge, parts):
return f"the {joined} of the {edge} edge"
+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}.")
+
+
# The Crossing page's ways in, in the page's order. Edge and Part of the edge are two readings of
# one edge, so choosing either drops the other.
WAYS = ("shortcut", "edge", "part", "corner")
@@ -184,7 +194,8 @@ def crossing_machines(peers: list) -> list:
"""(id, label) for every paired machine a zone can lead to, in the list's order: never a phone,
which is never dialled (WIRE.md section 5). The entry migrated from 1.4.x has the id ""."""
labels = peerlist.labels(peers)
- return [(entry.get("id") or "", labels[entry["token"]]) for entry in peers if entry.get("port") != 0]
+ return [(entry.get("id") or "", labels[entry["token"]]) for entry in peers
+ if entry.get("in_use", True) is True and entry.get("port") != 0]
def crossing_state_sentence(paired, heard, sending, connected, armed, paused, full_screen_app, name="the other machine") -> str:
@@ -278,9 +289,14 @@ def ways_summary(methods, edge, parts, corner, key_name, style, name="the other
"""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."""
+ 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."
- methods = set(methods)
ways = []
if "edge" in methods:
ways.append(f"push through the whole {edge} edge")
diff --git a/win_app/peers_view.py b/win_app/peers_view.py
index 3d673e6..9e7c2d9 100644
--- a/win_app/peers_view.py
+++ b/win_app/peers_view.py
@@ -42,6 +42,8 @@ def describe(entry: dict, label: str, *, up: bool, driving: bool, input_there: b
"""`up`: a link to this machine is live, either way round. `driving`: its input is on this PC.
`input_there`: this PC's input is on it. `kind` and `status`: what the link this PC dials to it
last reported."""
+ if entry.get("in_use", True) is not True:
+ return PeerState("amber", "NOT IN USE", f"{label} is not in use on this PC.")
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.")
diff --git a/win_app/sender.py b/win_app/sender.py
index fc3948f..0918b32 100644
--- a/win_app/sender.py
+++ b/win_app/sender.py
@@ -63,9 +63,7 @@ INPUT_TYPES = protocol.INPUT_TYPES
# What the owner's reasons for bringing input home say, naming the machine (WIRE.md section 5).
HOME_REASONS = {
- "owned": "{name} is being driven from another machine",
"not_allowed": "{name} does not accept input from this one",
- "busy": "{name} is driving another machine",
"sent_home": "{name} sent the input back",
"link_lost": "Lost the link to {name}",
"no_answer": "{name} did not answer",
@@ -178,6 +176,10 @@ class LinkSender:
self._clipboard_stamp = None
# The machine this PC's input last landed on, as an id text, for the shortcut's choice.
self._last_on: Optional[str] = None
+ self._jump_modifiers = set()
+ self._jump_swallowed = set()
+ self._jump_pressed = set()
+ self.jump_recording = False
self._reported_redirecting = False
self._followed_at = 0.0
self._overflowed = False
@@ -251,7 +253,8 @@ class LinkSender:
id (the one migrated from 1.4.x), of the first this PC dials, by its token."""
peer = self.shortcut_target()
entry = self._peers.get(peer) if peer is not None else next(
- (item for item in self._entries if item.get("send") and item.get("host") and item.get("port")), None)
+ (item for item in self._entries if item.get("in_use", True) is True and item.get("send")
+ and item.get("host") and item.get("port")), None)
return (self._statuses.get(self.links.key_of(entry)) if entry is not None else None) or NOT_CONNECTED_STATUS
def shortcut_target(self) -> Optional[bytes]:
@@ -376,6 +379,42 @@ class LinkSender:
self._forget_held(peer)
self._feed(lambda o: o.link_down(peer))
+ def handle_jump_key(self, name: str, down: bool, vk: Optional[int] = None) -> bool:
+ """Handles a recorded local chord before trigger detection or ordinary key routing. Keys are
+ known by virtual key where there is one: the name carries Shift, so a Shift let go before the
+ key would make its release a different name."""
+ modifiers = {"alt", "alt_r", "cmd", "cmd_r", "ctrl", "ctrl_r", "shift", "shift_r"}
+ if name in modifiers:
+ if down:
+ self._jump_modifiers.add(name)
+ else:
+ self._jump_modifiers.discard(name)
+ return False
+ held = vk if vk is not None else name
+ if not down:
+ self._jump_pressed.discard(held)
+ if held in self._jump_swallowed:
+ self._jump_swallowed.discard(held)
+ return True
+ return False
+ # A key already down when its modifiers arrive repeats; it is not a press of the chord.
+ repeat = held in self._jump_pressed
+ self._jump_pressed.add(held)
+ if held in self._jump_swallowed:
+ return True
+ if repeat or self.jump_recording:
+ return False
+ chord = ways.jump_chord(self._jump_modifiers, name)
+ target = protocol.read_id(ways.jump_peer(self._entries, chord)) if chord else None
+ if target is None:
+ return False
+ self._jump_swallowed.add(held)
+ if self.owner == target:
+ self.set_redirecting(False)
+ else:
+ self.go(target)
+ return True
+
def on_key(self, name: str, down: bool, vk: Optional[int] = None, us: Optional[str] = None) -> bool:
"""One key, from the hook thread: True when it is not for this PC. Held keys are known by
their virtual key where there is one: the name is the character with Shift applied, so
@@ -698,7 +737,12 @@ class LinkSender:
def send_arrangement(self, peer: bytes, edge: str, set_at: int) -> bool:
"""Tells a peer which of this PC's edges faces it, when the change was made here."""
- return self.send_to(peer, protocol.arrangement_v6(edge, set_at, self._own_id))
+ settings = {"machine_id": protocol.id_text(self._own_id), "peers": self._entries, "zones": self._zone_list}
+ peer_text = protocol.id_text(peer)
+ way_back = ways.has_way(settings, peer_text)
+ way_back_by = protocol.read_id(ways.way_back_by(settings, peer_text))
+ return self.send_to(peer, protocol.arrangement_v6(edge, set_at, self._own_id,
+ way_back=way_back, way_back_by=way_back_by))
def peers_up(self) -> list:
return [peer for peer in self._peers if self.links.up(peer)]
@@ -958,8 +1002,13 @@ class LinkSender:
elif moved.why in ("asked", "switch"):
self._report_arrival(None)
else:
- reason = HOME_REASONS.get(moved.why, "{name} returned the input")
- self._alert(reason.format(name=self._name(moved.left)))
+ other = ""
+ if isinstance(moved.other, bytes) and moved.other != self._own_id:
+ 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 reason is None:
+ reason = HOME_REASONS.get(moved.why, "{name} returned the input").format(name=self._name(moved.left))
+ self._alert(reason)
def _land(self, edge: str, offset: float) -> None:
"""The peer pushed the pointer back through its zone: land it on the edge of this PC it comes
@@ -999,7 +1048,13 @@ class LinkSender:
if action.why == "unreachable" and self._accepts.get(action.peer) is False:
self._alert("Cannot switch — " + HOME_REASONS["not_allowed"].format(name=name))
return
- self._alert(f"Cannot switch — {name} could not be reached")
+ 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"
+ self._alert(reason)
def _learn_hardware(self, peer: bytes) -> None:
"""A peer's hardware address, read from the ARP table while the entry is fresh, for the wake-up
diff --git a/win_app/tests/test_crossing_matrix.py b/win_app/tests/test_crossing_matrix.py
index 368ee09..95ac2b9 100644
--- a/win_app/tests/test_crossing_matrix.py
+++ b/win_app/tests/test_crossing_matrix.py
@@ -283,6 +283,8 @@ class ArrangementHeldByBothTests(unittest.TestCase):
sender=types.SimpleNamespace(refresh=lambda: self.refreshed.append("sender")),
server=types.SimpleNamespace(peers_changed=lambda: self.refreshed.append("server")),
_tell=lambda peer: self.refreshed.append("answered"),
+ _read_crossing=lambda: None,
+ _crossing_settings=lambda: app_config.load_settings(self.path),
)
def arrive(self, edge, stamp, by=None):
diff --git a/win_app/tests/test_key_up_after_switch_back.py b/win_app/tests/test_key_up_after_switch_back.py
index c9e5068..67a40f6 100644
--- a/win_app/tests/test_key_up_after_switch_back.py
+++ b/win_app/tests/test_key_up_after_switch_back.py
@@ -58,6 +58,47 @@ class KeyUpAfterSwitchBackTest(unittest.TestCase):
self.sender.set_redirecting(False)
self.assertEqual(self.keys(), [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP])
+ def test_the_jump_chord_for_the_current_machine_returns_input_home(self):
+ entry = self.rig.settings.data["peers"][0]
+ entry["jump_key"] = "ctrl+shift+2"
+ self.sender.refresh()
+ self.assertFalse(self.sender.handle_jump_key("ctrl", True))
+ self.assertFalse(self.sender.handle_jump_key("shift", True))
+ self.assertTrue(self.sender.handle_jump_key("2", True))
+ self.assertFalse(self.sender.redirecting)
+ self.assertTrue(self.sender.handle_jump_key("2", True))
+ self.assertFalse(self.sender.redirecting)
+ self.assertTrue(self.sender.handle_jump_key("2", False))
+
+ def test_a_key_already_down_when_its_modifiers_arrive_is_not_a_jump(self):
+ self.rig.settings.data["peers"][0]["jump_key"] = "ctrl+shift+2"
+ self.sender.refresh()
+ self.assertFalse(self.sender.handle_jump_key("2", True, 0x32))
+ self.assertFalse(self.sender.handle_jump_key("ctrl", True))
+ self.assertFalse(self.sender.handle_jump_key("shift", True))
+ self.assertFalse(self.sender.handle_jump_key("2", True, 0x32))
+ self.assertTrue(self.sender.redirecting)
+ self.assertFalse(self.sender.handle_jump_key("2", False, 0x32))
+
+ def test_a_swallowed_key_is_released_by_its_virtual_key_even_when_shift_changed_its_name(self):
+ self.rig.settings.data["peers"][0]["jump_key"] = "ctrl+shift+@"
+ self.sender.refresh()
+ self.sender.handle_jump_key("ctrl", True)
+ self.sender.handle_jump_key("shift", True)
+ self.assertTrue(self.sender.handle_jump_key("@", True, 0x32))
+ self.sender.handle_jump_key("shift", False)
+ self.assertTrue(self.sender.handle_jump_key("2", False, 0x32))
+ self.assertFalse(self.sender.handle_jump_key("@", True, 0x32))
+
+ def test_nothing_jumps_while_a_jump_key_is_being_recorded(self):
+ self.rig.settings.data["peers"][0]["jump_key"] = "ctrl+shift+2"
+ self.sender.refresh()
+ self.sender.jump_recording = True
+ self.sender.handle_jump_key("ctrl", True)
+ self.sender.handle_jump_key("shift", True)
+ self.assertFalse(self.sender.handle_jump_key("2", True, 0x32))
+ self.assertTrue(self.sender.redirecting)
+
if __name__ == "__main__":
unittest.main()
diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.py
index 65be512..7f3e0ec 100644
--- a/win_app/tests/test_links.py
+++ b/win_app/tests/test_links.py
@@ -193,10 +193,16 @@ class TakingTests(unittest.TestCase):
self.sender.set_redirecting(True)
self.rig.inbound(B, protocol.refuse_msg(1, "busy"))
self.assertFalse(self.sender.redirecting)
- self.assertEqual(self.rig.alerts, ["Mac is driving another machine"])
+ self.assertEqual(self.rig.alerts, ["Can't cross to Mac: it is driving another machine."])
self.assertEqual(self.rig.redirects, [True, False])
self.assertEqual(self.rig.arrivals, [])
+ def test_a_refusal_names_the_machine_this_pcs_input_is_on(self):
+ rig = Rig(entries=[harness.entry(B, "Mac", side="left"), harness.entry(C, "Rig", side="top")])
+ rig.sender.set_redirecting(True)
+ rig.inbound(B, protocol.refuse_msg(1, "busy", other=C))
+ self.assertEqual(rig.alerts, ["Can't cross to Mac: it is driving Rig."])
+
def test_the_shortcut_home_reports_where_the_pointer_is_and_lets_go(self):
self.sender.set_redirecting(True)
self.sender.set_redirecting(False)
@@ -360,7 +366,14 @@ class OnwardTests(unittest.TestCase):
self.switch(C)
self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned"))
self.assertEqual(self.sender.owner, B)
- self.assertEqual(self.rig.alerts[-1], "Cannot switch — Other could not be reached")
+ self.assertEqual(self.rig.alerts[-1], "Can't cross to Other: another machine is driving it.")
+ # And the machine in the way, named when the refusal says which one.
+ self.sender._owner._left_out.clear()
+ self.rig.drop(C)
+ self.rig.bring_up(C)
+ self.switch(C)
+ self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned", other=B))
+ self.assertEqual(self.rig.alerts[-1], "Can't cross to Other: it is being driven from Mac.")
class KeyTests(unittest.TestCase):
@@ -727,7 +740,10 @@ class ArrangementTests(unittest.TestCase):
rig = Rig()
self.assertTrue(rig.sender.send_arrangement(B, "left", 1790000001))
message = rig.sent(B, "arrangement")[0]
- self.assertEqual(message["data"], {"edge": "left", "set_at": 1790000001, "by": protocol.id_text(HERE)})
+ # way_back too, as every arrangement carries it (WIRE.md section 8).
+ self.assertEqual({key: message["data"][key] for key in ("edge", "set_at", "by")},
+ {"edge": "left", "set_at": 1790000001, "by": protocol.id_text(HERE)})
+ self.assertIsInstance(message["data"]["way_back"], bool)
def test_no_link_up_means_the_app_must_use_the_peers_own(self):
rig = Rig(up=())
diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.py
index e9e94d6..6987b98 100644
--- a/win_app/tests/test_pages_win.py
+++ b/win_app/tests/test_pages_win.py
@@ -15,6 +15,13 @@ except ImportError: # PySide6 is only in the Windows venv
class PagesWinTest(unittest.TestCase):
+ def test_crossing_machine_picker_omits_peers_not_in_use(self):
+ peers = [
+ {"id": "A", "name": "Bee", "token": "ta", "port": 24820},
+ {"id": "B", "name": "Sea", "token": "tb", "port": 24820, "in_use": False},
+ ]
+ self.assertEqual(pages_win.crossing_machines(peers), [("A", "Bee")])
+
def test_keys_match_pages_in_order(self):
self.assertEqual(pages_win.KEYS, tuple(page[0] for page in pages_win.PAGES))
@@ -108,6 +115,14 @@ class DesignGroupsTest(unittest.TestCase):
class CrossingWaysTest(unittest.TestCase):
+ def test_a_shared_side_names_its_holder_and_uses_plural_when_needed(self):
+ self.assertEqual(pages_win.share_sentence(["Bee"], "right", "Oak"),
+ "Bee already crosses from the right edge of this PC. The thirds you pick go to Oak; "
+ "the rest stay with Bee.")
+ self.assertEqual(pages_win.share_sentence(["Bee", "Sea"], "top", "Oak"),
+ "Bee and Sea already cross from the top edge of this PC. The thirds you pick go to Oak; "
+ "the rest stay where they are.")
+
def test_edge_and_part_of_the_edge_exclude_each_other(self):
self.assertEqual(pages_win.toggle_way(["shortcut", "edge"], "part", True), ["shortcut", "part"])
self.assertEqual(pages_win.toggle_way(["part", "corner"], "edge", True), ["edge", "corner"])
@@ -162,6 +177,14 @@ class CrossingWaysTest(unittest.TestCase):
"the bottom-right corner or hold Right Ctrl.")
self.assertIn("choose at least one way", summary([], "left", [], "top_left", "F13", "hold"))
+ def test_with_no_side_learned_the_summary_still_names_the_shortcut_which_needs_none(self):
+ summary = pages_win.ways_summary
+ self.assertEqual(summary(["edge", "corner", "shortcut"], "", [], "top_left", "Right Ctrl", "double_tap", "Bee"),
+ "Input moves to Bee when you press Right Ctrl twice. Its edges and corner wait until this PC "
+ "knows which side Bee is on.")
+ self.assertEqual(summary(["edge"], "", [], "top_left", "Right Ctrl", "double_tap", "Bee"),
+ "Nothing moves input to Bee until this PC knows which side it is on.")
+
def test_the_key_cap_line_says_how_the_key_is_pressed(self):
self.assertEqual(pages_win.trigger_phrase("Right Ctrl", "double_tap"), "Right Ctrl, twice")
self.assertEqual(pages_win.trigger_phrase("Right Ctrl", "hold"), "Right Ctrl, held")
diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.py
index cd5a3f4..ebe6f6c 100644
--- a/win_app/tests/test_pairing_window.py
+++ b/win_app/tests/test_pairing_window.py
@@ -30,8 +30,10 @@ ID_A = b"\x0a" * 15 + b"\x01"
ID_B = b"\x0b" * 15 + b"\x02"
-def peer(identity, name, token, host, platform="macos", paired_at=1_780_000_000):
- return pairing.peer_entry(identity, name, platform, 24820, token, host, paired_at)
+def peer(identity, name, token, host, platform="macos", paired_at=1_780_000_000, in_use=True):
+ entry = pairing.peer_entry(identity, name, platform, 24820, token, host, paired_at)
+ entry["in_use"] = in_use
+ return entry
@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")
@@ -84,6 +86,30 @@ class MachinesWindowTest(unittest.TestCase):
self.assertEqual(row.word.text(), "Waiting")
self.assertIn("Studio Mac", row.detail.text())
+ def test_the_direction_switches_start_under_a_closed_disclosure(self):
+ window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"))
+ row = next(iter(window.machines.rows.values()))
+ self.assertFalse(row.directions.isChecked())
+ self.assertTrue(row.direction_group.isHidden())
+ row.directions.click()
+ self.assertFalse(row.direction_group.isHidden())
+
+ def test_the_send_button_names_the_only_machine_in_use(self):
+ window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"),
+ peer(ID_B, "Inactive", TOKEN_B, "192.0.2.11", in_use=False))
+ window.sender.shortcut_target = lambda: None
+ self.assertEqual(window._redirect_text(), "Send input to Studio Mac")
+
+ def test_the_paired_announcement_omits_machines_not_in_use(self):
+ window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"),
+ peer(ID_B, "Inactive", TOKEN_B, "192.0.2.11", in_use=False))
+ sent = []
+ window._send_to = lambda ident, message: sent.append((ident, message)) or True
+ window._send_paired()
+ self.assertEqual(len(sent), 1)
+ self.assertEqual(sent[0][0], ID_A)
+ self.assertEqual(sent[0][1]["data"]["ids"], [])
+
def test_any_token_from_1_4_x_asks_to_pair_again(self):
# "A" * 43 has pairing's shape: 1.4.x kept no record of whether a token was paired or typed.
for token in ("typed by hand", "A" * 43):
@@ -133,6 +159,18 @@ class MachinesWindowTest(unittest.TestCase):
rows = list(window.machines.rows.values())
self.assertEqual([(row.send.isChecked(), row.allow.isChecked()) for row in rows], [(True, False), (False, True)])
+ def test_the_tray_send_items_omit_machines_not_in_use(self):
+ entries = [
+ peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"),
+ peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"),
+ peer(b"\x0c" * 15 + b"\x03", "Spare", protocol.id_text(bytes(range(2, 34))), "192.0.2.12"),
+ ]
+ window = self.open(*entries)
+ window._edit_peer(protocol.id_text(bytes(range(2, 34))), in_use=False)
+ window._after_peers_edit()
+ window._refresh_tray_machines()
+ self.assertEqual(list(window.machine_actions), [protocol.id_text(ID_A), protocol.id_text(ID_B)])
+
def test_the_trays_ticks_change_every_machine_in_one_write(self):
window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))
window._set_every_peer("allow_drive", False)
diff --git a/win_app/tests/test_pc_three_machines.py b/win_app/tests/test_pc_three_machines.py
index 757b715..b3baf3e 100644
--- a/win_app/tests/test_pc_three_machines.py
+++ b/win_app/tests/test_pc_three_machines.py
@@ -7,6 +7,7 @@ import os
import sys
import tempfile
import unittest
+from unittest import mock
from pathlib import Path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -15,6 +16,7 @@ from links_rig import B, C, Rig, edge_zone
import app_config
import pages_win
+import sender as sender_module
from core import protocol
from core import ways
from core.tests import responder_harness as harness
@@ -92,6 +94,11 @@ class ShortcutMachineTests(unittest.TestCase):
self.assertTrue(rig.sender.connected)
self.assertEqual(rig.sender.status, "Connected to Sea")
+ def test_the_status_does_not_name_a_machine_not_in_use(self):
+ rig = self.rig(up=(), b={"in_use": False})
+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), False, "Bee is unreachable")
+ self.assertEqual(rig.sender.status, sender_module.NOT_CONNECTED_STATUS)
+
class SetWaysTests(unittest.TestCase):
"""Each machine's side and zones are written one machine at a time, under the settings lock, and
@@ -364,6 +371,55 @@ class WindowTests(unittest.TestCase):
class CrossingPageTests(WindowTests):
+ def sharing_side(self):
+ settings = app_config.load_settings(self.path)
+ for peer in settings["peers"]:
+ peer.update(side="right", side_set_at=100 if peer["id"] == BT else 200, side_by=HIGH)
+ settings["zones"] = [{"peer": BT, "kind": "edge"}, {"peer": CT, "kind": "edge", "off": True}]
+ app_config.write_settings(self.path, settings)
+ self.window._pull_peer_fields()
+ self.window._choose_machine(CT)
+ return self.window
+
+ def test_the_share_panel_offers_thirds_below_the_side_and_hides_the_blocked_sentence(self):
+ window = self.sharing_side()
+ self.assertFalse(window.share_module.isHidden())
+ self.assertEqual([window.share_tiles[p].text() for p in ("start", "middle", "end")],
+ ["Top\nBee", "Middle\nBee", "Bottom\nSea"])
+ self.assertTrue(window.blocked_note.isHidden())
+
+ def test_a_tile_cycles_its_machine_and_share_saves_and_tells_each_one(self):
+ window = self.sharing_side()
+ window.share_tiles["start"].click()
+ self.assertEqual(window.share_tiles["start"].text(), "Top\nSea")
+ window.share_button.click()
+ zones = {(zone["peer"], zone["kind"]): zone for zone in self.saved()["zones"]}
+ self.assertEqual(zones[(BT, "part")]["parts"], ["middle"])
+ self.assertEqual(zones[(CT, "part")]["parts"], ["start", "end"])
+ self.assertTrue(zones[(BT, "edge")].get("off"))
+ self.assertTrue(zones[(CT, "edge")].get("off"))
+ self.assertEqual({peer for peer, _data in self.arrangements()}, {B, C})
+
+ def test_turning_on_edge_keeps_it_off_and_focuses_the_share_button(self):
+ window = self.sharing_side()
+ # An offscreen window is never active, so the focus asked for is what can be checked.
+ with mock.patch.object(window.share_button, "setFocus") as focus:
+ window.way_boxes["edge"].setChecked(True)
+ self.assertFalse(window.way_boxes["edge"].isChecked())
+ self.assertFalse(window.share_module.isHidden())
+ self.assertTrue(window.blocked_note.isHidden())
+ focus.assert_called()
+
+ def test_turning_on_an_overlapping_part_keeps_it_off_and_focuses_the_share_button(self):
+ window = self.sharing_side()
+ # An offscreen window is never active, so the focus asked for is what can be checked.
+ with mock.patch.object(window.share_button, "setFocus") as focus:
+ window.way_boxes["part"].setChecked(True)
+ self.assertFalse(window.way_boxes["part"].isChecked())
+ self.assertFalse(window.share_module.isHidden())
+ self.assertTrue(window.blocked_note.isHidden())
+ focus.assert_called()
+
def test_with_two_machines_paired_the_page_offers_a_choice_of_machine(self):
window = self.window
self.assertFalse(window.machine_row.isHidden())
@@ -406,15 +462,43 @@ class CrossingPageTests(WindowTests):
self.window.way_boxes["corner"].setChecked(True)
self.assertIs(self.arrangements()[-1][1]["way_back"], True)
+ def test_moving_one_machine_tells_every_machine_whose_way_back_it_changed(self):
+ settings = self.saved()
+ settings["peers"][0].update(side="left", side_set_at=100, side_by=HIGH)
+ settings["peers"][1].update(side="left", side_set_at=200, side_by=HIGH)
+ settings["zones"] = [{"peer": BT, "kind": "edge"}, {"peer": CT, "kind": "edge", "off": True}]
+ app_config.write_settings(self.path, settings)
+ self.window._pull_peer_fields()
+ self.assertEqual(ways.way_back_by(self.window._crossing_settings(), CT), BT)
+ self.window._choose_machine(BT)
+ self.window._set_arrangement("right")
+ self.assertCountEqual([peer for peer, _data in self.arrangements()], [B, C])
+
+ def test_removing_the_machine_in_the_way_tells_the_one_it_blocked(self):
+ settings = self.saved()
+ settings["peers"][0].update(side="left", side_set_at=100, side_by=HIGH)
+ settings["peers"][1].update(side="left", side_set_at=200, side_by=HIGH)
+ settings["zones"] = [{"peer": BT, "kind": "edge", "off": True}, {"peer": CT, "kind": "edge"}]
+ app_config.write_settings(self.path, settings)
+ self.window._pull_peer_fields()
+ self.assertEqual(ways.way_back_by(self.window._crossing_settings(), BT), CT)
+
+ self.window._remove_peer(harness.TOKENS[C])
+
+ told = [(peer, data) for peer, data in self.arrangements() if peer == B]
+ self.assertEqual(len(told), 1)
+ self.assertFalse(told[0][1]["way_back"])
+ self.assertNotIn("way_back_by", told[0][1])
+
def test_an_arrangement_that_changed_something_is_answered_with_this_pcs_own(self):
window = self.window
- window.bridge.arrangement.emit(CT, "left", 500, HIGH, True)
+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, True, None)
(peer, data), = self.arrangements()
self.assertEqual((peer, data["edge"], data["set_at"], data["by"], data["way_back"]), (C, "right", 500, HIGH, True))
self.assertIs(self.peer(CT)["way_back"], True)
- window.bridge.arrangement.emit(CT, "left", 500, HIGH, True)
+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, True, None)
self.assertEqual(len(self.arrangements()), 1)
- window.bridge.arrangement.emit(CT, "left", 500, HIGH, False)
+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, False, None)
self.assertEqual(len(self.arrangements()), 2)
self.assertIs(self.peer(CT)["way_back"], False)
@@ -432,7 +516,7 @@ class CrossingPageTests(WindowTests):
self.window.sender.arrangement_callback(C, {**read, "set_at": 501, "way_back": True})
self.assertEqual([args[4] for args in heard], [False, True])
- def test_a_way_that_would_clash_is_refused_with_the_sentence_and_the_box_goes_back(self):
+ def test_a_way_with_a_share_offer_keeps_its_box_off_and_shows_the_panel(self):
window = self.window
window._choose_machine(CT)
window._set_arrangement("left")
@@ -440,10 +524,11 @@ class CrossingPageTests(WindowTests):
window.way_boxes["edge"].setChecked(True)
self.assertFalse(window.way_boxes["edge"].isChecked())
self.assertEqual(self.path.read_bytes(), before)
- self.assertFalse(window.clash_note.isHidden())
- self.assertIn("Bee and Sea would both lead from the left edge of this PC", window.clash_note.text())
+ self.assertFalse(window.share_module.isHidden())
+ self.assertIn("Bee already crosses from the left edge", window.share_sentence.text())
+ self.assertTrue(window.blocked_note.isHidden())
window._choose_machine(BT)
- self.assertTrue(window.clash_note.isHidden())
+ self.assertTrue(window.share_module.isHidden())
def test_ways_written_here_reach_that_machines_zones_only(self):
window = self.window
@@ -472,14 +557,15 @@ class CrossingPageTests(WindowTests):
window._choose_machine(BT)
self.assertTrue(window.missing_note.isHidden())
- def test_a_machine_whose_side_another_holds_is_named_with_the_one_that_holds_it(self):
+ def test_a_machine_whose_side_another_holds_is_named_in_the_share_panel(self):
window = self.window
window._on_arrangement(CT, "right", 500, HIGH)
window._choose_machine(CT)
- self.assertFalse(window.blocked_note.isHidden())
- self.assertIn("Sea has no way in: Bee already leads from the left edge of this PC", window.blocked_note.text())
- window._choose_machine(BT)
+ self.assertFalse(window.share_module.isHidden())
+ self.assertIn("Bee already crosses from the left edge", window.share_sentence.text())
self.assertTrue(window.blocked_note.isHidden())
+ window._choose_machine(BT)
+ self.assertTrue(window.share_module.isHidden())
def test_a_machine_that_said_no_way_leads_back_is_named_until_it_says_one_does(self):
window = self.window
@@ -490,6 +576,14 @@ class CrossingPageTests(WindowTests):
window._on_arrangement(BT, "right", 50, HIGH, True)
self.assertTrue(window.no_way_back_note.isHidden())
+ def test_an_arrangement_names_the_machine_holding_the_way_back_side(self):
+ window = self.window
+ window._choose_machine(CT)
+ window._on_arrangement(CT, "right", 500, HIGH, False, BT)
+ sea = next(item for item in app_config.load_settings(self.path)["peers"] if item["id"] == CT)
+ self.assertEqual(sea["way_back_by"], BT)
+ self.assertIn("Bee on its right too", window.no_way_back_note.text())
+
def test_an_arrangement_from_the_machine_not_shown_moves_only_its_side(self):
window = self.window
window._on_arrangement(CT, "left", 500, HIGH)
@@ -578,10 +672,16 @@ class DiagramWidgetTests(unittest.TestCase):
self.assertEqual(picture._unplaced, "Not placed yet: Dee")
self.assertFalse(picture.grab().isNull())
- def test_one_machine_with_no_side_is_drawn_on_the_right_as_before(self):
+ def test_one_machine_with_no_side_is_drawn_on_the_right_but_no_edge_lights_until_a_side_is_held(self):
+ # This PC's engine crosses no edge for a machine with no side, as the page's Not learned yet says.
picture = diagram.ArrangementDiagram()
- picture.set_machines([self.machine("b", "Bee", "", ["edge"], chosen=True)], "Right Ctrl", "hold", False)
+ picture.set_machines([self.machine("b", "Bee", "", ["edge", "part"], chosen=True)], "Right Ctrl", "hold", False)
self.assertEqual(picture._unplaced, "")
+ self.assertEqual(diagram._drawn_side({"side": ""}, True), "right")
+ self.assertEqual(picture._marks[("edge", "b", "right")], 0.0)
+ self.assertEqual(picture._marks[("track", "b", "right")], 0.0)
+ self.assertEqual(picture._marks[("part", "b", "right", "middle")], 0.0)
+ picture.set_machines([self.machine("b", "Bee", "right", ["edge"], chosen=True)], "Right Ctrl", "hold", False)
self.assertEqual(picture._marks[("edge", "b", "right")], 1.0)
diff --git a/win_app/tests/test_peers_view.py b/win_app/tests/test_peers_view.py
index 249e630..7edbfcd 100644
--- a/win_app/tests/test_peers_view.py
+++ b/win_app/tests/test_peers_view.py
@@ -28,6 +28,10 @@ def state(peer=None, **link):
class DescribeTest(unittest.TestCase):
+ def test_a_machine_not_in_use_shows_its_own_status(self):
+ found = state(entry(in_use=False), up=True)
+ self.assertEqual((found.tone, found.word), ("amber", "NOT IN USE"))
+
def test_a_peer_whose_input_is_on_this_pc_is_driving_it(self):
found = state(up=True, driving=True)
self.assertEqual((found.word, found.tone), ("Driving this PC", "signal"))
diff --git a/win_app/tests/test_same_on_both.py b/win_app/tests/test_same_on_both.py
index f00105f..ecd2b39 100644
--- a/win_app/tests/test_same_on_both.py
+++ b/win_app/tests/test_same_on_both.py
@@ -141,9 +141,13 @@ class SameOnBothTest(unittest.TestCase):
def test_announcing_carries_a_chosen_arrangement_the_peers_it_may_send_to_and_the_settings(self):
settings = app_config.load_settings(self.path)
settings["peers"][0]["id"] = protocol.id_text(harness.B)
+ inactive = dict(settings["peers"][0], id=protocol.id_text(harness.C), token="inactive", in_use=False)
+ settings["peers"].append(inactive)
app_config.write_settings(self.path, settings)
self.peers = {harness.B: {"settings"}}
- self.assertEqual([m["type"] for m in self.window._announce(harness.B)], ["paired", "settings"])
+ messages = self.window._announce(harness.B)
+ self.assertEqual([m["type"] for m in messages], ["paired", "settings"])
+ self.assertEqual(messages[0]["data"]["ids"], [])
settings["peers"][0].update(side="left", side_set_at=500, side_by=self.window._config.machine_id)
app_config.write_settings(self.path, settings)
messages = self.window._announce(harness.B)
diff --git a/win_app/tests/test_settings_migration.py b/win_app/tests/test_settings_migration.py
index 898bd2c..9220d89 100644
--- a/win_app/tests/test_settings_migration.py
+++ b/win_app/tests/test_settings_migration.py
@@ -38,7 +38,7 @@ OWN_ID = b64(bytes([9]) * 16)
# What a migrated entry is, for the fixture: every field of section 1's table.
MIGRATED_PEER = {
"id": "", "name": "MacBook Pro", "platform": "macos", "host": "192.0.2.10", "port": 24820,
- "hw": "aa:bb:cc:dd:ee:ff", "send": True, "allow_drive": True, "side": "left", "side_set_at": 1790000000,
+ "hw": "aa:bb:cc:dd:ee:ff", "send": True, "allow_drive": True, "in_use": True, "side": "left", "side_set_at": 1790000000,
"paired_with": [], "paired_at": 0, "linked": False, "from_1_4": True,
}
@@ -95,6 +95,39 @@ class MigrationTests(Folder):
if key not in MOVED_OR_DROPPED and key != "port":
self.assertEqual(settings[key], value, key)
+ def test_peer_in_use_must_be_a_boolean(self):
+ settings = app_config.load_settings(self.path)
+ settings["peers"][0]["in_use"] = "yes"
+ self.put(settings)
+ with self.assertRaises(app_config.SettingsFileError):
+ app_config.load_settings(self.path)
+
+ def test_jump_key_must_be_a_recorded_chord_and_round_trips(self):
+ settings = app_config.load_settings(self.path)
+ settings["peers"][0]["jump_key"] = "ctrl+shift+2"
+ app_config.write_settings(self.path, settings)
+ self.assertEqual(app_config.load_settings(self.path)["peers"][0]["jump_key"], "ctrl+shift+2")
+ settings["peers"][0]["jump_key"] = "nonsense"
+ with self.assertRaises(app_config.SettingsFileError):
+ app_config.write_settings(self.path, settings)
+
+ def test_load_rejects_a_malformed_jump_key(self):
+ settings = app_config.load_settings(self.path)
+ settings["peers"][0]["jump_key"] = "ctrl"
+ self.put(settings)
+ with self.assertRaises(app_config.SettingsFileError):
+ app_config.load_settings(self.path)
+
+ def test_jump_key_clash_is_refused_without_saving_and_can_be_cleared(self):
+ settings = app_config.load_settings(self.path)
+ peer_id = settings["peers"][0]["id"]
+ app_config.set_jump_key(self.path, peer_id, "ctrl+shift+2", "alt_r")
+ with self.assertRaises(app_config.ConfigError):
+ app_config.set_jump_key(self.path, peer_id, "ctrl+alt+2", "alt_r")
+ self.assertEqual(app_config.load_settings(self.path)["peers"][0]["jump_key"], "ctrl+shift+2")
+ app_config.set_jump_key(self.path, peer_id, "", "alt_r")
+ self.assertEqual(app_config.load_settings(self.path)["peers"][0]["jump_key"], "")
+
def test_the_machine_id_is_sixteen_random_bytes_in_b64_and_never_zero(self):
ids = set()
for _ in range(3):
diff --git a/win_app/widgets.py b/win_app/widgets.py
index b5fd4dc..cd108a1 100644
--- a/win_app/widgets.py
+++ b/win_app/widgets.py
@@ -24,6 +24,7 @@ from PySide6.QtWidgets import (
import motion
import theme
import tokens
+from core import ways as core_ways
LEFT_CTRL_VK = 0xA2
# The smallest a Segmented cell or small button is drawn, so each is a fair target.
@@ -564,6 +565,101 @@ class InputRecorder(QPushButton):
return False
+class JumpKeyRecorder(QPushButton):
+ """Records a modifier chord and keeps its local spelling for one peer."""
+
+ def __init__(self, on_record, on_arm=None, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.on_record = on_record
+ self.on_arm = on_arm
+ self.value = ""
+ self.armed = False
+ self.setProperty("vernier", "keycap")
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.setFixedHeight(42)
+ row = QHBoxLayout(self)
+ row.setContentsMargins(12, 0, 12, 0)
+ row.setSpacing(10)
+ self.key = label("Choose a key combination", "keycap")
+ self.hint = label("Click, then press a key combination", "small")
+ self.key.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self.hint.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ row.addWidget(self.key, 1)
+ row.addWidget(self.hint, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
+ self.clicked.connect(self._toggle)
+ self._names = {"ctrl": "Win", "cmd": "Ctrl", "alt": "Alt", "shift": "Shift"}
+
+ 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"
+ self.setAccessibleName(f"Jump straight here key, {shown}")
+ if not self.armed:
+ self.key.setText(shown)
+
+ def cancel(self) -> None:
+ if not self.armed:
+ return
+ self.armed = False
+ QApplication.instance().removeEventFilter(self)
+ if self.on_arm is not None:
+ self.on_arm(False)
+ self.set_value(self.value)
+ set_role(self.key, "keycap")
+ self.hint.setText("Click, then press a key combination")
+ set_role(self, "keycap")
+
+ def _toggle(self) -> None:
+ if self.armed:
+ self.cancel()
+ return
+ self.armed = True
+ self.key.setText("Press a key combination…")
+ set_role(self.key, "keycap-live")
+ self.hint.setText("Click again to cancel")
+ set_role(self, "keycap-live")
+ QApplication.instance().installEventFilter(self)
+ if self.on_arm is not None:
+ self.on_arm(True)
+
+ def eventFilter(self, watched, event) -> bool:
+ if not self.armed:
+ return False
+ if event.type() == QEvent.Type.KeyPress:
+ modifiers = event.modifiers()
+ held = []
+ for flag, name in ((Qt.KeyboardModifier.ControlModifier, "cmd"),
+ (Qt.KeyboardModifier.AltModifier, "alt"),
+ (Qt.KeyboardModifier.ShiftModifier, "shift"),
+ (Qt.KeyboardModifier.MetaModifier, "ctrl")):
+ if modifiers & flag:
+ held.append(name)
+ key = event.text().lower()
+ if not key or len(key) != 1 or not key.isprintable() or key == " ":
+ value = event.key()
+ key = next((f"f{i}" for i in range(1, 25) if value == getattr(Qt.Key, f"Key_F{i}")), "")
+ names = {Qt.Key.Key_Backspace: "backspace", Qt.Key.Key_Delete: "delete", Qt.Key.Key_Left: "left",
+ Qt.Key.Key_Right: "right", Qt.Key.Key_Up: "up", Qt.Key.Key_Down: "down",
+ Qt.Key.Key_Home: "home", Qt.Key.Key_End: "end", Qt.Key.Key_PageUp: "page_up",
+ Qt.Key.Key_PageDown: "page_down", Qt.Key.Key_Insert: "insert", Qt.Key.Key_Tab: "tab",
+ Qt.Key.Key_Return: "enter", Qt.Key.Key_Enter: "enter", Qt.Key.Key_Escape: "esc",
+ Qt.Key.Key_Space: "space"}
+ key = key or names.get(value, "")
+ chord = core_ways.jump_chord(held, key)
+ if chord:
+ self.cancel()
+ self.set_value(chord)
+ self.on_record(chord)
+ return True
+ if event.type() == QEvent.Type.KeyRelease:
+ return True
+ if event.type() == QEvent.Type.MouseButtonPress:
+ inside = isinstance(watched, QWidget) and (watched is self or self.isAncestorOf(watched))
+ self.cancel()
+ return inside
+ return False
+
+
class PageButton(QPushButton):
"""One entry in the sidebar's page list, with an optional tone dot for a page that
needs attention."""