diff --git a/README.md b/README.md index 48fbebd..dfccea8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Wine Access `wine-access` is a standalone Wine-hosted accessibility helper for screen -readers that implement its Wine D-Bus protocol. An Orca endpoint is -available for future Orca-side integration; stock Orca does not implement -the required Wine methods. +readers that implement its Wine D-Bus protocol. Stock Orca does not implement +the required Wine methods; the Orca user extension in [`orca/`](orca/README.md) +adds them and starts the helper for Orca. It provides these capabilities: @@ -247,6 +247,9 @@ value, states, description, position, count and window title, in that order. The reader handles focus tracking, event filtering and presentation; preserve repeated editor actions and exclude password values as described below. +The [Orca extension](orca/README.md) implements this endpoint, including the +optional review methods, and supervises the helper for each Wine prefix. + Orca's existing `SpeakMessage` and `DisplayMessage` methods have different names/signatures. Wine Access does not translate to those methods. An Orca contributor must implement the Wine methods above for the capabilities they diff --git a/orca/README.md b/orca/README.md new file mode 100644 index 0000000..f1e8c26 --- /dev/null +++ b/orca/README.md @@ -0,0 +1,102 @@ +# Wine Access for Orca + +An Orca 51 user extension that lets stock Orca use the Wine Access helper. +It publishes the Wine methods on Orca's own D-Bus service connection and +starts one helper per active Wine prefix, so Orca reads standard Wine +controls, native menus, Edit and Scintilla editing feedback, NVDA +Controller/Tolk speech and braille, UIA notifications, and dialog messages. + +## Install + +1. Build and install the helper as described in the main README. +2. Copy `orca/wine_access/` to `~/.local/share/orca/extensions/`. +3. Approve it with `orca --approve-extension wine_access` and restart Orca. + Approval records a hash of the package; approve again after any update. + +Only one reader's helper can run on a Wine desktop/prefix at a time. Stop +Cthulhu's Wine helper before using Orca for that prefix, and disable this +extension before returning to Cthulhu. The extension does not stop or replace +Cthulhu-managed helpers; the helper's existing singleton guard rejects a +second instance. Installing these files alone does not change Cthulhu's +default endpoint or helper startup. + +The extension looks for `wine-access.exe` in `$WINE_ACCESS_HELPER`, +`~/.local/libexec/wine-access/`, `~/.nix-profile/libexec/wine-access/`, +Home Manager's current generation, the NixOS user and system profiles, +`/usr/local/libexec/wine-access/`, `/usr/libexec/wine-access/`, and then +`PATH`. + +## Endpoint + +| | | +| --- | --- | +| Bus name | `org.gnome.Orca1.Service` (owned by Orca) | +| Object | `/org/gnome/Orca1/Service/WineAccess` | +| Interface | `org.gnome.Orca1.WineAccess` | + +It implements `SpeakText`, `CancelSpeech`, `BrailleMessage`, `SpeakSsml` +(answering `ERROR_CALL_NOT_IMPLEMENTED`), `PresentAccessibleEvent`, and the +optional review methods `RegisterWineReviewProvider` and +`PresentWineReviewFocus`. The extension class has no Orca-decorated commands, +so Orca publishes nothing of its own at that module path. + +## Helper supervision + +Every two seconds the extension scans `/proc` for the user's Wine processes +(`wine`, `wine64`, their preloaders and Nix `.wine-wrapped` launchers), +ignoring Wine's own service processes and anything outside Orca's D-Bus +session and display. For each prefix (`WINEPREFIX`, +`STEAM_COMPAT_DATA_PATH/pfx`, or `~/.wine`) it starts: + +```sh +wine-access.exe --reader orca --reader-path /org/gnome/Orca1/Service/WineAccess \ + --reader-interface org.gnome.Orca1.WineAccess +``` + +with the program's own `WINELOADER`, display and bus, and +`ORCA_WINE_ACCESS_MANAGED=1`. 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. +Helper output is appended to +`~/.local/state/orca-wine-access/.log`. + +## Presentation + +- Focus bursts are coalesced for 50 ms; repeated output within 100 ms is + dropped, and a state event that changes nothing audible stays quiet. +- Values, name and state changes are read for the focused source; selections + may come from another source in the focused window (combo box lists). +- `text` events are presented immediately and never merged, so repeated + characters are heard. Typed characters (`kind=8`) follow Orca's character + echo setting and are skipped when Orca's key echo already spoke the key. + Navigation, selection and deletion reports interrupt speech; single + characters use Orca's capitalization style. +- Password fields: values and editor feedback are never presented. +- Window titles are announced when they change, since Wine windows are not + visible to AT-SPI. +- Dialog messages: when review focus enters a new window with role `dialog`, + the extension captures it once with `CaptureWindow` and presents its + visible, unprotected labels after the focused control. Text that arrives + before that window's focus waits up to 300 ms for it. + +## Tests + +```sh +python3 -m pytest orca/tests/test_presenter.py orca/tests/test_manager.py \ + orca/tests/test_service.py orca/tests/test_review.py +dbus-run-session -- xvfb-run -a python3 orca/tests/integration_test.py --build-dir build +``` + +The unit tests need `dasbus`. The integration test needs a built tree, Wine, +both MinGW compilers and `widl`; it hosts the extension's interface, presenter, +dialog reader and helper manager under Orca's bus name on a private display +and bus, lets the manager start the helper, runs the Notepad and controller +fixtures, and checks what Orca would present. To check the extension against +an installed Orca, run `orca/tests/orca_api_check.py` with Orca's Python +environment; it loads the extension and verifies the Orca APIs it calls. + +Recorded presentations do not prove audible speech. For live acceptance, +open Wine Notepad with Orca running and check the window title, line, +word and character movement, selection and Backspace feedback, the File +menu, and the save dialog's buttons and message. diff --git a/orca/tests/integration_test.py b/orca/tests/integration_test.py new file mode 100644 index 0000000..5242c71 --- /dev/null +++ b/orca/tests/integration_test.py @@ -0,0 +1,221 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""End-to-end test: real Wine, real wine-access helper, this extension's code. + +Run from the repository root after building, inside a private display and bus: + dbus-run-session -- xvfb-run -a python3 orca/tests/integration_test.py --build-dir build + +The extension's D-Bus interface and presenter are hosted under Orca's service +name with Orca's output replaced by a recorder. The extension's manager finds +the Wine prefix and launches the helper itself. Upstream's Notepad fixture +then drives actual Wine Notepad, and the controller fixture sends NVDA +Controller speech. Assertions check what Orca would have presented. +""" + +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import time + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "wine_access")) + +from dasbus.connection import SessionMessageBus # noqa: E402 +from gi.repository import GLib # noqa: E402 + +from manager import HelperManager # noqa: E402 +from presenter import WineEvent, WineEventPresenter # noqa: E402 +from review import DialogReader, gio_capture # noqa: E402 +from service import INTERFACE, OBJECT_PATH, WineAccessInterface # noqa: E402 + +READER_ARGUMENTS = ["--reader", "orca", "--reader-path", OBJECT_PATH, + "--reader-interface", INTERFACE] + + +class RecordingOrca: + """Stands in for the extension's Orca backend and records its output.""" + + def __init__(self, connection): + self.output = [] + self.presenter = WineEventPresenter( + lambda message, interrupt: self.output.append(("present", message, interrupt)), + lambda text, inserted: self.output.append(("echo", text, inserted)), + GLib.timeout_add, GLib.source_remove) + self.dialogs = DialogReader(gio_capture(connection), self.presenter.present_after_focus) + + def register_review(self, sender, path, version): + self.output.append(("review-registered", sender)) + return self.dialogs.register(sender, path, version) + + def review_focus(self, sender, window, focus, revision, title, role): + return self.dialogs.focus(sender, window, focus, revision, title, role) + + def speak_text(self, text, interrupt): + self.output.append(("speak", text, interrupt)) + return bool(text) + + def cancel_speech(self): + self.output.append(("cancel",)) + return True + + def braille_message(self, text): + self.output.append(("braille", text)) + return bool(text) + + def present_event(self, *arguments): + return self.presenter.handle(WineEvent(*arguments)) + + +def pump(seconds, until=lambda: False): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline and not until(): + while GLib.MainContext.default().iteration(False): + pass + time.sleep(0.01) + + +def windows_path(path): + return "Z:" + str(path).replace("/", "\\") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--build-dir", default="build", type=Path) + args = parser.parse_args() + args.source = Path(__file__).resolve().parents[2] + build = args.build_dir.resolve() + args.helper = str(build / "wine-access.exe") + args.generated = build / "generated" + + bus = SessionMessageBus() + orca = RecordingOrca(bus.connection) + bus.publish_object(OBJECT_PATH, WineAccessInterface(orca)) + bus.register_service("org.gnome.Orca1.Service") + + temporary = Path(tempfile.mkdtemp(prefix="orca-wine-access-")) + env = os.environ.copy() + env.update(WINEPREFIX=str(temporary / "prefix"), WINEDEBUG="-all", + WINEDLLOVERRIDES="mscoree,mshtml=") + env.pop("ORCA_WINE_ACCESS_MANAGED", None) + processes = [] + manager = HelperManager(READER_ARGUMENTS, helper=args.helper, + log_directory=temporary / "logs") + # Only manage this test's prefix, never the user's own Wine programs. + own_prefix = os.path.realpath(env["WINEPREFIX"]) + discover = manager.discover + manager.discover = lambda: {p: v for p, v in discover().items() if p == own_prefix} + failures = [] + succeeded = False + print("Test files:", temporary, flush=True) + + def check(condition, message): + print(("PASS: " if condition else "FAIL: ") + message) + if not condition: + failures.append(message) + + try: + fixtures = {name: temporary / f"{name}-fixture.exe" for name in ("notepad", "controller")} + tests = args.source / "tests" + subprocess.run(["x86_64-w64-mingw32-gcc", "-Wall", "-mwindows", "-o", str(fixtures["notepad"]), + str(tests / "notepad_fixture.c"), "-luser32"], check=True) + # Like upstream's controller test: a client stub with an explicit binding. + idl = temporary / "nvdaController.idl" + idl.write_text((args.source / "nvdaController.idl").read_text().replace( + "\n uuid(", "\n implicit_handle(handle_t controllerBinding),\n uuid(")) + subprocess.run(["widl", "--win64", "-c", "-o", str(temporary / "nvdaController_c.c"), + str(idl)], check=True) + subprocess.run(["x86_64-w64-mingw32-gcc", "-Wall", "-I" + str(temporary), + "-I" + str(args.generated), "-o", str(fixtures["controller"]), + str(tests / "controller_fixture.c"), "-lrpcrt4"], check=True) + subprocess.run(["wineboot", "-u"], env=env, check=True, timeout=120) + + # An idle Wine program makes the prefix active before the fixtures run. + idle = subprocess.Popen(["wine", "cmd.exe"], env=env, stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + processes.append(idle) + prefix = os.path.realpath(env["WINEPREFIX"]) + pump(20, lambda: (manager.poll(), prefix in manager.prefixes + and manager.prefixes[prefix].process is not None)[1]) + state = manager.prefixes.get(prefix) + check(state is not None and state.process is not None, + "manager discovered the Wine prefix and started the helper") + if state is None or state.process is None: + return 1 + pump(3) + check(state.process.poll() is None, + "helper accepted the extension's interface (introspection check passed)") + + ready = temporary / "ready" + fixture_env = dict(env, WINE_ACCESS_FIXTURE_READY=windows_path(ready)) + notepad = subprocess.Popen(["wine", str(fixtures["notepad"])], env=fixture_env) + processes.append(notepad) + pump(60, lambda: (manager.poll(), notepad.poll() is not None)[1]) + pump(1) + check(notepad.returncode == 0, f"Notepad fixture finished ({notepad.returncode})") + + echoes = [(text, inserted) for kind, text, inserted in + (o for o in orca.output if o[0] == "echo")] + typed = [text for text, inserted in echoes if inserted] + navigation = [text for text, inserted in echoes if not inserted] + presented = [o[1] for o in orca.output if o[0] == "present"] + check(typed == ["z", "z", "space", "new line"], f"typed characters echoed: {typed}") + for expected in ("e", "l", "beta", "Notepad second line", "N selected", + "N unselected", "N deleted"): + check(expected in navigation, f"editor feedback {expected!r}") + check(navigation.count("l") == 2, "repeated characters both presented") + check(any("Notepad" in message for message in presented), + f"window title presented: {[m for m in presented if 'Notepad' in m][:3]}") + for button in ("Yes", "No", "Cancel"): + check(any(message.startswith(button) for message in presented), + f"save dialog button {button!r} presented") + print("Presented:", presented) + check(any(o[0] == "review-registered" for o in orca.output), + "helper registered as a review provider") + buttons = [i for i, m in enumerate(presented) if m.startswith("Yes, button")] + message = presented[buttons[0] + 1] if buttons and buttons[0] + 1 < len(presented) else "" + check("untitled" in message.lower() or "save" in message.lower(), + f"save dialog message read after its button: {message!r}") + dialog_reads = [m for m in presented if m == message] + check(len(dialog_reads) == 1, "dialog message read once, not on every Tab") + + before = len(orca.output) + controller = subprocess.Popen(["wine", str(fixtures["controller"])], env=env) + processes.append(controller) + pump(30, lambda: (manager.poll(), controller.poll() is not None)[1]) + pump(1) + calls = orca.output[before:] + print("Controller calls:", calls) + check(controller.returncode == 0, "controller fixture got the expected replies, SSML 120 included") + check(("speak", "Controller speech", False) in calls, "NVDA speakText reached SpeakText") + check(("cancel",) in calls, "NVDA cancelSpeech reached CancelSpeech") + check(("braille", "Controller braille") in calls, "NVDA brailleMessage reached BrailleMessage") + check(state.process.poll() is None, "helper still running after both fixtures") + + idle.stdin.close() + for process in processes: + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + subprocess.run(["wineserver", "-k"], env=env, timeout=30) + manager.prefixes[prefix].last_seen -= 60 + manager.poll() + check(prefix not in manager.prefixes, "helper stopped once the prefix went idle") + succeeded = not failures + return 1 if failures else 0 + finally: + manager.shutdown() + for process in processes: + if process.poll() is None: + process.kill() + subprocess.run(["wineserver", "-k"], env=env, timeout=30) + if not succeeded: + print("Logs and prefix kept in", temporary) + else: + shutil.rmtree(temporary, ignore_errors=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/orca/tests/orca_api_check.py b/orca/tests/orca_api_check.py new file mode 100644 index 0000000..e4ad4b6 --- /dev/null +++ b/orca/tests/orca_api_check.py @@ -0,0 +1,24 @@ +"""Loads the extension inside Orca's Python and checks the Orca APIs it uses.""" +import inspect, sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from orca import dbus_service, presentation_manager, typing_echo_presenter +import wine_access +from wine_access import WineAccess + +ext = WineAccess() +assert ext.module_name == "WineAccess" +registration = dbus_service._ModuleRegistration.from_module_instance("WineAccess", ext) +assert registration.is_empty(), "Orca would publish its own WineAccess object and clash" +assert hasattr(ext.controller, "_bus"), "Orca's controller no longer exposes its bus" +pm = presentation_manager.get_manager() +assert "kill_flash" in inspect.signature(pm.interrupt_presentation).parameters +for name in ("present_message", "speak_message", "speak_character", "present_braille_message"): + assert callable(getattr(pm, name)), name +echo = typing_echo_presenter.get_presenter() +for name in ("get_key_echo_enabled", "get_character_echo_enabled", "get_action_keys_enabled", + "get_alphabetic_keys_enabled", "get_numeric_keys_enabled", "get_punctuation_keys_enabled"): + assert isinstance(getattr(echo, name)(), bool), name +print("echo settings: key", echo.get_key_echo_enabled(), "character", echo.get_character_echo_enabled()) +print("helper found:", ext._manager.helper) +print("PASS: extension loads in Orca 51 and every Orca API it calls exists") diff --git a/orca/tests/test_manager.py b/orca/tests/test_manager.py new file mode 100644 index 0000000..7fb9498 --- /dev/null +++ b/orca/tests/test_manager.py @@ -0,0 +1,220 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Prefix discovery and helper supervision against a fake /proc.""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +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 + + +class FakeProcess: + pid_counter = 90000 + + def __init__(self, command, **kwargs): + FakeProcess.pid_counter += 1 + self.pid = FakeProcess.pid_counter + self.command = command + self.env = kwargs["env"] + self.returncode = None + self.terminated = False + + def poll(self): + return self.returncode + + def terminate(self): + self.terminated = True + self.returncode = 0 + + def wait(self, timeout=None): + return self.returncode + + def kill(self): + self.returncode = -9 + + +class FakeProc: + """A /proc tree with symlinked exe, environ and cmdline files.""" + + def __init__(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + self.bin = self.root / "bin" + self.bin.mkdir() + for name in ("wine", ".wine-wrapped", "wine64-preloader", "python3"): + path = self.bin / name + path.write_text("") + path.chmod(0o755) + self.proc = self.root / "proc" + self.proc.mkdir() + + def add(self, pid, exe, environment, cmdline="app.exe"): + entry = self.proc / str(pid) + entry.mkdir() + (entry / "exe").symlink_to(self.bin / exe) + (entry / "environ").write_bytes( + b"\0".join(f"{k}={v}".encode() for k, v in environment.items()) + b"\0") + (entry / "cmdline").write_bytes(cmdline.encode() + b"\0") + + def remove(self, pid): + for child in (self.proc / str(pid)).iterdir(): + child.unlink() + (self.proc / str(pid)).rmdir() + + +class DiscoveryTests(unittest.TestCase): + def setUp(self): + self.fake = FakeProc() + self.addCleanup(self.fake.directory.cleanup) + + def test_prefix_defaults_and_steam(self): + self.assertEqual(prefix_for({"HOME": "/home/u"}), os.path.realpath("/home/u/.wine")) + self.assertEqual(prefix_for({"STEAM_COMPAT_DATA_PATH": "/s/1"}), os.path.realpath("/s/1/pfx")) + self.assertEqual(prefix_for({"WINEPREFIX": "/games/p"}), os.path.realpath("/games/p")) + + def test_loader_recognises_nix_wrapper_and_preloader(self): + self.fake.add(1, ".wine-wrapped", {}) + self.fake.add(2, "wine64-preloader", {}) + self.fake.add(3, "python3", {}) + self.assertEqual(loader_for(1, {}, self.fake.proc), str(self.fake.bin / "wine")) + self.assertEqual(loader_for(2, {}, self.fake.proc), str(self.fake.bin / "wine")) + self.assertIsNone(loader_for(3, {}, self.fake.proc)) + + def test_other_sessions_are_left_alone(self): + self.fake.add(30, "wine", {"WINEPREFIX": "/p/mine", "DISPLAY": ":0", + "DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus"}) + self.fake.add(31, "wine", {"WINEPREFIX": "/p/test", "DISPLAY": ":99", + "DBUS_SESSION_BUS_ADDRESS": "unix:path=/tmp/private"}) + self.fake.add(32, "wine", {"WINEPREFIX": "/p/nobus"}) + manager = HelperManager([], helper="/h", proc=self.fake.proc) + session = {"DISPLAY": ":0", "DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus"} + with unittest.mock.patch.dict(os.environ, session): + found = sorted(manager.discover()) + self.assertEqual(found, sorted([os.path.realpath("/p/mine"), os.path.realpath("/p/nobus")])) + + def test_equivalent_session_spellings_match(self): + ours = {"DISPLAY": ":0.0", + "DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus,guid=abc"} + for theirs in ({"DISPLAY": ":0", "DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus"}, + {"DISPLAY": "unix:0.0"}, {"DISPLAY": "localhost:0"}): + self.assertTrue(manager_module.same_session(theirs, ours), theirs) + for theirs in ({"DISPLAY": ":1"}, {"DISPLAY": "remote:0"}, + {"DBUS_SESSION_BUS_ADDRESS": "unix:path=/tmp/other"}): + self.assertFalse(manager_module.same_session(theirs, ours), theirs) + + def test_discovery_skips_services_managed_and_non_wine(self): + self.fake.add(10, "wine", {"WINEPREFIX": "/p/a"}, r"C:\Games\game.exe") + 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"}) + manager = HelperManager([], helper="/h", proc=self.fake.proc) + self.assertEqual(list(manager.discover()), [os.path.realpath("/p/a")]) + + +class SupervisionTests(unittest.TestCase): + def setUp(self): + self.fake = FakeProc() + self.addCleanup(self.fake.directory.cleanup) + self.now = 1000.0 + self.spawned = [] + + def spawn(command, **kwargs): + process = FakeProcess(command, **kwargs) + self.spawned.append(process) + return process + + session = unittest.mock.patch.dict(os.environ, {"DISPLAY": ":7"}) + session.start() + self.addCleanup(session.stop) + self.manager = HelperManager(["--reader", "orca"], helper="/helper.exe", + proc=self.fake.proc, + log_directory=self.fake.root / "logs", + clock=lambda: self.now, spawn=spawn) + self.prefix = os.path.realpath("/p/game") + self.fake.add(20, "wine", {"WINEPREFIX": "/p/game", "DISPLAY": ":7", + "WINELOADER": str(self.fake.bin / "wine")}) + + def test_starts_one_helper_with_prefix_loader_and_display(self): + self.manager.poll() + self.manager.poll() + self.assertEqual(len(self.spawned), 1) + helper = self.spawned[0] + self.assertEqual(helper.command, ["/helper.exe", "--reader", "orca"]) + self.assertEqual(helper.env["WINEPREFIX"], self.prefix) + self.assertEqual(helper.env["WINELOADER"], str(self.fake.bin / "wine")) + self.assertEqual(helper.env["DISPLAY"], ":7") + self.assertEqual(helper.env[manager_module.MANAGED_KEY], "1") + + def test_quick_exit_backs_off_then_restarts(self): + self.manager.poll() + self.spawned[0].returncode = 1 + self.now += 1 + self.manager.poll() + self.assertEqual(len(self.spawned), 1) + self.now += 2 + self.manager.poll() + self.assertEqual(len(self.spawned), 2) + + def test_stops_after_idle_grace(self): + self.manager.poll() + self.fake.remove(20) + self.now += manager_module.IDLE_GRACE_SECONDS - 1 + self.manager.poll() + self.assertFalse(self.spawned[0].terminated) + self.now += 2 + self.manager.poll() + self.assertTrue(self.spawned[0].terminated) + self.assertEqual(self.manager.prefixes, {}) + + def test_leftover_helper_from_previous_orca_is_replaced(self): + self.fake.add(21, "wine", {"WINEPREFIX": "/p/game", "DISPLAY": ":7", + manager_module.MANAGED_KEY: "1"}, + "/x/libexec/wine-access/wine-access.exe.so") + self.fake.add(22, "wine", {"WINEPREFIX": "/p/game", "DISPLAY": ":7", + manager_module.MANAGED_KEY: "1"}, "C:\\x\\wine-access-menu-host32.exe") + killed = [] + with unittest.mock.patch.object(manager_module.os, "kill", + lambda pid, sig: killed.append((pid, sig))): + self.manager.poll() + self.assertEqual(killed, [(21, manager_module.signal.SIGTERM)]) + self.assertEqual(self.spawned, []) + self.fake.remove(21) + self.fake.remove(22) + self.now += 1 + self.manager.poll() + self.assertEqual(len(self.spawned), 1) + + def test_no_helper_installed_does_nothing(self): + self.manager.helper = None + self.manager.poll() + self.assertEqual(self.spawned, []) + + def test_cthulhu_helper_is_never_retired(self): + # Both readers use the same helper executable. Only Orca's own + # management marker authorizes retiring a leftover process. + for pid, name in ((21, "wine-access.exe.so"), + (22, "cthulhu-wine-access.exe.so")): + self.fake.add(pid, "wine", {"WINEPREFIX": "/p/game", "DISPLAY": ":7", + "CTHULHU_WINE_ACCESS_MANAGED": "1"}, name) + with unittest.mock.patch.object(manager_module.os, "kill") as kill: + self.manager.poll() + self.manager.shutdown() + kill.assert_not_called() + self.assertEqual(self.manager.stale, {}) + self.assertTrue(self.spawned[0].terminated) + + def test_shutdown_stops_helpers(self): + self.manager.poll() + self.manager.shutdown() + self.assertTrue(self.spawned[0].terminated) + + +if __name__ == "__main__": + unittest.main() diff --git a/orca/tests/test_presenter.py b/orca/tests/test_presenter.py new file mode 100644 index 0000000..152ffeb --- /dev/null +++ b/orca/tests/test_presenter.py @@ -0,0 +1,205 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Presentation rules for helper events, without Orca or a main loop.""" + +from pathlib import Path +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "wine_access")) + +from presenter import FOCUS_DEBOUNCE_MS, HOLD_MS, WineEvent, WineEventPresenter # noqa: E402 + + +class Harness: + def __init__(self): + self.output = [] + self.timers = {} + self.next_id = 1 + self.now = 100.0 + self.presenter = WineEventPresenter( + lambda message, interrupt: self.output.append(("present", message, interrupt)), + lambda text, inserted: self.output.append(("echo", text, inserted)), + self.schedule, self.cancel, lambda: self.now) + + def schedule(self, milliseconds, callback): + assert milliseconds in (FOCUS_DEBOUNCE_MS, HOLD_MS) + handle, self.next_id = self.next_id, self.next_id + 1 + self.timers[handle] = (milliseconds, callback) + return handle + + def cancel(self, handle): + self.timers.pop(handle, None) + + def fire(self): + """Runs due timers in the order their delays would expire.""" + while self.timers: + handle = min(self.timers, key=lambda h: (self.timers[h][0], h)) + callback = self.timers.pop(handle)[1] + callback() + + def send(self, source, kind, name="", role="", value="", states="", description="", + position=0, count=0, window="App"): + return self.presenter.handle(WineEvent(source, kind, name, role, value, states, + description, position, count, window)) + + +class FocusTests(unittest.TestCase): + def setUp(self): + self.h = Harness() + + def test_focus_waits_for_burst_and_names_new_window(self): + self.assertTrue(self.h.send("a", "focus", "OK", "button")) + self.assertEqual(self.h.output, []) + self.h.fire() + self.assertEqual(self.h.output, [("present", "OK, button, App", True)]) + + def test_only_last_focus_of_burst_is_spoken(self): + self.h.send("a", "focus", "First", "button") + self.h.send("b", "focus", "Second", "button") + self.h.fire() + self.assertEqual(self.h.output, [("present", "Second, button, App", True)]) + + def test_window_title_spoken_only_when_it_changes(self): + self.h.send("a", "focus", "OK", "button") + self.h.fire() + self.h.now += 1 + self.h.send("b", "focus", "Cancel", "button") + self.h.fire() + self.assertEqual(self.h.output[-1], ("present", "Cancel, button", True)) + + def test_client_role_and_position_states(self): + self.h.send("a", "focus", "Item", "client", states="selected, focusable", + position=2, count=5) + self.h.fire() + self.assertEqual(self.h.output, [("present", "Item, selected, 2 of 5, App", True)]) + + def test_title_only_focus(self): + self.h.send("a", "focus") + self.h.fire() + self.assertEqual(self.h.output, [("present", "App", True)]) + + def test_value_within_burst_refines_pending_focus(self): + self.h.send("combo", "focus", "Size", "combo box", "Small") + self.h.send("combo", "value", "Size", "combo box", "Large") + self.h.fire() + self.assertEqual(self.h.output, [("present", "Size, combo box, Large, App", True)]) + + +class ChangeTests(unittest.TestCase): + def setUp(self): + self.h = Harness() + self.h.send("a", "focus", "Size", "combo box", "Small") + self.h.fire() + self.h.output.clear() + self.h.now += 1 + + def test_value_change_of_focused_control(self): + self.assertTrue(self.h.send("a", "value", "Size", "combo box", "Large")) + self.assertEqual(self.h.output, [("present", "Size, combo box, Large", False)]) + + def test_background_value_is_ignored(self): + self.assertFalse(self.h.send("other", "value", "Volume", "slider", "5")) + self.assertEqual(self.h.output, []) + + def test_selection_from_internal_list_in_same_window_is_accepted(self): + self.assertTrue(self.h.send("list", "selection", "Large", "list item")) + self.assertFalse(self.h.send("list2", "selection", "X", "list item", window="Other")) + self.assertEqual(self.h.output, [("present", "Large, list item", False)]) + + def test_duplicates_within_100ms_are_dropped(self): + self.h.send("a", "value", "Size", "combo box", "Large") + self.h.now += 0.05 + self.assertFalse(self.h.send("a", "value", "Size", "combo box", "Large")) + self.h.now += 0.2 + self.assertTrue(self.h.send("a", "value", "Size", "combo box", "Large")) + self.assertEqual(len(self.h.output), 2) + + def test_unchanged_state_event_stays_quiet(self): + self.h.send("a", "state", "Size", "combo box", "Large") + self.h.now += 5 + self.assertFalse(self.h.send("a", "state", "Size", "combo box", "Large")) + + def test_unknown_event_type_rejected(self): + self.assertFalse(self.h.send("a", "bogus", "x")) + + +class EditorTests(unittest.TestCase): + def setUp(self): + self.h = Harness() + + def test_text_flushes_pending_focus_first(self): + self.h.send("edit", "focus", "", "edit", "hello") + self.assertTrue(self.h.send("edit", "text", "h", states="kind=8 start=1")) + self.assertEqual(self.h.output, [("present", "edit, hello, App", True), + ("echo", "h", True)]) + self.assertEqual(self.h.timers, {}) + + def test_repeated_characters_are_never_merged(self): + self.h.send("edit", "focus", "", "edit") + self.h.fire() + for _ in range(3): + self.assertTrue(self.h.send("edit", "text", "l", states="kind=3")) + self.assertEqual([o for o in self.h.output if o[0] == "echo"], + [("echo", "l", False)] * 3) + + def test_text_from_unfocused_source_ignored(self): + self.h.send("edit", "focus", "", "edit") + self.h.fire() + self.assertFalse(self.h.send("other", "text", "x", states="kind=8")) + + def test_password_field_is_silent(self): + self.h.send("pw", "focus", "Password", "edit", "secret", description="password") + self.h.fire() + self.assertEqual(self.h.output, [("present", "Password, edit, password, App", True)]) + self.assertFalse(self.h.send("pw", "text", "s", states="kind=8")) + self.h.now += 1 + self.h.send("pw", "value", "Password", "edit", "secret2") + self.assertNotIn("secret", " ".join(o[1] for o in self.h.output)) + + def test_password_state_change_protects_field(self): + self.h.send("e", "focus", "PIN", "edit") + self.h.fire() + self.h.now += 1 + self.h.send("e", "state", "PIN", "edit", states="password") + self.assertFalse(self.h.send("e", "text", "1", states="kind=8")) + + def test_dialog_text_follows_pending_focus(self): + self.h.send("b", "focus", "Yes", "button") + self.h.presenter.present_after_focus("Save changes?", "App") + self.assertEqual(self.h.output, []) + self.h.fire() + self.assertEqual(self.h.output, [("present", "Yes, button, App", True), + ("present", "Save changes?", False)]) + + def test_dialog_text_arriving_before_focus_waits_for_it(self): + self.h.presenter.present_after_focus("Save changes?", "App") + self.h.send("b", "focus", "Yes", "button") + self.h.fire() + self.assertEqual(self.h.output, [("present", "Yes, button, App", True), + ("present", "Save changes?", False)]) + + def test_dialog_text_spoken_alone_if_no_focus_follows(self): + self.h.send("b", "focus", "Yes", "button") + self.h.fire() + self.h.presenter.present_after_focus("Save changes?", "App") + self.assertEqual(len(self.h.output), 1) + self.h.fire() + self.assertEqual(self.h.output[-1], ("present", "Save changes?", False)) + + def test_focus_in_other_window_does_not_take_dialog_text(self): + self.h.presenter.present_after_focus("Save changes?", "Dialog") + self.h.send("b", "focus", "OK", "button", window="Main") + self.h.fire() + self.assertEqual(self.h.output, [("present", "OK, button, Main", True), + ("present", "Save changes?", False)]) + + def test_closed_presenter_ignores_events(self): + self.h.send("a", "focus", "OK", "button") + self.h.presenter.close() + self.assertEqual(self.h.timers, {}) + self.assertFalse(self.h.send("a", "focus", "OK", "button")) + self.assertEqual(self.h.output, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/orca/tests/test_review.py b/orca/tests/test_review.py new file mode 100644 index 0000000..6c6956b --- /dev/null +++ b/orca/tests/test_review.py @@ -0,0 +1,81 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Dialog message reading through the review protocol.""" + +from pathlib import Path +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "wine_access")) + +from review import DialogReader, dialog_text # noqa: E402 + + +def node(role, name="", visible=True, protected=False, ranges=()): + return {"role": role, "name": name, "visible": visible, "protected": protected, + "ranges": list(ranges)} + + +REPLY = {"status": "ok", "nodes": [ + node("window", "Notepad"), + node("label", ""), # the message box icon + node("label", "Save changes to\r\n Untitled?"), + node("push button", "Yes"), + node("label", "Hidden", visible=False), + node("label", "secret", protected=True), + node("label", "Notepad"), + node("static text", "", ranges=[(0, 4, 0, 4, "More", (0, 0, 1, 1))]), +]} + + +class DialogTextTests(unittest.TestCase): + def test_visible_labels_only_without_title(self): + self.assertEqual(dialog_text(REPLY, "Notepad"), "Save changes to Untitled? More") + + def test_failed_capture_has_no_text(self): + self.assertEqual(dialog_text({"status": "stale", "nodes": REPLY["nodes"]}), "") + + +class ReaderTests(unittest.TestCase): + def setUp(self): + self.captures = [] + self.spoken = [] + self.reader = DialogReader(lambda *args: self.captures.append(args), + lambda text, window: self.spoken.append((text, window))) + self.assertTrue(self.reader.register(":1.5", "/review", 1)) + + def focus(self, window="w1", role="dialog", sender=":1.5"): + return self.reader.focus(sender, window, "f", 3, "Notepad", role) + + def test_dialog_captured_once_and_spoken(self): + self.assertTrue(self.focus()) + self.assertTrue(self.focus()) + self.assertEqual(len(self.captures), 1) + self.assertEqual(self.captures[0][:5], (":1.5", "/review", "w1", "f", 3)) + self.captures[0][5](REPLY) + self.assertEqual(self.spoken, [("Save changes to Untitled? More", "Notepad")]) + + def test_plain_windows_are_not_captured(self): + self.focus(role="window") + self.assertEqual(self.captures, []) + + def test_failed_capture_retries_on_next_focus(self): + self.focus() + self.captures[0][5](None) + self.focus() + self.assertEqual(len(self.captures), 2) + + def test_leaving_dialog_drops_late_reply_and_allows_reread(self): + self.focus() + self.focus(window="main", role="window") + self.captures[0][5](REPLY) + self.assertEqual(self.spoken, []) + self.focus() + self.assertEqual(len(self.captures), 2) + + def test_unregistered_sender_and_old_version_rejected(self): + self.assertFalse(self.focus(sender=":1.9")) + self.assertFalse(self.reader.register(":1.6", "/review", 0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/orca/tests/test_service.py b/orca/tests/test_service.py new file mode 100644 index 0000000..22d1bea --- /dev/null +++ b/orca/tests/test_service.py @@ -0,0 +1,72 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""The published interface matches the signatures wine-access checks.""" + +from pathlib import Path +import sys +import unittest +from xml.etree import ElementTree + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "wine_access")) + +from service import INTERFACE, WineAccessInterface, ssml_status # noqa: E402 + +# From wine-access's README: method -> (input signature, output signature). +REQUIRED = { + "SpeakText": ("sb", "b"), + "CancelSpeech": ("", "b"), + "BrailleMessage": ("s", "b"), + "SpeakSsml": ("ss", "i"), + "PresentAccessibleEvent": ("sssssssiis", "b"), + # Optional review protocol version 1. + "RegisterWineReviewProvider": ("ou", "b"), + "PresentWineReviewFocus": ("ssstssb(iiii)", "b"), +} + + +class Backend: + def speak_text(self, text, interrupt): + return True + + def cancel_speech(self): + raise RuntimeError("Orca failed") + + def braille_message(self, text): + return text + + def present_event(self, *arguments): + self.arguments = arguments + return True + + +class InterfaceTests(unittest.TestCase): + def test_signatures_match_helper_contract(self): + root = ElementTree.fromstring(WineAccessInterface.__dbus_xml__) + interface = root.find(f"interface[@name='{INTERFACE}']") + found = {} + for method in interface.findall("method"): + args = method.findall("arg") + found[method.get("name")] = ( + "".join(a.get("type") for a in args if a.get("direction") == "in"), + "".join(a.get("type") for a in args if a.get("direction") == "out")) + self.assertEqual(found, REQUIRED) + + def test_backend_errors_answer_false(self): + service = WineAccessInterface(Backend()) + self.assertTrue(service.SpeakText("hi", False)) + self.assertFalse(service.CancelSpeech()) + self.assertFalse(service.BrailleMessage("")) + + def test_event_arguments_pass_through_in_order(self): + backend = Backend() + service = WineAccessInterface(backend) + service.PresentAccessibleEvent("s", "focus", "n", "r", "v", "st", "d", 1, 2, "w") + self.assertEqual(backend.arguments, ("s", "focus", "n", "r", "v", "st", "d", 1, 2, "w")) + + def test_ssml_status_codes(self): + self.assertEqual(ssml_status("Hi"), 120) + self.assertEqual(ssml_status("

