Skip to content

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

Beamer 1.5.12

Toby Kalkman968e5b87cdff
diff --git a/README.md b/README.md
index e06356c..e2e2d02 100644
--- a/README.md
+++ b/README.md
@@ -71,9 +71,10 @@ for arm64, follow [the Linux instructions](docs/flatpak-build.md).
two Grant buttons on the Permissions page (Accessibility, then Input Monitoring), then Relaunch
Beamer on the same page: macOS only passes keys to an app started after the grant, so until then
the pointer crosses but the keyboard does not. On Windows,
- run the installer. It is not code-signed, because a certificate costs money and Beamer is free,
- so Windows says "Windows protected your PC" the first time: choose More info, then Run anyway.
- Beamer on Windows runs as administrator, so expect one UAC prompt when you open it. On Linux,
+ run the installer. It is signed with a Certum code-signing certificate, but Windows may still
+ say "Windows protected your PC" the first time: choose More info, then Run anyway. The installer
+ asks for administrator permission once, for Beamer's firewall rules; Beamer itself runs with
+ your normal rights. On Linux,
follow [Install on Linux](#install-on-linux) to install Beamer from the Kalkman Code repository.
2. **Pair them.** On one machine, choose Pair a machine to show a six-digit code. On the other,
choose that machine from the list and enter the code. It lasts a minute and works once. If it
@@ -165,7 +166,7 @@ About Beamer.
| Crossing | A drawing of the arrangement, the ways in for each machine (edge, part of the edge, corner, notch), the full-screen hold, resistance, the shortcut and jump keys | A drawing of the arrangement, the ways in for each machine (edge, part of the edge, corner), the full-screen hold, resistance, the shortcut and jump keys |
| Keyboard | Key mapping, what stays on this Mac, each peer's pointer and scroll speed | Key mapping, including a Mac layout, what stays on this PC, each peer's pointer and scroll speed |
| Design | Crossing and switch styles, colours, Size and Length, landing animation, Match design, notch and trackpad controls, window appearance (System, Light or Dark) | Crossing and switch styles, colours, Size and Length, landing animation, Match design, window appearance (System, Light or Dark) |
-| Connection | Hide addresses, a peer's address, port and pairing details | Whether Windows Firewall lets a peer in, with a one-button fix; hide addresses; this PC's address, port and pairing details |
+| Connection | Hide addresses, a peer's address, port and pairing details | Whether Windows Firewall lets a peer in and what to do if not; hide addresses; this PC's address, port and pairing details |
Each machine sets its own zones and the machine beyond each one. These settings stay local even
when Same on all machines is on.
@@ -376,18 +377,17 @@ The installer puts Beamer in `%LOCALAPPDATA%\Beamer` for the current user with a
shortcut. Quit Beamer from the tray before installing a newer version over it; only one instance
runs at a time.
-Beamer runs elevated (its exe carries a `requireAdministrator` manifest), because Windows silently
-drops input from a non-elevated app aimed at an elevated window such as an admin PowerShell. Start
-Beamer when you sign in, on Overview, writes and removes an elevated `Beamer` logon task; nothing
-else touches autostart.
+Beamer launches with normal user permissions and no administrator prompt. It controls normal
+windows; administrator windows and Windows permission prompts need local input. Overview's
+start-at-sign-in switch uses the same normal permissions. Upgrading lowers an existing elevated
+startup task while preserving whether startup was enabled.
-Beamer needs two inbound rules on Private networks: TCP 24820 for input and UDP 24821 for pairing,
-both below the range Windows and macOS hand out for themselves. The app adds them on its first
-elevated start. Connection says in one sentence whether the Mac can get in and offers one
-button for whichever of three things usually stops it: the rule is missing (it adds it), Cancel was
-pressed on Windows' own "allow this app" prompt, which writes a block rule that beats any allow rule
-(it removes the block and adds the rule), or the network is classed as public (it marks the network
-private rather than opening the port on every public network).
+The installer requests administrator permission once for maintenance. It sets private-network
+rules for TCP 24820 input and UDP/TCP 24821 pairing, and attempts recovery of a stuck GameInput
+service. The app only checks firewall state: Connection explains when to rerun the installer or
+mark a trusted network Private in Windows Settings. Custom input ports need a matching rule
+configured by an administrator. If a SYSTEM or administrator window blocks input later, click a
+normal window locally to continue.
**The lock screen.** No elevation lets an app type there: it is the Winlogon secure desktop, which
admits only SYSTEM. On a PC with the author's separate unlock credential provider installed (not
@@ -437,10 +437,9 @@ On the Mac, double-click `mac_app/Install-Beamer-Mac.command`. It builds a self-
installs it at `/Applications/Beamer.app`, and leaves it closed so the permission prompts do not
appear unexpectedly.
-On Windows, run `win_app\Install-Beamer.ps1` from an admin PowerShell. It builds and installs
-`%LOCALAPPDATA%\Beamer\Beamer.exe`, adds a Start menu shortcut and the two firewall rules. From a
-non-admin PowerShell it still installs but skips the rules, which the app adds on its first
-elevated start.
+On Windows, run `win_app\Install-Beamer.ps1` from the signed-in user's PowerShell. It builds and
+installs `%LOCALAPPDATA%\Beamer\Beamer.exe`, adds a Start menu shortcut, then asks once for
+administrator permission to add the two firewall rules.
Pairing is the easy path, not the only one: each Connection page still takes an address, port and
shared token typed by hand, and they must match on both machines.
@@ -504,7 +503,8 @@ On Windows, from `win_app`:
```
It runs the tests, builds `Beamer.exe` and compiles `Beamer-Setup.iss` with Inno Setup 6 into
-`Beamer-Setup-<version>.exe`. The installer adds no firewall rules and leaves autostart off.
+`Beamer-Setup-<version>.exe`. The installer adds firewall rules; its optional start-at-sign-in
+task is off by default.
</details>
diff --git a/VERSION b/VERSION
index df80819..41336a1 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.5.11
+1.5.12
diff --git a/core/effects.py b/core/effects.py
index e99a802..46f84fd 100644
--- a/core/effects.py
+++ b/core/effects.py
@@ -763,6 +763,22 @@ def draw(effect_obj, kind, s, origin=(0.0, 0.0), scale=1.0):
pen.translate(*origin)
if scale != 1.0:
pen.scale(scale, scale)
+ if effect_obj.id not in ("glow", "beam"):
+ k = effect_depth_scale(s)
+ pen.scale(k, k)
+ # Inverse-map the real geometry so authored distances grow while display edges,
+ # the crossing point and the hardware notch stay in their original positions.
+ s = SimpleNamespace(**vars(s))
+ for field, dimensions in (("screen", ("w", "h")), ("point", ("x", "y")),
+ ("region", ("x", "y", "w", "h")),
+ ("notch", ("x", "y", "w", "h", "r"))):
+ value = getattr(s, field, None)
+ if value is not None:
+ values = vars(value).copy()
+ for dimension in dimensions:
+ if dimension in values:
+ values[dimension] /= k
+ setattr(s, field, SimpleNamespace(**values))
(effect_obj.depart if kind == "depart" else effect_obj.arrive)(pen, s)
if kind == "depart" and since is None and s.pressure < PUSH_FADE:
# Several designs' reduced-motion pushes draw at a floor opacity however light the push, so
@@ -1176,9 +1192,10 @@ def still_view(effect, place, effect_size="medium", pace=1.0, effect_size_fracti
scene points, 2:1, fitted round the marks of its resting frame: an effect shown at its real size
against the whole pointer journey filled a hundredth of its tile. The pointer glides in from
outside it. Idle, reduced motion and the hover loop share the camera. It is fitted at Normal, as
- the still is drawn, so a Length step neither moves it nor builds a scene."""
+ the still is drawn, and at Medium Size so changing Size never zooms away its growth."""
still_time(effect, place, effect_size, pace, effect_size_fraction)
- return _still_view(_still_key(effect), place, effect_size, 1.0, effect_size_fraction)
+ # Size is a visual comparison: fitting anew to its marks would zoom out as they grow.
+ return _still_view(_still_key(effect), place, "medium", 1.0, None)
def still_time(effect, place, effect_size="medium", pace=1.0, effect_size_fraction=None):
@@ -1217,9 +1234,8 @@ _SIZE_PRESETS = ("small", "medium", "large")
MIN_EFFECT_PACE = 0.25
MAX_EFFECT_PACE = 2.5
MIN_EFFECT_SIZE_FRACTION = 0.02
-MAX_EFFECT_SIZE_FRACTION = 0.08
+MAX_EFFECT_SIZE_FRACTION = 0.25
_MIN_EDGE_DEPTH = 24.0
-_MAX_EDGE_DEPTH = 144.0
_EFFECT_REFERENCE_DEPTH = 36.0
@@ -1278,11 +1294,11 @@ def edge_depth(screen_w, screen_h, size="medium", size_fraction=None):
"""The edge band's depth in screen units, scaled to the shorter side of its display."""
fraction = (float(size_fraction) if valid_effect_size_fraction(size_fraction)
else _SIZE_FRACTIONS.get(size, _SIZE_FRACTIONS["medium"]))
- return max(_MIN_EDGE_DEPTH, min(_MAX_EDGE_DEPTH, min(float(screen_w), float(screen_h)) * fraction))
+ return max(_MIN_EDGE_DEPTH, min(float(screen_w), float(screen_h)) * fraction)
def effect_depth_scale(s):
- """Scale material depths from their 1200 by 800 reference canvas to this screen and Size."""
+ """Scale authored distances from their 1200 by 800 reference canvas to this screen and Size."""
return edge_depth(s.screen.w, s.screen.h, getattr(s, "effect_size", "medium"),
getattr(s, "effect_size_fraction", None)) / _EFFECT_REFERENCE_DEPTH
diff --git a/core/fx_folio.py b/core/fx_folio.py
index 505421d..cd66519 100644
--- a/core/fx_folio.py
+++ b/core/fx_folio.py
@@ -3,7 +3,7 @@
import math
from core.i18n import N_
-from .effects import Effect, clamp, ease_out, effect_depth_scale, lerp
+from .effects import Effect, clamp, ease_out, lerp
from .fx_material import stroke, surface
@@ -15,15 +15,14 @@ def _sheet(pen, s, level, departing):
pushing = departing and t is None
p = clamp(s.pressure) if pushing else 1.0
u = 0.0 if pushing else clamp(t / duration)
- size = effect_depth_scale(s)
alpha = clamp(p * 5) if pushing else 1 - clamp((u - 0.58) / 0.42)
motion = 0.65 if s.reduced else p
at = surface(pen, s, departing)
span = (48, 90, 144)[level]
count = (2, 6, 12)[level]
- depth = (12, 28, 46)[level] * size
- base = 3 * size
- wall = 2 * size
+ depth = (12, 28, 46)[level]
+ base = 3
+ wall = 2
gap = 0.0
if not pushing and not s.reduced:
if departing:
diff --git a/core/fx_light.py b/core/fx_light.py
index da54adb..0079532 100644
--- a/core/fx_light.py
+++ b/core/fx_light.py
@@ -2,7 +2,7 @@
import math
-from .effects import clamp, ease_out, effect_depth_scale, parse_colour
+from .effects import clamp, ease_out, parse_colour
from .fx_material import stroke, surface
@@ -12,7 +12,6 @@ def _aperture(pen, s, departing):
return
pushing = departing and t is None
p = clamp(s.pressure) if pushing else 1.0
- size = effect_depth_scale(s)
u = 0.0 if pushing else clamp(t / 0.62)
alpha = clamp(p * 4) if pushing else 1 - u
opening = 0.65 if s.reduced else p
@@ -20,14 +19,14 @@ def _aperture(pen, s, departing):
opening = (1 - ease_out(u)) if not departing else 1 + math.sin(math.pi * u) * 0.8
at = surface(pen, s, departing)
span = 38 + 52 * opening
- depth = (3 + 13 * opening) * size
+ depth = (3 + 13 * opening)
pen.beginPath()
# A fixed path budget also carries the lens cleanly round corners and the notch.
for half in (0, 1):
for j in range(17):
x = (-span + 2 * span * j / 16) * (1 if half == 0 else -1)
envelope = max(0, 1 - (x / span) ** 2)
- y = 3 * size + envelope * depth * (1 if half == 0 else 0.18)
+ y = 3 + envelope * depth * (1 if half == 0 else 0.18)
(pen.moveTo if half == 0 and j == 0 else pen.lineTo)(*at(x, y))
pen.closePath()
a, b = at(-span, 0), at(span, 0)
diff --git a/core/fx_selvedge.py b/core/fx_selvedge.py
index 787ce1d..fe5de97 100644
--- a/core/fx_selvedge.py
+++ b/core/fx_selvedge.py
@@ -3,7 +3,7 @@
import math
from core.i18n import N_
-from .effects import Effect, clamp, ease_out, effect_depth_scale
+from .effects import Effect, clamp, ease_out
from .fx_material import stroke, surface
@@ -15,7 +15,6 @@ def _cloth(pen, s, level, departing):
pushing = departing and t is None
p = clamp(s.pressure) if pushing else 1.0
u = 0.0 if pushing else clamp(t / duration)
- size = effect_depth_scale(s)
alpha = clamp(p * 5) if pushing else 1 - clamp((u - 0.55) / 0.45)
tension = 0.55 if s.reduced else p
opening = 0.0
@@ -23,10 +22,10 @@ def _cloth(pen, s, level, departing):
if s.reduced:
alpha = 1 - u
elif departing:
- opening = math.sin(math.pi * ease_out(u)) * 29 * size
+ opening = math.sin(math.pi * ease_out(u)) * 29
tension = 1 - ease_out(u)
else:
- opening = 24 * size * (1 - ease_out(clamp(u / 0.65)))
+ opening = 24 * (1 - ease_out(clamp(u / 0.65)))
tension = 0.65 * (1 - ease_out(u))
at = surface(pen, s, departing)
span = (48, 88, 132)[level]
@@ -39,8 +38,8 @@ def _cloth(pen, s, level, departing):
for i in range(-8 if level == 2 else -5, 9 if level == 2 else 6):
x = i * 14
envelope = max(0, 1 - abs(x) / span)
- y = (5 + (rows - 1) * 4 + 13 * tension * envelope) * size
- pen.moveTo(*at(x, 2 * size))
+ y = (5 + (rows - 1) * 4 + 13 * tension * envelope)
+ pen.moveTo(*at(x, 2))
pen.lineTo(*at(x + math.copysign(opening * envelope, x or 1), y))
stroke(pen, palette[1 % len(palette)], 1.0, alpha * 0.62, s.dark)
for pigment, colour in enumerate(palette):
@@ -50,15 +49,15 @@ def _cloth(pen, s, level, departing):
continue
def yarn(x):
envelope = max(0, 1 - (x / span) ** 2)
- lift = (10 + level * 5) * tension * envelope * size
+ lift = (10 + level * 5) * tension * envelope
split = opening * envelope * (1 if row % 2 else -0.12)
- return max(2 * size, 7 * size + row * 4 * size + lift + split)
+ return max(2, 7 + row * 4 + lift + split)
pen.moveTo(*at(-span, yarn(-span)))
step = 2 * span / samples
for j in range(samples):
a, b = -span + j * step, -span + (j + 1) * step
# One cubic per half weave replaces a polyline's dense sampled geometry.
- weave = (3 if level < 2 else 7) * (1 - 0.65 * tension) * size * (-1 if (j + row) % 2 else 1)
+ weave = (3 if level < 2 else 7) * (1 - 0.65 * tension) * (-1 if (j + row) % 2 else 1)
c1, c2 = a + step / 3, b - step / 3
pen.bezierCurveTo(*at(c1, max(2, yarn(c1) + weave)),
*at(c2, max(2, yarn(c2) + weave)), *at(b, yarn(b)))
@@ -69,9 +68,9 @@ def _cloth(pen, s, level, departing):
for i in range(-4, 5):
x = i * 14
envelope = max(0, 1 - (x / span) ** 2)
- y = (9 + (10 + level * 5) * tension * envelope) * size + opening * envelope
- pen.moveTo(*at(x - 2, y - size))
- pen.lineTo(*at(x + 2, y + size))
+ y = (9 + (10 + level * 5) * tension * envelope) + opening * envelope
+ pen.moveTo(*at(x - 2, y - 1))
+ pen.lineTo(*at(x + 2, y + 1))
stroke(pen, palette[-1], 2.1, alpha * 0.85, s.dark)
diff --git a/core/tests/crossing_harness.py b/core/tests/crossing_harness.py
index bedb1cc..85c0a56 100644
--- a/core/tests/crossing_harness.py
+++ b/core/tests/crossing_harness.py
@@ -119,6 +119,8 @@ class Hand:
self.lock = threading.RLock()
self.sent = []
self.moved = []
+ self._input_sent = {}
+ self._input_acked = {}
self._closed = threading.Event()
self._keep_alive_thread = threading.Thread(target=self._keep_alive, name="hand-pings", daemon=True)
self._keep_alive_thread.start()
@@ -149,6 +151,8 @@ class Hand:
with self.lock:
link = self.links.pop(text(other.own), None)
if link is not None:
+ self._input_sent.pop(link, None)
+ self._input_acked.pop(link, None)
link.close()
self.carry_out(self.owner.link_down(text(other.own)))
@@ -169,7 +173,7 @@ class Hand:
self.sent.append((action.peer, dict(message["data"])))
try:
if message["type"] in protocol.INPUT_TYPES:
- link.input(message)
+ self._input_sent[link] = link.input(message)
else:
link.send(message)
except OSError:
@@ -208,7 +212,9 @@ class Hand:
while not link.inbox.empty():
message = link.inbox.get_nowait()
kind, data = message.get("type"), message.get("data") or {}
- if kind == protocol.MSG_SWITCH:
+ if kind == protocol.MSG_ACK:
+ self._input_acked[link] = max(self._input_acked.get(link, 0), data["seq"])
+ elif kind == protocol.MSG_SWITCH:
self.carry_out(self.owner.switch(peer, data))
elif kind == protocol.MSG_ACCEPT:
self.carry_out(self.owner.accept(peer, data))
@@ -228,6 +234,13 @@ class Hand:
self.pump()
return bool(predicate())
+ def input_settled(self):
+ # A zone's SWITCH precedes its input ACK on the same link. This fences the zone decision,
+ # not receiver callbacks, and includes input generated while pumping a hand-over.
+ with self.lock:
+ return self.owner._wait is None and all(
+ self._input_acked.get(link, 0) >= seq for link, seq in self._input_sent.items())
+
def go(self, peer, edge=None, offset=None, display=None, side=None):
with self.lock:
self.carry_out(self.owner.go(peer, edge, offset, display=display, side=side))
@@ -426,17 +439,17 @@ class Net:
for _ in range(PUSHES):
holder.hand.move(*delta)
here.screen.cursor = point
- # Every move is acked or acted on before the result is read.
- holder.hand.until(lambda: False, timeout=0.15)
- holder.hand.until(lambda: getattr(holder.hand.owner, "_wait", None) is None, timeout=0.5)
- self.settle(0.5)
+ self.test.assertTrue(holder.hand.until(holder.hand.input_settled),
+ "input ACK frontier or ownership did not complete after push")
+ self.test.assertTrue(self.settle(), "the desks did not settle after push")
return self.at(holder)
def shortcut(self, holder, other=None):
"""`holder`'s shortcut, menu or Send button: to `other`, or home with None."""
holder.hand.go(None if other is None or other is holder else other.id)
- holder.hand.until(lambda: getattr(holder.hand.owner, "_wait", None) is None, timeout=0.5)
- self.settle(0.5)
+ self.test.assertTrue(holder.hand.until(holder.hand.input_settled),
+ "input ACK frontier or ownership did not complete after shortcut")
+ self.test.assertTrue(self.settle(), "the desks did not settle after shortcut")
return self.at(holder)
def driven_by(self, desk):
diff --git a/core/tests/effect_size_probe.py b/core/tests/effect_size_probe.py
new file mode 100644
index 0000000..c13db80
--- /dev/null
+++ b/core/tests/effect_size_probe.py
@@ -0,0 +1,86 @@
+"""Geometry and optional native raster measurements; never opens a window."""
+
+import argparse
+import json
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+from core import effects
+
+
+STYLES = ("glow", "beam") + effects.EFFECT_IDS + ("locator",)
+
+
+def pen_for(style, depth, kind="depart", width=1920, height=1200):
+ fx = effects.LOCATOR if style == "locator" else effects.preview_effect(style)
+ return effects.draw(fx, kind, effects.state(
+ width, height, "mac", "switch" if style == "locator" else "edge",
+ ["#58c8f0", "#a673ec", "#f05e8a"], effect_size_fraction=depth / min(width, height),
+ region=SimpleNamespace(kind="edge", edge="right", x=width - 1, y=0, w=1, h=height),
+ point=effects.point(width - 1, height / 2), edge="right", along=0.5,
+ pressure=1.0, tick=None, since=0.18 if kind == "arrive" else None))
+
+
+def path_box(pen):
+ points = [segment[i:i + 2] for op in pen.ops for segment in op[1]
+ for i in range(1, len(segment) - 1, 2)]
+ return (min(x for x, y in points), min(y for x, y in points),
+ max(x for x, y in points), max(y for x, y in points))
+
+
+def raster_box(pen, ratio, width=1920, height=1200):
+ from core.tests.render_effect_parity import Bitmap
+ width, height = round(width * ratio), round(height * ratio)
+ bitmap = Bitmap(width, height, scale=ratio, transparent=True)
+ try:
+ bitmap.draw([pen])
+ alpha = bitmap.raw()[3::4].translate(bytes(0 if i < 8 else 1 for i in range(256)))
+ finally:
+ bitmap.close()
+ rows = [(y, alpha[y * width:(y + 1) * width]) for y in range(height)]
+ rows = [(y, row) for y, row in rows if row.strip(b"\0")]
+ return (min(width - len(row.lstrip(b"\0")) for y, row in rows), rows[0][0],
+ max(len(row.rstrip(b"\0")) for y, row in rows), rows[-1][0] + 1)
+
+
+class NativeSizeRasterTests(unittest.TestCase):
+ def test_native_marks_grow_at_one_and_two_device_pixels_per_point(self):
+ for ratio in (1, 2):
+ for style in STYLES:
+ kind = "arrive" if style == "locator" else "depart"
+ with self.subTest(ratio=ratio, style=style):
+ small = raster_box(pen_for(style, 24, kind), ratio)
+ large = raster_box(pen_for(style, 90, kind), ratio)
+ self.assertGreater((1920 * ratio - large[0]) /
+ (1920 * ratio - small[0]), 2.8)
+
+
+def measure(raster=False):
+ rows = []
+ for style in STYLES:
+ kind = "arrive" if style == "locator" else "depart"
+ for depth in (24, 90, 96, 300):
+ pen = pen_for(style, depth, kind)
+ box = path_box(pen)
+ for ratio in (1, 2):
+ row = dict(style=style, kind=kind, selected_points=depth, device_ratio=ratio,
+ selection_valid=effects.valid_effect_size_fraction(depth / 1200),
+ path_control_box_pixels=[round(v * ratio, 3) for v in box],
+ path_depth_pixels=round((1920 - box[0]) * ratio, 3),
+ path_height_pixels=round((box[3] - box[1]) * ratio, 3))
+ if raster:
+ box_px = raster_box(pen, ratio)
+ row.update(alpha_box_pixels=box_px,
+ alpha_depth_pixels=1920 * ratio - box_px[0],
+ alpha_height_pixels=box_px[3] - box_px[1])
+ rows.append(row)
+ return rows
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("output", type=Path)
+ parser.add_argument("--raster", action="store_true")
+ args = parser.parse_args()
+ args.output.write_text(json.dumps(measure(args.raster), indent=2) + "\n", encoding="utf-8")
diff --git a/core/tests/test_address_choice_commit.py b/core/tests/test_address_choice_commit.py
index 8595964..9c70109 100644
--- a/core/tests/test_address_choice_commit.py
+++ b/core/tests/test_address_choice_commit.py
@@ -1,6 +1,8 @@
"""Explicit address commits use the pin signal, including an unchanged address."""
from types import SimpleNamespace
+import copy
+import threading
import unittest
from unittest import mock
@@ -8,6 +10,64 @@ from core.tests.app_methods import load_methods
class AddressCommitTests(unittest.TestCase):
+ def test_qt_pin_control_saves_only_the_chosen_machine(self):
+ saved = {"peers": [{"token": "first", "host": "192.0.2.10", "host_pinned": True},
+ {"token": "second", "host": "192.0.2.11", "host_pinned": True}]}
+
+ def write(_path, settings):
+ saved.update(copy.deepcopy(settings))
+
+ config = SimpleNamespace(SETTINGS_LOCK=threading.RLock(),
+ load_settings=lambda _: copy.deepcopy(saved), write_settings=write)
+ methods = load_methods("win_app/kvm_bridge_win.py", "WindowsApplication",
+ ("_edit_peer", "_set_peer_pin"),
+ {"app_config": config, "ConfigError": ValueError})
+ window = methods()
+ window.config_path = "synthetic"
+ window._after_peers_edit = lambda: None
+ window._set_peer_pin("first", False)
+ self.assertIs(saved["peers"][0]["host_pinned"], False)
+ self.assertIs(saved["peers"][1]["host_pinned"], True)
+ window._set_peer_pin("first", True)
+ self.assertIs(saved["peers"][0]["host_pinned"], True)
+ self.assertEqual(saved["peers"][0]["host"], "192.0.2.10")
+
+ def test_releasing_a_pin_allows_discovery_and_pinning_stops_drift(self):
+ from core.tests.test_link import FakeClock, Side
+
+ side = Side()
+ side.peer().update(host="192.0.2.10", host_pinned=True)
+ methods = load_methods("mac_app/settings_store.py", "SettingsStore", ("set_peer",),
+ {"copy": copy, "SettingsError": ValueError})
+ store = methods()
+ store.lock = threading.RLock()
+ store.current = side.settings.load
+
+ def save(settings):
+ side.settings.save(settings)
+ return side.settings.load()
+
+ store.save_settings = save
+ token = side.peer()["token"]
+ store.set_peer(token, host_pinned=False)
+ clock = FakeClock()
+ link = side.link(clock=clock)
+ clock.now += 11
+ link.follow([{"name": "Far", "address": "198.51.100.10"}])
+ self.assertEqual(link._try_host, "198.51.100.10")
+ store.set_peer(token, host_pinned=True)
+ link.follow([{"name": "Far", "address": "203.0.113.10"}])
+ tried = []
+
+ def offline(address, timeout=None):
+ tried.append(address)
+ link._stop.set()
+ raise OSError("synthetic offline peer")
+
+ link._factory = offline
+ link._run()
+ self.assertEqual(tried, [("192.0.2.10", 24820)])
+
def test_mac_connection_commit_marks_the_same_address_as_explicit(self):
cfg = SimpleNamespace(host="192.0.2.10")
store = mock.Mock()
diff --git a/core/tests/test_arrival_grace.py b/core/tests/test_arrival_grace.py
index 3bd3838..c22b9af 100644
--- a/core/tests/test_arrival_grace.py
+++ b/core/tests/test_arrival_grace.py
@@ -123,6 +123,29 @@ class ReturnEdgeArrivalGrace(unittest.TestCase):
self.assertEqual(return_edge.arrival_position(monitors, "left", 0.0), (0, 0))
self.assertEqual(return_edge.arrival_position([monitors[0]], "left", 0.0), (0, 10))
+ def test_focus_display_and_side_land_on_the_mapped_display_beside_a_negative_x_display(self):
+ main = return_edge.Rect(0, 0, 1920, 1080)
+ laptop = return_edge.Rect(-1440, -900, 1440, 900)
+ mapped = {"main": main, "laptop": laptop}
+ link = SimpleNamespace(peer_id=b"owner-peer-id!!!", name="Owner")
+ positions = []
+ desktop = SimpleNamespace(
+ monitors=lambda: [main, laptop], display_map=lambda: mapped,
+ set_cursor_position_with_callback=lambda x, y, on_placed, *, place_if_current:
+ positions.append((x, y)) or place_if_current(on_placed),
+ )
+ responder = receiver.LinkResponder.__new__(receiver.LinkResponder)
+ responder._lock = threading.RLock()
+ responder._owner, responder._visit = link, 1
+ responder._arriving_visit, responder._armed = 1, []
+ responder._callbacks = {"arrival": None}
+
+ with mock.patch.object(receiver.LinkResponder, "_desktop_module", return_value=desktop), \
+ mock.patch.object(receiver.LinkResponder, "_begin_unlock"):
+ responder._land(link, {"edge": "left", "offset": 0.5, "display": "main", "side": "left"}, 1)
+
+ self.assertEqual(positions, [(0, 540)])
+
def test_take_starts_grace_only_for_the_zone_back_to_its_owner(self):
self.assertEqual(self._take({"stay": True}), (return_edge.HOLD, return_edge.CROSS))
diff --git a/core/tests/test_crossing_input_fence.py b/core/tests/test_crossing_input_fence.py
new file mode 100644
index 0000000..574e1c9
--- /dev/null
+++ b/core/tests/test_crossing_input_fence.py
@@ -0,0 +1,80 @@
+"""Real loopback input completion and explicit harness timeout outcomes."""
+
+import json
+import threading
+import unittest
+from unittest import mock
+
+from core import protocol, receiver
+from core.tests.test_crossing_e2e import Pair
+
+
+class RealResponderInputFence(Pair):
+ def test_shortcut_does_not_return_a_desk_after_ownership_wait_timeout(self):
+ with mock.patch.object(self.mac.hand, "go"), mock.patch.object(self.mac.hand, "until", return_value=False):
+ with self.assertRaisesRegex(AssertionError, "ownership.*complete"):
+ self.net.shortcut(self.mac)
+
+ def test_shortcut_does_not_return_a_desk_before_settings_settle(self):
+ with mock.patch.object(self.mac.hand, "go"), mock.patch.object(self.mac.hand, "until", return_value=True):
+ with mock.patch.object(self.net, "settle", return_value=False):
+ with self.assertRaisesRegex(AssertionError, "settle"):
+ self.net.shortcut(self.mac)
+
+ def test_visiting_push_waits_for_real_receiver_input_before_returning(self):
+ self.assertTrue(self.place(self.mac, self.pc, "right"))
+ self.settled()
+ self.assertIs(self.net.shortcut(self.pc, self.mac), self.mac)
+ self.assertTrue(self.pc.hand.until(
+ lambda: self.mac.machine.responder.owner == self.pc.own, timeout=0.5))
+
+ entered, release, processed, finished = (threading.Event() for _ in range(4))
+ answers, errors, gate_timeouts = [], [], []
+ actual = receiver.LinkResponder._on_input
+ target = self.mac.machine.responder
+
+ def gated(server, link, message):
+ if server is target and message.get("type") == protocol.MSG_MOUSEMOVE:
+ entered.set()
+ if not release.wait(2.0):
+ gate_timeouts.append(True)
+ result = actual(server, link, message)
+ processed.set()
+ return result
+ return actual(server, link, message)
+
+ def push():
+ try:
+ answers.append(self.net.push(self.pc, "right", 1 / 6))
+ except BaseException as error:
+ errors.append(error)
+ finally:
+ finished.set()
+
+ with mock.patch.object(receiver.LinkResponder, "_on_input", gated):
+ worker = threading.Thread(target=push, name="real-input-fence-push", daemon=True)
+ worker.start()
+ try:
+ self.assertTrue(entered.wait(1.0), "the real receiver never entered the gated input")
+ returned_before_release = finished.wait(0.65)
+ print("FENCE_BEFORE_RELEASE " + json.dumps({
+ "returned": returned_before_release, "processed": processed.is_set(),
+ "errors": [{"type": type(error).__name__, "message": str(error)} for error in errors],
+ "answers": len(answers)}), flush=True)
+ self.assertFalse(returned_before_release,
+ "Net._push exhausted its explicit deadline before the gated real input was released")
+ self.assertFalse(processed.is_set(), "the closed receiver gate did not hold")
+ finally:
+ release.set()
+ worker.join(2.0)
+ self.assertFalse(worker.is_alive(), "the push worker did not finish after receiver release")
+ self.assertFalse(gate_timeouts, "the fixture gate reached its emergency release bound")
+ self.assertTrue(processed.is_set(), "the real receiver did not process the released input")
+ self.assertEqual(errors, [], "the push raised instead of completing its real input")
+ self.assertEqual(len(answers), 1)
+ self.assertIs(answers[0], self.pc)
+ self.assertIs(self.net.at(self.pc), self.pc)
+
+
+if __name__ == "__main__":
+ unittest.main(defaultTest="RealResponderInputFence", verbosity=2)
diff --git a/core/tests/test_effect_size.py b/core/tests/test_effect_size.py
index 20a558e..895fb76 100644
--- a/core/tests/test_effect_size.py
+++ b/core/tests/test_effect_size.py
@@ -17,9 +17,9 @@ class EdgeDepthTests(unittest.TestCase):
self.assertAlmostEqual(effects.edge_depth(1512, 982, size), laptop)
self.assertAlmostEqual(effects.edge_depth(3840, 2160, size), television)
- def test_small_displays_keep_a_usable_floor_and_large_displays_a_ceiling(self):
+ def test_small_displays_keep_a_usable_floor_and_large_displays_keep_the_fraction(self):
self.assertEqual(effects.edge_depth(320, 240, "small"), 24.0)
- self.assertEqual(effects.edge_depth(16000, 9000, "large"), 144.0)
+ self.assertEqual(effects.edge_depth(16000, 9000, "large"), 540.0)
def test_glow_and_beam_draw_the_selected_depth(self):
expected = {"small": 29.46, "medium": 44.19, "large": 58.92}
diff --git a/core/tests/test_effect_size_scaling.py b/core/tests/test_effect_size_scaling.py
new file mode 100644
index 0000000..3e6c773
--- /dev/null
+++ b/core/tests/test_effect_size_scaling.py
@@ -0,0 +1,58 @@
+"""Size must change the marks, including styles that never read the setting themselves."""
+
+import unittest
+from types import SimpleNamespace
+
+from core import effects
+
+
+def frame(style, depth, kind="depart", reduced=False, width=1920, height=1200):
+ return effects.draw(effects.preview_effect(style), kind, effects.state(
+ width, height, "windows", "edge", ["#58c8f0", "#a673ec", "#f05e8a"],
+ effect_size_fraction=depth / min(width, height), reduced=reduced,
+ region=SimpleNamespace(kind="edge", edge="right", x=width - 1, y=0, w=1, h=height),
+ point=effects.point(width - 1, height / 2), edge="right", along=0.5,
+ pressure=1.0, tick=None, since=None if kind == "depart" else 0.18))
+
+
+class SizeScalingTests(unittest.TestCase):
+ def test_preview_camera_does_not_zoom_out_when_size_grows(self):
+ for style in effects.EFFECT_IDS:
+ for place in ("edge", "corner", "notch", "switch"):
+ with self.subTest(style=style, place=place):
+ self.assertEqual(effects.still_view(style, place, effect_size_fraction=0.02),
+ effects.still_view(style, place, effect_size_fraction=0.075))
+
+ def test_every_style_changes_its_drawn_depth_with_size(self):
+ for style in ("glow", "beam") + effects.EFFECT_IDS:
+ for kind in ("depart", "arrive"):
+ if style in ("glow", "beam") and kind == "arrive":
+ continue
+ for reduced in (False, True):
+ with self.subTest(style=style, kind=kind, reduced=reduced):
+ small = frame(style, 24, kind, reduced)
+ large = frame(style, 90, kind, reduced)
+ self.assertIsNotNone(small)
+ self.assertIsNotNone(large)
+ small_depth = 1920 - small.bounds[0]
+ large_depth = 1920 - large.bounds[0]
+ self.assertGreater(large_depth / small_depth, 2.8)
+
+ def test_large_displays_can_use_a_quarter_of_the_shorter_side(self):
+ for width, height, expected in ((3840, 2160, 540), (7680, 4320, 1080),
+ (3840, 2160, 540)):
+ with self.subTest(width=width, height=height):
+ self.assertTrue(effects.valid_effect_size_fraction(0.25))
+ self.assertEqual(effects.edge_depth(width, height, size_fraction=0.25), expected)
+
+ def test_drawing_does_not_change_the_callers_geometry(self):
+ state = effects.state(1920, 1200, "mac", "edge", ["#ffffff"],
+ effect_size_fraction=0.075, point=effects.point(1919, 600),
+ region=SimpleNamespace(kind="edge", edge="right", x=1919, y=0, w=1, h=1200),
+ pressure=1, tick=None, since=None, along=0.5)
+ effects.draw(effects.effect("skin"), "depart", state)
+ self.assertEqual((state.screen.w, state.point.x, state.region.h), (1920, 1919, 1200))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/tests/test_firewall_contract.py b/core/tests/test_firewall_contract.py
new file mode 100644
index 0000000..cb8321c
--- /dev/null
+++ b/core/tests/test_firewall_contract.py
@@ -0,0 +1,28 @@
+"""The shared shell accepts the Linux firewall stand-in's complete status contract."""
+
+from types import SimpleNamespace
+import unittest
+
+from core.tests.app_methods import load_methods
+from win_app.linux_stand_ins import FirewallStatus
+
+
+class LinuxFirewallContractTests(unittest.TestCase):
+ def test_a_covered_linux_status_can_update_the_shared_shell(self):
+ roles = []
+ shell = load_methods('win_app/kvm_bridge_win.py', 'WindowsApplication', ('_on_firewall',), {
+ 'portable_runtime': SimpleNamespace(enabled=lambda: False),
+ 'firewall_win': SimpleNamespace(advise=lambda _: SimpleNamespace(
+ sentence='Synthetic firewall status', button='Check again', action=None)),
+ 'widgets': SimpleNamespace(set_role=lambda _widget, role: roles.append(role)),
+ })()
+ shell._closing = False
+ shell._firewall_busy = True
+ shell._firewall_again = False
+ shell.firewall_note = SimpleNamespace(setText=lambda _: None)
+ shell.firewall_button = SimpleNamespace(setText=lambda _: None, setEnabled=lambda _: None)
+ status = FirewallStatus(24820, allowed=True, covered=True)
+ shell._on_firewall(status)
+ self.assertIs(shell._firewall_status, status)
+ self.assertEqual(roles, ['note'])
+ self.assertFalse(shell._firewall_busy)
diff --git a/core/tests/test_length_size_sliders.py b/core/tests/test_length_size_sliders.py
index f5c3619..a9529b7 100644
--- a/core/tests/test_length_size_sliders.py
+++ b/core/tests/test_length_size_sliders.py
@@ -14,10 +14,10 @@ class LengthSizeSliderTests(unittest.TestCase):
self.assertEqual(effects.length_preset(0.25), "short")
self.assertEqual(effects.size_preset(0.08), "large")
- def test_fractional_size_scales_against_short_edge_and_keeps_clamp(self):
+ def test_fractional_size_scales_against_short_edge_and_keeps_minimum(self):
self.assertEqual(effects.edge_depth(1920, 1080, size_fraction=0.03), 32.4)
self.assertEqual(effects.edge_depth(640, 480, size_fraction=0.02), 24)
- self.assertEqual(effects.edge_depth(3840, 2160, size_fraction=0.08), 144)
+ self.assertEqual(effects.edge_depth(3840, 2160, size_fraction=0.08), 172.8)
def test_each_style_play_time_uses_shared_effect_timing_and_pace(self):
self.assertEqual(effects.play_through_seconds("beam", 2.0), 1.2)
diff --git a/core/tests/test_release_body.py b/core/tests/test_release_body.py
new file mode 100644
index 0000000..cbf6183
--- /dev/null
+++ b/core/tests/test_release_body.py
@@ -0,0 +1,48 @@
+"""Exercise the offline release-body generator; never creates a public release."""
+
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+from core import updates
+
+
+class ReleaseBodyTests(unittest.TestCase):
+ def generate(self, notes, *args):
+ with tempfile.TemporaryDirectory() as folder:
+ path = Path(folder) / "notes.md"
+ path.write_text(notes, encoding="utf-8")
+ return subprocess.run([sys.executable, str(Path(__file__).resolve().parents[2]
+ / "tools" / "release_body.py"), "--notes", str(path), *args],
+ capture_output=True, text=True, encoding="utf-8")
+
+ def test_default_patch_body_is_quiet_and_keeps_notes(self):
+ result = self.generate("Fix accented account names.\n")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, "<!-- beamer-notify: quiet -->\n\nFix accented account names.\n")
+ self.assertFalse(updates.newer_release("1.5.11", {
+ "tag_name": "v1.5.12", "body": result.stdout}).notify)
+
+ def test_important_replaces_template_mark_and_alerts(self):
+ result = self.generate("<!-- beamer-notify: quiet -->\n\nFix broken updates.\n",
+ "--notify", "important")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, "<!-- beamer-notify: important -->\n\nFix broken updates.\n")
+ self.assertTrue(updates.newer_release("1.5.11", {
+ "tag_name": "v1.5.12", "body": result.stdout}).notify)
+
+ def test_existing_important_mark_is_preserved_without_an_override(self):
+ result = self.generate("<!-- beamer-notify: important -->\n\nFix crash.\n")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.count("beamer-notify:"), 1)
+ self.assertIn("<!-- beamer-notify: important -->", result.stdout)
+
+ def test_ambiguous_or_invalid_metadata_is_rejected(self):
+ for notes in ("<!-- beamer-notify: typo -->\nFixes.\n",
+ "<!-- beamer-notify: important -->\n<!-- beamer-notify: quiet -->\nFixes."):
+ with self.subTest(notes=notes):
+ result = self.generate(notes)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(result.stdout, "")
diff --git a/core/tests/test_switch_arrival.py b/core/tests/test_switch_arrival.py
index 62020a7..6cfe917 100644
--- a/core/tests/test_switch_arrival.py
+++ b/core/tests/test_switch_arrival.py
@@ -133,14 +133,16 @@ class NearestEdgeTests(unittest.TestCase):
class LocatorTests(unittest.TestCase):
- def _bounds(self, since, reduced):
- pen = effects.draw(effects.LOCATOR, "arrive", arrival_state(effects.LOCATOR, since, reduced))
+ def _bounds(self, since, reduced, fraction=None):
+ state = arrival_state(effects.LOCATOR, since, reduced)
+ state.effect_size_fraction = fraction
+ pen = effects.draw(effects.LOCATOR, "arrive", state)
return None if pen is None else pen.bounds
- def test_it_is_never_more_than_260pt_across(self):
+ def test_reference_size_is_never_more_than_260pt_across(self):
for reduced in (False, True):
for step in range(0, 80):
- box = self._bounds(step / 100.0, reduced)
+ box = self._bounds(step / 100.0, reduced, fraction=36.0 / 1117.0)
if box is None:
continue
with self.subTest(since=step / 100.0, reduced=reduced):
diff --git a/core/tests/test_updates.py b/core/tests/test_updates.py
index 662a095..6671c09 100644
--- a/core/tests/test_updates.py
+++ b/core/tests/test_updates.py
@@ -10,6 +10,29 @@ def release(tag, **extra):
class NewerReleaseTests(unittest.TestCase):
+ def test_patch_notification_policy_reads_only_the_machine_readable_mark(self):
+ for body, notify in (
+ (None, False), ("Small fixes.", False),
+ ("Fixes a crash.\n<!-- announce -->", False),
+ ("<!-- beamer-notify: important -->", True),
+ ("Notes\n <!-- beamer-notify: important --> \nMore notes", True),
+ ("<!-- beamer-notify: quiet -->", False),
+ ("<!-- beamer-notify: typo -->", False),
+ ("Text <!-- beamer-notify: important -->", False),
+ (123, False),
+ ):
+ with self.subTest(body=body):
+ found = updates.newer_release("1.5.10", release("v1.5.12", body=body))
+ self.assertEqual(found[0], "1.5.12")
+ self.assertEqual(found.notify, notify)
+
+ def test_new_minor_or_major_alerts_even_when_latest_is_a_quiet_patch(self):
+ for current, latest in (("1.4.9", "v1.5.12"), ("1.9.9", "v2.0.1"),
+ ("1.5.12", "v1.6.0")):
+ with self.subTest(current=current, latest=latest):
+ self.assertTrue(updates.newer_release(current, release(
+ latest, body="<!-- beamer-notify: quiet -->")).notify)
+
def test_every_newer_stable_patch_is_offered(self):
self.assertIsNotNone(updates.newer_release("1.4.0", release("v1.4.1", body="Small fixes.")))
self.assertIsNotNone(updates.newer_release("1.4.0", release("v1.4.1")))
@@ -21,7 +44,7 @@ class NewerReleaseTests(unittest.TestCase):
def test_a_newer_tag_is_offered_with_its_page(self):
self.assertEqual(updates.newer_release("1.3.3", release("v1.4.0")),
- ("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0"))
+ updates.Release("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0"))
def test_the_same_or_an_older_tag_is_not(self):
self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.0")))
@@ -45,7 +68,7 @@ class NewerReleaseTests(unittest.TestCase):
def test_a_page_outside_the_project_is_replaced_by_the_releases_page(self):
found = updates.newer_release("1.3.3", release("v1.4.0", html_url="https://example.com/beamer.exe"))
- self.assertEqual(found, ("1.4.0", updates.RELEASES_PAGE))
+ self.assertEqual(found, updates.Release("1.4.0", updates.RELEASES_PAGE))
class BetaTests(unittest.TestCase):
@@ -80,6 +103,101 @@ class BetaTests(unittest.TestCase):
class CheckerTests(unittest.TestCase):
+ def test_skipped_quiet_patch_does_not_consume_a_later_important_notice(self):
+ results = []
+ checker = updates.Checker("1.5.10", lambda: True, results.append,
+ fetcher=lambda: json.dumps(release("v1.5.11")).encode())
+ checker.check_once()
+ self.assertEqual(checker.latest[0], "1.5.11")
+ self.assertIsNone(updates.visible_notice(results[-1], True, ""))
+ checker.fetcher = lambda: json.dumps(release(
+ "v1.5.12", body="<!-- beamer-notify: important -->")).encode()
+ checker.check_once()
+ important = results[-1]
+ self.assertEqual(updates.visible_notice(important, True, ""), important)
+ checker.check_once()
+ self.assertIsNone(updates.visible_notice(results[-1], True, "1.5.12"))
+
+ def test_manual_request_arriving_after_worker_reads_flag_is_not_lost(self):
+ import threading
+ from unittest.mock import patch
+
+ finished = threading.Event()
+ checker = updates.Checker("1.5.11", lambda: False, lambda found: None,
+ fetcher=lambda: json.dumps(release("v1.5.11")).encode(),
+ on_check=lambda state, found: finished.set() if state == "current" else None)
+ original = checker._manual.is_set
+ injected = False
+
+ def read_before_request():
+ nonlocal injected
+ pending = original()
+ if not injected:
+ injected = True
+ checker.check_now(manual=True)
+ return pending
+
+ with patch.object(checker._manual, "is_set", side_effect=read_before_request):
+ checker.check_now()
+ checker.start()
+ try:
+ self.assertTrue(finished.wait(2), "an explicit request was lost at the wake boundary")
+ finally:
+ checker.stop()
+ checker._thread.join(2)
+
+ def test_error_payload_is_not_reported_as_up_to_date(self):
+ checks = []
+ checker = updates.Checker("1.5.11", lambda: True, lambda found: None,
+ fetcher=lambda: b'{"message":"rate limited"}',
+ on_check=lambda state, found: checks.append(state))
+ checker.check_once(manual=True)
+ self.assertEqual(checks, ["checking", "failed"])
+
+ def test_explicit_check_works_with_automatic_checks_off_without_changing_setting(self):
+ automatic, checks = [], []
+ checker = updates.Checker("1.5.9", lambda: False, automatic.append,
+ fetcher=lambda: json.dumps(release("v1.5.11")).encode(),
+ on_check=lambda state, found: checks.append((state, found)))
+ checker.check_once(manual=True)
+ self.assertEqual(automatic, [])
+ self.assertEqual(checks, [("checking", None), ("available", checker.latest)])
+ self.assertEqual(checker.latest[0], "1.5.11")
+ self.assertFalse(checker.enabled())
+
+ def test_explicit_check_reports_current_and_failure_without_discarding_cached_update(self):
+ checks = []
+ checker = updates.Checker("1.5.11", lambda: True, lambda found: None,
+ fetcher=lambda: json.dumps(release("v1.5.11")).encode(),
+ on_check=lambda state, found: checks.append((state, found)))
+ checker.check_once(manual=True)
+ self.assertEqual(checks[-1], ("current", None))
+ checker.latest = ("1.5.12", updates.RELEASES_PAGE)
+ checker.fetcher = lambda: (_ for _ in ()).throw(OSError("offline"))
+ checker.check_once(manual=True)
+ self.assertEqual(checks[-1], ("failed", None))
+ self.assertEqual(checker.latest[0], "1.5.12")
+
+ def test_explicit_request_wakes_the_worker_and_finishes(self):
+ import threading
+ finished = threading.Event()
+ checks = []
+ def checked(state, found):
+ checks.append(state)
+ if state == "current":
+ finished.set()
+ checker = updates.Checker("1.5.11", lambda: False, lambda found: None,
+ fetcher=lambda: json.dumps(release("v1.5.11")).encode(),
+ on_check=checked)
+ checker.start()
+ try:
+ checker.check_now(manual=True)
+ self.assertTrue(finished.wait(2))
+ self.assertEqual(checks, ["checking", "current"])
+ finally:
+ checker.stop()
+ checker._thread.join(2)
+
def test_switching_off_during_a_request_discards_its_answer(self):
enabled = True
results = []
@@ -109,7 +227,7 @@ class CheckerTests(unittest.TestCase):
def test_reports_a_newer_release(self):
checker, results = self.make(release("v1.4.0"))
checker.check_once()
- self.assertEqual(results, [("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0")])
+ self.assertEqual(results, [updates.Release("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0")])
def test_reports_none_when_current(self):
checker, results = self.make(release("v1.3.3"))
@@ -131,15 +249,26 @@ class CheckerTests(unittest.TestCase):
class NoticeTests(unittest.TestCase):
+ def test_a_quiet_patch_never_becomes_a_notice_even_after_an_explicit_check(self):
+ found = updates.newer_release("1.5.10", release("v1.5.12"))
+ self.assertIsNone(updates.visible_notice(found, True, ""))
+ self.assertIsNone(updates.visible_notice(found, False, "", requested=True))
+
+ def test_explicit_request_resurfaces_a_dismissed_release_with_automatic_checks_off(self):
+ found = updates.Release("1.5.11", updates.RELEASES_PAGE)
+ self.assertEqual(updates.visible_notice(found, False, "1.5.11", requested=True), found)
+ self.assertIsNone(updates.visible_notice(found, False, "1.5.11"))
+ self.assertIsNone(updates.visible_notice(found, True, "1.5.11"))
+
def test_dismissal_survives_a_new_check_but_not_a_newer_version(self):
- found = ("1.5.10", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.10")
+ found = updates.Release("1.5.10", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.10")
self.assertEqual(updates.visible_notice(found, True, ""), found)
self.assertIsNone(updates.visible_notice(found, True, "1.5.10"))
- newer = ("1.5.11", updates.RELEASES_PAGE)
+ newer = updates.Release("1.5.11", updates.RELEASES_PAGE)
self.assertEqual(updates.visible_notice(newer, True, "1.5.10"), newer)
def test_off_setting_hides_a_cached_result_and_none_stays_hidden(self):
- self.assertIsNone(updates.visible_notice(("1.6.0", updates.RELEASES_PAGE), False, ""))
+ self.assertIsNone(updates.visible_notice(updates.Release("1.6.0", updates.RELEASES_PAGE), False, ""))
self.assertIsNone(updates.visible_notice(None, True, ""))
@@ -159,7 +288,7 @@ class PortableCheckerTests(unittest.TestCase):
checker, results = self.make([{"name": self.NAME, "browser_download_url": self.URL}])
page = "https://github.com/kalkman-code/beamer/releases/tag/v1.5.10"
self.assertEqual(checker.download_url, self.URL)
- self.assertEqual(checker.latest, ("1.5.10", page))
+ self.assertEqual(checker.latest, updates.Release("1.5.10", page, False))
self.assertEqual(results, [checker.latest])
def test_missing_portable_zip_never_offers_the_installer(self):
diff --git a/core/tests/test_windows_launch_manifest.py b/core/tests/test_windows_launch_manifest.py
new file mode 100644
index 0000000..d8b2b4c
--- /dev/null
+++ b/core/tests/test_windows_launch_manifest.py
@@ -0,0 +1,29 @@
+"""Packaging must allow an ordinary Explorer launch without requesting elevation."""
+
+import runpy
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+
+class WindowsLaunchManifestTests(unittest.TestCase):
+ def test_main_executable_does_not_request_administrator_or_uiaccess(self):
+ source = Path(__file__).resolve().parents[2] / "win_app"
+ options = {}
+
+ def executable(*args, **kwargs):
+ options.update(kwargs)
+
+ runpy.run_path(str(source / "build.spec"), init_globals={
+ "SPECPATH": str(source),
+ "Analysis": lambda *args, **kwargs: SimpleNamespace(
+ binaries=[], pure=[], scripts=[], datas=[]),
+ "PYZ": lambda value: value,
+ "EXE": executable,
+ })
+ self.assertFalse(options.get("uac_admin", False))
+ self.assertFalse(options.get("uac_uiaccess", False))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/updates.py b/core/updates.py
index 6163be5..03f714f 100644
--- a/core/updates.py
+++ b/core/updates.py
@@ -1,8 +1,8 @@
"""Whether a newer Beamer has been released, for both apps.
-One HTTPS request to GitHub's public releases API when the app starts and once a day after, sending
-nothing but the request itself, and only while the `check_updates` setting is on. A newer release
-is shown quietly in the window and the menu; nothing downloads or installs, and nothing pops up.
+One HTTPS request to GitHub's public releases API at startup and once a day while automatic
+checks are on, or on an explicit check. All newer releases appear on the Updates page. Only
+important patches and newer minor/major versions raise a notice; nothing downloads or installs.
"""
from __future__ import annotations
@@ -12,6 +12,7 @@ import logging
import re
import sys
import threading
+from typing import NamedTuple
LATEST_URL = "https://api.github.com/repos/kalkman-code/beamer/releases/latest"
RELEASES_PAGE = "https://github.com/kalkman-code/beamer/releases/latest"
@@ -23,6 +24,12 @@ LOGGER = logging.getLogger(__name__)
_VERSION = re.compile(r"^v?(\d+)\.(\d+)(?:\.(\d+))?(?:-beta\.(\d+))?$")
+class Release(NamedTuple):
+ version: str
+ url: str
+ notify: bool = True
+
+
def _parse(text):
"""((major, minor, patch), is_beta) or None."""
match = _VERSION.match(str(text or "").strip())
@@ -40,7 +47,7 @@ def parse_version(text):
def newer_release(current, payload):
- """(version text, page url) when `payload`, the API's JSON, names a release worth offering over
+ """Release(version, url, notify) when the API's JSON names a release worth offering over
`current`, else None. Every newer stable version counts, including patch releases. Drafts and
prereleases never count, nor does a tag that names a beta. A beta install is offered its own
release (1.5.0-beta.1 to 1.5.0) and anything newer, never an older one."""
@@ -56,12 +63,19 @@ def newer_release(current, payload):
url = payload.get("html_url")
if not isinstance(url, str) or not url.startswith("https://github.com/kalkman-code/beamer/"):
url = RELEASES_PAGE
- return (str(tag).lstrip("v"), url)
+ body = payload.get("body")
+ important = isinstance(body, str) and any(
+ line.strip() == "<!-- beamer-notify: important -->" for line in body.splitlines())
+ return Release(str(tag).lstrip("v"), url, important or theirs[:2] > ours[:2])
-def visible_notice(found, enabled, dismissed):
- """Dismissal is local to one version; the off setting also hides cached answers."""
- return found if enabled and found and found[0] != dismissed else None
+def visible_notice(found, enabled, dismissed, requested=False):
+ """Quiet releases stay on the Updates page, including after an explicit request.
+
+ A requested alerting release resurfaces until dismissed again. Dismissal is per version,
+ so skipping or dismissing a quiet patch cannot suppress a later important release.
+ """
+ return found if (enabled or requested) and found and found.notify and (requested or found[0] != dismissed) else None
def _portable_download(version, payload):
@@ -99,20 +113,25 @@ def fetch(url=LATEST_URL):
class Checker:
"""Checks now and every CHECK_EVERY_SECONDS on its own thread while `enabled()` says so, and
- calls `on_result((version, url) or None)` on that thread after each check that got an answer;
- the owner marshals it. A failed check keeps the last answer and logs once."""
+ calls `on_result(Release or None)` on that thread after each check that got an answer;
+ the owner marshals it. A failed check keeps the last answer and logs once. Explicit checks use
+ `on_check(state, found)` instead, also on the worker thread, so the UI can show progress/errors
+ and display the requested answer even while automatic checks are off."""
- def __init__(self, current, enabled, on_result, fetcher=fetch, logger=None, portable=False):
+ def __init__(self, current, enabled, on_result, fetcher=fetch, logger=None, portable=False,
+ on_check=None):
self.current = current
self.enabled = enabled
self.on_result = on_result
self.fetcher = fetcher
self.logger = logger or LOGGER
self.portable = portable
+ self.on_check = on_check
self.latest = None
self.download_url = None
self._wake = threading.Event()
self._stop = threading.Event()
+ self._manual = threading.Event()
self._thread = None
self._failed = False
@@ -121,39 +140,67 @@ class Checker:
self._thread = threading.Thread(target=self._run, name="Beamer-updates", daemon=True)
self._thread.start()
- def check_now(self):
- """After the setting is switched on, rather than waiting a day."""
+ def check_now(self, manual=False):
+ """Wake the worker; an explicit check also works with automatic checks off."""
+ if manual:
+ self._manual.set()
self._wake.set()
def stop(self):
self._stop.set()
self._wake.set()
- def check_once(self):
- if parse_version(self.current) is None or not self.enabled():
+ def _checked(self, state, found=None):
+ if self.on_check is not None:
+ try:
+ self.on_check(state, found)
+ except Exception:
+ self.logger.exception("manual update callback failed")
+
+ def check_once(self, manual=False):
+ if self._stop.is_set():
return
+ if parse_version(self.current) is None:
+ if manual:
+ self._checked("failed")
+ return
+ if not manual and not self.enabled():
+ return
+ if manual:
+ self._checked("checking")
try:
payload = json.loads(self.fetcher().decode("utf-8"))
+ if not isinstance(payload, dict) or _parse(payload.get("tag_name")) is None:
+ raise ValueError("release response has no recognised version")
except Exception as exc:
if not self._failed:
self.logger.info("could not check for a newer Beamer: %s", exc)
self._failed = True
+ if manual and not self._stop.is_set():
+ self._checked("failed")
return
self._failed = False
- if not self.enabled() or self._stop.is_set():
+ if (not manual and not self.enabled()) or self._stop.is_set():
return
self.latest = newer_release(self.current, payload)
self.download_url = (_portable_download(self.latest[0], payload)
if self.portable and self.latest else None)
if self.latest:
self.logger.info("Beamer %s is available", self.latest[0])
+ if manual:
+ self._checked("available" if self.latest else "current", self.latest)
+ return
try:
self.on_result(self.latest)
except Exception:
self.logger.exception("update result callback failed")
def _run(self):
+ self.check_once()
while not self._stop.is_set():
- self.check_once()
self._wake.wait(CHECK_EVERY_SECONDS)
self._wake.clear()
+ manual = self._manual.is_set()
+ if manual:
+ self._manual.clear()
+ self.check_once(manual=manual)
diff --git a/flatpak/uk.co.kalkman.beamer.metainfo.xml b/flatpak/uk.co.kalkman.beamer.metainfo.xml
index 95f4adc..1a7bf0d 100644
--- a/flatpak/uk.co.kalkman.beamer.metainfo.xml
+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml
@@ -43,6 +43,9 @@
</screenshots>
<content_rating type="oars-1.1"/>
<releases>
+ <release version="1.5.12" date="2026-10-23">
+ <description><p>Adds a Check for updates button to the Updates section on macOS, Windows and Linux. It works even when automatic checks are off, says when a check fails, and shows any newer version with a download link or Flatpak update instructions. Nothing downloads or installs automatically.</p><p>From this version, bug-fix patches no longer raise the update banner or menu alert unless they are marked important. They still appear on the Updates page and in manual checks.</p><p>Windows starts without an administrator prompt. The installer asks for permission separately to set up firewall rules, move existing Beamer startup tasks to normal rights and restart the GameInput service if present. Beamer can no longer control administrator windows or Windows permission prompts from another machine, no longer restarts GameInput while running, and its Firewall page now only checks the rules: run the installer again to repair them.</p><p>Fixes a crossing from Windows to a Mac with more than one display landing on the wrong display instead of the one set for that edge. Input from another machine now wakes a sleeping Mac display.</p><p>The Membrane, Sparks and Instrument crossing styles now follow the Size setting, and Light, Folio and Selvedge grow in every direction instead of only deeper. Switch effects such as Ring follow Size too. The largest Size is now 25% of the display's shorter side, up from 8% with a 144-point cap. The Design preview keeps the same zoom while Size changes, so it can crop larger marks.</p><p>Desktop machine rows have a Pin address switch: keep the address you chose, or turn it off to follow automatic address changes. On macOS, the Dock and menu bar controls sit higher on Overview, and the menu bar menu has a Show in Dock checkbox.</p></description>
+ </release>
<release version="1.5.11" date="2026-10-22">
<description><p>Fixes the pointer falling seconds behind when a 1000 Hz mouse bends, reverses or drags: once the link is behind, the pointer now goes straight to its latest position instead of replaying every step. Clicks, keys, scrolling and the clipboard still arrive in order around the motion.</p><p>Moves are sent at once while the other machine keeps up, and paced only once it falls behind. A settings file this version cannot read, such as one written by a newer Beamer, no longer crashes the window and is never overwritten.</p></description>
</release>
diff --git a/locales/beamer.pot b/locales/beamer.pot
index 7435edd..bbe4a3b 100644
--- a/locales/beamer.pot
+++ b/locales/beamer.pot
@@ -1609,6 +1609,10 @@ msgstr ""
msgid "Idle"
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Get update"
+msgstr ""
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "What's new"
msgstr ""
@@ -1653,6 +1657,10 @@ msgstr ""
msgid "Show in menu bar"
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Automatically check for updates"
+msgstr ""
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "Check for updates"
msgstr ""
@@ -1949,10 +1957,30 @@ msgstr ""
msgid "At login"
msgstr ""
+#: mac_app/kvm_bridge_app.py
+msgid "Dock and menu bar"
+msgstr ""
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "Updates"
msgstr ""
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Checking for updates…"
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Beamer is up to date."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Update available."
+msgstr ""
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Could not check for updates. Check your connection and try again."
+msgstr ""
+
#: mac_app/kvm_bridge_app.py mac_app/widgets.py win_app/kvm_bridge_win.py
msgid "Match design with"
msgstr ""
@@ -2216,11 +2244,11 @@ msgid "Ways: set on the Crossing page · {state}"
msgstr ""
#: mac_app/kvm_bridge_app.py
-msgid "With the Dock icon off, Beamer stays in the menu bar and appears in the Dock while its window is open. The Dock and the menu bar are never both off: the one still showing cannot be switched off."
+msgid "For menu-bar-only use, turn off Show in Dock and close this window. Beamer stays in the menu bar. Its Dock icon appears while this window is open."
msgstr ""
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
-msgid "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."
+msgid "Checks GitHub at startup and once a day. Updates are downloaded and installed by you."
msgstr ""
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
@@ -2481,12 +2509,12 @@ msgstr ""
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
#, python-brace-format
-msgid "Download Beamer {version}"
+msgid "Beamer {version} is available."
msgstr ""
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
#, python-brace-format
-msgid "Beamer {version} is available."
+msgid "Download Beamer {version}"
msgstr ""
#. {reason} is the system's reason for refusing the login item.
@@ -3422,6 +3450,14 @@ msgstr ""
msgid "Re-pair"
msgstr ""
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pin address"
+msgstr ""
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Keeps this address through reconnects and re-pairing. Turn off to follow address changes automatically."
+msgstr ""
+
#: mac_app/machines_panel.py win_app/machines_win.py
msgid "Hide directions"
msgstr ""
@@ -4131,63 +4167,48 @@ msgstr ""
msgid "No push. Current pressure is 0 of {threshold} pointer units."
msgstr ""
-#: win_app/firewall_win.py win_app/linux_stand_ins.py
-msgid "Check again"
-msgstr ""
-
#: win_app/firewall_win.py
-msgid "Windows Firewall is blocking Beamer's input or pairing traffic. This can happen when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rules for private networks."
+msgid "Windows treats this network as public; if you trust it, change its network profile to Private in Windows Settings."
msgstr ""
#: win_app/firewall_win.py
-msgid "Fix the firewall"
+msgid "Beamer's firewall rules need attention; run the Beamer installer again to repair them for private networks."
msgstr ""
-#: win_app/firewall_win.py
-#, python-brace-format
-msgid "Beamer could not read the Windows Firewall: {error}"
+#: win_app/firewall_win.py win_app/linux_stand_ins.py
+msgid "Check again"
msgstr ""
#: win_app/firewall_win.py
-msgid "Trust this network"
+msgid "Windows Firewall has a block rule affecting Beamer's input or pairing traffic; ask your administrator to review Beamer's inbound block rules in Windows Firewall."
msgstr ""
#: win_app/firewall_win.py
-#, python-brace-format
-msgid "{sentence} Beamer is not running as administrator, so it cannot make this change itself: quit Beamer and open it again from the Start menu."
+msgid "this private network"
msgstr ""
#: win_app/firewall_win.py
-#, python-brace-format
-msgid "Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will say this PC is unreachable. This happens when the installer was run without administrator rights. Fixing it adds the rule for private networks."
+msgid "this network"
msgstr ""
#: win_app/firewall_win.py
#, python-brace-format
-msgid "Windows treats {names} as a public network, so some of Beamer's firewall rules do not cover it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."
-msgstr ""
-
-#: win_app/firewall_win.py
-msgid "this private network"
-msgstr ""
-
-#: win_app/firewall_win.py
-msgid "this network"
+msgid "Beamer could not read the Windows Firewall: {error}"
msgstr ""
#: win_app/firewall_win.py
#, python-brace-format
-msgid "Beamer's firewall rule does not apply on this network (Windows calls it {names}). Fixing it rewrites the rule to cover it."
+msgid "Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine discover this PC."
msgstr ""
#: win_app/firewall_win.py
#, python-brace-format
-msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule covering this network for {rules}, so {effects}. Fixing it replaces Beamer's inbound firewall rules."
+msgid "This managed network needs Windows Firewall rules for Beamer; ask your administrator to allow its receiver on TCP {port} and pairing on UDP and TCP {pairing_port} for the Domain profile."
msgstr ""
#: win_app/firewall_win.py
#, python-brace-format
-msgid "Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine discover this PC."
+msgid "Beamer uses custom port {port}; ask your administrator to allow that port for Beamer on trusted networks."
msgstr ""
#: win_app/global_shortcut_portal.py
@@ -4198,6 +4219,10 @@ msgstr ""
msgid "Beamer — Identify screens"
msgstr ""
+#: win_app/input_injector.py
+msgid "Windows blocked Beamer's input; use administrator windows locally and click a normal window on this PC to continue."
+msgstr ""
+
#: win_app/kvm_bridge_win.py
msgid "Beamer's website"
msgstr ""
@@ -4470,10 +4495,6 @@ msgstr ""
msgid "Checking…"
msgstr ""
-#: win_app/kvm_bridge_win.py
-msgid "Fixing…"
-msgstr ""
-
#: win_app/kvm_bridge_win.py
msgid "This PC drives machines"
msgstr ""
@@ -4527,7 +4548,7 @@ msgid "Delay:"
msgstr ""
#: win_app/kvm_bridge_win.py
-msgid "Start at sign-in needs the same administrator account that runs Beamer."
+msgid "Start at sign-in needs Beamer to run as the signed-in account."
msgstr ""
#: win_app/kvm_bridge_win.py
@@ -4612,11 +4633,15 @@ msgid "This desktop has no system tray, so Beamer's window is all there is: clos
msgstr ""
#: win_app/kvm_bridge_win.py
-msgid "Update through your software store."
+msgid "Update through your software store, or download the Flatpak from the release page and open it."
msgstr ""
#: win_app/kvm_bridge_win.py
-msgid "Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps."
+msgid "Beamer controls normal windows; use administrator windows and Windows permission prompts locally."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "Starts in the tray when you sign in, without an administrator prompt."
msgstr ""
#: win_app/kvm_bridge_win.py
@@ -4696,7 +4721,11 @@ msgid ""
msgstr ""
#: win_app/kvm_bridge_win.py
-msgid "When enabled, a logon task starts Beamer elevated without a UAC prompt, so it can send input to administrator apps."
+msgid "No portable download is available for this release. See What's new."
+msgstr ""
+
+#: win_app/kvm_bridge_win.py
+msgid "When enabled, Beamer starts in the tray with your normal permissions."
msgstr ""
#: win_app/kvm_bridge_win.py
@@ -4840,6 +4869,11 @@ msgstr ""
msgid "Pairing…"
msgstr ""
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Pin address for {name}"
+msgstr ""
+
#: win_app/machines_win.py
#, python-brace-format
msgid "{name}: {status}"
diff --git a/locales/it.po b/locales/it.po
index a143e08..152837a 100644
--- a/locales/it.po
+++ b/locales/it.po
@@ -1618,6 +1618,10 @@ msgstr "Scorciatoia: {style} {key} ·"
msgid "Idle"
msgstr "Inattivo"
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Get update"
+msgstr "Scarica l'aggiornamento"
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "What's new"
msgstr "Novità"
@@ -1662,6 +1666,10 @@ msgstr "Mostra nel Dock"
msgid "Show in menu bar"
msgstr "Mostra nella barra dei menu"
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Automatically check for updates"
+msgstr "Controlla automaticamente gli aggiornamenti"
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "Check for updates"
msgstr "Controlla aggiornamenti"
@@ -1975,10 +1983,30 @@ msgstr "Uguale su tutti i computer"
msgid "At login"
msgstr "Al login"
+#: mac_app/kvm_bridge_app.py
+msgid "Dock and menu bar"
+msgstr "Dock e barra dei menu"
+
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "Updates"
msgstr "Aggiornamenti"
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Checking for updates…"
+msgstr "Ricerca aggiornamenti…"
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Beamer is up to date."
+msgstr "Beamer è aggiornato."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Update available."
+msgstr "Aggiornamento disponibile."
+
+#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
+msgid "Could not check for updates. Check your connection and try again."
+msgstr "Impossibile controllare gli aggiornamenti. Controlla la connessione e riprova."
+
#: mac_app/kvm_bridge_app.py mac_app/widgets.py win_app/kvm_bridge_win.py
msgid "Match design with"
msgstr "Segui l'aspetto di"
@@ -2259,12 +2287,12 @@ msgid "Ways: set on the Crossing page · {state}"
msgstr "Vie: si impostano nella pagina Passaggio · {state}"
#: mac_app/kvm_bridge_app.py
-msgid "With the Dock icon off, Beamer stays in the menu bar and appears in the Dock while its window is open. The Dock and the menu bar are never both off: the one still showing cannot be switched off."
-msgstr "Con l'icona del Dock disattivata, Beamer resta nella barra dei menu e appare nel Dock mentre la sua finestra è aperta. Il Dock e la barra dei menu non sono mai disattivati entrambi: quello ancora visibile non può essere disattivato."
+msgid "For menu-bar-only use, turn off Show in Dock and close this window. Beamer stays in the menu bar. Its Dock icon appears while this window is open."
+msgstr "Per usare Beamer solo dalla barra dei menu, disattiva Mostra nel Dock e chiudi questa finestra. Beamer resta nella barra dei menu. L'icona nel Dock appare quando questa finestra è aperta."
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
-msgid "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."
-msgstr "Chiede a GitHub una volta al giorno se c'è una versione più recente di Beamer. Non viene inviato nulla oltre alla richiesta stessa."
+msgid "Checks GitHub at startup and once a day. Updates are downloaded and installed by you."
+msgstr "Controlla GitHub all'avvio e una volta al giorno. Scarichi e installi tu gli aggiornamenti."
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
msgid "System"
@@ -2532,13 +2560,13 @@ msgstr "Disattivato"
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
#, python-brace-format
-msgid "Download Beamer {version}"
-msgstr "Scarica Beamer {version}"
+msgid "Beamer {version} is available."
+msgstr "Beamer {version} è disponibile."
#: mac_app/kvm_bridge_app.py win_app/kvm_bridge_win.py
#, python-brace-format
-msgid "Beamer {version} is available."
-msgstr "Beamer {version} è disponibile."
+msgid "Download Beamer {version}"
+msgstr "Scarica Beamer {version}"
#. {reason} is the system's reason for refusing the login item.
#: mac_app/kvm_bridge_app.py
@@ -3482,6 +3510,14 @@ msgstr "Codice mostrato sull'altro computer"
msgid "Re-pair"
msgstr "Riabbina"
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Pin address"
+msgstr "Mantieni questo indirizzo"
+
+#: mac_app/machines_panel.py win_app/machines_win.py
+msgid "Keeps this address through reconnects and re-pairing. Turn off to follow address changes automatically."
+msgstr "Mantiene questo indirizzo dopo le riconnessioni e un nuovo abbinamento. Disattiva per seguire automaticamente i cambiamenti di indirizzo."
+
#: mac_app/machines_panel.py win_app/machines_win.py
msgid "Hide directions"
msgstr "Nascondi direzioni"
@@ -4193,41 +4229,21 @@ msgstr "Pressione attuale {pressure} su {threshold} unità del puntatore sul bor
msgid "No push. Current pressure is 0 of {threshold} pointer units."
msgstr "Nessuna spinta. La pressione attuale è 0 su {threshold} unità del puntatore."
-#: win_app/firewall_win.py win_app/linux_stand_ins.py
-msgid "Check again"
-msgstr "Controlla di nuovo"
-
#: win_app/firewall_win.py
-msgid "Windows Firewall is blocking Beamer's input or pairing traffic. This can happen when Cancel was pressed on Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling does not clear it. Fixing it removes the block and adds the right rules for private networks."
-msgstr "Windows Firewall sta bloccando il traffico di input o di abbinamento di Beamer. Può succedere se è stato premuto Annulla nella richiesta di Windows «Consenti l'accesso» per l'app: una regola di blocco prevale su qualsiasi regola di autorizzazione, quindi reinstallare non risolve il problema. La correzione rimuove il blocco e aggiunge le regole corrette per le reti private."
+msgid "Windows treats this network as public; if you trust it, change its network profile to Private in Windows Settings."
+msgstr "Windows considera pubblica questa rete; se ti fidi, cambia il profilo di rete in Privato nelle Impostazioni di Windows."
#: win_app/firewall_win.py
-msgid "Fix the firewall"
-msgstr "Correggi il firewall"
+msgid "Beamer's firewall rules need attention; run the Beamer installer again to repair them for private networks."
+msgstr "Le regole del firewall di Beamer vanno corrette; esegui di nuovo il programma di installazione di Beamer per ripararle sulle reti private."
-#: win_app/firewall_win.py
-#, python-brace-format
-msgid "Beamer could not read the Windows Firewall: {error}"
-msgstr "Beamer non è riuscito a leggere Windows Firewall: {error}"
-
-#: win_app/firewall_win.py
-msgid "Trust this network"
-msgstr "Considera attendibile questa rete"
-
-#: win_app/firewall_win.py
-#, python-brace-format
-msgid "{sentence} Beamer is not running as administrator, so it cannot make this change itself: quit Beamer and open it again from the Start menu."
-msgstr "{sentence} Beamer non è in esecuzione come amministratore, quindi non può fare questa modifica da solo: esci da Beamer e aprilo di nuovo dal menu Start."
-
-#: win_app/firewall_win.py
-#, python-brace-format
-msgid "Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will say this PC is unreachable. This happens when the installer was run without administrator rights. Fixing it adds the rule for private networks."
-msgstr "Windows Firewall non ha una regola che consenta agli altri tuoi computer di raggiungere Beamer sulla porta {port}, quindi diranno che questo PC non è raggiungibile. Succede quando il programma di installazione è stato eseguito senza diritti di amministratore. La correzione aggiunge la regola per le reti private."
+#: win_app/firewall_win.py win_app/linux_stand_ins.py
+msgid "Check again"
+msgstr "Controlla di nuovo"
#: win_app/firewall_win.py
-#, python-brace-format
-msgid "Windows treats {names} as a public network, so some of Beamer's firewall rules do not cover it and your other machines cannot get in. Trusting it marks the network as private, which lets them in without opening the port on every other network this PC joins."
-msgstr "Windows considera {names} una rete pubblica, quindi alcune regole del firewall di Beamer non la coprono e gli altri tuoi computer non possono accedere. Considerandola attendibile, la rete diventa privata: così possono accedere senza aprire la porta su tutte le altre reti a cui questo PC si collega."
+msgid "Windows Firewall has a block rule affecting Beamer's input or pairing traffic; ask your administrator to review Beamer's inbound block rules in Windows Firewall."
+msgstr "Una regola di blocco del Firewall di Windows riguarda il traffico di input o di abbinamento di Beamer; chiedi all'amministratore di controllare le regole di blocco in entrata di Beamer nel Firewall di Windows."
#: win_app/firewall_win.py
msgid "this private network"
@@ -4239,18 +4255,23 @@ msgstr "questa rete"
#: win_app/firewall_win.py
#, python-brace-format
-msgid "Beamer's firewall rule does not apply on this network (Windows calls it {names}). Fixing it rewrites the rule to cover it."
-msgstr "La regola del firewall di Beamer non vale su questa rete (Windows la chiama {names}). La correzione riscrive la regola per includerla."
+msgid "Beamer could not read the Windows Firewall: {error}"
+msgstr "Beamer non è riuscito a leggere Windows Firewall: {error}"
+
+#: win_app/firewall_win.py
+#, python-brace-format
+msgid "Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine discover this PC."
+msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer sulla porta {port} su {where}, e consente a un nuovo computer di trovare questo PC."
#: win_app/firewall_win.py
#, python-brace-format
-msgid "Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule covering this network for {rules}, so {effects}. Fixing it replaces Beamer's inbound firewall rules."
-msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer sulla porta {port}, ma nessuna regola copre questa rete per {rules}, quindi {effects}. La correzione sostituisce le regole in entrata del firewall di Beamer."
+msgid "This managed network needs Windows Firewall rules for Beamer; ask your administrator to allow its receiver on TCP {port} and pairing on UDP and TCP {pairing_port} for the Domain profile."
+msgstr "Questa rete gestita richiede regole del Firewall di Windows per Beamer; chiedi all'amministratore di consentire il ricevitore sulla porta TCP {port} e l'abbinamento su UDP e TCP {pairing_port} per il profilo Dominio."
#: win_app/firewall_win.py
#, python-brace-format
-msgid "Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine discover this PC."
-msgstr "Windows Firewall consente agli altri tuoi computer di raggiungere Beamer sulla porta {port} su {where}, e consente a un nuovo computer di trovare questo PC."
+msgid "Beamer uses custom port {port}; ask your administrator to allow that port for Beamer on trusted networks."
+msgstr "Beamer usa la porta personalizzata {port}; chiedi all'amministratore di consentirla per Beamer sulle reti attendibili."
#: win_app/global_shortcut_portal.py
msgid "Send input to another machine"
@@ -4260,6 +4281,10 @@ msgstr "Invia input a un altro computer"
msgid "Beamer — Identify screens"
msgstr "Beamer — Identifica gli schermi"
+#: win_app/input_injector.py
+msgid "Windows blocked Beamer's input; use administrator windows locally and click a normal window on this PC to continue."
+msgstr "Windows ha bloccato l'input di Beamer; usa localmente le finestre con privilegi di amministratore e fai clic su una finestra normale di questo PC per continuare."
+
#: win_app/kvm_bridge_win.py
msgid "Beamer's website"
msgstr "Sito di Beamer"
@@ -4536,10 +4561,6 @@ msgstr "Verifica di Windows Firewall…"
msgid "Checking…"
msgstr "Verifica…"
-#: win_app/kvm_bridge_win.py
-msgid "Fixing…"
-msgstr "Correzione…"
-
#: win_app/kvm_bridge_win.py
msgid "This PC drives machines"
msgstr "Questo PC controlla gli altri computer"
@@ -4593,8 +4614,8 @@ msgid "Delay:"
msgstr "Ritardo:"
#: win_app/kvm_bridge_win.py
-msgid "Start at sign-in needs the same administrator account that runs Beamer."
-msgstr "L'avvio all'accesso richiede lo stesso account amministratore che esegue Beamer."
+msgid "Start at sign-in needs Beamer to run as the signed-in account."
+msgstr "Per avviarsi all'accesso, Beamer deve essere eseguito con l'account attualmente connesso."
#: win_app/kvm_bridge_win.py
msgid "Each chip is a side of this screen; click one to add or remove it. The side a machine touches crosses on its lit thirds; any other free side wraps round to it, arriving on its far side. A corner is a diagonal push, shown as a square on the map."
@@ -4680,12 +4701,16 @@ msgid "This desktop has no system tray, so Beamer's window is all there is: clos
msgstr "Questo desktop non ha un'area di notifica, quindi la finestra di Beamer è tutto ciò che c'è: chiuderla chiude Beamer."
#: win_app/kvm_bridge_win.py
-msgid "Update through your software store."
-msgstr "Aggiorna tramite il tuo gestore software."
+msgid "Update through your software store, or download the Flatpak from the release page and open it."
+msgstr "Aggiorna tramite il tuo negozio di software oppure scarica il file Flatpak dalla pagina della versione e aprilo."
+
+#: win_app/kvm_bridge_win.py
+msgid "Beamer controls normal windows; use administrator windows and Windows permission prompts locally."
+msgstr "Beamer controlla le finestre normali; gestisci localmente le finestre con privilegi di amministratore e le richieste di autorizzazione di Windows."
#: win_app/kvm_bridge_win.py
-msgid "Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps."
-msgstr "Si avvia con privilegi elevati all'accesso senza richiesta UAC, così Beamer può inviare input alle app amministratore."
+msgid "Starts in the tray when you sign in, without an administrator prompt."
+msgstr "All'accesso si avvia nell'area di notifica, senza richiesta di privilegi di amministratore."
#: win_app/kvm_bridge_win.py
msgid "Seam crossings need X11 on Linux."
@@ -4768,8 +4793,12 @@ msgstr ""
"{link}"
#: win_app/kvm_bridge_win.py
-msgid "When enabled, a logon task starts Beamer elevated without a UAC prompt, so it can send input to administrator apps."
-msgstr "Se attivo, un'attività all'accesso avvia Beamer con privilegi elevati senza richiesta UAC, così può inviare input alle app amministratore."
+msgid "No portable download is available for this release. See What's new."
+msgstr "Per questa versione non è disponibile un download portatile. Consulta Novità."
+
+#: win_app/kvm_bridge_win.py
+msgid "When enabled, Beamer starts in the tray with your normal permissions."
+msgstr "Se attivo, Beamer si avvia nell'area di notifica con i tuoi normali privilegi."
#: win_app/kvm_bridge_win.py
msgid "Only the installed app can start at sign-in."
@@ -4915,6 +4944,11 @@ msgstr "Cifre di abbinamento"
msgid "Pairing…"
msgstr "Abbinamento…"
+#: win_app/machines_win.py
+#, python-brace-format
+msgid "Pin address for {name}"
+msgstr "Mantieni questo indirizzo per {name}"
+
#: win_app/machines_win.py
#, python-brace-format
msgid "{name}: {status}"
diff --git a/mac_app/input_injector_mac.py b/mac_app/input_injector_mac.py
index 6a918b2..2cd696a 100644
--- a/mac_app/input_injector_mac.py
+++ b/mac_app/input_injector_mac.py
@@ -17,8 +17,10 @@ guards AppKit, so this module stays importable, and its behaviour fakeable,
on a machine without it.
"""
+import ctypes
import functools
import logging
+import sys
import threading
import time
import unicodedata
@@ -135,6 +137,51 @@ _scroll_remainders: Dict[str, List[float]] = {"line": [0.0, 0.0], "pixel": [0.0,
# thread injecting while a reconnect's release_all snapshots and clears would
# otherwise press a key that nothing then remembers to release.
_state_lock = threading.RLock()
+_HID_QUARTZ = Quartz
+_power_api = None
+_power_assertion_id = ctypes.c_uint32(0)
+_power_last_activity = float("-inf")
+_power_warning_logged = False
+_POWER_API_UNAVAILABLE = object()
+_IOPM_USER_ACTIVE_LOCAL = 0
+
+
+def _load_power_api():
+ if not sys.platform == "darwin":
+ raise OSError("IOKit display activity is only available on macOS")
+ core_foundation = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
+ iokit = ctypes.CDLL("/System/Library/Frameworks/IOKit.framework/IOKit")
+ create_string = core_foundation.CFStringCreateWithCString
+ create_string.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
+ create_string.restype = ctypes.c_void_p
+ name = create_string(None, b"Beamer remote input", 0x08000100)
+ if not name:
+ raise OSError("CFStringCreateWithCString failed")
+ declare_activity = iokit.IOPMAssertionDeclareUserActivity
+ declare_activity.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32)]
+ declare_activity.restype = ctypes.c_int32
+ return declare_activity, name
+
+
+def _wake_display_for_remote_input() -> None:
+ global _power_api, _power_last_activity, _power_warning_logged
+ now = time.monotonic()
+ if now - _power_last_activity < 1.0 or _power_api is _POWER_API_UNAVAILABLE:
+ return
+ _power_last_activity = now
+ try:
+ if _power_api is None:
+ _power_api = _load_power_api()
+ declare_activity, name = _power_api
+ status = declare_activity(name, _IOPM_USER_ACTIVE_LOCAL, ctypes.byref(_power_assertion_id))
+ if status != 0:
+ raise OSError(f"IOPMAssertionDeclareUserActivity returned {status}")
+ except Exception as error:
+ if not _power_warning_logged:
+ LOGGER.warning("Could not wake the Mac display for remote input: %s", error)
+ _power_warning_logged = True
+ if _power_api is None:
+ _power_api = _POWER_API_UNAVAILABLE
def _locked(function):
@@ -435,6 +482,9 @@ def _held_button() -> Optional[str]:
def _post(event) -> None:
quartz = _require()
+ # Only an event bound for the system's HID tap is user activity; a swapped-in fake must not keep a real display awake.
+ if quartz is _HID_QUARTZ:
+ _wake_display_for_remote_input()
quartz.CGEventSetIntegerValueField(event, quartz.kCGEventSourceUserData, INJECTED_MARK)
quartz.CGEventPost(quartz.kCGHIDEventTap, event)
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index 035b42a..6b5fd89 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -1320,13 +1320,17 @@ class ControlWindow(AppKit.NSObject):
self.update_notice_text = widgets.Label("", theme.TYPE["body"], wrap=True)
self.update_notice.add(self.update_notice_text.view)
actions = widgets.stack(vertical=False, spacing=12)
+ self.update_action = widgets.Button(tr("Get update"), self, "downloadUpdate:", style="primary")
+ widgets.add(actions, self.update_action.view, full_width=False)
self.update_notes = widgets.Button(tr("What's new"), self, "downloadUpdate:")
self.update_dismiss = widgets.Button(tr("Dismiss"), self, "dismissUpdate:")
widgets.add(actions, self.update_notes.view, full_width=False)
widgets.add(actions, self.update_dismiss.view, full_width=False)
self.update_notice.add(actions)
self.update_notice.view.setHidden_(True)
- widgets.add(pane, self.update_notice.view)
+ pane.addArrangedSubview_(self.update_notice.view)
+ self.update_notice_width = self.update_notice.view.widthAnchor().constraintEqualToAnchor_(pane.widthAnchor())
+ self.update_notice_width.setPriority_(AppKit.NSLayoutPriorityDragThatCannotResizeWindow)
# The page host is the only part of the pane that gives way when the window is resized;
# the commit bar keeps its height on every page.
host = widgets.stack(spacing=0)
@@ -2351,11 +2355,11 @@ class ControlWindow(AppKit.NSObject):
widgets.add(body, self.panel.machines_module.view)
widgets.add(body, self.panel.own_name_module().view)
widgets.add(body, self.panel.sheet.view)
+ widgets.add(body, self._dock_module().view)
widgets.add(body, self._status_module().view)
widgets.add(body, self._keyboard_module().view)
widgets.add(body, self._same_module().view)
widgets.add(body, self._login_module().view)
- widgets.add(body, self._dock_module().view)
widgets.add(body, self._updates_module().view)
@objc.python_method
@@ -2854,14 +2858,14 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _dock_module(self):
module = widgets.Module()
- module.add(widgets.eyebrow(tr("Window")))
+ module.add(widgets.eyebrow(tr("Dock and menu bar")))
self.dock_switch = widgets.Switch(tr("Show in Dock"), on_change=self._set_show_in_dock)
self.tray_switch = widgets.Switch(tr("Show in menu bar"), on_change=self._set_show_in_tray)
module.add(self.dock_switch.view)
module.add(self.tray_switch.view)
module.add(widgets.note(tr(
- "With the Dock icon off, Beamer stays in the menu bar and appears in the Dock while its window is open. "
- "The Dock and the menu bar are never both off: the one still showing cannot be switched off."
+ "For menu-bar-only use, turn off Show in Dock and close this window. "
+ "Beamer stays in the menu bar. Its Dock icon appears while this window is open."
)).view)
self._reflect_visibility()
return module
@@ -2910,15 +2914,22 @@ class ControlWindow(AppKit.NSObject):
def _updates_module(self):
module = widgets.Module()
module.add(widgets.eyebrow(tr("Updates")))
- self.updates_switch = widgets.Switch(tr("Check for updates"), on_change=self._set_check_updates)
+ self.updates_switch = widgets.Switch(tr("Automatically check for updates"), on_change=self._set_check_updates)
self.updates_switch.value = self.controller.cfg.check_updates
module.add(self.updates_switch.view)
module.add(widgets.note(tr(
- "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."
+ "Checks GitHub at startup and once a day. Updates are downloaded and installed by you."
)).view)
+ self.check_updates_button = widgets.Button(tr("Check for updates"), self, "checkForUpdates:", full_width=True)
+ module.add(self.check_updates_button.view)
+ self.update_status = widgets.note("")
+ module.add(self.update_status.view)
self.update_button = widgets.Button(tr("Download"), self, "downloadUpdate:", style="primary", full_width=True)
self.update_button.view.setHidden_(True)
module.add(self.update_button.view)
+ self.update_page_notes = widgets.Button(tr("What's new"), self, "downloadUpdate:", full_width=True)
+ self.update_page_notes.view.setHidden_(True)
+ module.add(self.update_page_notes.view)
self.update_url = None
return module
@@ -2937,23 +2948,46 @@ class ControlWindow(AppKit.NSObject):
(self.update_handler or self.show_update)(None)
@objc.python_method
- def show_update(self, found):
- """`found` is (version, url) for a newer release, or None."""
- if not self.controller.cfg.check_updates:
+ def show_update(self, found, manual=False):
+ """`found` is a core Release for a newer version, or None."""
+ if not manual and not self.controller.cfg.check_updates:
found = None
+ self._manual_update = manual
self._update = found
self.update_url = found[1] if found else None
+ self.update_status.set(tr("Beamer {version} is available.").format(version=found[0]) if found else "")
+ motion.set_hidden(self.update_page_notes.view, found is None)
if found:
self.update_button.set_title(tr("Download Beamer {version}").format(version=found[0]))
motion.set_hidden(self.update_button.view, found is None)
self._refresh_update_notice()
+ def checkForUpdates_(self, _sender):
+ if self.update_checker is not None:
+ self.show_update_check("checking", None)
+ self.update_checker.check_now(manual=True)
+
+ @objc.python_method
+ def show_update_check(self, state, found):
+ self.check_updates_button.set_enabled(state != "checking")
+ text = {"checking": tr("Checking for updates…"),
+ "current": tr("Beamer is up to date."),
+ "available": tr("Update available."),
+ "failed": tr("Could not check for updates. Check your connection and try again.")}[state]
+ self.update_status.set(text)
+ if state in ("available", "current"):
+ (self.update_handler or self.show_update)(found, manual=True)
+ if state == "current":
+ self.update_status.set(text)
+
@objc.python_method
def _refresh_update_notice(self):
found = updates.visible_notice(self._update, self.controller.cfg.check_updates,
- self.settings_store.current().get("dismissed_update_version", ""))
+ self.settings_store.current().get("dismissed_update_version", ""),
+ requested=getattr(self, "_manual_update", False))
if found:
self.update_notice_text.set(tr("Beamer {version} is available.").format(version=found[0]))
+ self.update_notice_width.setActive_(bool(found))
self.update_notice.view.setHidden_(not bool(found))
def dismissUpdate_(self, _sender):
@@ -2965,8 +2999,12 @@ class ControlWindow(AppKit.NSObject):
except SettingsError as exc:
self.logger.warning("Update dismissal could not be saved: %s", exc)
return
+ self._manual_update = False
self.controller.update_config(cfg)
- self._refresh_update_notice()
+ if self.update_handler:
+ self.update_handler(self._update)
+ else:
+ self._refresh_update_notice()
def downloadUpdate_(self, _sender):
if self.update_url:
@@ -4245,7 +4283,7 @@ class ControlWindow(AppKit.NSObject):
self.length_select = _DesignSliderChoice(tr("Length"), 25, 250, 5, 100, (0.5, 1.0, 2.0),
effects.LENGTHS, self._design_slider_changed,
tr("Sets the effect's playback time."))
- self.size_select = _DesignSliderChoice(tr("Size"), 20, 80, 1, 1000, (0.03, 0.045, 0.06),
+ self.size_select = _DesignSliderChoice(tr("Size"), 20, 250, 1, 1000, (0.03, 0.045, 0.06),
effects.SIZES, self._design_slider_changed,
tr("Sets effect depth relative to the shorter screen edge."))
self.length_readout = design_readout()
@@ -5110,6 +5148,7 @@ class TrayApp(rumps.App):
self.update_checker = updates.Checker(
VERSION, lambda: self.controller.cfg.check_updates,
lambda found: AppHelper.callAfter(self._update_found, found), logger=logger,
+ on_check=lambda state, found: AppHelper.callAfter(self.control_window.show_update_check, state, found),
)
self.control_window.update_checker = self.update_checker
self.control_window.update_handler = self._update_found
@@ -5124,6 +5163,8 @@ class TrayApp(rumps.App):
# One tick per direction, so either can be switched off while the other keeps working.
self.send_item = _tray_item(tr("This Mac drives other machines"), callback=self.toggle_send_to_windows)
self.receive_item = _tray_item(tr("Other machines drive this Mac"), callback=self.toggle_windows_drives)
+ self.dock_item = _tray_item(tr("Show in Dock"), callback=self.toggle_dock)
+ self.dock_item.state = self.settings_store.current().get("show_in_dock", True)
self._symbol = None
super().__init__(
"Beamer",
@@ -5140,6 +5181,7 @@ class TrayApp(rumps.App):
self.receive_item,
rumps.separator,
_tray_item(tr("Settings…"), callback=self.open_window),
+ self.dock_item,
_tray_item(tr("Reload configuration"), callback=self.reload_config),
_tray_item(tr("Open log folder"), callback=self.open_log_folder),
rumps.separator,
@@ -5158,18 +5200,21 @@ class TrayApp(rumps.App):
self.full_screen_timer.start()
self.update_checker.start()
- def _update_found(self, found):
+ def _update_found(self, found, manual=False):
"""On the main thread. The version line in the menu becomes the way to the download."""
- if not self.controller.cfg.check_updates:
+ if not manual and not self.controller.cfg.check_updates:
found = None
self.update_url = found[1] if found else None
- if found:
- _set_tray_title(self.header_item, tr("Beamer {version} is available…").format(version=found[0]))
+ notice = updates.visible_notice(found, self.controller.cfg.check_updates,
+ self.control_window.settings_store.current().get("dismissed_update_version", ""),
+ requested=manual)
+ if notice:
+ _set_tray_title(self.header_item, tr("Beamer {version} is available…").format(version=notice[0]))
self.header_item.set_callback(self.open_update)
else:
_set_tray_title(self.header_item, tr("Beamer {version}").format(version=VERSION))
self.header_item.set_callback(None)
- self.control_window.show_update(found)
+ self.control_window.show_update(found, manual=manual)
def open_update(self, _sender):
if self.update_url:
@@ -5351,11 +5396,17 @@ class TrayApp(rumps.App):
def open_window(self, _sender):
self.control_window.show()
+ def toggle_dock(self, _sender):
+ self.control_window._set_show_in_dock(not self.settings_store.current().get("show_in_dock", True))
+
def apply_activation_policy(self, window_open=None):
if window_open is None:
window_open = self.control_window.window.isVisible()
settings = self.settings_store.current()
show_in_dock = settings.get("show_in_dock", True)
+ dock_item = getattr(self, "dock_item", None)
+ if dock_item is not None:
+ dock_item.state = show_in_dock
policy = dock_visibility.activation_policy(show_in_dock, window_open)
AppKit.NSApp.setActivationPolicy_(
AppKit.NSApplicationActivationPolicyRegular
diff --git a/mac_app/machines_panel.py b/mac_app/machines_panel.py
index 3943495..4e60a1c 100644
--- a/mac_app/machines_panel.py
+++ b/mac_app/machines_panel.py
@@ -287,7 +287,8 @@ class MachinesPanel:
for r in rows))
key += (tuple(sorted(self.directions_open)),)
mode = getattr(getattr(self.owner, "shortcut_goes_to", None), "value", "last")
- key += (mode, tuple((entry.get("token"), entry.get("shortcut_cycle") is not False)
+ key += (mode, tuple((entry.get("token"), entry.get("shortcut_cycle") is not False,
+ entry.get("host_pinned") is not False)
for entry in self.controller.book.peers()))
if key != self._rows_key:
self._rows_key = key
@@ -365,6 +366,14 @@ class MachinesPanel:
widgets.add(body, widgets.note(tr("Left out of the layout. The shortcut and the menu still reach it.")).view)
widgets.add(body, widgets.note(self._shown(state.detail)).view)
entry = next((item for item in self.controller.book.peers() if item.get("token") == row.token), {})
+ if not row.phone:
+ pin = widgets.Switch(tr("Pin address"),
+ on_change=lambda on, t=row.token: self._direction(t, host_pinned=on))
+ pin.value = bool(entry.get("host")) and entry.get("host_pinned") is not False
+ pin.set_enabled(bool(entry.get("host")))
+ pin.view.setToolTip_(tr("Keeps this address through reconnects and re-pairing. Turn off to follow address changes automatically."))
+ pin.view.focus_id = (row.token, "host_pinned")
+ widgets.add(body, pin.view)
if not row.phone and getattr(getattr(self.owner, "shortcut_goes_to", None), "value", "last") == "ticked":
cycle = widgets.Switch(tr("In the shortcut's cycle"),
on_change=lambda on, peer=entry.get("id"): self.owner._set_shortcut_cycle(peer, on))
diff --git a/mac_app/settings_store.py b/mac_app/settings_store.py
index 1b9563e..8364d2d 100644
--- a/mac_app/settings_store.py
+++ b/mac_app/settings_store.py
@@ -383,10 +383,10 @@ class SettingsStore:
self.save_settings(outcome["settings"])
def set_peer(self, token, **switches):
- """Turns `send`, `allow_drive` and `in_use` on or off for the machine holding `token`; returns
+ """Turns a local peer switch 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")
+ if not switches or any(name not in ("send", "allow_drive", "in_use", "host_pinned") or not isinstance(value, bool) for name, value in switches.items()):
+ raise SettingsError("only send, allow_drive, in_use and host_pinned 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)
diff --git a/mac_app/setup.py b/mac_app/setup.py
index a6e5960..d41bbb1 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -75,8 +75,8 @@ setup(
"packages": ["rumps", "cffi", "nacl"],
# core/effects.py imports its fx_* modules by name at first use, which py2app's import
# scan cannot see, so they are named here or the bundle ships without a single effect.
- # The rest of core/ is 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.
+ # Other explicit imports supplement the dependency scan; naming core whole would ship
+ # its tests and Qt-only capture/portable modules too.
"includes": [
"objc", "AppKit", "ApplicationServices", "Quartz", "UserNotifications",
"core.crash_log", "core.effects", "core.i18n", "core.locale", "core.idle_pointer", "core.ignored", "core.keytable", "core.link", "core.owner", "core.pairing",
diff --git a/mac_app/tests/fixtures/effects_parity/qt_reference_frames.zip b/mac_app/tests/fixtures/effects_parity/qt_reference_frames.zip
index 3bd20ad..123992d 100644
Binary files a/mac_app/tests/fixtures/effects_parity/qt_reference_frames.zip and b/mac_app/tests/fixtures/effects_parity/qt_reference_frames.zip differ
diff --git a/mac_app/tests/test_dock_window.py b/mac_app/tests/test_dock_window.py
index ceebfc4..5f12152 100644
--- a/mac_app/tests/test_dock_window.py
+++ b/mac_app/tests/test_dock_window.py
@@ -25,6 +25,17 @@ REGULAR, ACCESSORY = AppKit.NSApplicationActivationPolicyRegular, AppKit.NSAppli
class DockWindowTests(unittest.TestCase):
+ def test_menu_bar_toggle_changes_the_saved_dock_choice_and_reflects_the_tick(self):
+ self.tray.control_window = self.window
+ self.tray.dock_item = types.SimpleNamespace(state=True)
+ self.tray.apply_activation_policy(window_open=False)
+ kvm_bridge_app.TrayApp.toggle_dock(self.tray, None)
+ self.assertFalse(self.store.current()["show_in_dock"])
+ self.assertFalse(self.tray.dock_item.state)
+ kvm_bridge_app.TrayApp.toggle_dock(self.tray, None)
+ self.assertTrue(self.store.current()["show_in_dock"])
+ self.assertTrue(self.tray.dock_item.state)
+
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
diff --git a/mac_app/tests/test_driven_mac.py b/mac_app/tests/test_driven_mac.py
index 41b35c9..f910f45 100644
--- a/mac_app/tests/test_driven_mac.py
+++ b/mac_app/tests/test_driven_mac.py
@@ -6,6 +6,7 @@ import logging
import os
import sys
import unittest
+from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -96,6 +97,78 @@ class InjectorCase(unittest.TestCase):
return [(e.fields["code"], e.fields["down"], e.fields["flags"]) for e in self.quartz.posted if e.kind == "key"]
+class UserActivityTests(InjectorCase):
+ def setUp(self):
+ super().setUp()
+ self._hid = mock.patch.object(injector, "_HID_QUARTZ", self.quartz)
+ self._hid.start()
+ injector._power_api = None
+ injector._power_assertion_id.value = 0
+ injector._power_last_activity = float("-inf")
+ injector._power_warning_logged = False
+ self.addCleanup(setattr, injector, "_power_api", None)
+ self.addCleanup(setattr, injector._power_assertion_id, "value", 0)
+
+ def tearDown(self):
+ # Stop treating the fake as the HID tap before release_all posts, so teardown never reaches real IOKit.
+ self._hid.stop()
+ super().tearDown()
+
+ def test_a_fake_quartz_never_declares_activity(self):
+ self._hid.stop()
+ call = mock.Mock(return_value=0)
+ with mock.patch.object(injector, "_load_power_api", return_value=(call, "activity-name")):
+ injector.inject_key("a", True)
+ self._hid.start()
+
+ self.assertEqual(len(self.quartz.posted), 1)
+ call.assert_not_called()
+
+ def test_remote_input_declares_user_activity_on_first_event(self):
+ call = mock.Mock(return_value=0)
+ with mock.patch.object(injector, "_load_power_api", return_value=(call, "activity-name")):
+ injector.inject_key("a", True)
+
+ call.assert_called_once_with("activity-name", injector._IOPM_USER_ACTIVE_LOCAL, mock.ANY)
+
+ def test_remote_input_activity_is_throttled_during_a_burst(self):
+ call = mock.Mock(return_value=0)
+ with mock.patch.object(injector, "_load_power_api", return_value=(call, "activity-name")), \
+ mock.patch.object(injector.time, "monotonic", side_effect=(10.0, 10.5)):
+ injector.inject_key("a", True)
+ injector.inject_key("a", False)
+
+ call.assert_called_once()
+
+ def test_remote_input_activity_is_declared_again_after_one_second(self):
+ call = mock.Mock(return_value=0)
+ with mock.patch.object(injector, "_load_power_api", return_value=(call, "activity-name")), \
+ mock.patch.object(injector.time, "monotonic", side_effect=(10.0, 11.0)):
+ injector.inject_key("a", True)
+ injector.inject_key("a", False)
+
+ self.assertEqual(call.call_count, 2)
+
+ def test_no_injected_input_does_not_declare_activity(self):
+ call = mock.Mock(return_value=0)
+ with mock.patch.object(injector, "_load_power_api", return_value=(call, "activity-name")):
+ with self.assertLogs(injector.LOGGER, "WARNING"):
+ injector.inject_key("unknown-key", True)
+
+ call.assert_not_called()
+
+ def test_a_failed_activity_call_does_not_stop_input_or_log_repeatedly(self):
+ call = mock.Mock(side_effect=OSError("IOKit unavailable"))
+ with mock.patch.object(injector, "_load_power_api", return_value=(call, "activity-name")), \
+ mock.patch.object(injector.time, "monotonic", side_effect=(10.0, 11.0)), \
+ self.assertLogs(injector.LOGGER, "WARNING") as logs:
+ injector.inject_key("a", True)
+ injector.inject_key("a", False)
+
+ self.assertEqual(len(self.quartz.posted), 2)
+ self.assertEqual(len(logs.records), 1)
+
+
class NavigationKeyFlagTests(InjectorCase):
"""A real arrow, F key, Home, End, Page Up, Page Down or forward delete carries the Fn flag
(arrows the numeric-pad flag too), and system shortcuts match on it, so every such key the PC
diff --git a/mac_app/tests/test_effect_layouts.py b/mac_app/tests/test_effect_layouts.py
index 399fa6c..b7fcb3a 100644
--- a/mac_app/tests/test_effect_layouts.py
+++ b/mac_app/tests/test_effect_layouts.py
@@ -130,34 +130,61 @@ class EveryLayoutTests(unittest.TestCase):
def test_an_effect_is_framed_as_its_display_alone(self):
seen = []
+ def probe(pen, s):
+ pen.moveTo(s.screen.w, s.screen.h)
+ seen.append(pen._path[-1][1:])
+ pen.moveTo(s.point.x, s.point.y)
+ seen.append(pen._path[-1][1:])
fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
- lambda pen, s: seen.append((s.screen.w, s.screen.h, s.point.x, s.point.y, s.edge)), 0.0, 0.5)
+ probe, 0.0, 0.5)
player = effects.Player()
player.arrive(0.0, "edge", (1730.0, 500.0), "left", (1728.0, 0.0, 1920.0, 1080.0))
player.frames(0.1, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
- self.assertEqual(seen, [(1920.0, 1080.0, 2.0, 500.0, "left")])
+ self.assertEqual(len(seen), 2)
+ for actual, expected in zip(seen, [(3648.0, 1080.0), (1730.0, 500.0)]):
+ self.assertEqual(len(actual), len(expected))
+ for got, want in zip(actual, expected):
+ self.assertAlmostEqual(got, want)
def test_an_edge_strip_along_the_whole_desktop_is_cut_to_the_display(self):
seen = []
- fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: seen.append(vars(s.region)),
+ def probe(pen, s):
+ r = s.region
+ pen.moveTo(r.x, r.y)
+ pen.lineTo(r.x + r.w, r.y + r.h)
+ seen.extend(pen._path)
+ fx = effects.Effect("probe", "Probe", "quiet", "", probe,
lambda pen, s: None, 0.5, 0.0)
player = effects.Player()
display = (1728.0, 0.0, 1920.0, 1080.0)
player.push(0.0, "edge", {"kind": "edge", "edge": "right", "x": 3647.0, "y": 0.0, "w": 1.0, "h": 1517.0},
(3647.0, 500.0), 0.5, display=display)
player.frames(0.0, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
- self.assertEqual((seen[0]["x"], seen[0]["y"], seen[0]["h"]), (1919.0, 0.0, 1080.0))
+ self.assertEqual(len(seen), 2)
+ for actual, expected in zip(seen, [("M", 3647.0, 0.0), ("L", 3648.0, 1080.0)]):
+ self.assertEqual(len(actual), len(expected))
+ self.assertEqual(actual[0], expected[0])
+ for got, want in zip(actual[1:], expected[1:]):
+ self.assertAlmostEqual(got, want)
def test_the_notch_is_only_seen_on_its_own_display(self):
seen = []
+ def probe(pen, s):
+ notch = getattr(s, "notch", None)
+ if notch is None:
+ seen.append(None)
+ else:
+ pen.moveTo(notch.x, notch.y)
+ seen.append(pen._path[-1][1:])
fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
- lambda pen, s: seen.append(getattr(s, "notch", None)), 0.0, 0.5)
+ probe, 0.0, 0.5)
displays = LAYOUTS["left of the primary"]
for display in displays:
player = effects.Player()
player.arrive(0.0, "edge", (display[0] + display[2] / 2.0, display[1] + 2.0), "top", display)
player.frames(0.1, fx, (3648.0, 1380.0, "mac"), PALETTE, False, True, notch_on(displays))
- self.assertEqual((seen[0].x, seen[0].y), (NOTCH["x"], 0.0))
+ self.assertAlmostEqual(seen[0][0], 1920.0 + NOTCH["x"])
+ self.assertAlmostEqual(seen[0][1], 0.0)
self.assertIsNone(seen[1])
diff --git a/mac_app/tests/test_effect_size_raster.py b/mac_app/tests/test_effect_size_raster.py
new file mode 100644
index 0000000..43c1535
--- /dev/null
+++ b/mac_app/tests/test_effect_size_raster.py
@@ -0,0 +1,7 @@
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.tests.effect_size_probe import NativeSizeRasterTests
diff --git a/mac_app/tests/test_machines_panel.py b/mac_app/tests/test_machines_panel.py
index 407b3ea..81a8100 100644
--- a/mac_app/tests/test_machines_panel.py
+++ b/mac_app/tests/test_machines_panel.py
@@ -183,6 +183,26 @@ class Base(unittest.TestCase):
class ListTests(Base):
+ def test_address_pin_can_be_released_and_restored_per_machine(self):
+ self.pair(FIRST, SECOND_TOKEN, "Studio", host_pinned=True)
+ self.window.direction_handler = lambda token, **change: self.store.set_peer(token, **change)
+ self.panel.refresh()
+
+ def pin_control():
+ stack = [self.row_with_control(SECOND_TOKEN, "host_pinned")]
+ while stack:
+ view = stack.pop()
+ if getattr(view, "focus_id", None) == (SECOND_TOKEN, "host_pinned"):
+ return view
+ stack.extend(view.subviews())
+
+ pin_control().press()
+ self.assertIs(self.store.current()["peers"][1]["host_pinned"], False)
+ self.store.save(settings_store.config_to_raw(self.store.load()))
+ self.panel.refresh()
+ pin_control().press()
+ self.assertIs(self.store.current()["peers"][1]["host_pinned"], True)
+
def test_renaming_a_machine_saves_on_return_and_escape_cancels(self):
self.pair(FIRST, SECOND_TOKEN, "Studio")
self.panel.refresh()
@@ -313,13 +333,14 @@ class DirectionAndRemovalTests(Base):
self.panel.refresh()
row = self.rows()[0]
self.assertEqual(len([view for view in self.descend(row)
- if view.accessibilityRole() == AppKit.NSAccessibilityCheckBoxRole]), 1)
+ if view.accessibilityRole() == AppKit.NSAccessibilityCheckBoxRole]), 2)
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), 3)
- switches[1].callback()
- switches[2].callback()
+ self.assertEqual(len(switches), 4)
+ for view in switches:
+ if getattr(view, "focus_id", (None, None))[1] in ("drives", "driven"):
+ view.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",)})
diff --git a/mac_app/tests/test_settings_layout_acceptance.py b/mac_app/tests/test_settings_layout_acceptance.py
index 30620b5..d8214ba 100644
--- a/mac_app/tests/test_settings_layout_acceptance.py
+++ b/mac_app/tests/test_settings_layout_acceptance.py
@@ -331,9 +331,30 @@ class SettingsLayoutAcceptanceTests(unittest.TestCase):
with self.subTest(dark=dark, width=width):
for family in control.glow_style_select.rows:
self.assertEqual(family.columns, 3 if column >= 600 else 2 if column >= 400 else 1)
- self.assertEqual(control.length_row.field_owner.stacked, column < 560)
+ if column < 560:
+ self.assertTrue(control.length_row.field_owner.stacked)
+ elif column >= 576:
+ self.assertFalse(control.length_row.field_owner.stacked)
self.assertEqual(control.sidebar.rows['design'][3].view.isHidden(), width < 640)
+ def test_design_rows_stay_stacked_through_the_sidebar_width_change(self):
+ control = offscreen_control_window()
+ control._select_page("design")
+ settle(control.window)
+ for width, stacked in ((760, True), (780, True), (800, True), (820, False),
+ (800, True), (780, True), (760, True)):
+ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)
+ settle(control.window)
+ self.assertAlmostEqual(control.window.frame().size.width, width, delta=.5)
+ self.assertFalse(control.window.isVisible())
+ for name, row in (("Length", control.length_row), ("Size", control.size_row)):
+ owner = row.field_owner
+ self.assertEqual(owner.stacked, stacked, f"{name} at window width {width}")
+ frame = owner.control.frame()
+ self.assertGreater(frame.size.width, 0)
+ self.assertGreaterEqual(frame.origin.x, -.5)
+ self.assertLessEqual(frame.origin.x + frame.size.width, row.bounds().size.width + 1)
+
def test_long_buttons_grow_in_height_and_machine_names_remain_available(self):
button = widgets.Button('A longer action whose full label needs several lines in this column', None, None)
host = widgets.box()
diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.py
index 1fe7125..c87c5d9 100644
--- a/mac_app/tests/test_settings_store.py
+++ b/mac_app/tests/test_settings_store.py
@@ -15,6 +15,16 @@ from settings_store import SettingsError, SettingsStore, config_to_raw
class SettingsStoreTests(unittest.TestCase):
+ def test_unpin_survives_flat_saves_and_reload(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "settings.json"
+ store = SettingsStore(path)
+ store.save(self.valid_raw(), pin_address=True)
+ token = store.current()["peers"][0]["token"]
+ store.set_peer(token, host_pinned=False)
+ store.save(config_to_raw(store.load()))
+ self.assertIs(SettingsStore(path).current()["peers"][0]["host_pinned"], False)
+
def test_explicitly_saving_the_same_learnt_host_pins_it(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "settings.json"
diff --git a/mac_app/tests/test_update_notice.py b/mac_app/tests/test_update_notice.py
index 30eca8e..0466943 100644
--- a/mac_app/tests/test_update_notice.py
+++ b/mac_app/tests/test_update_notice.py
@@ -6,12 +6,116 @@ from unittest import mock
import kvm_bridge_app as kvm
import settings_store
import test_crossing_page_machines as fixture
+from core import updates
-FOUND = ("1.5.11", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.11")
+FOUND = updates.Release("1.5.11", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.11")
class UpdateNoticeTest(fixture.Page):
+ def test_hidden_notice_does_not_keep_a_width_link_to_the_window(self):
+ window = self.build([])
+ notice = window.update_notice.view
+
+ def window_width_links():
+ pending = [window.window.contentView()]
+ links = []
+ while pending:
+ view = pending.pop()
+ pending.extend(view.subviews())
+ links.extend(constraint for constraint in view.constraints()
+ if constraint.isActive() and constraint.firstItem() == notice
+ and constraint.firstAttribute() == kvm.AppKit.NSLayoutAttributeWidth
+ and constraint.secondAttribute() == kvm.AppKit.NSLayoutAttributeWidth)
+ return links
+
+ self.assertTrue(notice.isHidden())
+ self.assertEqual(window_width_links(), [])
+ window.show_update(FOUND)
+ self.assertFalse(notice.isHidden())
+ self.assertEqual(len(window_width_links()), 1)
+ window.dismissUpdate_(None)
+ self.assertTrue(notice.isHidden())
+ self.assertEqual(window_width_links(), [])
+ window.show_update_check("available", FOUND)
+ self.assertFalse(notice.isHidden())
+ self.assertEqual(len(window_width_links()), 1)
+
+ def test_quiet_patch_stays_on_updates_page_even_when_explicitly_requested(self):
+ window = self.build([])
+ quiet = updates.newer_release("1.5.10", {"tag_name": "v1.5.12"})
+ window.show_update(quiet)
+ self.assertTrue(window.update_notice.view.isHidden())
+ self.assertFalse(window.update_button.view.isHidden())
+ self.assertFalse(window.update_page_notes.view.isHidden())
+ self.assertIn("1.5.12", window.update_status.view.stringValue())
+ window._set_check_updates(False)
+ window.show_update_check("available", quiet)
+ self.assertTrue(window.update_notice.view.isHidden())
+ self.assertIn("1.5.12", window.update_status.view.stringValue())
+
+ def test_quiet_patch_does_not_change_menu_header_but_important_release_does_once(self):
+ window = self.build([])
+ header = SimpleNamespace(title="", set_callback=lambda cb: setattr(header, "callback", cb))
+ tray = SimpleNamespace(controller=self.controller, control_window=window, header_item=header,
+ open_update=lambda _sender: None, update_url=None)
+ window.update_handler = lambda found, **kw: kvm.TrayApp._update_found(tray, found, **kw)
+ window.update_handler(updates.newer_release("1.5.10", {"tag_name": "v1.5.11"}))
+ self.assertIsNone(header.callback)
+ self.assertNotIn("available", header.title)
+ important = updates.newer_release("1.5.10", {
+ "tag_name": "v1.5.12", "body": "<!-- beamer-notify: important -->"})
+ window.update_handler(important)
+ self.assertIsNotNone(header.callback)
+ window.dismissUpdate_(None)
+ window.update_handler(important)
+ self.assertTrue(window.update_notice.view.isHidden())
+ self.assertIsNone(header.callback)
+
+ def test_explicit_check_resurfaces_a_dismissed_action_until_dismissed_again(self):
+ window = self.build([])
+ window.show_update(FOUND)
+ window.dismissUpdate_(None)
+ window._set_check_updates(False)
+ window.show_update_check("available", FOUND)
+ self.assertFalse(window.update_notice.view.isHidden())
+ window.dismissUpdate_(None)
+ self.assertTrue(window.update_notice.view.isHidden())
+
+ def test_manual_check_is_visible_and_works_when_automatic_checks_are_off(self):
+ window = self.build([])
+ window._set_check_updates(False)
+ window.update_checker = mock.Mock()
+ self.assertFalse(window.check_updates_button.view.isHidden())
+ self.assertEqual(window.check_updates_button.view.title(), "Check for updates")
+ window.check_updates_button.view.performClick_(None)
+ window.update_checker.check_now.assert_called_once_with(manual=True)
+ self.assertFalse(self.controller.cfg.check_updates)
+ self.assertFalse(window.check_updates_button.view.isEnabled())
+ window.show_update_check("available", FOUND)
+ self.assertFalse(window.update_notice.view.isHidden())
+ self.assertFalse(window.update_button.view.isHidden())
+ self.assertIn("1.5.11", window.update_status.view.stringValue())
+ self.assertTrue(window.check_updates_button.view.isEnabled())
+
+ def test_manual_check_reports_no_update_and_retryable_failure(self):
+ window = self.build([])
+ window.show_update_check("current", None)
+ self.assertIn("up to date", window.update_status.view.stringValue())
+ window.show_update_check("checking", None)
+ self.assertFalse(window.check_updates_button.view.isEnabled())
+ window.show_update_check("failed", None)
+ self.assertIn("try again", window.update_status.view.stringValue())
+ self.assertTrue(window.check_updates_button.view.isEnabled())
+
+ def test_update_notice_has_an_explicit_update_action(self):
+ window = self.build([])
+ workspace = mock.Mock()
+ with mock.patch.object(kvm.AppKit, "NSWorkspace", SimpleNamespace(sharedWorkspace=lambda: workspace)):
+ window.show_update(FOUND)
+ window.update_action.view.performClick_(None)
+ self.assertEqual(workspace.openURL_.call_args.args[0].absoluteString(), FOUND[1])
+
def test_dismissal_survives_rebuilding_and_other_settings_changes(self):
window = self.build([])
window.show_update(FOUND)
@@ -26,7 +130,7 @@ class UpdateNoticeTest(fixture.Page):
window = self.build([])
window.show_update(FOUND)
self.assertTrue(window.update_notice.view.isHidden())
- window.show_update(("1.5.12", FOUND[1]))
+ window.show_update(updates.Release("1.5.12", FOUND[1]))
self.assertFalse(window.update_notice.view.isHidden())
def test_switching_off_hides_the_notice_and_late_answers(self):
diff --git a/mac_app/widgets.py b/mac_app/widgets.py
index 59da4dc..5029847 100644
--- a/mac_app/widgets.py
+++ b/mac_app/widgets.py
@@ -957,7 +957,8 @@ class FieldRow:
self.arrange(640)
def arrange(self, width):
- stacked = self.caption is None or width < 528
+ # The sidebar expands at 800 pt, briefly narrowing the page while the window grows.
+ stacked = self.caption is None or width < (544 if self.stacked is True else 528)
if self.selector is not None:
self.selector.set_available_width(max(0, width - (0 if stacked else 196)))
if stacked == self.stacked:
diff --git a/tools/import_probe.py b/tools/import_probe.py
index 0666b5f..736d236 100644
--- a/tools/import_probe.py
+++ b/tools/import_probe.py
@@ -31,6 +31,11 @@ def module_names(platform: str) -> list:
folder, entry, extra = APPS[platform]
own = sorted(path.stem for path in (REPO / folder).glob("*.py") if path.stem not in entry)
core = sorted(f"core.{path.stem}" for path in (REPO / "core").glob("*.py") if path.stem != "__init__")
+ if platform == "mac":
+ # Qt capture and Windows portable state have no callers in the Mac app.
+ core = [name for name in core if name not in {
+ "core.capture_types", "core.portable_runtime", "core.portable_store",
+ }]
return ["core"] + core + own + extra
diff --git a/tools/release_body.py b/tools/release_body.py
new file mode 100644
index 0000000..279b697
--- /dev/null
+++ b/tools/release_body.py
@@ -0,0 +1,24 @@
+"""Prepare GitHub release notes locally with explicit notification metadata."""
+
+import argparse
+from pathlib import Path
+import sys
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--notes", type=Path, required=True)
+ parser.add_argument("--notify", choices=("quiet", "important"))
+ args = parser.parse_args()
+ lines = args.notes.read_text(encoding="utf-8").splitlines()
+ marks = [line.strip() for line in lines if "beamer-notify:" in line]
+ valid = {f"<!-- beamer-notify: {kind} -->": kind for kind in ("quiet", "important")}
+ if len(marks) > 1 or any(mark not in valid for mark in marks):
+ parser.error("notes must contain at most one valid beamer-notify metadata line")
+ kind = args.notify or (valid[marks[0]] if marks else "quiet")
+ notes = "\n".join(line for line in lines if "beamer-notify:" not in line).strip()
+ sys.stdout.write(f"<!-- beamer-notify: {kind} -->\n\n{notes}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/win_app/Beamer-Setup.iss b/win_app/Beamer-Setup.iss
index b4d93a7..101315b 100644
--- a/win_app/Beamer-Setup.iss
+++ b/win_app/Beamer-Setup.iss
@@ -21,28 +21,36 @@ DisableProgramGroupPage=yes
OutputBaseFilename=Beamer-Setup-{#AppVersion}
Compression=lzma2/max
SolidCompression=yes
-; The installer itself still runs per-user; Beamer.exe carries its own requireAdministrator
-; manifest (see build.spec) so SendInput can reach elevated windows. Explorer honours that
-; manifest automatically (UAC shield on the shortcuts), no change needed here for that part.
+; File installation and every Beamer operation stay with the original user. Only the fixed
+; maintenance script requests administrator permission.
PrivilegesRequired=lowest
UninstallDisplayIcon={app}\Beamer.exe
-; The single-instance mutex Beamer.exe holds. A running Beamer is elevated, so this per-user setup
-; can neither close it nor replace its locked exe; setup asks for it to be quit from the tray first.
+; An older elevated receiver must still be quit before its executable can be replaced.
AppMutex=Beamer.Receiver
SetupIconFile=Beamer.ico
; Beamer.exe is x64. This refuses 32-bit Windows with the installer's own message; Windows 11 on
; ARM is allowed, as it runs x64 apps under emulation.
ArchitecturesAllowed=x64compatible
+; When build_win_app.ps1 passes /DSignInstaller and /Sbeamer=..., ISCC signs the setup engine
+; extracted to %TEMP% during install and the uninstaller (SignedUninstaller). Without the define,
+; local builds without a certificate still compile an unsigned installer.
+#ifdef SignInstaller
+SignTool=beamer
+SignedUninstaller=yes
+#endif
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Tasks]
; Autostart is asked for, never assumed, so it starts unticked.
-Name: "autostart"; Description: "Start Beamer elevated at sign-in without another UAC prompt"; GroupDescription: "Startup options:"; Flags: unchecked
+Name: "autostart"; Description: "Start Beamer at sign-in"; GroupDescription: "Startup options:"; Flags: unchecked
[Files]
+Source: "Invoke-InstallMaintenance.ps1"; Flags: dontcopy
Source: "dist\Beamer.exe"; DestDir: "{app}"; Flags: ignoreversion
+Source: "Install-Maintenance.ps1"; DestDir: "{app}"; Flags: ignoreversion
+Source: "Invoke-InstallMaintenance.ps1"; DestDir: "{app}"; Flags: ignoreversion
[Icons]
; The same paths Install-Beamer.ps1 writes, so either installer replaces the other's shortcuts
@@ -50,46 +58,46 @@ Source: "dist\Beamer.exe"; DestDir: "{app}"; Flags: ignoreversion
Name: "{autoprograms}\Beamer"; Filename: "{app}\Beamer.exe"
[InstallDelete]
-; Remove pre-task autostart entries. A Startup shortcut launches the requireAdministrator exe
-; through Explorer and raises UAC on every sign-in, even when the scheduled task is also present.
+; Remove pre-task autostart entries so there is only one starter.
Type: files; Name: "{userstartup}\Beamer.lnk"
[Registry]
; The same legacy Run entry has the same UAC behaviour as the old Startup shortcut.
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueName: "Beamer"; Flags: deletevalue
-[Run]
-; CreateProcess refuses a requireAdministrator exe from this non-elevated setup (error 740);
-; shellexec lets Windows raise the UAC prompt instead.
-Filename: "{app}\Beamer.exe"; Description: "{cm:LaunchProgram,Beamer}"; Flags: nowait postinstall skipifsilent shellexec
-
[UninstallRun]
-; The elevated app reads the interactive account from the session, then removes its task, the
-; legacy global task and firewall rules without relying on the UAC administrator's identity.
-Filename: "{app}\Beamer.exe"; Parameters: "--uninstall-cleanup"; Flags: runhidden shellexec waituntilterminated; Verb: runas; RunOnceId: "BeamerCleanup"
+; The same fixed maintenance entry removes only this user's tasks and this executable's rules.
+Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ""{app}\Invoke-InstallMaintenance.ps1"" -ExePath ""{app}\Beamer.exe"" -Remove"; Flags: runhidden waituntilterminated; RunOnceId: "BeamerCleanup"
[Code]
-function RunTaskOperation(const Filename, Params: String; var ResultCode: Integer): Boolean;
-begin
- if IsAdmin then
- Result := Exec(Filename, Params, '', SW_HIDE, ewWaitUntilTerminated, ResultCode)
- else
- Result := ShellExec('runas', Filename, Params, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
-end;
-
-function TaskCommandFailure(const Action: String; const Started: Boolean; const ResultCode: Integer): String;
+function OperationFailure(const Action: String; const Started: Boolean; const ResultCode: Integer): String;
begin
if (not Started) and (ResultCode = 1223) then
Result := 'You cancelled the permission request.'
else if not Started then
- Result := 'Windows could not start the task operation: ' + SysErrorMessage(ResultCode)
+ Result := 'Windows could not start the installer operation: ' + SysErrorMessage(ResultCode)
else
Result := 'Windows returned exit code ' + IntToStr(ResultCode) + '.';
Result := Action + ' ' + Result;
end;
-// Keep the old elevated starter until first run migrates it successfully. This also preserves
-// autostart when a silent upgrade does not launch Beamer after replacing the executable.
+function PowerShellPath: String;
+begin
+ Result := ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe');
+end;
+
+function InitializeSetup: Boolean;
+var
+ ResultCode: Integer;
+ Started: Boolean;
+begin
+ ExtractTemporaryFile('Invoke-InstallMaintenance.ps1');
+ Started := Exec(PowerShellPath, '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' +
+ ExpandConstant('{tmp}\Invoke-InstallMaintenance.ps1') + '" -CheckIdentityOnly', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
+ Result := Started and (ResultCode = 0);
+ if not Result then
+ MsgBox('Beamer must be installed by the signed-in user. Run the installer normally; give administrator permission only when maintenance asks.', mbError, MB_OK);
+end;
procedure CurStepChanged(CurStep: TSetupStep);
var
@@ -97,14 +105,20 @@ var
Started: Boolean;
Failure: String;
begin
- if (CurStep = ssPostInstall) and WizardIsTaskSelected('autostart') then
+ if CurStep = ssPostInstall then
begin
- Started := RunTaskOperation(ExpandConstant('{app}\Beamer.exe'), '--enable-autostart', ResultCode);
+ Started := Exec(PowerShellPath, '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' +
+ ExpandConstant('{app}\Invoke-InstallMaintenance.ps1') + '" -ExePath "' +
+ ExpandConstant('{app}\Beamer.exe') + '"', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
+ if (not Started) or (ResultCode <> 0) then
+ RaiseException(OperationFailure('Beamer was installed, but administrator maintenance did not complete.', Started, ResultCode));
+ if not WizardIsTaskSelected('autostart') then Exit;
+ Started := Exec(ExpandConstant('{app}\Beamer.exe'), '--enable-autostart', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
if (not Started) or (ResultCode <> 0) then
begin
- Failure := TaskCommandFailure('Could not run Beamer sign-in setup.', Started, ResultCode);
+ Failure := OperationFailure('Could not run Beamer sign-in setup.', Started, ResultCode);
Log(Failure);
- RaiseException('Beamer was installed, but start at sign-in was not configured. It requires Beamer and the signed-in session to use the same administrator account. ' + Failure);
+ RaiseException('Beamer was installed, but start at sign-in was not configured. ' + Failure);
end;
end;
end;
diff --git a/win_app/Install-Beamer.ps1 b/win_app/Install-Beamer.ps1
index 9283f03..edf85ed 100644
--- a/win_app/Install-Beamer.ps1
+++ b/win_app/Install-Beamer.ps1
@@ -11,21 +11,22 @@ trap {
break
}
+$PowerShellPath = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
+$MaintenanceLauncher = Join-Path $PSScriptRoot 'Invoke-InstallMaintenance.ps1'
+& $PowerShellPath -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $MaintenanceLauncher -CheckIdentityOnly
+if ($LASTEXITCODE -ne 0) { throw 'The installer must run for the signed-in user.' }
+
$InstallDir = Join-Path $env:LOCALAPPDATA 'Beamer'
$ExeSource = Join-Path $PSScriptRoot 'dist\Beamer.exe'
$ExeDestination = Join-Path $InstallDir 'Beamer.exe'
-# Beamer.exe now carries a requireAdministrator manifest (build.spec uac_admin=True) so
-# SendInput can reach elevated windows, e.g. an admin terminal, which UIPI otherwise
-# silently discards input for. The firewall rules below need this session elevated too.
-$IsElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
-
& "$PSScriptRoot\build_win_app.ps1"
if (-not (Test-Path $ExeSource)) { throw 'The Windows build did not produce Beamer.exe' }
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
-Get-Process 'Beamer' -ErrorAction SilentlyContinue | Stop-Process -Force
-Get-Process 'Beamer' -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
+$InstalledProcesses = @(Get-Process 'Beamer' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $ExeDestination })
+$InstalledProcesses | Stop-Process -Force
+$InstalledProcesses | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
# The exe can stay locked for a moment after the process has gone: the copy can fail with
# "being used by another process" straight after Wait-Process returns, and succeed on a rerun.
for ($attempt = 1; ; $attempt++) {
@@ -49,44 +50,17 @@ $StartMenuShortcut.Save()
# No installer writes a desktop shortcut; delete any this or an older install left.
Remove-Item -Path (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Beamer.lnk') -Force -ErrorAction SilentlyContinue
-# Startup used to be a plain shortcut in the Startup folder. Explorer launches a
-# requireAdministrator exe from there with a UAC prompt on every logon instead of
-# starting silently, so startup is now a Scheduled Task (RunLevel Highest) instead.
-# Remove any shortcut left behind by a previous install so there isn't a second starter.
+# Remove pre-task startup entries so there is only one starter.
$StartupPath = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup\Beamer.lnk'
Remove-Item -Path $StartupPath -Force -ErrorAction SilentlyContinue
# Defensively remove a legacy Run-key entry too, in case an older install used one instead.
Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'Beamer' -ErrorAction SilentlyContinue
-if ($IsElevated) {
- # Start at logon belongs to the app: the switch on its Overview page writes and removes the
- # Beamer task, and the installer never does, on install or reinstall.
- try {
- Get-NetFirewallRule -DisplayName 'Beamer Receiver (TCP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
- # 24820 and 24821, not the old 51820/51821: those sat inside the 49152-65535 range
- # Windows hands out for itself, and a WinNAT reservation landing on the receiver's port
- # left the PC unable to listen while its outward link carried on working.
- New-NetFirewallRule -DisplayName 'Beamer Receiver (TCP-In)' -Direction Inbound -Protocol TCP -LocalPort 24820 -Action Allow -Profile Private -Program $ExeDestination | Out-Null
- # The pairing beacon answers the Mac on UDP 24821; without this the Mac never sees the PC.
- Get-NetFirewallRule -DisplayName 'Beamer Pairing (UDP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
- New-NetFirewallRule -DisplayName 'Beamer Pairing (UDP-In)' -Direction Inbound -Protocol UDP -LocalPort 24821 -Action Allow -Profile Private -Program $ExeDestination | Out-Null
- # The pairing exchange itself runs over TCP on the same number while a code is on screen.
- Get-NetFirewallRule -DisplayName 'Beamer Pairing (TCP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
- New-NetFirewallRule -DisplayName 'Beamer Pairing (TCP-In)' -Direction Inbound -Protocol TCP -LocalPort 24821 -Action Allow -Profile Private -Program $ExeDestination | Out-Null
- Write-Host 'Private-network firewall rules installed (TCP 24820 receiver, UDP and TCP 24821 pairing).' -ForegroundColor Green
- } catch {
- Write-Host "Could not install the firewall rule: $_" -ForegroundColor Yellow
- }
-} else {
- Write-Host 'This session is not elevated, so the firewall rules were not configured. Re-run this installer from an admin PowerShell.' -ForegroundColor Yellow
-}
+& $PowerShellPath -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $MaintenanceLauncher -ExePath $ExeDestination
+if ($LASTEXITCODE -ne 0) { throw 'Beamer was installed, but administrator maintenance did not complete.' }
-# Beamer.exe is manifested requireAdministrator, so launching it from a non-elevated
-# session needs an explicit elevation request; from an already-elevated session this
-# just runs it without a further prompt.
if ($Interactive) {
- Start-Process -FilePath $ExeDestination -WorkingDirectory $InstallDir -Verb RunAs
Write-Host "Beamer installed at $ExeDestination" -ForegroundColor Green
Read-Host 'Press Enter to close'
} else {
diff --git a/win_app/Install-Maintenance.ps1 b/win_app/Install-Maintenance.ps1
new file mode 100644
index 0000000..ee86876
--- /dev/null
+++ b/win_app/Install-Maintenance.ps1
@@ -0,0 +1,104 @@
+[CmdletBinding()]
+param(
+ [string]$ExePath,
+ [string]$UserSid,
+ [switch]$Remove
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Resolve-BeamerUserSid([string]$Identity) {
+ if ($Identity -match '^S-1-') {
+ return ([Security.Principal.SecurityIdentifier]$Identity).Value
+ }
+ return ([Security.Principal.NTAccount]$Identity).Translate([Security.Principal.SecurityIdentifier]).Value
+}
+
+function Update-BeamerAutostart([string]$ExePath, [string]$UserSid, [switch]$Remove) {
+ $expectedPath = [IO.Path]::GetFullPath($ExePath)
+ foreach ($task in @(Get-ScheduledTask -TaskPath '\' -ErrorAction Stop)) {
+ if ($task.TaskName -ne 'Beamer' -and $task.TaskName -notlike 'Beamer-*') { continue }
+ [xml]$xml = Export-ScheduledTask -TaskName $task.TaskName -TaskPath '\' -ErrorAction Stop
+ $ns = New-Object Xml.XmlNamespaceManager($xml.NameTable)
+ $ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
+ $principals = $xml.SelectNodes('/t:Task/t:Principals/t:Principal', $ns)
+ $actions = $xml.SelectNodes('/t:Task/t:Actions/*', $ns)
+ if ($principals.Count -ne 1 -or $actions.Count -ne 1 -or $actions[0].LocalName -ne 'Exec') { continue }
+ $principal = $principals[0]
+ if ($principal.LogonType -ne 'InteractiveToken') { continue }
+ try {
+ if ((Resolve-BeamerUserSid $principal.UserId) -ne $UserSid) { continue }
+ $command = [string]$actions[0].Command
+ if (-not [IO.Path]::IsPathRooted($command)) { continue }
+ if (-not [string]::Equals([IO.Path]::GetFullPath($command), $expectedPath, [StringComparison]::OrdinalIgnoreCase)) { continue }
+ } catch { continue }
+ if ($Remove) {
+ Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath '\' -Confirm:$false -ErrorAction Stop
+ continue
+ }
+ if ($principal.RunLevel -ne 'HighestAvailable') { continue }
+ # Keep the existing task definition: disabled startup, arguments and logon triggers are user choices.
+ $principal.RunLevel = 'LeastPrivilege'
+ Register-ScheduledTask -TaskName $task.TaskName -TaskPath '\' -Xml $xml.OuterXml -Force -ErrorAction Stop | Out-Null
+ }
+}
+
+function Remove-BeamerFirewall([string]$ExePath) {
+ foreach ($name in @('Beamer Receiver (TCP-In)', 'Beamer Pairing (UDP-In)', 'Beamer Pairing (TCP-In)')) {
+ foreach ($rule in @(Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue)) {
+ $filter = $rule | Get-NetFirewallApplicationFilter -ErrorAction Stop
+ if ([string]::Equals($filter.Program, $ExePath, [StringComparison]::OrdinalIgnoreCase)) {
+ $rule | Remove-NetFirewallRule -ErrorAction Stop
+ }
+ }
+ }
+}
+
+function Repair-BeamerFirewall([string]$ExePath) {
+ Remove-BeamerFirewall -ExePath $ExePath
+ $rules = @(
+ @{ Name = 'Beamer Receiver (TCP-In)'; Protocol = 'TCP'; Port = 24820 },
+ @{ Name = 'Beamer Pairing (UDP-In)'; Protocol = 'UDP'; Port = 24821 },
+ @{ Name = 'Beamer Pairing (TCP-In)'; Protocol = 'TCP'; Port = 24821 }
+ )
+ foreach ($rule in $rules) {
+ New-NetFirewallRule -DisplayName $rule.Name -Direction Inbound -Protocol $rule.Protocol -LocalPort $rule.Port -Action Allow -Profile Private -Program $ExePath -ErrorAction Stop | Out-Null
+ }
+}
+
+function Repair-BeamerGameInput {
+ if (Get-Service -Name 'GameInputSvc' -ErrorAction SilentlyContinue) {
+ try {
+ Restart-Service -Name 'GameInputSvc' -ErrorAction Stop
+ } catch {
+ # The receiver can still run; its remote controller reports when a local click is needed.
+ Write-Warning 'GameInput could not be restarted. A local click may be needed to release remote controller focus.'
+ }
+ }
+}
+
+if ($MyInvocation.InvocationName -ne '.') {
+ try {
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)
+ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
+ throw 'Installer maintenance requires administrator permission.'
+ }
+ if (-not [IO.Path]::IsPathRooted($ExePath) -or [IO.Path]::GetFileName($ExePath) -ine 'Beamer.exe' -or -not (Test-Path -LiteralPath $ExePath -PathType Leaf)) {
+ throw 'Installer maintenance requires the installed Beamer.exe path.'
+ }
+ $ExePath = [IO.Path]::GetFullPath($ExePath)
+ $UserSid = ([Security.Principal.SecurityIdentifier]$UserSid).Value
+ Update-BeamerAutostart -ExePath $ExePath -UserSid $UserSid -Remove:$Remove
+ if ($Remove) {
+ Remove-BeamerFirewall -ExePath $ExePath
+ } else {
+ Repair-BeamerFirewall -ExePath $ExePath
+ Repair-BeamerGameInput
+ }
+ exit 0
+ } catch {
+ Write-Error $_ -ErrorAction Continue
+ exit 1
+ }
+}
diff --git a/win_app/Invoke-InstallMaintenance.ps1 b/win_app/Invoke-InstallMaintenance.ps1
new file mode 100644
index 0000000..9177d4e
--- /dev/null
+++ b/win_app/Invoke-InstallMaintenance.ps1
@@ -0,0 +1,37 @@
+[CmdletBinding()]
+param([string]$ExePath, [switch]$CheckIdentityOnly, [switch]$Remove)
+
+$ErrorActionPreference = 'Stop'
+try {
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)
+ $UserSid = $identity.User.Value
+ $IsElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+ if ($IsElevated) {
+ $sessionId = (Get-Process -Id $PID).SessionId
+ foreach ($shell in @(Get-CimInstance -ClassName Win32_Process -Filter "Name='explorer.exe' AND SessionId=$sessionId" -ErrorAction Stop)) {
+ $owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwnerSid -ErrorAction Stop
+ if ($owner.ReturnValue -ne 0 -or $owner.Sid -ne $UserSid) {
+ throw 'Beamer must be installed by the signed-in user. Run the installer normally; give administrator permission only when maintenance asks.'
+ }
+ }
+ }
+ if ($CheckIdentityOnly) { exit 0 }
+ $MaintenancePath = Join-Path $PSScriptRoot 'Install-Maintenance.ps1'
+ $PowerShellPath = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
+ # -File passes literal arguments, including apostrophes and shell metacharacters in profile paths.
+ # These paths end in fixed filenames, so Windows command-line quoting cannot swallow a closing quote.
+ if ($ExePath.Contains('"') -or $MaintenancePath.Contains('"')) { throw 'Invalid installer path.' }
+ $arguments = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "{0}" -ExePath "{1}" -UserSid "{2}"' -f $MaintenancePath, $ExePath, $UserSid
+ if ($Remove) { $arguments += ' -Remove' }
+ if ($IsElevated) {
+ $process = Start-Process -FilePath $PowerShellPath -ArgumentList $arguments -WindowStyle Hidden -Wait -PassThru
+ } else {
+ $process = Start-Process -FilePath $PowerShellPath -ArgumentList $arguments -Verb RunAs -WindowStyle Hidden -Wait -PassThru
+ }
+ if ($process.ExitCode -ne 0) { throw "Installer maintenance failed (exit code $($process.ExitCode))." }
+ exit 0
+} catch {
+ Write-Error $_ -ErrorAction Continue
+ exit 1
+}
diff --git a/win_app/app_config.py b/win_app/app_config.py
index 94891ba..cff507b 100644
--- a/win_app/app_config.py
+++ b/win_app/app_config.py
@@ -345,7 +345,7 @@ def validate_config(config: Config) -> None:
if not effects.valid_effect_pace(config.effect_pace):
raise ConfigError("effect_pace must be a number from 0.25 to 2.5")
if not effects.valid_effect_size_fraction(config.effect_size_fraction):
- raise ConfigError("effect_size_fraction must be a number from 0.02 to 0.08")
+ raise ConfigError("effect_size_fraction must be a number from 0.02 to 0.25")
if config.frame_rate not in tuple(value for value, _name, _divisor in effects.FRAME_RATES):
raise ConfigError("frame_rate must be one of: display, half, quarter")
if not isinstance(config.paired_with, str):
diff --git a/win_app/autostart_win.py b/win_app/autostart_win.py
index 5fcfcbe..8b413ee 100644
--- a/win_app/autostart_win.py
+++ b/win_app/autostart_win.py
@@ -1,12 +1,8 @@
"""Start at logon, owned by the app: each interactive account has its own scheduled task, so there
is no config field to disagree with it.
-A scheduled task rather than a Run key or a Startup shortcut: Beamer.exe is manifested
-requireAdministrator, and Explorer starts such an exe from either of those with a UAC prompt on
-every logon. A task with the highest run level starts it elevated and silently for an
-administrator account. Windows cannot do that for a standard account without storing another
-user's credentials, so the switch is unavailable when a different administrator approved this
-launch.
+The task uses the signed-in user's ordinary token, including standard accounts. The installer
+lowers old elevated tasks without changing whether the user enabled them.
Registered from XML, not `schtasks /create /sc onlogon`: that form cannot set a working directory
and gives every task a 72-hour execution limit, which would stop Beamer three days after logon.
@@ -92,7 +88,7 @@ def task_name(user: str) -> str:
def can_run_for_current_user() -> bool:
- """The requireAdministrator app can start silently only for the account that elevated it."""
+ """Do not configure another user's session after an over-the-shoulder administrator launch."""
return current_user().casefold() == _process_user().casefold()
@@ -114,7 +110,7 @@ def task_xml(exe: str, user: str, arguments: str = "--hidden") -> str:
<Principal id="Author">
<UserId>{escape(user)}</UserId>
<LogonType>InteractiveToken</LogonType>
- <RunLevel>HighestAvailable</RunLevel>
+ <RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
<Settings>
@@ -170,6 +166,8 @@ def _replacement_ready(root, exe: str, arguments: str) -> bool:
for trigger in root.findall("t:Triggers/t:LogonTrigger", ns))
and ntpath.normcase(command) == ntpath.normcase(exe)
and root.findtext("t:Actions/t:Exec/t:Arguments", "", ns) == arguments
+ and root.findtext("t:Principals/t:Principal/t:RunLevel", "", ns) == "LeastPrivilege"
+ and root.findtext("t:Principals/t:Principal/t:LogonType", "", ns) == "InteractiveToken"
)
@@ -231,7 +229,7 @@ def set_enabled(enabled: bool, exe: str, user: Optional[str] = None, run: Runner
result = run(["schtasks", "/delete", "/tn", name, "/f"])
else:
if not can_run_for_current_user():
- raise OSError("Beamer can start elevated at sign-in only for an administrator account")
+ raise OSError("Start at sign-in needs Beamer to run as the signed-in account")
fd, path = tempfile.mkstemp(suffix=".xml")
try:
with os.fdopen(fd, "w", encoding="utf-16") as handle:
diff --git a/win_app/build.spec b/win_app/build.spec
index f86a722..ebf349d 100644
--- a/win_app/build.spec
+++ b/win_app/build.spec
@@ -55,8 +55,6 @@ executable = EXE(
codesign_identity=None,
entitlements_file=None,
icon=str(source_dir / "Beamer.ico"),
- # Embeds a requireAdministrator manifest so the receiver always runs elevated.
- # Windows UIPI silently drops SendInput events aimed at a focused elevated
- # window (e.g. an admin terminal) when the sender isn't elevated too.
- uac_admin=True,
+ # Elevated targets remain protected by UIPI; installation owns maintenance privileges.
+ uac_admin=False,
)
diff --git a/win_app/build_win_app.ps1 b/win_app/build_win_app.ps1
index aa85bf1..1fdf06f 100644
--- a/win_app/build_win_app.ps1
+++ b/win_app/build_win_app.ps1
@@ -86,7 +86,15 @@ Write-Output "Built $Output"
if ($Release) {
$Version = (Get-Content (Join-Path $ProjectDir 'VERSION') -Raw).Trim()
$ReleaseDir = [IO.Path]::GetFullPath((Join-Path $ProjectDir "..\docs\beamer-releases\$Version"))
- & $Iscc "/O$ReleaseDir" Beamer-Setup.iss
+ $IsccArgs = @("/O$ReleaseDir")
+ if ($SignTool) {
+ # Same signtool line as Sign-BeamerArtifact. Inno Setup turns $q into a quote and $f into the
+ # quoted file it signs; literal quotes here would be re-quoted on the way to ISCC.
+ $IsccArgs += '/DSignInstaller'
+ $IsccArgs += '/Sbeamer=$q' + $SignTool + '$q sign /sha1 EA6F2A81A84E49D31FF7965A50D7DE771601DA0A /tr http://time.certum.pl /td sha256 /fd sha256 $f'
+ }
+ $IsccArgs += 'Beamer-Setup.iss'
+ & $Iscc @IsccArgs
if ($LASTEXITCODE -ne 0) { throw 'Inno Setup failed' }
$Setup = Join-Path $ReleaseDir "Beamer-Setup-$Version.exe"
Sign-BeamerArtifact $Setup
diff --git a/win_app/desktop_win.py b/win_app/desktop_win.py
index 4550565..ce3218c 100644
--- a/win_app/desktop_win.py
+++ b/win_app/desktop_win.py
@@ -105,12 +105,7 @@ def set_cursor_position(x: int, y: int) -> None:
def set_cursor_position_with_callback(x: int, y: int, on_placed=None, *, place_if_current=None) -> None:
- """SetCursorPos returns FALSE with no error code, and SendInput is dropped
- in silence, whenever Windows' UIPI puts the foreground window above
- Beamer's integrity level, so a SendInput move is no fallback. The one such
- window seen so far is GameInput's (see input_injector); for it the
- placement runs again once the service has been restarted, and anything
- else in front is named in the log."""
+ """Report blocked placement without claiming that the receiver arrived."""
_require()
x, y = int(x), int(y)
def place():
@@ -121,22 +116,18 @@ def set_cursor_position_with_callback(x: int, y: int, on_placed=None, *, place_i
return True
return False
- # Only the warp and its completion share the receiver's ownership lock. Service restart
- # scheduling stays outside it, and every deferred retry validates its visit again.
+ # The warp and its completion share the receiver's ownership lock.
result = place_if_current(place) if place_if_current is not None else place()
if result is not False:
return
error = ctypes.get_last_error()
import input_injector
- # Placed through this function again, so a refusal after the restart is logged too.
- if input_injector.release_gameinput_foreground(after=lambda: set_cursor_position_with_callback(
- x, y, on_placed, place_if_current=place_if_current)):
- return
blocker = input_injector.foreground_class()
# A hold at the return edge lands here on every move, so once per blocker.
if blocker != _refused_under[0]:
_refused_under[0] = blocker
+ input_injector.report_input_problem()
LOGGER.warning(
"SetCursorPos refused (error %s) with %r in the foreground; Windows refuses Beamer's input "
"while a window above its integrity level is in front, until a click on this PC",
diff --git a/win_app/firewall_win.py b/win_app/firewall_win.py
index a2b57b9..5b266bb 100644
--- a/win_app/firewall_win.py
+++ b/win_app/firewall_win.py
@@ -193,72 +193,20 @@ def interpret(payload: dict, exe: str, port: int, elevated: bool = True) -> Fire
def advise(status: FirewallStatus) -> Advice:
- """One sentence a non-technical person can act on, and the one button that fixes it."""
+ """Explain the next step without offering privileged changes from the app."""
port = status.port
pairing_udp = status.pairing_allowed and status.pairing_covered
pairing_tcp = status.pairing_tcp_allowed and status.pairing_tcp_covered
- rule_profiles = ("Private",) + (("Domain",) if "DomainAuthenticated" in status.lan_profiles else ())
if status.error:
return Advice(tr("Beamer could not read the Windows Firewall: {error}").format(error=status.error), tr("Check again"), "check")
if status.blocked:
- advice = Advice(
- tr("Windows Firewall is blocking Beamer's input or pairing traffic. This can happen when Cancel was pressed on "
- "Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling "
- "does not clear it. Fixing it removes the block and adds the right rules for private networks."),
- tr("Fix the firewall"),
- "repair",
- rule_profiles,
- )
- elif not status.allowed:
- advice = Advice(
- tr("Windows Firewall has no rule letting your other machines reach Beamer on port {port}, so they will "
- "say this PC is unreachable. This happens when the installer was run without administrator rights. "
- "Fixing it adds the rule for private networks.").format(port=port),
- tr("Fix the firewall"),
- "repair",
- rule_profiles,
- )
- elif status.public_interfaces and not (status.covered and pairing_udp and pairing_tcp):
- names = ", ".join(alias for _, alias in status.public_interfaces if alias) or "this network"
- advice = Advice(
- tr("Windows treats {names} as a public network, so some of Beamer's firewall rules do not cover it and "
- "your other machines cannot get in. Trusting it marks the network as private, which lets them in without "
- "opening the port on every other network this PC joins.").format(names=names),
- tr("Trust this network"),
- "trust",
- )
- elif not status.covered:
- names = ", ".join(status.lan_profiles)
- advice = Advice(
- tr("Beamer's firewall rule does not apply on this network (Windows calls it {names}). "
- "Fixing it rewrites the rule to cover it.").format(names=names),
- tr("Fix the firewall"),
- "repair",
- rule_profiles,
- )
- elif not pairing_udp or not pairing_tcp:
- missing = []
- if not pairing_udp:
- missing.append((
- f"the pairing beacon on UDP {PAIRING_PORT}",
- "a machine that has not been set up by hand will never see this PC in its list, and this PC will not "
- "hear other machines' pairing announcements",
- ))
- if not pairing_tcp:
- missing.append((
- f"the pairing exchange on TCP {PAIRING_PORT}",
- "a machine that finds this PC cannot finish pairing with it",
- ))
- advice = Advice(
- tr("Windows Firewall lets your other machines reach Beamer on port {port}, but there is no rule covering this network for "
- "{rules}, so {effects}. Fixing it replaces Beamer's inbound firewall rules.").format(
- port=port, rules=" or for ".join(rule for rule, _ in missing),
- effects=" and ".join(effect for _, effect in missing)),
- tr("Fix the firewall"),
- "repair",
- rule_profiles,
+ return Advice(
+ tr("Windows Firewall has a block rule affecting Beamer's input or pairing traffic; ask your administrator "
+ "to review Beamer's inbound block rules in Windows Firewall."),
+ tr("Check again"), "check",
)
- else:
+ healthy = status.allowed and status.covered and pairing_udp and pairing_tcp
+ if healthy:
where = tr("this private network") if "Private" in status.lan_profiles else tr("this network")
return Advice(
tr("Windows Firewall lets your other machines reach Beamer on port {port} on {where}, and lets a new machine "
@@ -266,15 +214,20 @@ def advise(status: FirewallStatus) -> Advice:
tr("Check again"),
"check",
)
- if not status.elevated:
+ if "DomainAuthenticated" in status.lan_profiles:
return Advice(
- tr("{sentence} Beamer is not running as administrator, so it cannot make this change itself: "
- "quit Beamer and open it again from the Start menu.").format(sentence=advice.sentence),
- advice.button,
- None,
- advice.rule_profiles,
+ tr("This managed network needs Windows Firewall rules for Beamer; ask your administrator to allow its receiver "
+ "on TCP {port} and pairing on UDP and TCP {pairing_port} for the Domain profile.").format(
+ port=port, pairing_port=PAIRING_PORT),
+ tr("Check again"), "check",
)
- return advice
+ if status.allowed and status.public_interfaces:
+ sentence = tr("Windows treats this network as public; if you trust it, change its network profile to Private in Windows Settings.")
+ else:
+ sentence = tr("Beamer's firewall rules need attention; run the Beamer installer again to repair them for private networks.")
+ if port != protocol.DEFAULT_PORT:
+ sentence = tr("Beamer uses custom port {port}; ask your administrator to allow that port for Beamer on trusted networks.").format(port=port)
+ return Advice(sentence, tr("Check again"), "check")
# ---------------------------------------------------------------- Windows
diff --git a/win_app/input_injector.py b/win_app/input_injector.py
index a1db393..fb07059 100644
--- a/win_app/input_injector.py
+++ b/win_app/input_injector.py
@@ -3,7 +3,6 @@
import ctypes
import functools
import logging
-import subprocess
import sys
import threading
import time
@@ -11,10 +10,20 @@ import unicodedata
from typing import Callable, Dict, List, Optional, Set, Tuple
from core.keytable import EVDEV_US
-from core import windows_tools
+from core.i18n import tr
LOGGER = logging.getLogger(__name__)
+on_problem = None
+_problem_at = float("-inf")
+
+
+def report_input_problem() -> None:
+ global _problem_at
+ now = time.monotonic()
+ if on_problem is not None and now - _problem_at >= 30:
+ _problem_at = now
+ on_problem(tr("Windows blocked Beamer's input; use administrator windows locally and click a normal window on this PC to continue."))
_IS_WINDOWS = sys.platform == "win32"
@@ -110,7 +119,9 @@ def _send_input(*inputs: INPUT) -> None:
array = (INPUT * count)(*inputs)
sent = user32.SendInput(count, array, ctypes.sizeof(INPUT))
if sent != count:
- raise ctypes.WinError(ctypes.get_last_error())
+ error = ctypes.get_last_error()
+ report_input_problem()
+ raise OSError(error, "Windows refused Beamer's input (administrator windows require local input)")
def _vk_key_scan(ch: str) -> int:
@@ -474,25 +485,9 @@ def inject_mouse_move(dx: int, dy: int) -> None:
watch_foreground()
-# GameInputSvc.exe runs as SYSTEM in the console session and keeps a hidden
-# window of this class, and Windows can hand that window the foreground when
-# the foreground app closes (closing a Hyper-V VM Connection window did it).
-# While it is in front, UIPI refuses every SetCursorPos
-# and silently drops every SendInput from Beamer, which is elevated but not
-# SYSTEM, so the Mac's pointer goes dead on the PC. Nothing Beamer can call
-# takes the foreground back -- SetForegroundWindow, SwitchToThisWindow and an
-# injected Alt tap were all refused -- and moving the PC's own mouse does not
-# either; a click on the PC does, and so does restarting the service, which
-# takes the window with it and leaves Windows to activate an ordinary one.
+# GameInput can leave a SYSTEM-owned window in front; only local input can leave it.
GAMEINPUT_WINDOW_CLASS = "GameInputServiceWindow"
-GAMEINPUT_RESTART = ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
- "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Restart-Service GameInputSvc -Force"]
-# A restart that did not free the pointer must not become a restart loop.
-GAMEINPUT_RESTART_COOLDOWN_SECONDS = 60.0
-
_seen_foreground = [None]
-_gameinput_lock = threading.Lock()
-_gameinput_restarted_at = [float("-inf")]
def _window_class(hwnd) -> str:
@@ -514,53 +509,16 @@ def watch_foreground() -> None:
if hwnd == _seen_foreground[0]:
return
if hwnd and _window_class(hwnd) == GAMEINPUT_WINDOW_CLASS:
- # Never marked seen, so a restart that failed or is cooling down is
- # tried again on a later move.
release_gameinput_foreground()
return
_seen_foreground[0] = hwnd
def release_gameinput_foreground(after: Optional[Callable[[], None]] = None) -> bool:
- """If GameInput's window holds the foreground, restart GameInputSvc on a
- thread of its own -- it takes a second or two, and the caller is the
- session thread that must keep draining pings -- then run `after`. False
- when GameInput is not in front, or a restart is already running or ran
- within the cooldown."""
- from core import portable_runtime
- if portable_runtime.enabled():
- return False
- if foreground_class() != GAMEINPUT_WINDOW_CLASS:
- return False
- if time.monotonic() - _gameinput_restarted_at[0] < GAMEINPUT_RESTART_COOLDOWN_SECONDS:
- return False
- if not _gameinput_lock.acquire(blocking=False):
- return False
- _gameinput_restarted_at[0] = time.monotonic()
-
- def restart() -> None:
- try:
- LOGGER.warning(
- "GameInput's service window has the foreground, where Windows refuses Beamer's input; restarting GameInputSvc to free it"
- )
- try:
- completed = windows_tools.run(GAMEINPUT_RESTART, encoding="utf-8", timeout=30)
- except (OSError, subprocess.TimeoutExpired):
- LOGGER.exception("Could not restart GameInputSvc; a click on this PC frees the pointer")
- return
- if completed.returncode != 0:
- LOGGER.error("Restarting GameInputSvc failed (%s): %s", completed.returncode, completed.stderr.strip())
- return
- LOGGER.info("GameInputSvc restarted; %r now has the foreground", foreground_class())
- if after is not None:
- after()
- except Exception:
- LOGGER.exception("Freeing the foreground from GameInput failed")
- finally:
- _gameinput_lock.release()
-
- threading.Thread(target=restart, name="Beamer-gameinput", daemon=True).start()
- return True
+ """Report the SYSTEM-window limitation; service recovery belongs to installation."""
+ if foreground_class() == GAMEINPUT_WINDOW_CLASS:
+ report_input_problem()
+ return False
BUTTON_DOWN_FLAGS = {
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index f69fd75..3b266b8 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -342,8 +342,7 @@ class StatusBridge(QObject):
alert = Signal(str, str)
# (version, url) when a newer Beamer is out, else None.
update = Signal(object)
- # The firewall rules are in place (or could not be), so the sockets may open.
- rules_ready = Signal()
+ update_check = Signal(str, object)
permission = Signal(str, str, str, bool)
@@ -588,7 +587,7 @@ class WindowsApplication(QWidget):
self.identify_screens = IdentifyScreens(self)
self.bridge.shook_home.connect(self._on_shake)
self.bridge.update.connect(self._on_update)
- self.bridge.rules_ready.connect(self._listen)
+ self.bridge.update_check.connect(self._on_update_check)
self.bridge.permission.connect(self._on_permission)
self._update = None
self._effects_failed = False
@@ -611,7 +610,6 @@ class WindowsApplication(QWidget):
self._firewall_tone: Optional[str] = None
self._firewall_busy = False
self._firewall_again = False
- self._firewall_auto_repaired = False
self._host = default_config().host
self._last_seen_state: Optional[ServerState] = None
self._receiver_port: Optional[int] = None
@@ -742,6 +740,7 @@ class WindowsApplication(QWidget):
self.update_checker = updates.Checker(
VERSION, lambda: self._config is None or self._config.check_updates, self.bridge.update.emit,
logger=LOGGER, portable=portable_runtime.enabled(),
+ on_check=self.bridge.update_check.emit,
)
self._paired = False
try:
@@ -840,6 +839,11 @@ class WindowsApplication(QWidget):
self.update_notice = widgets.Module("", heading=True)
self.update_notice_text = self.update_notice.eyebrow
actions = QHBoxLayout()
+ self.update_action = QPushButton(tr("Get update"))
+ self.update_action.setProperty("vernier", "primary")
+ self.update_action.clicked.connect(
+ lambda: self.open_update() if portal.sandboxed() else self.download_update())
+ actions.addWidget(self.update_action)
self.update_notes = QPushButton(tr("What's new"))
self.update_notes.clicked.connect(self.open_update)
actions.addWidget(self.update_notes)
@@ -956,6 +960,7 @@ class WindowsApplication(QWidget):
on_repair=self._re_pair,
on_pair_phone=self._pair_phone,
on_pair_nearby=self._start_nearby,
+ on_pin=self._set_peer_pin,
)
layout.addWidget(self.machines)
layout.addWidget(self._name_module(current))
@@ -1126,21 +1131,30 @@ class WindowsApplication(QWidget):
def _updates_module(self, current: Config) -> QWidget:
module = widgets.Module(tr("Updates"))
- self.updates_switch = widgets.Switch(tr("Check for updates"))
+ self.updates_switch = widgets.Switch(tr("Automatically check for updates"))
self.updates_switch.setFont(theme.font(theme.TYPE["body"]))
self.updates_switch.setChecked(current.check_updates)
self.updates_switch.toggled.connect(self._set_check_updates)
module.body.addWidget(self.updates_switch)
module.body.addWidget(widgets.label(
- tr("Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."),
+ tr("Checks GitHub at startup and once a day. Updates are downloaded and installed by you."),
"note",
wrap=True,
))
+ self.check_updates_button = QPushButton(tr("Check for updates"))
+ self.check_updates_button.clicked.connect(self.check_for_updates)
+ module.body.addWidget(self.check_updates_button)
+ self.update_status = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.update_status)
self.update_button = QPushButton(tr("Download"))
self.update_button.setProperty("vernier", "primary")
self.update_button.clicked.connect(self.download_update)
self.update_button.setVisible(False)
module.body.addWidget(self.update_button)
+ self.update_page_notes = QPushButton(tr("What's new"))
+ self.update_page_notes.clicked.connect(self.open_update)
+ self.update_page_notes.setVisible(False)
+ module.body.addWidget(self.update_page_notes)
return module
def _set_check_updates(self, enabled: bool) -> None:
@@ -1153,18 +1167,43 @@ class WindowsApplication(QWidget):
else:
self._on_update(None)
- def _on_update(self, found) -> None:
- """(version, url) for a newer release, or None; on the GUI thread."""
- if self._config is None or not self._config.check_updates:
+ def check_for_updates(self) -> None:
+ self._on_update_check("checking", None)
+ self.update_checker.check_now(manual=True)
+
+ def _on_update_check(self, state, found) -> None:
+ self.check_updates_button.setEnabled(state != "checking")
+ text = {"checking": tr("Checking for updates…"),
+ "current": tr("Beamer is up to date."),
+ "available": tr("Update available."),
+ "failed": tr("Could not check for updates. Check your connection and try again.")}[state]
+ self.update_status.setText(text)
+ if state in ("available", "current"):
+ self._on_update(found, manual=True)
+ if state == "current":
+ self.update_status.setText(text)
+
+ def _on_update(self, found, manual=False) -> None:
+ """A core Release or None; on the GUI thread."""
+ if self._config is None or (not manual and not self._config.check_updates):
found = None
+ self._manual_update = manual
self._update = found
+ self.update_status.setText(tr("Beamer {version} is available.").format(version=found[0]) if found else "")
+ if found and portal.sandboxed():
+ self.update_status.setText(self.update_status.text() + " " + tr(
+ "Update through your software store, or download the Flatpak from the release page and open it."))
+ elif found and portable_runtime.enabled() and not self.update_checker.download_url:
+ self.update_status.setText(self.update_status.text() + " " + tr(
+ "No portable download is available for this release. See What's new."))
+ self.update_page_notes.setVisible(found is not None)
self.update_button.setText(tr("Download Beamer {version}").format(version=found[0]) if found else tr("Download"))
if portable_runtime.enabled() and found:
self.update_button.setText(tr("Download portable zip"))
- motion.set_shown(self.update_button, found is not None and not portal.sandboxed()
- and (not portable_runtime.enabled() or bool(self.update_checker.download_url)))
- self.header_action.setText(tr("Beamer {version} is available…").format(version=found[0]) if found else tr("Beamer {version}").format(version=VERSION))
- self.header_action.setEnabled(found is not None and not portal.sandboxed())
+ can_download = found is not None and not portal.sandboxed() and (
+ not portable_runtime.enabled() or bool(self.update_checker.download_url))
+ motion.set_shown(self.update_button, can_download)
+ self.update_action.setVisible(found is not None and (portal.sandboxed() or can_download))
self._refresh_update_notice()
def _refresh_update_notice(self) -> None:
@@ -1173,13 +1212,20 @@ class WindowsApplication(QWidget):
except (ConfigError, OSError):
LOGGER.exception("Update notice settings could not be read")
self.update_notice.hide()
+ self.header_action.setText(tr("Beamer {version}").format(version=VERSION))
+ self.header_action.setEnabled(False)
return
found = updates.visible_notice(self._update, self._config is not None and self._config.check_updates,
- settings.get("dismissed_update_version", ""))
+ settings.get("dismissed_update_version", ""),
+ requested=getattr(self, "_manual_update", False))
+ self.header_action.setText(tr("Beamer {version} is available…").format(version=found[0]) if found else tr("Beamer {version}").format(version=VERSION))
+ self.header_action.setEnabled(found is not None and not portal.sandboxed())
if found:
text = tr("Beamer {version} is available.").format(version=found[0])
if portal.sandboxed():
- text += " " + tr("Update through your software store.")
+ text += " " + tr("Update through your software store, or download the Flatpak from the release page and open it.")
+ elif portable_runtime.enabled() and not self.update_checker.download_url:
+ text += " " + tr("No portable download is available for this release. See What's new.")
self.update_notice_text.setText(text)
self.update_notice.setVisible(bool(found))
@@ -1194,6 +1240,7 @@ class WindowsApplication(QWidget):
except (ConfigError, OSError):
LOGGER.exception("Update dismissal could not be saved")
return
+ self._manual_update = False
self._refresh_update_notice()
def open_update(self) -> None:
@@ -1201,6 +1248,8 @@ class WindowsApplication(QWidget):
QDesktopServices.openUrl(QUrl(self._update[1]))
def download_update(self) -> None:
+ if portal.sandboxed():
+ return
if portable_runtime.enabled():
if self._update and self.update_checker.download_url:
QDesktopServices.openUrl(QUrl(self.update_checker.download_url))
@@ -1295,6 +1344,10 @@ class WindowsApplication(QWidget):
tr("On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an "
"edge, so the edges are never held for one and a drag can cross."), "note", wrap=True)
module.body.addWidget(self.wayland_crossing_note)
+ if sys.platform == "win32":
+ module.body.addWidget(widgets.label(
+ tr("Beamer controls normal windows; use administrator windows and Windows permission prompts locally."),
+ "note", wrap=True))
for widget in (self.hold_switch, own_note, hold_note):
widget.setVisible(not platform_parts.WAYLAND)
# Wayland gives an app no way to hide the pointer.
@@ -2103,11 +2156,11 @@ class WindowsApplication(QWidget):
if exe and not account_known:
hint = tr("Windows could not identify the signed-in account, so start at sign-in is unavailable.")
elif exe and not can_start:
- hint = tr("Start at sign-in needs the same administrator account that runs Beamer.")
+ hint = tr("Start at sign-in needs Beamer to run as the signed-in account.")
elif enabled:
- hint = tr("Starts elevated at sign-in without a UAC prompt, so Beamer can send input to administrator apps.")
+ hint = tr("Starts in the tray when you sign in, without an administrator prompt.")
elif exe:
- hint = tr("When enabled, a logon task starts Beamer elevated without a UAC prompt, so it can send input to administrator apps.")
+ hint = tr("When enabled, Beamer starts in the tray with your normal permissions.")
else:
hint = tr("Only the installed app can start at sign-in.")
self.logon_hint = widgets.label(hint, "note", wrap=True)
@@ -3719,7 +3772,7 @@ class WindowsApplication(QWidget):
self.length_choice = _DesignChoiceSlider(
"length", 25, 250, 5, 100, (0.5, 1.0, 2.0), effects.LENGTHS)
self.size_choice = _DesignChoiceSlider(
- "size", 20, 80, 1, 1000, (0.03, 0.045, 0.06), effects.SIZES)
+ "size", 20, 250, 1, 1000, (0.03, 0.045, 0.06), effects.SIZES)
self.frame_rate_choice = widgets.Choice(
tuple((value, tr(name)) for value, name, _divisor in effects.FRAME_RATES),
3, current.frame_rate, on_change=self._apply_look)
@@ -4226,6 +4279,10 @@ class WindowsApplication(QWidget):
if self._edit_peer(token, allow_drive=bool(enabled)):
self._after_peers_edit()
+ def _set_peer_pin(self, token: str, enabled: bool) -> None:
+ if self._edit_peer(token, host_pinned=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):
@@ -4808,33 +4865,7 @@ class WindowsApplication(QWidget):
def _firewall_action(self) -> None:
if portable_runtime.enabled():
return
- # Only the built exe changes the firewall, by the button or on its own. From source the
- # executable is python.exe, and repair() replaces Beamer's rules by name, so a test run on
- # the PC took the installed Beamer's rules with it and cut the Mac's link (29-09-2026).
- if not getattr(sys, "frozen", False):
- LOGGER.info("Running from source; the firewall is left as it is")
- return
- advice = self._firewall_advice
- if advice is None or advice.action is None:
- return
- if advice.action == "repair":
- profiles = advice.rule_profiles
-
- def job(exe, port):
- firewall_win.repair(exe, port, profiles)
- return firewall_win.status(exe, port)
-
- elif advice.action == "trust":
- indexes = [index for index, _ in (self._firewall_status.public_interfaces if self._firewall_status else ())]
-
- def job(exe, port):
- firewall_win.trust_network(indexes)
- return firewall_win.status(exe, port)
-
- else:
- self._check_firewall()
- return
- self._run_firewall(job, tr("Fixing…"))
+ self._check_firewall()
def _run_firewall(self, job, working: str) -> None:
"""One PowerShell at a time, off the GUI thread. A request arriving mid-run is folded
@@ -4871,13 +4902,13 @@ class WindowsApplication(QWidget):
self.firewall_note.setText(advice.sentence)
if status.error:
tone = "note-fault"
- elif advice.action == "check":
+ elif (not status.blocked and status.allowed and status.covered
+ and status.pairing_allowed and status.pairing_covered
+ and status.pairing_tcp_allowed and status.pairing_tcp_covered):
tone = "note"
else:
tone = "note-amber"
- # Remembered for the sidebar dot: "check" is the healthy end-state (its button just
- # offers a manual re-check), so `advice.action is not None` alone would mark Firewall
- # as needing attention even when everything is fine.
+ # Every action now rechecks; the sidebar reflects rule coverage, not button wording.
self._firewall_tone = tone
widgets.set_role(self.firewall_note, tone)
self.firewall_button.setText(advice.button)
@@ -4886,19 +4917,6 @@ class WindowsApplication(QWidget):
self._firewall_again = False
self._check_firewall()
return
- # A missing rule with the rights to write one is not a question for the
- # user: the release installer cannot add it, so a fresh install would
- # otherwise sit unreachable until someone found this page. A block rule
- # or a public network is still theirs to decide.
- if (
- advice.action == "repair"
- and status.elevated
- and firewall_win.missing_rule(status)
- and not self._firewall_auto_repaired
- ):
- self._firewall_auto_repaired = True
- LOGGER.info("No firewall rule for this executable; adding one")
- self._firewall_action()
# -- theming, tray, lifecycle ------------------------------------------------------------
@@ -5099,27 +5117,7 @@ class WindowsApplication(QWidget):
def start(self) -> None:
self.update_checker.start()
- if not portable_runtime.enabled() and getattr(sys, "frozen", False) and firewall_win.is_elevated():
- # Beamer's own rules before any socket opens: a listener Windows has no rule for makes
- # it ask, and a click on Allow there writes rules for every network, public ones too,
- # where Beamer's are for private networks only. Not from source: see _firewall_action.
- threading.Thread(target=self._rules_then_listen, name="Beamer-firewall-first", daemon=True).start()
- else:
- self._listen()
-
- def _rules_then_listen(self) -> None:
- if portable_runtime.enabled():
- self.bridge.rules_ready.emit()
- return
- try:
- exe, port = self._firewall_target()
- status = firewall_win.status(exe, port)
- if firewall_win.missing_rule(status):
- LOGGER.info("Adding this PC's firewall rules before listening")
- firewall_win.repair(exe, port, ("Private",))
- except Exception:
- LOGGER.exception("The firewall rules could not be added before listening")
- self.bridge.rules_ready.emit()
+ self._listen()
def _listen(self) -> None:
if self._closing:
diff --git a/win_app/linux_stand_ins.py b/win_app/linux_stand_ins.py
index b3c972f..18de70f 100644
--- a/win_app/linux_stand_ins.py
+++ b/win_app/linux_stand_ins.py
@@ -27,6 +27,9 @@ class FirewallStatus:
elevated: bool = False
error: str = ""
pairing_allowed: bool = True
+ pairing_covered: bool = True
+ pairing_tcp_allowed: bool = True
+ pairing_tcp_covered: bool = True
@dataclass(frozen=True)
diff --git a/win_app/machines_win.py b/win_app/machines_win.py
index 28b9251..b4b006c 100644
--- a/win_app/machines_win.py
+++ b/win_app/machines_win.py
@@ -334,7 +334,8 @@ class PeerRow(QWidget):
def __init__(self, token: str, on_send: Callable, on_allow: Callable, on_in_use: Callable,
on_left_out: Callable, on_remove: Callable, on_rename: Optional[Callable] = None,
- on_cycle: Optional[Callable] = None, on_repair: Optional[Callable] = None) -> None:
+ on_cycle: Optional[Callable] = None, on_repair: Optional[Callable] = None,
+ on_pin: Optional[Callable] = None) -> None:
super().__init__()
self.setProperty("vernier", "plain")
self.token = token
@@ -381,6 +382,10 @@ class PeerRow(QWidget):
column.addWidget(self.rename_note)
self.where = widgets.label("", "note-quiet", wrap=True)
column.addWidget(self.where)
+ self.pin_address = widgets.Switch(tr("Pin address"))
+ self.pin_address.setToolTip(tr("Keeps this address through reconnects and re-pairing. Turn off to follow address changes automatically."))
+ self.pin_address.toggled.connect(lambda on: (on_pin or (lambda *_: None))(self.token, on))
+ column.addWidget(self.pin_address)
self.detail = widgets.label("", "note", wrap=True)
column.addWidget(self.detail)
self.repair_button = _button(tr("Re-pair"), "small")
@@ -509,6 +514,12 @@ class PeerRow(QWidget):
self._same_on = same_on
self._left_out = entry.get("left_out") is True
dormant = peerlist.dormant_reason(entry) is not None
+ self.pin_address.setVisible(not self._phone and not asking)
+ self.pin_address.setEnabled(bool(entry.get("host")))
+ self.pin_address.setAccessibleName(tr("Pin address for {name}").format(name=label))
+ self.pin_address.blockSignals(True)
+ self.pin_address.setChecked(bool(entry.get("host")) and entry.get("host_pinned") is not False)
+ self.pin_address.blockSignals(False)
self.shortcut_cycle.setVisible(not self._phone and cycle_mode == "ticked")
self.shortcut_cycle.setEnabled(entry.get("in_use", True) is True and not dormant)
self.shortcut_cycle.blockSignals(True)
@@ -549,11 +560,11 @@ class MachinesModule(widgets.Module):
on_remove: Callable, on_pair: Callable, on_rename: Optional[Callable] = None,
on_cycle: Optional[Callable] = None, on_repair: Optional[Callable] = None,
on_pair_phone: Optional[Callable] = None,
- on_pair_nearby: Optional[Callable] = None) -> None:
+ on_pair_nearby: Optional[Callable] = None, on_pin: Optional[Callable] = None) -> None:
super().__init__(tr("Machines"))
self._callbacks = (on_send, on_allow, on_in_use, on_left_out, on_remove,
on_rename or (lambda *_: None), on_cycle,
- on_repair or (lambda *_: None))
+ on_repair or (lambda *_: None), on_pin)
self.rows: dict = {}
self.rows_layout = QVBoxLayout()
self.rows_layout.setContentsMargins(0, 0, 0, 0)
diff --git a/win_app/sender.py b/win_app/sender.py
index 22e1628..fd6bc54 100644
--- a/win_app/sender.py
+++ b/win_app/sender.py
@@ -1347,6 +1347,7 @@ class LinkSender:
message = protocol.focus_v6(
data["route"], data["target"], data.get("edge"), data.get("offset"),
data.get("resistance_px"), data.get("reach"), bool(data.get("stay")),
+ display=data.get("display"), side=data.get("side"),
)
elif kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):
preserve = message.pop("_preserve_key_name", False)
diff --git a/win_app/tests/test_autostart_win.py b/win_app/tests/test_autostart_win.py
index 169a68f..4dacc6b 100644
--- a/win_app/tests/test_autostart_win.py
+++ b/win_app/tests/test_autostart_win.py
@@ -33,12 +33,12 @@ class FakeSchtasks:
class TaskXmlTests(unittest.TestCase):
- def test_starts_hidden_elevated_and_never_times_out(self):
+ def test_starts_hidden_with_normal_privilege_and_never_times_out(self):
root = ET.fromstring(autostart_win.task_xml(EXE, r"STUDIO-PC\alex").replace('encoding="UTF-16"', ""))
self.assertEqual(root.find("t:Actions/t:Exec/t:Command", NS).text, EXE)
self.assertEqual(root.find("t:Actions/t:Exec/t:Arguments", NS).text, "--hidden")
self.assertEqual(root.find("t:Principals/t:Principal/t:UserId", NS).text, r"STUDIO-PC\alex")
- self.assertEqual(root.find("t:Principals/t:Principal/t:RunLevel", NS).text, "HighestAvailable")
+ self.assertEqual(root.find("t:Principals/t:Principal/t:RunLevel", NS).text, "LeastPrivilege")
self.assertEqual(root.find("t:Settings/t:ExecutionTimeLimit", NS).text, "PT0S")
self.assertEqual(root.find("t:Triggers/t:LogonTrigger/t:UserId", NS).text, r"STUDIO-PC\alex")
@@ -79,7 +79,7 @@ class SwitchTests(unittest.TestCase):
def test_refuses_silent_elevation_for_another_users_session(self):
fake = FakeSchtasks()
with patch.object(autostart_win, "can_run_for_current_user", return_value=False):
- with self.assertRaisesRegex(OSError, "administrator account"):
+ with self.assertRaisesRegex(OSError, "signed-in account"):
autostart_win.set_enabled(True, EXE, user="STUDIO-PC\\alex", run=fake)
self.assertEqual(fake.calls, [])
@@ -108,18 +108,18 @@ class SwitchTests(unittest.TestCase):
class InstallerTests(unittest.TestCase):
- def test_inno_setup_uses_the_checked_app_helper_for_start_at_sign_in(self):
+ def test_inno_setup_keeps_app_operations_unelevated(self):
setup = (Path(__file__).parents[1] / "Beamer-Setup.iss").read_text(encoding="utf-8")
self.assertIn("PrivilegesRequired=lowest", setup)
self.assertIn('Flags: unchecked', setup[setup.index('[Tasks]') : setup.index('[Files]')])
code = setup[setup.index("[Code]") :]
- self.assertIn("RunTaskOperation(ExpandConstant('{app}\\Beamer.exe'), '--enable-autostart', ResultCode)", code)
- self.assertIn("if IsAdmin then", code)
- self.assertIn("ShellExec('runas'", code)
+ self.assertIn("Exec(ExpandConstant('{app}\\Beamer.exe'), '--enable-autostart'", code)
+ self.assertIn("Invoke-InstallMaintenance.ps1", code)
+ self.assertNotIn("ShellExec('runas'", code)
self.assertIn("ewWaitUntilTerminated", code)
self.assertIn("ResultCode <> 0", code)
self.assertIn("RaiseException", code)
- self.assertIn("same administrator account", code)
+ self.assertNotIn("same administrator account", code)
self.assertNotIn("<Task version=", code)
self.assertNotIn('/Create /TN', code)
self.assertNotIn('/delete /tn "Beamer" /f', code)
diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.py
index d5def5b..38dfa2f 100644
--- a/win_app/tests/test_clipboard_win.py
+++ b/win_app/tests/test_clipboard_win.py
@@ -363,6 +363,7 @@ class ClipboardOrchestrationTests(unittest.TestCase):
self.assertEqual(win32.destroyed, [123, 123])
self.assertEqual(self.mem32.contents(win32.formats[CF_UNICODETEXT]), b"c\x00o\x00p\x00y\x00\x00\x00")
+ @unittest.skipUnless(sys.platform == "win32", "the fake clipboard buffer models Windows' 16-bit wchar_t ABI")
def test_rapid_large_unicode_writes_keep_the_latest_text(self):
win32 = FakeWin32(self.mem32)
copies = [f"copy {n}: café 日本語 \U0001d11e" for n in range(200)]
diff --git a/win_app/tests/test_effect_layouts.py b/win_app/tests/test_effect_layouts.py
index dd67a80..e8d33fb 100644
--- a/win_app/tests/test_effect_layouts.py
+++ b/win_app/tests/test_effect_layouts.py
@@ -130,34 +130,61 @@ class EveryLayoutTests(unittest.TestCase):
def test_an_effect_is_framed_as_its_display_alone(self):
seen = []
+ def probe(pen, s):
+ pen.moveTo(s.screen.w, s.screen.h)
+ seen.append(pen._path[-1][1:])
+ pen.moveTo(s.point.x, s.point.y)
+ seen.append(pen._path[-1][1:])
fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
- lambda pen, s: seen.append((s.screen.w, s.screen.h, s.point.x, s.point.y, s.edge)), 0.0, 0.5)
+ probe, 0.0, 0.5)
player = effects.Player()
player.arrive(0.0, "edge", (1730.0, 500.0), "left", (1728.0, 0.0, 1920.0, 1080.0))
player.frames(0.1, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
- self.assertEqual(seen, [(1920.0, 1080.0, 2.0, 500.0, "left")])
+ self.assertEqual(len(seen), 2)
+ for actual, expected in zip(seen, [(3648.0, 1080.0), (1730.0, 500.0)]):
+ self.assertEqual(len(actual), len(expected))
+ for got, want in zip(actual, expected):
+ self.assertAlmostEqual(got, want)
def test_an_edge_strip_along_the_whole_desktop_is_cut_to_the_display(self):
seen = []
- fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: seen.append(vars(s.region)),
+ def probe(pen, s):
+ r = s.region
+ pen.moveTo(r.x, r.y)
+ pen.lineTo(r.x + r.w, r.y + r.h)
+ seen.extend(pen._path)
+ fx = effects.Effect("probe", "Probe", "quiet", "", probe,
lambda pen, s: None, 0.5, 0.0)
player = effects.Player()
display = (1728.0, 0.0, 1920.0, 1080.0)
player.push(0.0, "edge", {"kind": "edge", "edge": "right", "x": 3647.0, "y": 0.0, "w": 1.0, "h": 1517.0},
(3647.0, 500.0), 0.5, display=display)
player.frames(0.0, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
- self.assertEqual((seen[0]["x"], seen[0]["y"], seen[0]["h"]), (1919.0, 0.0, 1080.0))
+ self.assertEqual(len(seen), 2)
+ for actual, expected in zip(seen, [("M", 3647.0, 0.0), ("L", 3648.0, 1080.0)]):
+ self.assertEqual(len(actual), len(expected))
+ self.assertEqual(actual[0], expected[0])
+ for got, want in zip(actual[1:], expected[1:]):
+ self.assertAlmostEqual(got, want)
def test_the_notch_is_only_seen_on_its_own_display(self):
seen = []
+ def probe(pen, s):
+ notch = getattr(s, "notch", None)
+ if notch is None:
+ seen.append(None)
+ else:
+ pen.moveTo(notch.x, notch.y)
+ seen.append(pen._path[-1][1:])
fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
- lambda pen, s: seen.append(getattr(s, "notch", None)), 0.0, 0.5)
+ probe, 0.0, 0.5)
displays = LAYOUTS["left of the primary"]
for display in displays:
player = effects.Player()
player.arrive(0.0, "edge", (display[0] + display[2] / 2.0, display[1] + 2.0), "top", display)
player.frames(0.1, fx, (3648.0, 1380.0, "mac"), PALETTE, False, True, notch_on(displays))
- self.assertEqual((seen[0].x, seen[0].y), (NOTCH["x"], 0.0))
+ self.assertAlmostEqual(seen[0][0], 1920.0 + NOTCH["x"])
+ self.assertAlmostEqual(seen[0][1], 0.0)
self.assertIsNone(seen[1])
diff --git a/win_app/tests/test_effect_size_raster.py b/win_app/tests/test_effect_size_raster.py
new file mode 100644
index 0000000..43c1535
--- /dev/null
+++ b/win_app/tests/test_effect_size_raster.py
@@ -0,0 +1,7 @@
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.tests.effect_size_probe import NativeSizeRasterTests
diff --git a/win_app/tests/test_firewall_first.py b/win_app/tests/test_firewall_first.py
index eea90cf..d3439a3 100644
--- a/win_app/tests/test_firewall_first.py
+++ b/win_app/tests/test_firewall_first.py
@@ -1,3 +1,5 @@
+"""The ordinary GUI never changes the firewall, even if a parent launched it elevated."""
+
import sys
import unittest
from types import SimpleNamespace
@@ -5,98 +7,29 @@ from unittest import mock
@unittest.skipUnless(sys.platform == "win32", "the app module needs Windows")
-class RulesBeforeListeningTests(unittest.TestCase):
- """A listener Windows has no rule for makes it ask, and Allow there opens every network."""
-
- def owner(self, events):
- import kvm_bridge_win
-
- owner = SimpleNamespace(
- update_checker=SimpleNamespace(start=lambda: None),
- _firewall_target=lambda: ("C:\\Beamer\\Beamer.exe", 24820),
- bridge=SimpleNamespace(rules_ready=SimpleNamespace(emit=lambda: events.append("listen"))),
- _listen=lambda: events.append("listen"),
- )
- owner._rules_then_listen = lambda: kvm_bridge_win.WindowsApplication._rules_then_listen(owner)
- return kvm_bridge_win, owner
-
- def status(self, allowed=False, blocked=False, error=""):
- return SimpleNamespace(allowed=allowed, blocked=blocked, error=error)
-
- def test_missing_rules_are_added_before_anything_listens(self):
- events = []
- module, owner = self.owner(events)
- with mock.patch.object(module.firewall_win, "status", return_value=self.status()), \
- mock.patch.object(module.firewall_win, "repair", side_effect=lambda *a: events.append("rules")):
- owner._rules_then_listen()
- self.assertEqual(events, ["rules", "listen"])
-
- def test_an_existing_rule_or_a_block_is_left_alone(self):
- for existing in (self.status(allowed=True), self.status(blocked=True), self.status(error="no PowerShell")):
- events = []
- module, owner = self.owner(events)
- with self.subTest(existing=existing), \
- mock.patch.object(module.firewall_win, "status", return_value=existing), \
- mock.patch.object(module.firewall_win, "repair", side_effect=lambda *a: events.append("rules")):
- owner._rules_then_listen()
- self.assertEqual(events, ["listen"])
-
- def test_a_failure_still_listens(self):
- events = []
- module, owner = self.owner(events)
- with mock.patch.object(module.firewall_win, "status", side_effect=OSError("denied")):
- owner._rules_then_listen()
- self.assertEqual(events, ["listen"])
-
- def test_without_elevation_it_listens_at_once(self):
- events = []
- module, owner = self.owner(events)
- with mock.patch.object(module.firewall_win, "is_elevated", return_value=False):
- module.WindowsApplication.start(owner)
- self.assertEqual(events, ["listen"])
-
-
[email protected](sys.platform == "win32", "the app module needs Windows")
-class FromSourceTests(unittest.TestCase):
- """29-09-2026: the test suite on the rig replaced the installed Beamer's rules with
- python.exe's, and the Mac's link timed out until Beamer restarted."""
-
- def run_both(self, frozen):
+class InstallerOwnedFirewallTests(unittest.TestCase):
+ def test_start_and_recheck_never_repair_rules_or_networks(self):
import kvm_bridge_win as module
- events = []
- owner = SimpleNamespace(
- update_checker=SimpleNamespace(start=lambda: None),
- _firewall_target=lambda: ("C:\\Beamer\\Beamer.exe", 24820),
- bridge=SimpleNamespace(rules_ready=SimpleNamespace(emit=lambda: None)),
- _listen=lambda: None,
- _firewall_advice=SimpleNamespace(action="repair", rule_profiles=("Private",)),
- _run_firewall=lambda job, working: job("C:\\Beamer\\Beamer.exe", 24820),
- )
- owner._rules_then_listen = lambda: module.WindowsApplication._rules_then_listen(owner)
-
- class Inline:
- def __init__(self, target, **kwargs):
- self.target = target
-
- def start(self):
- self.target()
-
- missing = SimpleNamespace(allowed=False, blocked=False, error="")
- with mock.patch.object(module.sys, "frozen", frozen, create=True), \
- mock.patch.object(module.threading, "Thread", Inline), \
- mock.patch.object(module.firewall_win, "is_elevated", return_value=True), \
- mock.patch.object(module.firewall_win, "status", return_value=missing), \
- mock.patch.object(module.firewall_win, "repair", side_effect=lambda *a: events.append("repair")):
- module.WindowsApplication.start(owner)
- module.WindowsApplication._firewall_action(owner)
- return events
-
- def test_the_built_exe_writes_its_rules_at_start_and_on_fix(self):
- self.assertEqual(self.run_both(frozen=True), ["repair", "repair"])
-
- def test_from_source_neither_path_touches_the_firewall(self):
- self.assertEqual(self.run_both(frozen=False), [])
+ for frozen in (False, True):
+ for elevated in (False, True):
+ events = []
+ owner = SimpleNamespace(
+ update_checker=SimpleNamespace(start=lambda: events.append("updates")),
+ _listen=lambda: events.append("listen"),
+ _check_firewall=lambda: events.append("check"),
+ _firewall_advice=SimpleNamespace(action="repair", rule_profiles=("Private",)),
+ )
+ with self.subTest(frozen=frozen, elevated=elevated), \
+ mock.patch.object(module.sys, "frozen", frozen, create=True), \
+ mock.patch.object(module.firewall_win, "is_elevated", return_value=elevated), \
+ mock.patch.object(module.firewall_win, "repair") as repair, \
+ mock.patch.object(module.firewall_win, "trust_network") as trust:
+ module.WindowsApplication.start(owner)
+ module.WindowsApplication._firewall_action(owner)
+ self.assertEqual(events, ["updates", "listen", "check"])
+ repair.assert_not_called()
+ trust.assert_not_called()
if __name__ == "__main__":
diff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.py
index 2fa1fb5..7c66edb 100644
--- a/win_app/tests/test_firewall_win.py
+++ b/win_app/tests/test_firewall_win.py
@@ -15,10 +15,10 @@ import firewall_win
from firewall_win import advise, interpret
EXE = r"C:\Users\alex\AppData\Local\Beamer\Beamer.exe"
-PORT = 51820
+PORT = firewall_win.protocol.DEFAULT_PORT
-def rule(action="Allow", profile="Private", program=EXE, port="51820", protocol="TCP", enabled="True", direction="Inbound"):
+def rule(action="Allow", profile="Private", program=EXE, port=str(PORT), protocol="TCP", enabled="True", direction="Inbound"):
return {
"name": "{x}", "display": "Beamer Receiver (TCP-In)", "enabled": enabled, "action": action,
"direction": direction, "profile": profile, "program": program, "protocol": protocol,
@@ -52,19 +52,40 @@ def payload(rules=(), networks=(network(),)):
return {"rules": list(rules), "networks": list(networks)}
-class InterpretTests(unittest.TestCase):
+class InstallerAdviceAssertions:
+ def assert_installer_advice(self, status):
+ advice = advise(status)
+ self.assertEqual(advice.action, "check")
+ self.assertEqual(advice.button, "Check again")
+ self.assertIn("run the Beamer installer again", advice.sentence)
+ return advice
+
+ def assert_administrator_advice(self, status):
+ advice = advise(status)
+ self.assertEqual(advice.action, "check")
+ self.assertEqual(advice.button, "Check again")
+ self.assertIn("administrator", advice.sentence)
+ self.assertIn("Windows Firewall", advice.sentence)
+ self.assertNotIn("run the Beamer installer again", advice.sentence)
+ self.assertEqual(advice.rule_profiles, ("Private",))
+ return advice
+
+
+class InterpretTests(InstallerAdviceAssertions, unittest.TestCase):
def test_existing_rules_on_another_profile_do_not_trigger_automatic_repair(self):
rules = [rule(), pairing_rule(), pairing_tcp_rule(), pairing_tcp_rule(action="Block", profile="Domain")]
status = interpret(payload(rules, [network("Public")]), EXE, PORT)
self.assertFalse(firewall_win.missing_rule(status))
self.assertFalse(status.blocked)
- self.assertEqual(advise(status).action, "trust")
+ advice = advise(status)
+ self.assertEqual(advice.action, "check")
+ self.assertIn("Windows Settings", advice.sentence)
- def test_existing_misprofiled_pairing_rules_require_a_manual_repair(self):
+ def test_existing_misprofiled_pairing_rules_point_to_installer_repair(self):
rules = [rule(), pairing_rule(profile="Public"), pairing_tcp_rule(profile="Public")]
status = interpret(payload(rules), EXE, PORT)
self.assertFalse(firewall_win.missing_rule(status))
- self.assertEqual(advise(status).action, "repair")
+ self.assert_installer_advice(status)
def test_pairing_only_blocks_are_reported_and_never_auto_repaired(self):
for transport in ("TCP", "UDP"):
@@ -73,8 +94,7 @@ class InterpretTests(unittest.TestCase):
rule(action="Block", port=str(firewall_win.PAIRING_PORT), protocol=transport)]
status = interpret(payload(rules), EXE, PORT)
self.assertTrue(status.blocked)
- self.assertEqual(advise(status).action, "repair")
- self.assertIn("pairing", advise(status).sentence)
+ self.assert_administrator_advice(status)
self.assertFalse(firewall_win.missing_rule(status))
def test_pairing_rules_must_cover_every_lan_profile(self):
@@ -84,15 +104,18 @@ class InterpretTests(unittest.TestCase):
pairing_tcp_rule(profile="Public" if transport == "TCP" else "Private")]
status = interpret(payload(rules), EXE, PORT)
self.assertFalse(status.pairing_tcp_covered if transport == "TCP" else status.pairing_covered)
- self.assertEqual(advise(status).action, "repair")
+ self.assert_installer_advice(status)
self.assertFalse(firewall_win.missing_rule(status))
- def test_public_lan_with_private_pairing_rules_offers_trust(self):
+ def test_public_lan_advises_changing_the_profile_in_windows_settings(self):
rules = [rule(profile="Any"), pairing_rule(), pairing_tcp_rule()]
status = interpret(payload(rules, [network("Public")]), EXE, PORT)
self.assertFalse(status.pairing_covered)
self.assertFalse(status.pairing_tcp_covered)
- self.assertEqual(advise(status).action, "trust")
+ advice = advise(status)
+ self.assertEqual(advice.action, "check")
+ self.assertIn("Windows Settings", advice.sentence)
+ self.assertEqual(advice.button, "Check again")
def test_pairing_block_on_an_inactive_profile_does_not_hide_healthy_rules(self):
rules = [rule(), pairing_rule(), pairing_tcp_rule(),
@@ -112,13 +135,13 @@ class InterpretTests(unittest.TestCase):
self.assertTrue(status.pairing_tcp_allowed)
self.assertEqual(advise(status).action, "check")
- def test_no_rule_at_all(self):
+ def test_no_rule_at_all_points_to_installer_repair(self):
status = interpret(payload(), EXE, PORT)
self.assertFalse(status.allowed)
self.assertFalse(status.blocked)
self.assertFalse(status.covered)
self.assertEqual(status.active_profiles, ("Private",))
- self.assertEqual(advise(status).action, "repair")
+ advice = self.assert_installer_advice(status)
def test_correct_rule_on_private_lan(self):
status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule()]), EXE, PORT)
@@ -138,16 +161,16 @@ class InterpretTests(unittest.TestCase):
self.assertFalse(status.covered)
self.assertEqual(status.public_interfaces, ((9, "Ethernet"),))
advice = advise(status)
- self.assertEqual(advice.action, "trust")
- self.assertIn("Ethernet", advice.sentence)
- self.assertEqual(advice.button, "Trust this network")
+ self.assertEqual(advice.action, "check")
+ self.assertIn("Windows Settings", advice.sentence)
+ self.assertEqual(advice.button, "Check again")
def test_public_only_rule_on_private_lan_is_rewritten_not_trusted(self):
status = interpret(payload([rule(profile="Public")]), EXE, PORT)
self.assertTrue(status.allowed)
self.assertFalse(status.covered)
self.assertEqual(status.public_interfaces, ())
- self.assertEqual(advise(status).action, "repair")
+ self.assert_installer_advice(status)
def test_block_rule_beats_allow_rule(self):
# What Windows writes when Cancel is pressed on its own prompt: a block, any port, per profile.
@@ -155,9 +178,8 @@ class InterpretTests(unittest.TestCase):
status = interpret(payload(rules), EXE, PORT)
self.assertTrue(status.allowed)
self.assertTrue(status.blocked)
- advice = advise(status)
- self.assertEqual(advice.action, "repair")
- self.assertIn("blocking", advice.sentence)
+ advice = self.assert_administrator_advice(status)
+ self.assertIn("block rule", advice.sentence)
def test_block_rule_on_an_inactive_profile_is_harmless(self):
status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule(), rule(action="Block", profile="Public", port="Any")]), EXE, PORT)
@@ -171,7 +193,7 @@ class InterpretTests(unittest.TestCase):
def test_executable_path_not_matching_the_rule(self):
status = interpret(payload([rule(program=r"C:\Users\alex\code\Beamer\dist\Beamer.exe")]), EXE, PORT)
self.assertFalse(status.allowed)
- self.assertEqual(advise(status).action, "repair")
+ self.assert_installer_advice(status)
def test_path_match_ignores_case_and_slashes(self):
status = interpret(payload([rule(program=EXE.lower().replace("\\", "/"))]), EXE, PORT)
@@ -179,7 +201,7 @@ class InterpretTests(unittest.TestCase):
def test_port_must_cover_the_listen_port(self):
self.assertFalse(interpret(payload([rule(port="51821")]), EXE, PORT).allowed)
- self.assertTrue(interpret(payload([rule(port="51000-52000")]), EXE, PORT).allowed)
+ self.assertTrue(interpret(payload([rule(port="24000-25000")]), EXE, PORT).allowed)
self.assertTrue(interpret(payload([rule(port="Any")]), EXE, PORT).allowed)
self.assertFalse(interpret(payload([rule(protocol="UDP")]), EXE, PORT).allowed)
self.assertFalse(interpret(payload([rule(direction="Outbound")]), EXE, PORT).allowed)
@@ -203,17 +225,32 @@ class InterpretTests(unittest.TestCase):
self.assertTrue(status.covered)
self.assertEqual(advise(status).action, "check")
- def test_domain_lan_widens_the_rule_to_domain_never_public(self):
- status = interpret(payload([rule()], [network("DomainAuthenticated", alias="Ethernet")]), EXE, PORT)
- advice = advise(status)
- self.assertEqual(advice.action, "repair")
- self.assertEqual(advice.rule_profiles, ("Private", "Domain"))
+ def test_domain_lan_missing_receiver_rules_requires_administrator(self):
+ for rules in ([], [rule(), pairing_rule(), pairing_tcp_rule()]):
+ with self.subTest(rules=rules):
+ status = interpret(payload(rules, [network("DomainAuthenticated", alias="Ethernet")]), EXE, PORT)
+ advice = self.assert_administrator_advice(status)
+ self.assertIn("managed", advice.sentence)
+
+ def test_domain_lan_missing_pairing_coverage_requires_administrator(self):
+ rules = [rule(profile="Domain"), pairing_rule(), pairing_tcp_rule()]
+ status = interpret(payload(rules, [network("DomainAuthenticated")]), EXE, PORT)
+ self.assertTrue(status.covered)
+ advice = self.assert_administrator_advice(status)
+ self.assertIn("managed", advice.sentence)
- def test_not_elevated_explains_instead_of_offering(self):
+ def test_missing_default_port_rules_point_to_installer_regardless_of_elevation(self):
status = interpret(payload(), EXE, PORT, elevated=False)
+ advice = self.assert_installer_advice(status)
+ self.assertIn("run the Beamer installer again", advice.sentence)
+
+ def test_custom_port_advice_names_the_administrator_and_port(self):
+ status = interpret(payload(), EXE, 30000, elevated=True)
advice = advise(status)
- self.assertIsNone(advice.action)
- self.assertIn("not running as administrator", advice.sentence)
+ self.assertEqual(advice.action, "check")
+ self.assertEqual(advice.button, "Check again")
+ self.assertIn("custom port 30000", advice.sentence)
+ self.assertIn("administrator", advice.sentence)
def test_error_offers_a_recheck(self):
status = firewall_win.FirewallStatus(PORT, False, False, (), (), False, (), True, error="Access is denied")
@@ -314,22 +351,19 @@ if __name__ == "__main__":
unittest.main()
-class PairingRuleTests(unittest.TestCase):
+class PairingRuleTests(InstallerAdviceAssertions, unittest.TestCase):
"""An install made before pairing existed has the TCP rule and not the UDP one. Reporting
only the TCP rule told that user everything was fine while no Mac could ever discover them."""
- def test_tcp_rule_without_the_pairing_rule_is_reported_and_repairable(self):
+ def test_tcp_rule_without_the_pairing_rule_points_to_installer_repair(self):
status = interpret(payload([rule()]), EXE, PORT)
self.assertTrue(status.allowed)
self.assertFalse(status.pairing_allowed)
- advice = advise(status)
- self.assertEqual(advice.action, "repair")
- self.assertIn("pairing beacon", advice.sentence)
- self.assertIn("will not hear other machines' pairing announcements", advice.sentence)
+ advice = self.assert_installer_advice(status)
+ self.assertIn("run the Beamer installer again", advice.sentence)
- def test_a_missing_pairing_rule_is_one_this_app_may_add_by_itself(self):
- # An upgrade from 1.4.x has the receiver and the UDP rule and no TCP one: the first code shown
- # would otherwise make Windows ask, and a click on Allow writes rules for public networks too.
+ def test_a_missing_pairing_rule_is_reported_for_installer_repair(self):
+ # An upgrade from 1.4.x has the receiver and the UDP rule and no TCP one.
status = interpret(payload([rule(), pairing_rule()]), EXE, PORT)
self.assertTrue(firewall_win.missing_rule(status))
whole = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule()]), EXE, PORT)
@@ -353,20 +387,17 @@ class PairingRuleTests(unittest.TestCase):
status = interpret(payload([rule(), wrong]), EXE, PORT)
self.assertFalse(status.pairing_allowed)
- def test_pairing_rules_without_the_tcp_one_is_reported_and_repairable(self):
+ def test_pairing_rules_without_the_tcp_one_point_to_installer_repair(self):
# Installs from before pairing version 3 have the UDP beacon rule and not the TCP exchange.
status = interpret(payload([rule(), pairing_rule()]), EXE, PORT)
self.assertTrue(status.pairing_allowed)
self.assertFalse(status.pairing_tcp_allowed)
- advice = advise(status)
- self.assertEqual(advice.action, "repair")
- self.assertIn(f"TCP {firewall_win.PAIRING_PORT}", advice.sentence)
- self.assertNotIn("UDP", advice.sentence)
+ advice = self.assert_installer_advice(status)
+ self.assertIn("run the Beamer installer again", advice.sentence)
- def test_both_pairing_rules_missing_names_both(self):
- advice = advise(interpret(payload([rule()]), EXE, PORT))
- self.assertIn(f"UDP {firewall_win.PAIRING_PORT}", advice.sentence)
- self.assertIn(f"TCP {firewall_win.PAIRING_PORT}", advice.sentence)
+ def test_both_pairing_rules_missing_points_to_installer_repair(self):
+ status = interpret(payload([rule()]), EXE, PORT)
+ self.assert_installer_advice(status)
def test_a_disabled_or_udp_pairing_tcp_rule_does_not_count(self):
for wrong in (pairing_tcp_rule(enabled="False"), {**pairing_tcp_rule(), "protocol": "UDP"}):
@@ -377,8 +408,7 @@ class PairingRuleTests(unittest.TestCase):
status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule(action="Block")]), EXE, PORT)
self.assertFalse(status.pairing_tcp_allowed)
- def test_a_missing_tcp_rule_is_reported_before_the_pairing_rule(self):
- # Input not arriving at all is the bigger problem; one button fixes both.
+ def test_a_missing_receiver_rule_points_to_installer_repair(self):
status = interpret(payload([pairing_rule()]), EXE, PORT)
self.assertFalse(status.allowed)
- self.assertIn("no rule letting your other machines reach", advise(status).sentence)
+ self.assert_installer_advice(status)
diff --git a/win_app/tests/test_focus_sender.py b/win_app/tests/test_focus_sender.py
new file mode 100644
index 0000000..0bcd763
--- /dev/null
+++ b/win_app/tests/test_focus_sender.py
@@ -0,0 +1,26 @@
+import os
+import sys
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
+from links_rig import B, Rig
+
+
+class FocusSenderTests(unittest.TestCase):
+ def test_send_preserves_the_mapped_display_and_side(self):
+ rig = Rig()
+ # The owner's internal form (core/owner.py _take): a raw machine id, which _send rebuilds for the wire.
+ focus = {"type": protocol.MSG_FOCUS, "data": {"route": 1, "target": B, "edge": "right", "offset": 0.5,
+ "display": "macbook", "side": "left", "reach": []}}
+
+ rig.sender._send(B, focus)
+
+ sent = [message for peer, message in rig.links.sent if peer == B and message["type"] == protocol.MSG_FOCUS]
+ self.assertEqual(len(sent), 1)
+ self.assertEqual((sent[0]["data"]["display"], sent[0]["data"]["side"]), ("macbook", "left"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_gameinput_foreground.py b/win_app/tests/test_gameinput_foreground.py
index 5ae92a2..937f01e 100644
--- a/win_app/tests/test_gameinput_foreground.py
+++ b/win_app/tests/test_gameinput_foreground.py
@@ -1,17 +1,11 @@
-"""GameInput's SYSTEM window taking the foreground, exercised on any platform.
-
-While GameInputSvc's hidden window is in front, Windows refuses Beamer's
-SetCursorPos and drops its SendInput, and the only way out Beamer has is to
-restart the service. user32, subprocess.run and the restart thread are all
-faked here, so this suite runs on the Mac.
-"""
+"""UIPI refusals are reported without runtime service recovery."""
import ctypes
+import os
import subprocess
+import sys
import unittest
from unittest import mock
-import os
-import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -38,16 +32,6 @@ class FakeUser32:
return self.set_results.pop(0) if self.set_results else 1
-class InlineThread:
- """Runs the restart on start(), so a test sees its effects at once."""
-
- def __init__(self, target, name=None, daemon=None):
- self.target = target
-
- def start(self):
- self.target()
-
-
GAMEINPUT, EXPLORER = 0x5403CC, 0xD0002E
CLASSES = {GAMEINPUT: input_injector.GAMEINPUT_WINDOW_CLASS, EXPLORER: "CabinetWClass"}
@@ -55,120 +39,104 @@ CLASSES = {GAMEINPUT: input_injector.GAMEINPUT_WINDOW_CLASS, EXPLORER: "CabinetW
class GameInputForegroundTests(unittest.TestCase):
def setUp(self):
self.user32 = FakeUser32(CLASSES)
- self.restarts = []
-
- def restart(args, **kwargs):
- self.restarts.append((args, kwargs))
- self.user32.foreground = EXPLORER
- return subprocess.CompletedProcess(args, 0, b"", b"")
-
self.clock = [1000.0]
patches = [
mock.patch.object(input_injector, "user32", self.user32),
mock.patch.object(desktop_win, "user32", self.user32),
- mock.patch.object(input_injector.subprocess, "run", side_effect=restart),
- mock.patch.object(input_injector.threading, "Thread", InlineThread),
mock.patch.object(input_injector.time, "monotonic", lambda: self.clock[0]),
mock.patch.object(ctypes, "get_last_error", create=True, return_value=0),
mock.patch.object(input_injector, "_seen_foreground", [None]),
- mock.patch.object(input_injector, "_gameinput_restarted_at", [float("-inf")]),
+ mock.patch.object(input_injector, "_problem_at", float("-inf")),
mock.patch.object(desktop_win, "_refused_under", [None]),
]
for patch in patches:
patch.start()
self.addCleanup(patch.stop)
- def test_a_move_under_gameinput_restarts_the_service_without_a_console(self):
+ def test_gameinput_foreground_reports_the_limit_without_restarting_a_service(self):
self.user32.foreground = GAMEINPUT
- input_injector.watch_foreground()
- self.assertEqual(len(self.restarts), 1)
- args, kwargs = self.restarts[0]
- self.assertEqual(args, input_injector.GAMEINPUT_RESTART)
- self.assertIn("Restart-Service GameInputSvc", args[-1])
- self.assertEqual(kwargs["creationflags"], getattr(subprocess, "CREATE_NO_WINDOW", 0))
-
- def test_an_ordinary_foreground_is_left_alone(self):
+ notice = mock.Mock()
+ with mock.patch.object(input_injector, "on_problem", notice), \
+ mock.patch.object(subprocess, "run") as run, \
+ mock.patch.object(subprocess, "Popen") as popen, \
+ mock.patch.object(os, "system") as system:
+ input_injector.watch_foreground()
+
+ notice.assert_called_once()
+ self.assertIn("administrator windows locally", notice.call_args.args[0])
+ run.assert_not_called()
+ popen.assert_not_called()
+ system.assert_not_called()
+
+ def test_input_problem_notice_is_throttled_for_thirty_seconds(self):
+ notices = []
+ with mock.patch.object(input_injector, "on_problem", notices.append):
+ input_injector.report_input_problem()
+ self.clock[0] += 29
+ input_injector.report_input_problem()
+ self.clock[0] += 1
+ input_injector.report_input_problem()
+
+ self.assertEqual(len(notices), 2)
+ self.assertIn("click a normal window on this PC", notices[0])
+
+ def test_ordinary_foreground_does_not_report_a_problem(self):
self.user32.foreground = EXPLORER
- for _ in range(3):
+ notice = mock.Mock()
+ with mock.patch.object(input_injector, "on_problem", notice):
input_injector.watch_foreground()
- self.assertEqual(self.restarts, [])
+ notice.assert_not_called()
- def test_the_class_is_read_only_when_the_foreground_changes(self):
+ def test_successful_cursor_placement_runs_the_arrival_callback(self):
self.user32.foreground = EXPLORER
- with mock.patch.object(input_injector, "_window_class", wraps=input_injector._window_class) as lookup:
- for _ in range(5):
- input_injector.watch_foreground()
- self.assertEqual(lookup.call_count, 1)
+ placed = mock.Mock()
- def test_a_restart_that_did_not_free_it_waits_out_the_cooldown_then_tries_again(self):
- self.restarts_leave_gameinput_in_front()
- self.user32.foreground = GAMEINPUT
- input_injector.watch_foreground()
- self.clock[0] += 5
- input_injector.watch_foreground()
- self.assertEqual(len(self.restarts), 1)
- self.clock[0] += input_injector.GAMEINPUT_RESTART_COOLDOWN_SECONDS
- input_injector.watch_foreground()
- self.assertEqual(len(self.restarts), 2)
-
- def test_a_refused_arrival_is_placed_again_once_gameinput_is_gone(self):
- self.user32.foreground = GAMEINPUT
- self.user32.set_results = [0]
- desktop_win.set_cursor_position(1818, 2159)
- self.assertEqual(len(self.restarts), 1)
- self.assertEqual(self.user32.set_calls, [(1818, 2159), (1818, 2159)])
+ desktop_win.set_cursor_position_with_callback(
+ 1818, 2159, placed, place_if_current=lambda action: action(),
+ )
- def test_placement_callback_waits_for_the_gameinput_retry(self):
- self.user32.foreground = GAMEINPUT
- self.user32.set_results = [0]
- placed = mock.Mock()
+ placed.assert_called_once_with()
+ self.assertEqual(self.user32.set_calls, [(1818, 2159)])
- desktop_win.set_cursor_position_with_callback(1818, 2159, placed)
+ def test_failed_cursor_placement_does_not_claim_arrival_and_warns_once_per_blocker(self):
+ self.user32.foreground = EXPLORER
+ self.user32.set_results = [0, 0, 1, 0]
+ placed = mock.Mock()
+ notice = mock.Mock()
+ with mock.patch.object(input_injector, "report_input_problem", notice), \
+ self.assertLogs(desktop_win.LOGGER, "WARNING") as logs:
+ for _ in range(4):
+ desktop_win.set_cursor_position_with_callback(10, 20, placed)
placed.assert_called_once_with()
- self.assertEqual(self.user32.set_calls, [(1818, 2159), (1818, 2159)])
+ self.assertEqual(notice.call_count, 2)
+ self.assertEqual(len(logs.records), 2)
+ self.assertIn("CabinetWClass", logs.output[0])
- def test_pending_arrival_does_not_warp_after_its_visit_ends(self):
- self.user32.set_results = [0]
- current = [True]
+ def test_stale_visit_neither_moves_the_cursor_nor_calls_arrival(self):
placed = mock.Mock()
- with mock.patch.object(input_injector, "release_gameinput_foreground", return_value=True) as retry:
- desktop_win.set_cursor_position_with_callback(
- 1818, 2159, placed, place_if_current=lambda action: action() if current[0] else None)
+ current = [False]
- placed.assert_not_called()
- current[0] = False
- retry.call_args.kwargs["after"]()
+ desktop_win.set_cursor_position_with_callback(
+ 1818, 2159, placed,
+ place_if_current=lambda action: action() if current[0] else None,
+ )
- self.assertEqual(self.user32.set_calls, [(1818, 2159)])
+ self.assertEqual(self.user32.set_calls, [])
placed.assert_not_called()
- def test_failed_placement_does_not_claim_arrival_completed(self):
+ def test_refused_placement_does_not_call_arrival_even_for_a_current_visit(self):
self.user32.foreground = EXPLORER
self.user32.set_results = [0]
placed = mock.Mock()
- with self.assertLogs(desktop_win.LOGGER, "WARNING"):
- desktop_win.set_cursor_position_with_callback(10, 20, placed)
- placed.assert_not_called()
-
- def test_a_refusal_under_anything_else_is_logged_once_per_blocker(self):
- self.user32.foreground = EXPLORER
- self.user32.set_results = [0, 0, 0, 1, 0]
- with self.assertLogs(desktop_win.LOGGER, "WARNING") as logs:
- for _ in range(3):
- desktop_win.set_cursor_position(10, 10)
- desktop_win.set_cursor_position(10, 10)
- desktop_win.set_cursor_position(10, 10)
- self.assertEqual(len(logs.records), 2)
- self.assertIn("CabinetWClass", logs.output[0])
- self.assertEqual(self.restarts, [])
-
- def restarts_leave_gameinput_in_front(self):
- def restart(args, **kwargs):
- self.restarts.append((args, kwargs))
- return subprocess.CompletedProcess(args, 0, b"", b"")
+ with mock.patch.object(input_injector, "report_input_problem"):
+ desktop_win.set_cursor_position_with_callback(
+ 1818, 2159, placed,
+ place_if_current=lambda action: action(),
+ )
- input_injector.subprocess.run.side_effect = restart
+ self.assertEqual(self.user32.set_calls, [(1818, 2159)])
+ placed.assert_not_called()
if __name__ == "__main__":
diff --git a/win_app/tests/test_hide_addresses_win.py b/win_app/tests/test_hide_addresses_win.py
index f0d8756..1818ea2 100644
--- a/win_app/tests/test_hide_addresses_win.py
+++ b/win_app/tests/test_hide_addresses_win.py
@@ -3,9 +3,11 @@ starts no receiver, hooks or announcer."""
import json
import os
+import sys
import tempfile
import unittest
from pathlib import Path
+from unittest import mock
try:
from PySide6.QtWidgets import QApplication
@@ -62,8 +64,16 @@ class HideAddressesWindowTest(unittest.TestCase):
self.edit_settings(hide_addresses=True)
self.window.reload_config()
shown = []
- self.window.tray.showMessage = lambda title, message, *rest: shown.append(message)
- self.window._on_alert("Beamer", "Cannot switch — Connected to the Mac at 192.0.2.10")
+ if sys.platform.startswith("linux"):
+ import portal
+
+ with mock.patch.object(portal, "sandboxed", return_value=True), \
+ mock.patch.object(portal, "notify", side_effect=lambda _title, message: shown.append(message)):
+ self.window._on_alert("Beamer", "Cannot switch — Connected to the Mac at 192.0.2.10")
+ else:
+ self.window.tray = mock.Mock()
+ self.window._on_alert("Beamer", "Cannot switch — Connected to the Mac at 192.0.2.10")
+ shown.append(self.window.tray.showMessage.call_args.args[1])
self.assertEqual(shown, ["Cannot switch — Connected to the Mac at •••"])
diff --git a/win_app/tests/test_identify_screens_qt.py b/win_app/tests/test_identify_screens_qt.py
index 0490392..0433cc9 100644
--- a/win_app/tests/test_identify_screens_qt.py
+++ b/win_app/tests/test_identify_screens_qt.py
@@ -8,7 +8,7 @@ from unittest.mock import Mock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from PySide6.QtCore import QRect, QRectF, Qt
+from PySide6.QtCore import QEventLoop, QRect, QRectF, QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
@@ -100,7 +100,20 @@ class IdentifyOverlayTests(unittest.TestCase):
self.assertEqual(len(controller.windows), 1)
self.assertEqual(controller.windows[0].number, 1)
self.assertLessEqual(controller._expiry.remainingTime(), remaining)
- QTest.qWait(3150)
+ # Observe expiry directly; a separate wait timer can finish before an offscreen timeout
+ # is delivered, and a generous deadline allows for event-loop scheduling under load.
+ loop = QEventLoop()
+ deadline = QTimer()
+ expired = []
+ deadline.setSingleShot(True)
+ deadline.setTimerType(Qt.TimerType.PreciseTimer)
+ deadline.timeout.connect(loop.quit)
+ controller._expiry.timeout.connect(lambda: expired.append(True))
+ controller._expiry.timeout.connect(loop.quit)
+ deadline.start(5000)
+ loop.exec()
+ deadline.stop()
+ self.assertTrue(expired, "the three-second overlay expiry timer did not fire within five seconds")
self.assertFalse(controller.windows)
clock.return_value = 3.0
controller.show_numbers({"0": 2}, display)
diff --git a/win_app/tests/test_installer_maintenance.py b/win_app/tests/test_installer_maintenance.py
new file mode 100644
index 0000000..c89488b
--- /dev/null
+++ b/win_app/tests/test_installer_maintenance.py
@@ -0,0 +1,218 @@
+"""Installer checks use mocked mutations and a harmless maintenance handoff stub."""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+
+WIN_APP = Path(__file__).parents[1]
+MAINTENANCE = WIN_APP / "Install-Maintenance.ps1"
+
+
+class InstallerMaintenanceContractTests(unittest.TestCase):
+ def test_both_installers_use_one_narrow_maintenance_entry_point(self):
+ setup = (WIN_APP / "Beamer-Setup.iss").read_text(encoding="utf-8")
+ install = (WIN_APP / "Install-Beamer.ps1").read_text(encoding="utf-8")
+ self.assertTrue(MAINTENANCE.is_file(), "The installer-owned maintenance script is missing")
+ for source in (setup, install):
+ self.assertIn("Invoke-InstallMaintenance.ps1", source)
+ self.assertIn("-ExePath", source)
+ launcher = (WIN_APP / "Invoke-InstallMaintenance.ps1").read_text(encoding="utf-8")
+ self.assertIn("-UserSid", launcher)
+ self.assertIn("-Verb RunAs", launcher)
+ self.assertIn("-File", launcher)
+ self.assertNotIn("-Command", launcher)
+ self.assertIn("PrivilegesRequired=lowest", setup)
+ self.assertNotIn("Start-Process -FilePath $ExeDestination -WorkingDirectory $InstallDir -Verb RunAs", install)
+ self.assertNotIn("New-NetFirewallRule", install)
+ self.assertIn('$_.Path -eq $ExeDestination', install)
+ self.assertNotIn("--uninstall-cleanup", setup)
+ self.assertNotIn('[Run]', setup)
+ self.assertIn('-Remove', setup)
+
+ def test_elevation_cannot_launch_the_app_or_accept_an_arbitrary_command(self):
+ self.assertTrue(MAINTENANCE.is_file(), "The installer-owned maintenance script is missing")
+ source = MAINTENANCE.read_text(encoding="utf-8")
+ self.assertIn("GameInputSvc", source)
+ self.assertIn("Restart-Service", source)
+ self.assertIn("LeastPrivilege", source)
+ self.assertIn("InteractiveToken", source)
+ self.assertIn("Register-ScheduledTask", source)
+ self.assertNotIn("Start-Process", source)
+ self.assertNotIn("Invoke-Expression", source)
+ self.assertNotIn("EncodedCommand", source)
+ self.assertNotIn("settings.json", source)
+
+
[email protected](os.name == "nt", "PowerShell behaviour is checked on Windows")
+class MaintenanceBehaviourTests(unittest.TestCase):
+ def run_probe(self, probe):
+ self.assertTrue(MAINTENANCE.is_file(), "The installer-owned maintenance script is missing")
+ path = str(MAINTENANCE).replace("'", "''")
+ source = f"$ErrorActionPreference = 'Stop'\n. '{path}'\n" + probe
+ with tempfile.TemporaryDirectory(prefix="beamer-maintenance-") as directory:
+ script = Path(directory) / "probe.ps1"
+ script.write_text(source, encoding="utf-8-sig")
+ result = subprocess.run(
+ [shutil.which("powershell") or "pwsh", "-NoProfile", "-NonInteractive",
+ "-ExecutionPolicy", "Bypass", "-File", str(script)],
+ capture_output=True, text=True, timeout=30,
+ )
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
+ def test_migration_preserves_choices_and_ignores_other_users_and_actions(self):
+ self.run_probe(r'''
+$script:registered = @()
+$script:fixtures = @{}
+function Resolve-BeamerUserSid($Identity) { return $Identity }
+function Get-ScheduledTask { param($TaskPath, $ErrorAction)
+ return @($script:fixtures.Keys | ForEach-Object { [pscustomobject]@{ TaskName = $_; TaskPath = '\' } })
+}
+function Export-ScheduledTask { param($TaskName, $TaskPath, $ErrorAction) return $script:fixtures[$TaskName] }
+function Register-ScheduledTask { param($TaskName, $TaskPath, $Xml, [switch]$Force, $ErrorAction)
+ $script:registered += [pscustomobject]@{ Name = $TaskName; Xml = $Xml }
+}
+$template = '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>false</Enabled><UserId>S-1-5-21-123</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>{0}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals><Settings><Enabled>false</Enabled><ExecutionTimeLimit>PT0S</ExecutionTimeLimit></Settings><Actions Context="Author"><Exec><Command>{1}</Command><Arguments>--hidden --keep-this</Arguments><WorkingDirectory>C:\A &amp; B</WorkingDirectory></Exec>{2}</Actions></Task>'
+$script:fixtures['Beamer'] = $template -f 'S-1-5-21-123', 'C:\A &amp; B\Beamer.exe', ''
+$script:fixtures['Beamer-other-user'] = $template -f 'S-1-5-21-999', 'C:\A &amp; B\Beamer.exe', ''
+$script:fixtures['Beamer-other-exe'] = $template -f 'S-1-5-21-123', 'C:\Other\Beamer.exe', ''
+$script:fixtures['Beamer-extra-action'] = $template -f 'S-1-5-21-123', 'C:\A &amp; B\Beamer.exe', '<Exec><Command>C:\Other.exe</Command></Exec>'
+$script:fixtures['Unrelated'] = $script:fixtures['Beamer']
+Update-BeamerAutostart -ExePath 'C:\A & B\Beamer.exe' -UserSid 'S-1-5-21-123'
+if ($script:registered.Count -ne 1 -or $script:registered[0].Name -ne 'Beamer') { throw 'Changed an unrelated task or missed the matching task' }
+$expected = $script:fixtures['Beamer'].Replace('HighestAvailable', 'LeastPrivilege')
+[xml]$actual = $script:registered[0].Xml
+[xml]$wanted = $expected
+if ($actual.OuterXml -ne $wanted.OuterXml) { throw 'Migration changed existing user choices' }
+$script:registered = @()
+$script:fixtures = @{}
+Update-BeamerAutostart -ExePath 'C:\A & B\Beamer.exe' -UserSid 'S-1-5-21-123'
+if ($script:registered.Count) { throw 'Created startup when no task exists' }
+''')
+
+ def test_firewall_is_fixed_scope_and_service_recovery_is_optional(self):
+ self.run_probe(r'''
+$script:rules = @()
+$script:restarted = @()
+function Get-NetFirewallRule { param($DisplayName, $ErrorAction) return @() }
+function Remove-NetFirewallRule { param([Parameter(ValueFromPipeline=$true)]$InputObject) }
+function New-NetFirewallRule { param($DisplayName, $Direction, $Protocol, $LocalPort, $Action, $Profile, $Program, $ErrorAction)
+ $script:rules += [pscustomobject]@{ Name=$DisplayName; Port=$LocalPort; Protocol=$Protocol; Profile=$Profile; Program=$Program }
+}
+function Get-Service { param($Name, $ErrorAction) return $null }
+function Restart-Service { param($Name, [switch]$Force, $ErrorAction) $script:restarted += $Name }
+Repair-BeamerFirewall -ExePath 'C:\A & B\Beamer.exe'
+Repair-BeamerGameInput
+if ($script:rules.Count -ne 3) { throw 'Expected exactly three firewall rules' }
+if (@($script:rules | Where-Object { $_.Profile -ne 'Private' -or $_.Program -ne 'C:\A & B\Beamer.exe' }).Count) { throw 'Rule scope broadened' }
+if (($script:rules | ForEach-Object { "$($_.Protocol):$($_.Port)" }) -join ',' -ne 'TCP:24820,UDP:24821,TCP:24821') { throw 'Unexpected ports or protocols' }
+if ($script:restarted.Count) { throw 'Restarted absent GameInput service' }
+function Get-Service { param($Name, $ErrorAction) return [pscustomobject]@{ Name='GameInputSvc' } }
+Repair-BeamerGameInput
+if ($script:restarted.Count -ne 1 -or $script:restarted[0] -ne 'GameInputSvc') { throw 'Did not recover only GameInputSvc' }
+''')
+
+ def test_uninstall_removes_only_matching_tasks_and_program_rules(self):
+ self.run_probe(r'''
+$script:removedTasks = @()
+$script:removedRules = @()
+function Resolve-BeamerUserSid($Identity) { return $Identity }
+function Get-ScheduledTask { param($TaskPath, $ErrorAction) return [pscustomobject]@{ TaskName='Beamer'; TaskPath='\' } }
+function Export-ScheduledTask { param($TaskName, $TaskPath, $ErrorAction)
+ return '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Principals><Principal><UserId>S-1-5-21-123</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Actions><Exec><Command>C:\Beamer\Beamer.exe</Command></Exec></Actions></Task>'
+}
+function Unregister-ScheduledTask { param($TaskName, $TaskPath, $Confirm, $ErrorAction) $script:removedTasks += $TaskName }
+function Get-NetFirewallRule { param($DisplayName, $ErrorAction)
+ return @([pscustomobject]@{ Name='ours' }, [pscustomobject]@{ Name='other-install' })
+}
+function Get-NetFirewallApplicationFilter { param([Parameter(ValueFromPipeline=$true)]$InputObject)
+ process { if ($InputObject.Name -eq 'ours') { [pscustomobject]@{ Program='C:\Beamer\Beamer.exe' } } else { [pscustomobject]@{ Program='C:\Other\Beamer.exe' } } }
+}
+function Remove-NetFirewallRule { param([Parameter(ValueFromPipeline=$true)]$InputObject) process { $script:removedRules += $InputObject.Name } }
+Update-BeamerAutostart -ExePath 'C:\Beamer\Beamer.exe' -UserSid 'S-1-5-21-123' -Remove
+Remove-BeamerFirewall -ExePath 'C:\Beamer\Beamer.exe'
+if ($script:removedTasks.Count -ne 1 -or $script:removedTasks[0] -ne 'Beamer') { throw 'Matching task was not removed' }
+if ($script:removedRules.Count -ne 3 -or @($script:removedRules | Where-Object { $_ -ne 'ours' }).Count) { throw 'Removed another install firewall rule' }
+''')
+
+
[email protected](os.name == "nt", "Launcher handoff is checked on Windows")
+class LauncherArgumentHandoffTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ if not (os.environ.get("SSH_CLIENT") or os.environ.get("SSH_CONNECTION")):
+ raise unittest.SkipTest("Real launcher handoff requires an SSH session")
+ cls.powershell = str(Path(os.environ.get("SystemRoot", r"C:\Windows")) /
+ "System32/WindowsPowerShell/v1.0/powershell.exe")
+ probe = r'''
+$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
+$principal = New-Object Security.Principal.WindowsPrincipal($identity)
+[pscustomobject]@{
+ elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+ session = (Get-Process -Id $PID).SessionId
+ sid = $identity.User.Value
+} | ConvertTo-Json -Compress
+'''
+ result = subprocess.run(
+ [cls.powershell, "-NoProfile", "-NonInteractive", "-Command", probe],
+ capture_output=True, text=True, timeout=10,
+ )
+ if result.returncode:
+ raise unittest.SkipTest("Could not establish a safe noninteractive launcher context")
+ context = json.loads(result.stdout)
+ if not context["elevated"] or context["session"] != 0:
+ raise unittest.SkipTest("Real launcher handoff requires an elevated SSH process in session 0")
+ cls.caller_sid = context["sid"]
+
+ def prepare_launcher(self, directory):
+ root = Path(directory)
+ launcher = root / "Invoke-InstallMaintenance.ps1"
+ shutil.copyfile(WIN_APP / launcher.name, launcher)
+ (root / "Install-Maintenance.ps1").write_text(r'''
+[CmdletBinding()]
+param([string]$ExePath, [string]$UserSid, [switch]$Remove)
+$ErrorActionPreference = 'Stop'
+[pscustomobject]@{ ExePath=$ExePath; UserSid=$UserSid; Remove=[bool]$Remove } |
+ ConvertTo-Json -Compress | Set-Content -LiteralPath (Join-Path $PSScriptRoot 'received.json') -Encoding UTF8
+''', encoding="utf-8-sig")
+ return launcher
+
+ def run_file(self, script, *arguments):
+ return subprocess.run(
+ [self.powershell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
+ "-File", str(script), *arguments],
+ capture_output=True, text=True, timeout=30,
+ )
+
+ def test_file_handoff_keeps_metacharacters_sid_and_remove_literal(self):
+ with tempfile.TemporaryDirectory(prefix="ADMIN2 launcher ' & $(1+1) ; ", dir=WIN_APP.parent) as directory:
+ launcher = self.prepare_launcher(directory)
+ exe = str(Path(directory) / "Receiver ' & $(2+2) ; literal" / "Beamer.exe")
+ for remove in (False, True):
+ with self.subTest(remove=remove):
+ result = self.run_file(launcher, "-ExePath", exe, *(["-Remove"] if remove else []))
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ received = json.loads((Path(directory) / "received.json").read_text(encoding="utf-8-sig"))
+ self.assertEqual(received, {"ExePath": exe, "UserSid": self.caller_sid, "Remove": remove})
+
+ def test_quote_bearing_exe_path_is_rejected_before_child_launch(self):
+ with tempfile.TemporaryDirectory(prefix="ADMIN2 invalid argument ", dir=WIN_APP.parent) as directory:
+ self.prepare_launcher(directory)
+ driver = Path(directory) / "invoke-invalid.ps1"
+ driver.write_text(r'''
+$ErrorActionPreference = 'Stop'
+$badPath = $PSScriptRoot + '\bad"argument\Beamer.exe'
+& (Join-Path $PSScriptRoot 'Invoke-InstallMaintenance.ps1') -ExePath $badPath
+exit $LASTEXITCODE
+''', encoding="utf-8-sig")
+ result = self.run_file(driver)
+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("Invalid installer path", " ".join((result.stdout + result.stderr).split()))
+ self.assertFalse((Path(directory) / "received.json").exists(), "The maintenance child ran before path validation")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_links_loopback.py b/win_app/tests/test_links_loopback.py
index b84a575..0952e72 100644
--- a/win_app/tests/test_links_loopback.py
+++ b/win_app/tests/test_links_loopback.py
@@ -96,7 +96,8 @@ class Loopback(unittest.TestCase):
self.take()
self.far.stop()
self.assertTrue(wait_for(lambda: not self.sender.redirecting, 5))
- self.assertIn("Lost the link to Here", self.alerts)
+ # The owner returns home before the link thread reports the alert.
+ self.assertTrue(wait_for(lambda: "Lost the link to Here" in self.alerts, 5), self.alerts)
def test_a_peer_that_does_not_allow_driving_refuses_and_input_comes_home(self):
self.far.settings.peer(TOKENS[B])["allow_drive"] = False
diff --git a/win_app/tests/test_linux_permissions.py b/win_app/tests/test_linux_permissions.py
index 92a34d1..ed7adc6 100644
--- a/win_app/tests/test_linux_permissions.py
+++ b/win_app/tests/test_linux_permissions.py
@@ -238,6 +238,7 @@ class LinuxPermissionsTest(unittest.TestCase):
if surface.permission_state is not None:
surface.permission_state.on_change = surface._on_permission
surface._set_peer_send = surface._set_peer_allow = surface._set_peer_in_use = lambda *_args: None
+ surface._set_peer_pin = lambda *_args: None
surface._set_shortcut_cycle = lambda *_args: None
surface._re_pair = lambda *_args: None
surface._set_peer_left_out = surface._rename_peer = lambda *_args: None
diff --git a/win_app/tests/test_no_uac_autostart.py b/win_app/tests/test_no_uac_autostart.py
new file mode 100644
index 0000000..99a5cde
--- /dev/null
+++ b/win_app/tests/test_no_uac_autostart.py
@@ -0,0 +1,26 @@
+import unittest
+import xml.etree.ElementTree as ET
+from unittest.mock import patch
+
+import autostart_win
+
+
+class OrdinaryAutostartTests(unittest.TestCase):
+ def test_registered_task_runs_at_users_normal_privilege(self):
+ root = ET.fromstring(autostart_win.task_xml(r"C:\A & B\Beamer.exe", r"PC\user"))
+ self.assertEqual(root.findtext("{*}Principals/{*}Principal/{*}RunLevel"), "LeastPrivilege")
+ self.assertEqual(root.findtext("{*}Principals/{*}Principal/{*}LogonType"), "InteractiveToken")
+
+ def test_highest_task_cannot_count_as_a_completed_migration(self):
+ exe = r"C:\Beamer\Beamer.exe"
+ xml = autostart_win.task_xml(exe, r"PC\user").replace("LeastPrivilege", "HighestAvailable")
+ self.assertFalse(autostart_win._replacement_ready(ET.fromstring(xml), exe, "--hidden"))
+
+ def test_an_ordinary_signed_in_account_can_enable_startup(self):
+ with patch.object(autostart_win, "current_user", return_value=r"PC\standard"), \
+ patch.object(autostart_win, "_process_user", return_value=r"PC\standard"):
+ self.assertTrue(autostart_win.can_run_for_current_user())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_no_uac_runtime.py b/win_app/tests/test_no_uac_runtime.py
new file mode 100644
index 0000000..a86247f
--- /dev/null
+++ b/win_app/tests/test_no_uac_runtime.py
@@ -0,0 +1,69 @@
+"""Denied input stays visible without giving the ordinary app maintenance rights."""
+
+import ctypes
+import subprocess
+import unittest
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import desktop_win
+import firewall_win
+import input_injector
+
+
+class OrdinaryInputTests(unittest.TestCase):
+ def test_sendinput_refusal_reports_problem_without_spamming(self):
+ notices = []
+ with patch.object(input_injector, "user32", SimpleNamespace(SendInput=lambda *a: 0)), \
+ patch.object(input_injector, "on_problem", notices.append, create=True), \
+ patch.object(input_injector, "_problem_at", float("-inf"), create=True), \
+ patch.object(ctypes, "get_last_error", return_value=0, create=True):
+ for _ in range(3):
+ with self.assertRaises(OSError):
+ input_injector._send_input(input_injector.INPUT())
+ self.assertEqual(len(notices), 1)
+ self.assertIn("locally", notices[0])
+
+ def test_successful_input_has_no_warning(self):
+ notices = []
+ with patch.object(input_injector, "user32", SimpleNamespace(SendInput=lambda n, *a: n)), \
+ patch.object(input_injector, "on_problem", notices.append, create=True):
+ input_injector._send_input(input_injector.INPUT())
+ self.assertEqual(notices, [])
+
+ def test_gameinput_refusal_never_runs_service_maintenance(self):
+ notices, commands = [], []
+ with patch.object(input_injector, "foreground_class", return_value="GameInputServiceWindow"), \
+ patch.object(input_injector, "on_problem", notices.append, create=True), \
+ patch.object(input_injector, "_problem_at", float("-inf"), create=True), \
+ patch.object(subprocess, "run", side_effect=lambda *a, **k: commands.append(a)), \
+ patch.object(input_injector.threading, "Thread") as thread:
+ self.assertFalse(input_injector.release_gameinput_foreground())
+ self.assertEqual(commands, [])
+ thread.assert_not_called()
+ self.assertEqual(len(notices), 1)
+
+ def test_failed_cursor_placement_reports_problem(self):
+ notices = []
+ with patch.object(desktop_win, "user32", SimpleNamespace(SetCursorPos=lambda *a: 0)), \
+ patch.object(input_injector, "foreground_class", return_value="AdminWindow"), \
+ patch.object(input_injector, "on_problem", notices.append, create=True), \
+ patch.object(input_injector, "_problem_at", float("-inf"), create=True), \
+ patch.object(desktop_win, "_refused_under", [None]), \
+ patch.object(ctypes, "get_last_error", return_value=0, create=True):
+ desktop_win.set_cursor_position(10, 20)
+ self.assertEqual(len(notices), 1)
+
+
+class InstallerOwnedFirewallTests(unittest.TestCase):
+ def test_missing_rules_direct_user_to_installer_even_in_elevated_session(self):
+ for elevated in (False, True):
+ status = firewall_win.FirewallStatus(24820, False, False, ("Private",),
+ ("Private",), False, (), elevated)
+ advice = firewall_win.advise(status)
+ self.assertEqual(advice.action, "check")
+ self.assertIn("installer", advice.sentence)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.py
index c80a5e4..8c9dc9f 100644
--- a/win_app/tests/test_pages_win.py
+++ b/win_app/tests/test_pages_win.py
@@ -7,6 +7,7 @@ from unittest import mock
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import app_config
+import platform_parts
from core import effects
from core import ways
import pages_win
@@ -367,13 +368,14 @@ class CrossingPageTest(unittest.TestCase):
choice._buttons["quarter"].click()
self.assertEqual(app_config.load_config(self.path).frame_rate, "quarter")
- def test_mouse_only_switch_saves_applies_and_reflects_without_resaving(self):
+ def test_mouse_only_switch_saves_applies_when_supported_and_reflects_without_resaving(self):
from unittest import mock
self.assertFalse(self.page.mouse_only_switch.isChecked())
self.page.mouse_only_switch.click()
self.assertTrue(app_config.load_config(self.path).mouse_only)
- self.assertTrue(self.page.sender._ignore_gate.mouse_only)
+ wayland = sys.platform.startswith("linux") and platform_parts.session(os.environ) == "wayland"
+ self.assertEqual(self.page.sender._ignore_gate.mouse_only, not wayland)
config = app_config.load_config(self.path)
config.mouse_only = False
with mock.patch.object(self.page, "_persist") as persist:
diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.py
index a39aee2..80ac16b 100644
--- a/win_app/tests/test_pairing_window.py
+++ b/win_app/tests/test_pairing_window.py
@@ -43,6 +43,20 @@ def peer(identity, name, token, host, platform="macos", paired_at=1_780_000_000,
@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")
class MachinesWindowTest(unittest.TestCase):
+ def test_address_pin_can_be_released_and_restored_per_machine(self):
+ first = peer(ID_A, "Studio", TOKEN_A, "192.0.2.10")
+ first["host_pinned"] = True
+ self.open(first, peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))
+ row = self.window.machines.rows[TOKEN_A]
+ self.assertTrue(row.pin_address.isChecked())
+ row.pin_address.click()
+ self.assertIs(self.settings()["peers"][0]["host_pinned"], False)
+ self.window._persist()
+ self.assertIs(self.settings()["peers"][0]["host_pinned"], False)
+ row.pin_address.click()
+ self.assertIs(self.settings()["peers"][0]["host_pinned"], True)
+ self.assertIs(self.settings()["peers"][1]["host_pinned"], False)
+
def setUp(self):
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
self.app = QApplication.instance() or QApplication([])
diff --git a/win_app/tests/test_phone_ui.py b/win_app/tests/test_phone_ui.py
index 63bf283..8230a22 100644
--- a/win_app/tests/test_phone_ui.py
+++ b/win_app/tests/test_phone_ui.py
@@ -207,7 +207,7 @@ class PhoneUiTests(unittest.TestCase):
dict(KEEP_NOTE="kept", peerlist=peerlist))()
for name in ("name", "word", "where", "detail", "confirm_text", "in_use", "send", "allow",
"remove_button", "directions", "direction_group", "shortcut_cycle", "repair_button",
- "confirm", "left_out", "left_out_note"):
+ "confirm", "left_out", "left_out_note", "pin_address"):
setattr(row, name, Control())
row.led = SimpleNamespace(set_tone=lambda tone: None)
row.confirm.visible = False
@@ -217,6 +217,7 @@ class PhoneUiTests(unittest.TestCase):
self.assertEqual(row.where.text(), "iPhone")
self.assertFalse(row.directions.visible)
self.assertFalse(row.direction_group.visible)
+ self.assertFalse(row.pin_address.visible)
row._ask(False)
self.assertFalse(row.directions.visible)
self.assertTrue(row.in_use.visible)
diff --git a/win_app/tests/test_portable.py b/win_app/tests/test_portable.py
index b9b025a..94ece2d 100644
--- a/win_app/tests/test_portable.py
+++ b/win_app/tests/test_portable.py
@@ -2,6 +2,7 @@
import json
import os
+import subprocess
from pathlib import Path
import sys
import tempfile
@@ -208,13 +209,12 @@ class PortableTests(unittest.TestCase):
legacy.assert_not_called()
run.assert_not_called()
- def test_gameinput_service_is_not_queried_or_restarted_in_portable_mode(self):
+ def test_gameinput_service_is_not_restarted_in_portable_mode(self):
after = mock.Mock()
with mock.patch.object(input_injector, 'foreground_class') as foreground, \
- mock.patch.object(input_injector.windows_tools, 'run') as run, \
+ mock.patch.object(subprocess, 'run') as run, \
mock.patch.object(input_injector.threading, 'Thread') as thread:
self.assertFalse(input_injector.release_gameinput_foreground(after=after))
- foreground.assert_not_called()
run.assert_not_called()
thread.assert_not_called()
after.assert_not_called()
@@ -222,7 +222,6 @@ class PortableTests(unittest.TestCase):
def test_manual_automatic_and_startup_firewall_paths_never_mutate_host(self):
owner = SimpleNamespace(
update_checker=SimpleNamespace(start=mock.Mock()), _listen=mock.Mock(),
- bridge=SimpleNamespace(rules_ready=SimpleNamespace(emit=mock.Mock())),
firewall_note=mock.Mock(), firewall_button=mock.Mock(), _run_firewall=mock.Mock(),
_firewall_advice=SimpleNamespace(action='repair', rule_profiles=('Private',)),
)
@@ -233,12 +232,10 @@ class PortableTests(unittest.TestCase):
mock.patch.object(kvm.firewall_win, 'status') as status, \
mock.patch.object(kvm.threading, 'Thread') as thread:
kvm.WindowsApplication.start(owner)
- kvm.WindowsApplication._rules_then_listen(owner)
kvm.WindowsApplication._firewall_action(owner)
kvm.WindowsApplication._on_firewall(owner, SimpleNamespace(elevated=True))
kvm.WindowsApplication._check_firewall(owner)
owner._listen.assert_called_once()
- owner.bridge.rules_ready.emit.assert_called_once()
owner._run_firewall.assert_not_called()
owner.firewall_button.hide.assert_called_once()
for operation in (repair, trust, status, thread):
@@ -368,6 +365,10 @@ class PortableTests(unittest.TestCase):
owner.server.start.assert_not_called()
owner.sender.start.assert_not_called()
owner.hooks.start.assert_not_called()
+
+ @unittest.skipUnless(sys.platform == 'win32', 'pointer restoration is a Windows desktop API')
+ def test_blocked_controller_does_not_restore_pointer(self):
+ owner = SimpleNamespace(_input_controller_blocked=True)
with mock.patch.object(portable_runtime, 'enabled', return_value=False), \
mock.patch.object(kvm.desktop_win, 'restore_pointer') as restore, \
mock.patch.object(kvm.idle_pointer, 'IdlePointer') as pointer:
@@ -428,13 +429,28 @@ class PortableTests(unittest.TestCase):
fetcher=lambda: json.dumps(payload).encode(), portable=True)
checker.check_once()
owner = SimpleNamespace(_update=checker.latest, update_checker=checker)
- with mock.patch.object(kvm.QDesktopServices, 'openUrl') as opened:
+ with mock.patch.object(kvm.portal, 'sandboxed', return_value=False), \
+ mock.patch.object(kvm.QDesktopServices, 'openUrl') as opened:
kvm.WindowsApplication.download_update(owner)
self.assertEqual(opened.call_args.args[0].toString(), DOWNLOAD)
kvm.WindowsApplication.open_update(owner)
self.assertEqual(opened.call_args.args[0].toString(), PAGE)
self.assertEqual(opened.call_count, 2)
+ def test_flatpak_never_opens_portable_zip_directly(self):
+ payload = {'tag_name': 'v' + VERSION, 'html_url': PAGE,
+ 'assets': [{'name': 'Beamer-Portable-' + VERSION + '-windows-x64.zip',
+ 'browser_download_url': DOWNLOAD}]}
+ checker = updates.Checker('1.5.10', lambda: True, lambda result: None,
+ fetcher=lambda: json.dumps(payload).encode(), portable=True)
+ checker.check_once()
+ self.assertEqual(checker.download_url, DOWNLOAD)
+ owner = SimpleNamespace(_update=checker.latest, update_checker=checker)
+ with mock.patch.object(kvm.portal, 'sandboxed', return_value=True), \
+ mock.patch.object(kvm.QDesktopServices, 'openUrl') as opened:
+ kvm.WindowsApplication.download_update(owner)
+ opened.assert_not_called()
+
def test_missing_portable_asset_does_not_open_installer_or_release_page(self):
owner = SimpleNamespace(_update=(VERSION, PAGE),
update_checker=SimpleNamespace(download_url=None))
diff --git a/win_app/tests/test_qt_event_reentry.py b/win_app/tests/test_qt_event_reentry.py
new file mode 100644
index 0000000..2e4541a
--- /dev/null
+++ b/win_app/tests/test_qt_event_reentry.py
@@ -0,0 +1,38 @@
+"""Keep cold-process event conversion safe when earlier recorder fixtures are collected."""
+
+import os
+from pathlib import Path
+import subprocess
+import sys
+import unittest
+
+
[email protected](sys.platform == "win32", "Windows native heap-corruption regression")
+class QtEventReentryTests(unittest.TestCase):
+ def test_recording_then_constructing_a_widget_survives_collection(self):
+ root = Path(__file__).resolve().parents[2]
+ source = root / "win_app"
+ environment = dict(
+ os.environ,
+ QT_QPA_PLATFORM="offscreen",
+ PYSIDE6_OPTION_LAZY="1",
+ PYTHONFAULTHANDLER="1",
+ PYTHONPATH=os.pathsep.join((str(source / "tests"), str(source), str(root))),
+ )
+ # A fresh process preserves lazy type loading; earlier Qt tests can hide the fault.
+ for attempt in range(3):
+ with self.subTest(attempt=attempt):
+ result = subprocess.run(
+ [sys.executable, str(root / "scripts/ui_audit/guarded_tests.py"), "-v",
+ "test_ignored_page"],
+ cwd=source, env=environment, capture_output=True,
+ text=True, errors="replace", timeout=30,
+ )
+ output = result.stdout + result.stderr
+ self.assertEqual(result.returncode, 0, output)
+ self.assertIn("Ran 7 tests", output)
+ self.assertNotIn("skipped", output.lower())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_update_notice.py b/win_app/tests/test_update_notice.py
index 8fcb738..c16dd16 100644
--- a/win_app/tests/test_update_notice.py
+++ b/win_app/tests/test_update_notice.py
@@ -16,9 +16,10 @@ from PySide6.QtWidgets import QApplication
import app_config
import kvm_bridge_win as kvm
import theme
+from core import updates
-FOUND = ("1.5.11", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.11")
+FOUND = updates.Release("1.5.11", "https://github.com/kalkman-code/beamer/releases/tag/v1.5.11")
class UpdateNoticeTest(unittest.TestCase):
@@ -36,6 +37,7 @@ class UpdateNoticeTest(unittest.TestCase):
patch.object(threading.Thread, "start", side_effect=AssertionError("service started")),
patch.object(kvm.WindowsApplication, "_make_pairing", return_value=None),
patch.object(kvm.autostart_win, "installed_exe", return_value=None),
+ patch.object(kvm.portal, "sandboxed", return_value=False),
patch("core.locale.is_us_region", return_value=False),
):
blocker.start()
@@ -49,6 +51,115 @@ class UpdateNoticeTest(unittest.TestCase):
self.addCleanup(window.deleteLater)
return window
+ def test_quiet_patch_is_available_on_updates_page_without_a_banner_or_tray_alert(self):
+ quiet = updates.newer_release("1.5.10", {"tag_name": "v1.5.12"})
+ with patch.object(kvm.portal, "sandboxed", return_value=False):
+ self.window._on_update(quiet)
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.assertFalse(self.window.header_action.isEnabled())
+ self.assertNotIn("available", self.window.header_action.text())
+ self.assertFalse(self.window.update_button.isHidden())
+ self.assertFalse(self.window.update_page_notes.isHidden())
+ self.assertIn("1.5.12", self.window.update_status.text())
+ self.window._set_check_updates(False)
+ self.window._on_update_check("available", quiet)
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.assertFalse(self.window.header_action.isEnabled())
+ self.assertIn("1.5.12", self.window.update_status.text())
+
+ def test_quiet_flatpak_keeps_release_notes_on_the_updates_page(self):
+ quiet = updates.newer_release("1.5.10", {"tag_name": "v1.5.12"})
+ with patch.object(kvm.portal, "sandboxed", return_value=True), \
+ patch.object(kvm.QDesktopServices, "openUrl") as opened:
+ self.window._on_update(quiet)
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.assertFalse(self.window.update_page_notes.isHidden())
+ self.window.update_page_notes.click()
+ self.assertEqual(opened.call_args.args[0].toString(), quiet.url)
+ self.assertIn("software store", self.window.update_status.text())
+
+ def test_quiet_patch_without_a_portable_zip_explains_the_missing_download_on_updates_page(self):
+ quiet = updates.newer_release("1.5.10", {"tag_name": "v1.5.12"})
+ settings = app_config.load_settings(self.path)
+ with patch.object(kvm.portable_runtime, "enabled", return_value=True), \
+ patch.object(app_config, "load_settings", return_value=settings):
+ self.window._on_update_check("available", quiet)
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.assertTrue(self.window.update_button.isHidden())
+ self.assertFalse(self.window.update_page_notes.isHidden())
+ self.assertIn("No portable download", self.window.update_status.text())
+
+ def test_important_release_after_quiet_patch_alerts_until_dismissed(self):
+ self.window._on_update(updates.newer_release("1.5.10", {"tag_name": "v1.5.11"}))
+ important = updates.newer_release("1.5.10", {
+ "tag_name": "v1.5.12", "body": "<!-- beamer-notify: important -->"})
+ self.window._on_update(important)
+ self.assertFalse(self.window.update_notice.isHidden())
+ self.assertTrue(self.window.header_action.isEnabled())
+ self.window.update_dismiss.click()
+ self.window._on_update(important)
+ self.assertTrue(self.window.update_notice.isHidden())
+ self.assertFalse(self.window.header_action.isEnabled())
+
+ def test_manual_check_is_visible_and_works_when_automatic_checks_are_off(self):
+ self.window._set_check_updates(False)
+ self.assertFalse(self.window.check_updates_button.isHidden())
+ self.assertEqual(self.window.check_updates_button.text(), "Check for updates")
+ with patch.object(self.window.update_checker, "check_now") as check:
+ self.window.check_updates_button.click()
+ check.assert_called_once_with(manual=True)
+ self.assertFalse(self.window._config.check_updates)
+ self.assertFalse(self.window.check_updates_button.isEnabled())
+ self.window._on_update_check("available", FOUND)
+ self.assertFalse(self.window.update_notice.isHidden())
+ self.assertFalse(self.window.update_button.isHidden())
+ self.assertIn("1.5.11", self.window.update_status.text())
+ self.assertTrue(self.window.check_updates_button.isEnabled())
+
+ def test_manual_check_reports_no_update_and_retryable_failure(self):
+ self.window._on_update_check("current", None)
+ self.assertIn("up to date", self.window.update_status.text())
+ self.window._on_update_check("checking", None)
+ self.assertFalse(self.window.check_updates_button.isEnabled())
+ self.window._on_update_check("failed", None)
+ self.assertIn("try again", self.window.update_status.text())
+ self.assertTrue(self.window.check_updates_button.isEnabled())
+
+ def test_update_notice_has_an_explicit_update_action(self):
+ with patch.object(kvm.QDesktopServices, "openUrl") as opened:
+ self.window._on_update(FOUND)
+ self.window.update_action.click()
+ self.assertEqual(opened.call_args.args[0].toString(), FOUND[1])
+
+ def test_flatpak_update_action_opens_the_release_with_store_guidance(self):
+ with patch.object(kvm.portal, "sandboxed", return_value=True), \
+ patch.object(kvm.QDesktopServices, "openUrl") as opened:
+ self.window._on_update_check("available", FOUND)
+ self.assertFalse(self.window.update_action.isHidden())
+ self.window.update_action.click()
+ self.assertEqual(opened.call_args.args[0].toString(), FOUND[1])
+ self.assertIn("Flatpak", self.window.update_notice_text.text())
+
+ def test_explicit_flatpak_check_resurfaces_a_dismissed_action_until_dismissed_again(self):
+ with patch.object(kvm.portal, "sandboxed", return_value=True):
+ self.window._on_update(FOUND)
+ self.window.update_dismiss.click()
+ self.window._set_check_updates(False)
+ self.window._on_update_check("available", FOUND)
+ self.assertFalse(self.window.update_notice.isHidden())
+ self.assertFalse(self.window.update_action.isHidden())
+ self.window.update_dismiss.click()
+ self.assertTrue(self.window.update_notice.isHidden())
+
+
+ def test_missing_portable_download_is_explained_without_offering_installer(self):
+ settings = app_config.load_settings(self.path)
+ with patch.object(kvm.portable_runtime, "enabled", return_value=True), \
+ patch.object(app_config, "load_settings", return_value=settings):
+ self.window._on_update(FOUND)
+ self.assertTrue(self.window.update_action.isHidden())
+ self.assertIn("No portable download", self.window.update_notice_text.text())
+
def test_dismissal_survives_rebuilding_and_other_settings_changes(self):
self.window._on_update(FOUND)
self.assertFalse(self.window.update_notice.isHidden())
@@ -60,7 +171,7 @@ class UpdateNoticeTest(unittest.TestCase):
rebuilt = self.build()
rebuilt._on_update(FOUND)
self.assertTrue(rebuilt.update_notice.isHidden())
- rebuilt._on_update(("1.5.12", FOUND[1]))
+ rebuilt._on_update(updates.Release("1.5.12", FOUND[1]))
self.assertFalse(rebuilt.update_notice.isHidden())
def test_switching_off_hides_the_notice_and_late_answers(self):
diff --git a/win_app/widgets.py b/win_app/widgets.py
index 52a8024..4e2ea63 100644
--- a/win_app/widgets.py
+++ b/win_app/widgets.py
@@ -35,6 +35,13 @@ from PySide6.QtWidgets import (
QWidget,
)
+# Resolve lazy Qt wrappers before application event filters run: lazy conversion
+# during widget construction triggers the Windows heap-corruption regression.
+# Shiboken's cached-module hook only recognises a positional star-import fromlist.
+for _qt_module in ("PySide6.QtCore", "PySide6.QtGui", "PySide6.QtWidgets"):
+ __import__(_qt_module, globals(), locals(), ("*",))
+del _qt_module
+
import motion
import theme
import tokens