diff --git a/orca/README.md b/orca/README.md index 0ccd95f..48da190 100644 --- a/orca/README.md +++ b/orca/README.md @@ -97,7 +97,23 @@ proxy `WINELOADER` is bypassed), the game's `WINEESYNC`/`WINEFSYNC` are forwarded so the helper joins the running server, and the helper set is staged under the state directory because the container's wineserver cannot see a system `/usr/libexec` installation; see the main README's Steam -section. A helper stops 10 seconds after its prefix +section. + +## Controller-only mode + +Some games' anti-tamper code objects to the helper's injected hooks +(Diablo IV's Eidolon component kills the game shortly after it loses +focus when the native hook DLL is present). For those, the extension's +preferences offer controller-only mode: helpers run with +`--no-dialog-reader`, injecting nothing and polling no controls, while +NVDA/Tolk speech and braille keep working. Enable it for all +applications there, or list executable names (e.g. `Diablo IV.exe`) to +apply it per game. Settings are read when a helper starts, so neither +Orca nor the reader needs a restart; relaunch the game to switch modes. +`WINE_ACCESS_NO_DIALOG_READER=1` in Orca's environment forces the same +mode for every helper, for testing. + +A helper stops 10 seconds after its prefix goes idle and restarts with exponential backoff after quick failures. Helpers run in their own session and survive an Orca restart, so a newly loaded extension retires a marked helper it did not start before starting its own. diff --git a/orca/tests/test_manager.py b/orca/tests/test_manager.py index 2c0e833..4e144d7 100644 --- a/orca/tests/test_manager.py +++ b/orca/tests/test_manager.py @@ -12,7 +12,8 @@ import unittest.mock sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "wine_access")) import manager as manager_module # noqa: E402 -from manager import HelperManager, loader_for, prefix_for # noqa: E402 +from manager import (HelperManager, controller_only_arguments, # noqa: E402 + extra_helper_arguments, loader_for, prefix_for) class FakeProcess: @@ -104,6 +105,33 @@ class DiscoveryTests(unittest.TestCase): self.assertEqual(loader_for(2, {}, self.fake.proc), str(self.fake.bin / "wine")) self.assertIsNone(loader_for(3, {}, self.fake.proc)) + def test_extra_helper_arguments_controller_only_switch(self): + self.assertEqual(extra_helper_arguments({}), []) + self.assertEqual(extra_helper_arguments( + {"WINE_ACCESS_NO_DIALOG_READER": "0"}), []) + self.assertEqual(extra_helper_arguments( + {"WINE_ACCESS_NO_DIALOG_READER": "1"}), ["--no-dialog-reader"]) + + def test_controller_only_arguments_accepts_tuple(self): + # GSettings layers may hand string arrays back as tuples. + self.assertEqual(controller_only_arguments({"game.exe"}, ("Game.EXE",), False), + ["--no-dialog-reader"]) + + def test_controller_only_arguments_matching(self): + self.assertEqual(controller_only_arguments({"game.exe"}, [], False), []) + self.assertEqual(controller_only_arguments({"game.exe"}, ["Game.EXE"], False), + ["--no-dialog-reader"]) + self.assertEqual(controller_only_arguments({"other.exe"}, ["game.exe"], False), []) + self.assertEqual(controller_only_arguments(set(), [], True), + ["--no-dialog-reader"]) + + def test_discovery_collects_program_names(self): + self.fake.add(17, "wine", {"WINEPREFIX": "/p/x"}, r"S:\games\Game.exe") + self.fake.add(18, "wine", {"WINEPREFIX": "/p/x"}, r"S:\games\launcher.exe") + manager = HelperManager([], helper="/h", proc=self.fake.proc) + _environment, _loader, programs = manager.discover()[os.path.realpath("/p/x")] + self.assertEqual(programs, {"game.exe", "launcher.exe"}) + def test_loader_finds_proton_wine_from_preloader(self): # Steam Play runs games through the preloader deep in the Proton # tree; the loader beside no same-directory wine is files/bin/wine. @@ -137,6 +165,18 @@ class DiscoveryTests(unittest.TestCase): found = sorted(manager.discover()) self.assertEqual(found, sorted([os.path.realpath("/p/mine"), os.path.realpath("/p/nobus")])) + def test_discovery_ignores_proton_steam_shim_but_not_steam_client(self): + # Proton launches games through its builtin system32 steam.exe, + # which lingers like a Wine service after the game exits. A real + # Steam client installed in a prefix is an application. + self.fake.add(15, "wine", {"WINEPREFIX": "/p/shim"}, + r"c:\windows\system32\steam.exe") + self.fake.add(16, "wine", {"WINEPREFIX": "/p/client"}, + r"C:\Program Files (x86)\Steam\steam.exe") + manager = HelperManager([], helper="/h", proc=self.fake.proc) + self.assertEqual(list(manager.discover()), + [os.path.realpath("/p/client")]) + def test_pressure_vessel_bus_counts_as_our_session(self): # Steam Play games see the session bus through pressure-vessel's # filtered proxy at a fixed container path, never the host socket. @@ -164,6 +204,11 @@ class DiscoveryTests(unittest.TestCase): self.fake.add(11, "wine", {"WINEPREFIX": "/p/b"}, r"C:\windows\system32\services.exe") self.fake.add(12, "wine", {"WINEPREFIX": "/p/c", "ORCA_WINE_ACCESS_MANAGED": "1"}) self.fake.add(13, "python3", {"WINEPREFIX": "/p/d"}) + # Proton's gamepad overlay outlives the game for as long as the + # helper keeps the wineserver alive, so it must not keep the + # prefix active on its own either. + self.fake.add(14, "wine", {"WINEPREFIX": "/p/e"}, + r"S:\steamapps\common\Proton\files\share\xalia\xalia.exe") manager = HelperManager([], helper="/h", proc=self.fake.proc) self.assertEqual(list(manager.discover()), [os.path.realpath("/p/a")]) @@ -282,6 +327,62 @@ class SupervisionTests(unittest.TestCase): self.assertEqual(helper.env["DBUS_SESSION_BUS_ADDRESS"], "unix:path=/run/user/1000/bus") + def test_pressure_vessel_game_stages_helper_under_state_dir(self): + # A wineserver started inside pressure-vessel resolves paths in + # the container, whose /usr has no wine-access. The helper set is + # staged where both namespaces see it: under the home state dir. + origin = self.fake.root / "usr-libexec" + for name in ("wine-access.exe", "wine-access.exe.so", + "wine-access-menu.dll", "wine-access-menu32.dll", + "wine-access-menu-host32.exe"): + path = origin / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"content of {name}") + path.chmod(0o755) + self.manager.helper = str(origin / "wine-access.exe") + self.fake.remove(20) + self.fake.add(25, "wine", { + "WINEPREFIX": "/p/game", "DISPLAY": ":7", + "WINELOADER": str(self.fake.bin / "wine"), + "PRESSURE_VESSEL_RUNTIME": "steamrt4", + }, r"S:\games\game.exe") + self.manager.poll() + self.assertEqual(len(self.spawned), 1) + staged = self.fake.root / "logs" / "helper" / "wine-access.exe" + self.assertEqual(self.spawned[0].command[0], str(staged)) + self.assertEqual((staged.parent / "wine-access.exe.so").read_text(), + "content of wine-access.exe.so") + self.assertEqual((staged.parent / "wine-access-menu.dll").read_text(), + "content of wine-access-menu.dll") + + def test_listed_program_starts_controller_only_helper(self): + self.manager.arguments_for = ( + lambda programs: controller_only_arguments(programs, ["App.EXE"])) + self.manager.poll() + self.assertEqual(len(self.spawned), 1) + self.assertEqual(self.spawned[0].command, + ["/helper.exe", "--reader", "orca", "--no-dialog-reader"]) + + def test_listed_program_appearing_later_restarts_controller_only(self): + # A loader process can be discovered before the game itself, so a + # helper may start in full mode one pass before the listed + # program appears. It must then restart controller-only. + self.manager.arguments_for = ( + lambda programs: controller_only_arguments(programs, ["game.exe"])) + self.manager.poll() + self.assertEqual(len(self.spawned), 1) + self.assertNotIn("--no-dialog-reader", self.spawned[0].command) + self.fake.add(26, "wine", {"WINEPREFIX": "/p/game", "DISPLAY": ":7"}, + r"S:\games\Game.exe") + self.manager.poll() + self.assertTrue(self.spawned[0].terminated) + self.manager.poll() + self.assertEqual(len(self.spawned), 2) + self.assertIn("--no-dialog-reader", self.spawned[1].command) + # And it stays controller-only rather than flapping back. + self.manager.poll() + self.assertEqual(len(self.spawned), 2) + def test_no_helper_installed_does_nothing(self): self.manager.helper = None self.manager.poll() diff --git a/orca/wine_access/__init__.py b/orca/wine_access/__init__.py index a16eafc..62e193c 100644 --- a/orca/wine_access/__init__.py +++ b/orca/wine_access/__init__.py @@ -14,8 +14,9 @@ from gi.repository import GLib from orca import debug, presentation_manager, typing_echo_presenter from orca.extension import Extension +from orca.extension_preferences import ExtensionPreference -from .manager import HelperManager +from .manager import HelperManager, controller_only_arguments, extra_helper_arguments from .presenter import WineEvent, WineEventPresenter from .review import DialogReader, gio_capture from .service import INTERFACE, OBJECT_PATH, WineAccessInterface @@ -48,7 +49,33 @@ class WineAccess(Extension): self._retry_id = 0 self._presenter: WineEventPresenter | None = None self._dialogs: DialogReader | None = None - self._manager = HelperManager(READER_ARGUMENTS) + self._manager = HelperManager( + [*READER_ARGUMENTS, *extra_helper_arguments()], + arguments_for=self._helper_arguments) + + def get_preferences(self) -> list[ExtensionPreference]: + return [ + ExtensionPreference.boolean( + "controller-only", + "Controller-only mode for all applications (no control reading)", + False), + ExtensionPreference.string_list( + "controller-only-programs", + "Controller-only programs (executable names, e.g. Diablo IV.exe)", + []), + ExtensionPreference.info( + "Controller-only helpers serve NVDA/Tolk speech without " + "injecting hooks or reading standard controls. Use it for " + "games whose anti-tamper code objects to injected hooks. " + "Changes apply the next time a helper starts."), + ] + + def _helper_arguments(self, programs: set[str]) -> list[str]: + """Per-prefix helper flags from the live controller-only settings.""" + + always = self.settings.get("controller-only", False) + listed = self.settings.get("controller-only-programs", []) + return controller_only_arguments(programs, listed, always is True) # Extension lifecycle diff --git a/orca/wine_access/manager.py b/orca/wine_access/manager.py index 3993121..199a8ba 100644 --- a/orca/wine_access/manager.py +++ b/orca/wine_access/manager.py @@ -9,7 +9,7 @@ restart with exponential backoff. from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field import hashlib import os from pathlib import Path @@ -25,13 +25,27 @@ MAX_BACKOFF_SECONDS = 60.0 STABLE_RUN_SECONDS = 10.0 LOG_LIMIT_BYTES = 256 * 1024 HELPER_PROGRAM = "wine-access.exe.so" +# The files that must stay beside the helper launcher; see the staging in +# HelperManager._helper_for. +HELPER_SIBLINGS = ("wine-access-menu.dll", "wine-access-menu32.dll", + "wine-access-menu-host32.exe") LOADER_NAMES = {"wine", "wine64"} PRELOADER_NAMES = {"wine-preloader", "wine64-preloader"} # Wine's own background processes outlive applications while anything in the # prefix runs, including the helper; they must not keep a prefix active. +# xalia.exe is Proton's gamepad overlay, in the same position: it would +# otherwise keep the prefix "active" for as long as the helper it keeps +# alive holds the wineserver up, so the helper would never stop. WINE_SERVICES = {"services.exe", "explorer.exe", "winedevice.exe", "plugplay.exe", "svchost.exe", "rpcss.exe", "conhost.exe", "tabtip.exe", - "wineboot.exe", "winemenubuilder.exe", "start.exe", "wineserver"} + "wineboot.exe", "winemenubuilder.exe", "start.exe", "wineserver", + "xalia.exe"} +# Proton launches games through its builtin steam.exe shim, which lingers +# the same way. Only the shim's system32/syswow64 home qualifies: a real +# Steam client installed in a prefix runs from its own directory and is +# an application like any other. +WINE_SERVICE_PATHS = ("windows/system32/steam.exe", + "windows/syswow64/steam.exe") FORWARDED_ENVIRONMENT = ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", # A client joining a running server (Proton enables @@ -59,6 +73,37 @@ def helper_candidates() -> list[str]: return [path for path in candidates if path] +def extra_helper_arguments(environment: dict[str, str] = os.environ) -> list[str]: + """Extra helper flags from the reader's environment. + + WINE_ACCESS_NO_DIALOG_READER=1 runs helpers controller-only: no + WinEvent hooks, no native hook DLL in applications, no MSAA polling. + That is the mode for games whose anti-tamper code objects to injected + hooks; their NVDA/Tolk speech still works, standard controls don't. + """ + + if environment.get("WINE_ACCESS_NO_DIALOG_READER", "") not in ("", "0"): + return ["--no-dialog-reader"] + return [] + + +def controller_only_arguments(programs: set[str], listed, + always: bool = False) -> list[str]: + """--no-dialog-reader if controller-only applies to these programs. + + Matching is by lower-case executable file name, as reported by + discover(); entries in the user's list may use any case. Settings + layers hand string arrays back as lists or tuples depending on the + path taken, so any sequence of strings is accepted. + """ + + names = {name.lower() for name in listed + if isinstance(name, str)} if isinstance(listed, (list, tuple)) else set() + if always or programs & names: + return ["--no-dialog-reader"] + return [] + + def find_helper() -> str | None: for path in helper_candidates(): if os.access(path, os.X_OK): @@ -79,14 +124,28 @@ def read_environment(pid: int, proc: Path = Path("/proc")) -> dict[str, str]: return result -def program_name(pid: int, proc: Path = Path("/proc")) -> str: - """Lower-case file name of the program a process runs, Windows or Linux.""" +def program_path(pid: int, proc: Path = Path("/proc")) -> str: + """Lower-case argv0 of a process, with Windows separators normalized.""" try: argv0 = (proc / str(pid) / "cmdline").read_bytes().split(b"\0", 1)[0] except OSError: return "" - return argv0.decode(errors="replace").replace("\\", "/").rsplit("/", 1)[-1].lower() + return argv0.decode(errors="replace").replace("\\", "/").lower() + + +def program_name(pid: int, proc: Path = Path("/proc")) -> str: + """Lower-case file name of the program a process runs, Windows or Linux.""" + + return program_path(pid, proc).rsplit("/", 1)[-1] + + +def is_wine_service(pid: int, proc: Path = Path("/proc")) -> bool: + """Whether a process is Wine/Proton infrastructure, not an application.""" + + path = program_path(pid, proc) + return (path.rsplit("/", 1)[-1] in WINE_SERVICES + or path.endswith(WINE_SERVICE_PATHS)) def prefix_for(environment: dict[str, str]) -> str: @@ -208,6 +267,7 @@ class PrefixState: started_at: float = 0.0 failures: int = 0 next_start: float = 0.0 + extra_arguments: list[str] = field(default_factory=list) class HelperManager: @@ -221,9 +281,13 @@ class HelperManager: log_directory: Path | None = None, clock: Callable[[], float] = time.monotonic, spawn: Callable[..., subprocess.Popen] = subprocess.Popen, + arguments_for: Callable[[set[str]], list[str]] | None = None, ) -> None: self.helper = helper if helper is not None else find_helper() self.reader_arguments = reader_arguments + # Extra helper arguments for a prefix's program names, consulted + # at each spawn so settings changes need no reader restart. + self.arguments_for = arguments_for or (lambda programs: []) self.proc = proc self.log_directory = log_directory or Path( os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state") @@ -235,10 +299,10 @@ class HelperManager: # running by an Orca that was restarted. self.stale: dict[str, list[int]] = {} - def discover(self) -> dict[str, tuple[dict[str, str], str]]: - """Active prefixes with the environment and loader of one process each.""" + def discover(self) -> dict[str, tuple[dict[str, str], str, set[str]]]: + """Active prefixes: one process's environment/loader, all program names.""" - found: dict[str, tuple[dict[str, str], str]] = {} + found: dict[str, tuple[dict[str, str], str, set[str]]] = {} self.stale = {} uid = os.getuid() helpers = {state.process.pid for state in self.prefixes.values() @@ -264,9 +328,13 @@ class HelperManager: self.stale.setdefault(prefix_for(environment), []).append(pid) continue loader = loader_for(pid, environment, self.proc) - if loader is None or program_name(pid, self.proc) in WINE_SERVICES: + if loader is None or is_wine_service(pid, self.proc): continue - found.setdefault(prefix_for(environment), (environment, loader)) + prefix = prefix_for(environment) + if prefix in found: + found[prefix][2].add(program_name(pid, self.proc)) + else: + found[prefix] = (environment, loader, {program_name(pid, self.proc)}) return found def poll(self) -> bool: @@ -276,10 +344,10 @@ class HelperManager: return True now = self.clock() active = self.discover() - for prefix, (environment, loader) in active.items(): + for prefix, (environment, loader, programs) in active.items(): state = self.prefixes.setdefault(prefix, PrefixState()) state.last_seen = now - self._ensure_running(prefix, state, environment, loader, now) + self._ensure_running(prefix, state, environment, loader, now, programs) for prefix, state in list(self.prefixes.items()): self._record_exit(state, now) if prefix not in active and now - state.last_seen >= IDLE_GRACE_SECONDS: @@ -287,12 +355,57 @@ class HelperManager: del self.prefixes[prefix] return True - def _command(self) -> list[str]: - return [self.helper, *self.reader_arguments] + def _helper_for(self, source: dict[str, str]) -> str: + """The helper launcher path this prefix's wineserver can open. + + A wineserver started inside pressure-vessel resolves unix paths + in the container, whose /usr is the Steam Runtime, so a + system-installed helper is invisible to it (the spawn fails with + "ShellExecuteEx failed: File not found"). The home directory is + bound at the same path in both namespaces, so for such prefixes + stage a copy of the helper set under the state directory. + """ + + if "PRESSURE_VESSEL_RUNTIME" not in source: + return self.helper + origin = Path(self.helper) + stage = self.log_directory / "helper" + try: + stage.mkdir(parents=True, exist_ok=True) + names = [origin.name, origin.name + ".so", *HELPER_SIBLINGS] + for name in names: + source_file = origin.parent / name + target = stage / name + if not source_file.is_file(): + continue + if target.is_file() and target.read_bytes() == source_file.read_bytes(): + continue + shutil.copy2(source_file, target) + except OSError: + return self.helper + staged = stage / origin.name + return str(staged) if staged.is_file() else self.helper + + def _command(self, source: dict[str, str], programs: set[str]) -> list[str]: + return [self._helper_for(source), *self.reader_arguments, + *self.arguments_for(programs)] def _ensure_running(self, prefix: str, state: PrefixState, - source: dict[str, str], loader: str, now: float) -> None: + source: dict[str, str], loader: str, now: float, + programs: set[str]) -> None: self._record_exit(state, now) + if state.process is not None: + # A helper can start one pass before the program it serves is + # discovered (a loader process shows up first). If that + # program turns out to be controller-only, restart the helper + # in that mode; never downgrade a running controller-only + # helper the same way, or modes would flap with the process + # list. + if ("--no-dialog-reader" in self.arguments_for(programs) + and "--no-dialog-reader" not in state.extra_arguments): + self._stop(state) + else: + return if state.process is not None or now < state.next_start: return stale = self.stale.get(prefix, []) @@ -318,21 +431,22 @@ class HelperManager: environment[key] = source[key] environment.update(WINEPREFIX=prefix, WINELOADER=loader, WINEDEBUG="-all") environment[MANAGED_KEY] = "1" - log = self._log_file(prefix) + log = self._log_file(prefix, programs) try: state.process = self.spawn( - self._command(), env=environment, stdin=subprocess.DEVNULL, + self._command(source, programs), env=environment, stdin=subprocess.DEVNULL, stdout=log or subprocess.DEVNULL, stderr=log or subprocess.DEVNULL, start_new_session=True, ) state.started_at = now + state.extra_arguments = self.arguments_for(programs) except OSError: self._back_off(state, now) finally: if log is not None: log.close() - def _log_file(self, prefix: str): + def _log_file(self, prefix: str, programs: set[str]): try: self.log_directory.mkdir(parents=True, exist_ok=True) name = hashlib.sha256(prefix.encode()).hexdigest()[:12] @@ -340,7 +454,8 @@ class HelperManager: # Keep earlier starts for diagnosis, within a bounded size. mode = "a" if path.exists() and path.stat().st_size < LOG_LIMIT_BYTES else "w" log = open(path, mode, encoding="utf-8") - log.write(f"--- {time.strftime('%Y-%m-%d %H:%M:%S')} starting helper for {prefix}\n") + log.write(f"--- {time.strftime('%Y-%m-%d %H:%M:%S')} starting helper for {prefix} " + f"programs={sorted(programs)} extra={self.arguments_for(programs)}\n") log.flush() return log except OSError: diff --git a/tests/README.md b/tests/README.md index bf230cc..dc98c96 100644 --- a/tests/README.md +++ b/tests/README.md @@ -794,6 +794,20 @@ typing, arrow navigation, menus and shutdown, including password exclusion. Audible speech and physical Braille require separate live checks. This change adds diagnostics; it does not establish a fix for a remote machine's silence. +## build.sh Orca extension installation + +```sh +python3 tests/build_sh_orca_test.py +shellcheck build.sh +``` + +This check needs no Wine build. It stubs `cmake`, the tools `build.sh` +requires, and `orca`, then verifies the extension's shared copy is installed +under the chosen prefix only when Orca 51 or later is present, that the +per-user link and approve commands are printed without touching the user +extension directory, and that removal deletes the extension files even when +Orca is no longer installed while leaving unrelated files in place. + ## foobar2000 Preferences Run `menu_integration.py --fixture controls` and `--fixture foobar-controls`