Hi

"), 87) + self.assertEqual(ssml_status(""), 87) + + +if __name__ == "__main__": + unittest.main() diff --git a/orca/wine_access/__init__.py b/orca/wine_access/__init__.py new file mode 100644 index 0000000..abc5427 --- /dev/null +++ b/orca/wine_access/__init__.py @@ -0,0 +1,199 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Wine Access for Orca. + +Makes Orca read Windows programs running in Wine through the wine-access +helper (https://git.stormux.org/storm/wine-access): standard dialogs, menus, +lists and edit fields, plus NVDA Controller and Tolk speech from games and +MUD clients. The extension publishes the Wine methods the helper calls on +Orca's D-Bus service and starts one helper for each Wine prefix in use. +""" + +from __future__ import annotations + +from gi.repository import GLib + +from orca import debug, presentation_manager, typing_echo_presenter +from orca.extension import Extension + +from .manager import HelperManager +from .presenter import WineEvent, WineEventPresenter +from .review import DialogReader, gio_capture +from .service import INTERFACE, OBJECT_PATH, WineAccessInterface + +POLL_INTERVAL_MS = 2000 +READER_ARGUMENTS = ["--reader", "orca", "--reader-path", OBJECT_PATH, + "--reader-interface", INTERFACE] +# Multi-character labels the helper sends for typed whitespace. +ACTION_LABELS = {"space", "tab", "new line"} + + +def _log(*tokens: object) -> None: + debug.print_tokens(debug.LEVEL_INFO, ["WINE ACCESS:", *tokens], True) + + +class WineAccess(Extension): + """Reads Wine applications through the wine-access helper.""" + + GROUP_LABEL = "Wine Access" + DESCRIPTION = "Reads Windows programs running in Wine: dialogs, menus, lists, " \ + "edit fields, and NVDA/Tolk speech from games." + VERSION = "0.1.0" + AUTHOR = "Devin Prater" + WEBSITE = "https://git.stormux.org/storm/wine-access" + + def __init__(self) -> None: + super().__init__() + self._bus = None + self._poll_id = 0 + self._retry_id = 0 + self._presenter: WineEventPresenter | None = None + self._dialogs: DialogReader | None = None + self._manager = HelperManager(READER_ARGUMENTS) + + # Extension lifecycle + + def on_ready(self) -> None: + self._start() + + def on_enabled(self) -> None: + self._start() + + def on_disabled(self) -> None: + self._stop() + + def on_shutdown(self) -> None: + self._stop() + + def _start(self) -> None: + if self._bus is not None or self._retry_id: + return + if not self._publish(): + # Orca's D-Bus service may not be up yet. + self._retry_id = GLib.timeout_add_seconds(2, self._retry_publish) + return + if not self._manager.helper: + _log("wine-access helper not found; set WINE_ACCESS_HELPER or install it") + return + _log("helper", self._manager.helper) + self._manager.poll() + self._poll_id = GLib.timeout_add(POLL_INTERVAL_MS, self._manager.poll) + + def _retry_publish(self) -> bool: + self._retry_id = 0 + self._start() + return False + + def _publish(self) -> bool: + bus = getattr(self.controller, "_bus", None) + if bus is None: + return False + self._presenter = WineEventPresenter( + self._present, self._echo, GLib.timeout_add, GLib.source_remove) + self._dialogs = DialogReader(gio_capture(bus.connection), + self._presenter.present_after_focus) + try: + bus.publish_object(OBJECT_PATH, WineAccessInterface(self)) + except Exception as error: # pylint: disable=broad-exception-caught + _log("could not publish", OBJECT_PATH, error) + self._presenter = None + return False + self._bus = bus + _log("published", INTERFACE, "at", OBJECT_PATH) + return True + + def _stop(self) -> None: + for source in (self._poll_id, self._retry_id): + if source: + GLib.source_remove(source) + self._poll_id = self._retry_id = 0 + self._manager.shutdown() + if self._presenter is not None: + self._presenter.close() + self._presenter = None + self._dialogs = None + if self._bus is not None: + try: + self._bus.unpublish_object(OBJECT_PATH) + except Exception: # pylint: disable=broad-exception-caught + pass + self._bus = None + + # Backend for WineAccessInterface + + def speak_text(self, text: str, interrupt: bool) -> bool: + if not text: + return False + manager = presentation_manager.get_manager() + if interrupt: + manager.interrupt_presentation(kill_flash=False) + manager.speak_message(text) + return True + + def cancel_speech(self) -> bool: + presentation_manager.get_manager().interrupt_presentation(kill_flash=False) + return True + + def braille_message(self, text: str) -> bool: + if not text: + return False + presentation_manager.get_manager().present_braille_message(text) + return True + + def present_event(self, source: str, kind: str, name: str, role: str, value: str, + states: str, description: str, position: int, count: int, + window: str) -> bool: + if self._presenter is None: + return False + return self._presenter.handle(WineEvent( + source, kind, name, role, value, states, description, position, count, window)) + + def register_review(self, sender: str, path: str, version: int) -> bool: + return self._dialogs is not None and self._dialogs.register(sender, path, version) + + def review_focus(self, sender: str, window: str, focus: str, revision: int, + title: str, role: str) -> bool: + if self._dialogs is None: + return False + return self._dialogs.focus(sender, window, focus, revision, title, role) + + # Presenter output + + @staticmethod + def _present(message: str, interrupt: bool) -> None: + manager = presentation_manager.get_manager() + if interrupt: + manager.interrupt_presentation() + manager.present_message(message) + + @staticmethod + def _key_echo_spoke(text: str) -> bool: + """Whether Orca's key echo already announced the key that typed text.""" + + echo = typing_echo_presenter.get_presenter() + if not echo.get_key_echo_enabled(): + return False + if text in ACTION_LABELS: + return echo.get_action_keys_enabled() + if text.isalpha(): + return echo.get_alphabetic_keys_enabled() + if text.isdigit(): + return echo.get_numeric_keys_enabled() + return echo.get_punctuation_keys_enabled() + + def _echo(self, text: str, inserted: bool) -> None: + manager = presentation_manager.get_manager() + if inserted: + # Typed characters follow Orca's character echo setting, and are + # skipped when key echo has already spoken the key. + echo = typing_echo_presenter.get_presenter() + if not echo.get_character_echo_enabled() or self._key_echo_spoke(text): + return + else: + # Caret movement replaces whatever was being said. + manager.interrupt_presentation(kill_flash=False) + if len(text) > 1: + manager.present_braille_message(text) + if len(text) == 1: + manager.speak_character(text) + else: + manager.speak_message(text) diff --git a/orca/wine_access/manager.py b/orca/wine_access/manager.py new file mode 100644 index 0000000..1ebf226 --- /dev/null +++ b/orca/wine_access/manager.py @@ -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 .-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() diff --git a/orca/wine_access/presenter.py b/orca/wine_access/presenter.py new file mode 100644 index 0000000..c2e08a5 --- /dev/null +++ b/orca/wine_access/presenter.py @@ -0,0 +1,245 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Turns Wine Access helper events into Orca presentations. + +The helper sends normalized MSAA, menu and editor events through +PresentAccessibleEvent. Wine produces bursts of transient focus events, so +focus is coalesced briefly before it is spoken; editor actions are presented +immediately and never deduplicated, so repeated characters are all heard. +This class has no Orca dependency: output and timers are injected. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import time +from typing import Callable + +FOCUS_DEBOUNCE_MS = 50 +# How long text for a window waits for that window's focus to be presented. +HOLD_MS = 300 +DUPLICATE_SECONDS = 0.1 + +# Normalized MSAA state labels worth speaking. Editor diagnostics (offsets, +# action kinds) share the states field and must never be spoken. +SPOKEN_STATES = ( + "checked", "not checked", "half checked", "selected", "pressed", + "expanded", "collapsed", "unavailable", "read only", "password", "busy", +) +EVENT_TYPES = {"focus", "value", "selection", "text", "name", "state"} +INSERTED_ACTION = "kind=8" + + +def _state_labels(states: str) -> list[str]: + return [label.strip() for label in states.split(",") if label.strip()] + + +@dataclass +class WineEvent: + """One PresentAccessibleEvent call, in the helper's argument order.""" + + source: str + kind: str + name: str = "" + role: str = "" + value: str = "" + states: str = "" + description: str = "" + position: int = 0 + count: int = 0 + window: str = "" + + @property + def labels(self) -> list[str]: + return _state_labels(self.states) + + @property + def is_password(self) -> bool: + return self.description == "password" or "password" in self.labels + + +@dataclass +class _Pending: + source: str + window: str + message: str + parts: list[str] = field(default_factory=list) + after: list[str] = field(default_factory=list) + + +class WineEventPresenter: + """Applies focus tracking, filtering and coalescing to helper events. + + present(message, interrupt) speaks and brailles control feedback. + echo(text, inserted) presents editor feedback; inserted is True for typed + characters and False for navigation, selection and deletion reports. + schedule(milliseconds, callback) returns a handle for cancel(handle). + """ + + def __init__( + self, + present: Callable[[str, bool], None], + echo: Callable[[str, bool], None], + schedule: Callable[[int, Callable[[], bool]], object], + cancel: Callable[[object], None], + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._present = present + self._echo = echo + self._schedule = schedule + self._cancel = cancel + self._clock = clock + self._timer: object | None = None + self._pending: _Pending | None = None + self._focused = "" + self._protected = False + self._window = "" + self._last_key = "" + self._last_time = float("-inf") + self._held: tuple[str, list[str], object] | None = None + self._closed = False + + def handle(self, event: WineEvent) -> bool: + """Presents or queues one event. Returns True if it was accepted.""" + + if self._closed: + return False + kind = event.kind.casefold() + if kind not in EVENT_TYPES: + return False + if kind == "focus": + self._focused = event.source + self._protected = event.is_password + elif event.source != self._focused: + # Only list selections in the focused window may come from + # another source, e.g. a combo box's internal list. + window = self._pending.window if self._pending else self._window + if kind != "selection" or not event.window or event.window != window: + return False + if kind == "state": + self._protected = event.is_password + if self._protected and event.source == self._focused: + event.value = "" + + if kind == "text": + if self._protected or not event.name: + return False + # Speak the queued focus first; never merge or drop editor actions. + self._flush() + self._echo(event.name, INSERTED_ACTION in event.states.split()) + return True + + parts = self._parts(event) + if not parts and not (kind == "focus" and event.window): + return False + message = ", ".join(parts) + key = f"{event.source}\0{message or event.window}" + + # Losing focus reports a state event for the old control; stay quiet + # if nothing a user would hear has changed. + if kind == "state" and key == self._last_key: + return False + if key == self._last_key and self._clock() - self._last_time < DUPLICATE_SECONDS: + if kind == "focus": + self._pending = None + return False + + if kind == "focus": + previous = self._pending + self._pending = _Pending(event.source, event.window, message, parts) + if previous is not None and previous.window == event.window: + self._pending.after = previous.after + if self._held is not None and self._held[0] == event.window: + self._pending.after.extend(self._held[1]) + self._cancel(self._held[2]) + self._held = None + if self._timer is None: + self._timer = self._schedule(FOCUS_DEBOUNCE_MS, self._on_timer) + return True + + pending = self._pending + if pending is not None and ( + pending.source == event.source or (event.window and pending.window == event.window) + ): + # A value or selection inside the focus burst refines the focus. + pending.source, pending.message, pending.parts = event.source, message, parts + return True + + self._last_key, self._last_time = key, self._clock() + self._present(message, False) + return True + + @staticmethod + def _parts(event: WineEvent) -> list[str]: + role = "" if event.role.casefold() == "client" else event.role + parts = [part for part in (event.name, role, event.value, event.description) if part] + for label in event.labels: + if label in SPOKEN_STATES and label not in parts: + parts.append(label) + if event.position > 0 and event.count > 0: + parts.append(f"{event.position} of {event.count}") + return parts + + def present_after_focus(self, text: str, window: str) -> None: + """Presents text about a window, e.g. a dialog's message, after that + window's focus, so the focus announcement can't interrupt it.""" + + if self._closed or not text: + return + if self._pending is not None and self._pending.window == window: + self._pending.after.append(text) + return + if self._held is not None and self._held[0] == window: + self._held[1].append(text) + return + self._release_held() + # The focus may still be on its way, or may already have been spoken. + self._held = (window, [text], self._schedule(HOLD_MS, self._on_hold_timer)) + + def _on_hold_timer(self) -> bool: + held, self._held = self._held, None + if held is not None and not self._closed: + for text in held[1]: + self._present(text, False) + return False + + def _release_held(self) -> None: + if self._held is not None: + self._cancel(self._held[2]) + self._on_hold_timer() + + def _on_timer(self) -> bool: + self._timer = None + self._flush() + return False + + def _flush(self) -> None: + if self._timer is not None: + self._cancel(self._timer) + self._timer = None + pending, self._pending = self._pending, None + if pending is None or self._closed: + return + message = pending.message + if pending.window and pending.window != self._window: + # Wine windows are invisible to AT-SPI, so name a new window here. + if pending.window not in pending.parts: + message = f"{message}, {pending.window}" if message else pending.window + self._window = pending.window + self._last_key = f"{pending.source}\0{pending.message or pending.window}" + self._last_time = self._clock() + if message: + self._present(message, True) + for text in pending.after: + self._present(text, False) + + def close(self) -> None: + """Drops queued output; later events are ignored.""" + + self._closed = True + self._pending = None + if self._held is not None: + self._cancel(self._held[2]) + self._held = None + if self._timer is not None: + self._cancel(self._timer) + self._timer = None diff --git a/orca/wine_access/review.py b/orca/wine_access/review.py new file mode 100644 index 0000000..f3ba302 --- /dev/null +++ b/orca/wine_access/review.py @@ -0,0 +1,110 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Reads a dialog's message when focus enters it, using wine-access review. + +Focus events only describe the focused control, so a message box would be +heard as just its buttons. With review protocol version 1, the helper tells +the reader which window has focus; when that window is a new dialog, its +visible labels are captured once and presented after the focused control. +""" + +from __future__ import annotations + +from typing import Any, Callable + +REVIEW_INTERFACE = "org.stormux.Cthulhu1.WineReview" +PROTOCOL_VERSION = 1 +LABEL_ROLES = {"label", "static text"} + + +def dialog_text(reply: dict[str, Any], title: str = "") -> str: + """The visible, unprotected label text of a successful capture.""" + + if reply.get("status") != "ok": + return "" + texts = [] + for node in reply.get("nodes", []): + if node.get("role") not in LABEL_ROLES or not node.get("visible", False): + continue + if node.get("protected", False): + continue + text = node.get("name", "") or " ".join( + entry[4] for entry in node.get("ranges", []) if len(entry) > 4) + text = " ".join(text.split()) + if text and text != title and text not in texts: + texts.append(text) + return " ".join(texts) + + +def gio_capture(connection: Any) -> Callable[..., None]: + """A capture function calling the helper's CaptureWindow over Gio.""" + + from gi.repository import Gio, GLib # pylint: disable=import-outside-toplevel + + def capture(sender: str, path: str, window: str, focus: str, revision: int, + done: Callable[[dict[str, Any] | None], None]) -> None: + def finished(conn: Any, result: Any, _data: Any) -> None: + try: + value = conn.call_finish(result) + except GLib.Error: + done(None) + return + done(value.unpack()[0]) + + connection.call(sender, path, REVIEW_INTERFACE, "CaptureWindow", + GLib.Variant("(sst)", (window, focus, revision)), + GLib.VariantType.new("(a{sv})"), Gio.DBusCallFlags.NONE, + 1000, None, finished, None) + + return capture + + +class DialogReader: + """Tracks review providers and captures each newly focused dialog once. + + capture(sender, path, window, focus, revision, done) must call + done(reply) with the CaptureWindow reply, or done(None) on failure. + present(text, window) presents the dialog text after that window's focus. + """ + + def __init__(self, capture: Callable[..., None], present: Callable[[str, str], None]) -> None: + self._capture = capture + self._present = present + self._providers: dict[str, str] = {} + self._dialog: tuple[str, str] | None = None + + def register(self, sender: str, path: str, version: int) -> bool: + if version < PROTOCOL_VERSION or not sender: + return False + self._providers[sender] = path + return True + + def forget(self, sender: str) -> None: + self._providers.pop(sender, None) + + def focus(self, sender: str, window: str, focus: str, revision: int, + title: str, role: str) -> bool: + path = self._providers.get(sender) + if path is None: + return False + if role != "dialog": + self._dialog = None + return True + dialog = (sender, window) + if dialog == self._dialog: + return True + self._dialog = dialog + + def done(reply: dict[str, Any] | None) -> None: + if reply is None or reply.get("status") != "ok": + # Retry on the dialog's next focus notice. + if self._dialog == dialog: + self._dialog = None + return + if self._dialog != dialog: + return + text = dialog_text(reply, title) + if text: + self._present(text, title) + + self._capture(sender, path, window, focus, revision, done) + return True diff --git a/orca/wine_access/service.py b/orca/wine_access/service.py new file mode 100644 index 0000000..4cb5a1e --- /dev/null +++ b/orca/wine_access/service.py @@ -0,0 +1,100 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""The D-Bus object wine-access calls on Orca's service connection. + +dasbus builds the interface from these type hints, so this module must not +use postponed annotations. +""" + +from xml.etree import ElementTree + +from typing import Tuple + +from dasbus.server.interface import accepts_additional_arguments, dbus_interface +from dasbus.typing import Bool, Int, ObjPath, Str, UInt32, UInt64 + +INTERFACE = "org.gnome.Orca1.WineAccess" +OBJECT_PATH = "/org/gnome/Orca1/Service/WineAccess" + +ERROR_INVALID_PARAMETER = 87 +ERROR_CALL_NOT_IMPLEMENTED = 120 + + +def ssml_status(ssml: str) -> int: + """Windows status for SpeakSsml: SSML timing and marks aren't supported.""" + + try: + root = ElementTree.fromstring(ssml) + except ElementTree.ParseError: + return ERROR_INVALID_PARAMETER + if root.tag.rsplit("}", 1)[-1].lower() != "speak": + return ERROR_INVALID_PARAMETER + return ERROR_CALL_NOT_IMPLEMENTED + + +@dbus_interface(INTERFACE) +class WineAccessInterface: + """Forwards helper requests to a backend; a failure answers False.""" + + def __init__(self, backend): + self._backend = backend + + def _call(self, name, *arguments): + try: + return bool(getattr(self._backend, name)(*arguments)) + except Exception: # pylint: disable=broad-exception-caught + return False + + def SpeakText(self, text: Str, interrupt: Bool) -> Bool: # pylint: disable=invalid-name + return self._call("speak_text", text, interrupt) + + def CancelSpeech(self) -> Bool: # pylint: disable=invalid-name + return self._call("cancel_speech") + + def BrailleMessage(self, text: Str) -> Bool: # pylint: disable=invalid-name + return self._call("braille_message", text) + + def SpeakSsml(self, source: Str, ssml: Str) -> Int: # pylint: disable=invalid-name + del source + return ssml_status(ssml) + + def PresentAccessibleEvent( # pylint: disable=invalid-name,too-many-arguments + self, + source: Str, + event_type: Str, + name: Str, + role: Str, + value: Str, + states: Str, + description: Str, + position: Int, + count: Int, + window_title: Str, + ) -> Bool: + return self._call("present_event", source, event_type, name, role, value, + states, description, position, count, window_title) + + # Optional review protocol version 1: the helper's review object is + # called back on the sender's connection, so pass the sender along. + + @accepts_additional_arguments + def RegisterWineReviewProvider( # pylint: disable=invalid-name + self, path: ObjPath, version: UInt32, **info + ) -> Bool: + return self._call("register_review", info["call_info"]["sender"], path, version) + + @accepts_additional_arguments + def PresentWineReviewFocus( # pylint: disable=invalid-name,too-many-arguments + self, + instance: Str, + window: Str, + focus: Str, + revision: UInt64, + title: Str, + role: Str, + protected: Bool, + bounds: Tuple[Int, Int, Int, Int], + **info + ) -> Bool: + del instance, protected, bounds + return self._call("review_focus", info["call_info"]["sender"], window, focus, + revision, title, role)