Add Orca extension for Wine accessibility

Publish the Wine Access protocol on Orca’s service connection and manage helpers per active Wine prefix. Add presentation, dialog capture, documentation, and tests.

Preserve the Cthulhu default and shared helper code. Document the single-reader limit and verify Orca cleanup leaves Cthulhu-managed helpers alone. Retain integration artifacts on exceptional failures.

Validation: 45 Orca unit tests passed; 11 existing test-environment checks passed; version metadata checks, Python compilation, and staged whitespace checks passed. Full Wine integration and live speech/braille remain unverified here because MinGW, Xvfb, and Orca are unavailable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Devin PraterandClaude Opus 5.5 authored and Storm Dragon committed 2026-10-21 15:42:13 -04:00
1 parent b57681d159
commit 418f671066
13 files changed
+1913 -3

No files matched your search

+328
View File
@@ -0,0 +1,328 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
"""Runs one wine-access helper per active Wine prefix.
Wine processes are found through /proc. A helper starts in the same prefix,
with the same Wine loader and display, pointed at this extension's D-Bus
object, and stops once the prefix has been idle for a while. Failed helpers
restart with exponential backoff.
"""
from __future__ import annotations
from dataclasses import dataclass
import hashlib
import os
from pathlib import Path
import shutil
import signal
import subprocess
import time
from typing import Callable
MANAGED_KEY = "ORCA_WINE_ACCESS_MANAGED"
IDLE_GRACE_SECONDS = 10.0
MAX_BACKOFF_SECONDS = 60.0
STABLE_RUN_SECONDS = 10.0
LOG_LIMIT_BYTES = 256 * 1024
HELPER_PROGRAM = "wine-access.exe.so"
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.
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"}
FORWARDED_ENVIRONMENT = ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS")
def helper_candidates() -> list[str]:
"""Where the helper may be installed, most specific first."""
user = os.environ.get("USER", "")
candidates = [
os.environ.get("WINE_ACCESS_HELPER", ""),
os.path.expanduser("~/.local/libexec/wine-access/wine-access.exe"),
os.path.expanduser("~/.nix-profile/libexec/wine-access/wine-access.exe"),
# NixOS per-user profiles don't link libexec; Home Manager's current
# generation does.
os.path.expanduser("~/.local/state/home-manager/gcroots/current-home/"
"home-path/libexec/wine-access/wine-access.exe"),
f"/etc/profiles/per-user/{user}/libexec/wine-access/wine-access.exe" if user else "",
"/run/current-system/sw/libexec/wine-access/wine-access.exe",
"/usr/local/libexec/wine-access/wine-access.exe",
"/usr/libexec/wine-access/wine-access.exe",
]
return [path for path in candidates if path]
def find_helper() -> str | None:
for path in helper_candidates():
if os.access(path, os.X_OK):
return path
return shutil.which("wine-access.exe")
def read_environment(pid: int, proc: Path = Path("/proc")) -> dict[str, str]:
try:
raw = (proc / str(pid) / "environ").read_bytes()
except OSError:
return {}
result = {}
for entry in raw.split(b"\0"):
key, sep, value = entry.partition(b"=")
if sep:
result[key.decode(errors="replace")] = value.decode(errors="replace")
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."""
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()
def prefix_for(environment: dict[str, str]) -> str:
"""The process's Wine prefix; Wine itself defaults to ~/.wine."""
prefix = environment.get("WINEPREFIX")
if not prefix and environment.get("STEAM_COMPAT_DATA_PATH"):
prefix = os.path.join(environment["STEAM_COMPAT_DATA_PATH"], "pfx")
if not prefix:
home = environment.get("HOME") or os.path.expanduser("~")
prefix = os.path.join(home, ".wine")
return os.path.realpath(os.path.expanduser(prefix))
def loader_for(pid: int, environment: dict[str, str], proc: Path = Path("/proc")) -> str | None:
"""The Wine loader that runs this process, or None if it isn't Wine."""
try:
executable = os.readlink(proc / str(pid) / "exe")
except OSError:
return None
name = os.path.basename(executable)
# Nix wraps programs as .<name>-wrapped beside the real launcher.
if name.startswith(".") and name.endswith("-wrapped"):
name = name[1:-len("-wrapped")]
if name not in LOADER_NAMES | PRELOADER_NAMES:
return None
configured = environment.get("WINELOADER")
if configured and os.access(configured, os.X_OK):
return configured
directory = os.path.dirname(executable)
for candidate in (name.removesuffix("-preloader"), "wine"):
loader = os.path.join(directory, candidate)
if os.access(loader, os.X_OK):
return loader
return None
def _display(value: str) -> str:
"""X display without screen number or local host: ':0.0' -> ':0'."""
host, _, rest = value.rpartition(":")
if host in ("unix", "localhost"):
host = ""
return f"{host}:{rest.split('.', 1)[0]}"
def _bus(value: str) -> str:
"""The socket of a D-Bus address, ignoring guid and other keys."""
for part in value.split(";")[0].partition(":")[2].split(","):
key, _, setting = part.partition("=")
if key in ("path", "abstract"):
return setting
return value
def same_session(environment: dict[str, str], ours: dict[str, str]) -> bool:
"""Whether a process shares our D-Bus session and display.
A helper for another session (another login, or a test's private bus and
display) could never reach this reader, so such processes are left alone.
"""
for key, normal in (("DBUS_SESSION_BUS_ADDRESS", _bus), ("DISPLAY", _display)):
theirs, mine = environment.get(key), ours.get(key)
if theirs and mine and normal(theirs) != normal(mine):
return False
return True
@dataclass
class PrefixState:
process: subprocess.Popen | None = None
last_seen: float = 0.0
started_at: float = 0.0
failures: int = 0
next_start: float = 0.0
class HelperManager:
"""Reconciles running helpers with the Wine prefixes in use."""
def __init__(
self,
reader_arguments: list[str],
helper: str | None = None,
proc: Path = Path("/proc"),
log_directory: Path | None = None,
clock: Callable[[], float] = time.monotonic,
spawn: Callable[..., subprocess.Popen] = subprocess.Popen,
) -> None:
self.helper = helper if helper is not None else find_helper()
self.reader_arguments = reader_arguments
self.proc = proc
self.log_directory = log_directory or Path(
os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state")
) / "orca-wine-access"
self.clock = clock
self.spawn = spawn
self.prefixes: dict[str, PrefixState] = {}
# Helpers marked as ours but not started by this instance, e.g. left
# 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."""
found: dict[str, tuple[dict[str, str], str]] = {}
self.stale = {}
uid = os.getuid()
helpers = {state.process.pid for state in self.prefixes.values()
if state.process is not None}
try:
entries = list(self.proc.iterdir())
except OSError:
return found
for entry in entries:
if not entry.name.isdigit() or int(entry.name) in helpers:
continue
try:
if entry.stat().st_uid != uid:
continue
except OSError:
continue
pid = int(entry.name)
environment = read_environment(pid, self.proc)
if not environment or not same_session(environment, os.environ):
continue
if environment.get(MANAGED_KEY) == "1":
if program_name(pid, self.proc) == HELPER_PROGRAM:
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:
continue
found.setdefault(prefix_for(environment), (environment, loader))
return found
def poll(self) -> bool:
"""One reconciliation pass; returns True so it can be a GLib timeout."""
if not self.helper:
return True
now = self.clock()
active = self.discover()
for prefix, (environment, loader) in active.items():
state = self.prefixes.setdefault(prefix, PrefixState())
state.last_seen = now
self._ensure_running(prefix, state, environment, loader, now)
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:
self._stop(state)
del self.prefixes[prefix]
return True
def _command(self) -> list[str]:
return [self.helper, *self.reader_arguments]
def _ensure_running(self, prefix: str, state: PrefixState,
source: dict[str, str], loader: str, now: float) -> None:
self._record_exit(state, now)
if state.process is not None or now < state.next_start:
return
stale = self.stale.get(prefix, [])
if stale:
# Only one helper may own a Wine desktop; retire the leftover one
# and start ours on a later pass.
for pid in stale:
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass
state.next_start = now + 1.0
return
environment = os.environ.copy()
for key in FORWARDED_ENVIRONMENT:
if source.get(key):
environment[key] = source[key]
environment.update(WINEPREFIX=prefix, WINELOADER=loader, WINEDEBUG="-all")
environment[MANAGED_KEY] = "1"
log = self._log_file(prefix)
try:
state.process = self.spawn(
self._command(), env=environment, stdin=subprocess.DEVNULL,
stdout=log or subprocess.DEVNULL, stderr=log or subprocess.DEVNULL,
start_new_session=True,
)
state.started_at = now
except OSError:
self._back_off(state, now)
finally:
if log is not None:
log.close()
def _log_file(self, prefix: str):
try:
self.log_directory.mkdir(parents=True, exist_ok=True)
name = hashlib.sha256(prefix.encode()).hexdigest()[:12]
path = self.log_directory / f"{name}.log"
# 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.flush()
return log
except OSError:
return None
@staticmethod
def _back_off(state: PrefixState, now: float) -> None:
state.failures += 1
state.next_start = now + min(2 ** state.failures, MAX_BACKOFF_SECONDS)
def _record_exit(self, state: PrefixState, now: float) -> None:
if state.process is None or state.process.poll() is None:
return
quick = now - state.started_at < STABLE_RUN_SECONDS
state.process = None
if quick:
self._back_off(state, now)
else:
state.failures = 0
state.next_start = now
@staticmethod
def _stop(state: PrefixState) -> None:
process, state.process = state.process, None
if process is None or process.poll() is not None:
return
process.terminate()
try:
process.wait(timeout=2.0)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def shutdown(self) -> None:
for state in self.prefixes.values():
self._stop(state)
self.prefixes.clear()