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

+221
View File
@@ -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())
+24
View File
@@ -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")
+220
View File
@@ -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()
+205
View File
@@ -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()
+81
View File
@@ -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()
+72
View File
@@ -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("<speak>Hi</speak>"), 120)
self.assertEqual(ssml_status("<p>Hi</p>"), 87)
self.assertEqual(ssml_status("<speak>"), 87)
if __name__ == "__main__":
unittest.main()