Echo voice now used for its adjusters so prieview can be done while setting the voice.

This commit is contained in:
Storm Dragon committed 2026-10-15 23:33:02 -04:00
1 parent 70d447667e
commit 0834b47b55
26 files changed
+1080 -52

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
"""Real reader/preferences/GTK flow against a private, completion-aware SSIP server."""
import json
import os
from pathlib import Path
import socket
import subprocess
import tempfile
import threading
import time
from native_x11 import wait_for
class PreviewSpeechServer:
def __init__(self, path):
self.listener = socket.socket(socket.AF_UNIX)
self.listener.bind(str(path))
self.listener.listen()
self.lock = threading.RLock()
self.clients = {}
self.spoken = []
threading.Thread(target=self.accept_clients, daemon=True).start()
def accept_clients(self):
while True:
try:
connection, _ = self.listener.accept()
except OSError:
return
with self.lock:
clientId = len(self.clients) + 1
client = {"socket": connection, "lock": threading.RLock(), "notifications": False,
"module": "main", "voice": "", "active": None}
self.clients[clientId] = client
threading.Thread(target=self.serve_client, args=(clientId, client), daemon=True).start()
def reply(self, client, text):
with client["lock"]:
try:
client["socket"].sendall(text.encode())
except OSError:
pass
def finish(self, clientId, client, record, canceled=False):
with self.lock:
if client["active"] is not record:
return
client["active"] = None
record["finished"], record["canceled"] = True, canceled
if client["notifications"]:
code = 703 if canceled else 702
self.reply(client, f"{code}-1\r\n{code}-{clientId}\r\n{code} DONE\r\n")
def serve_client(self, clientId, client):
try:
with client["socket"].makefile("rb") as stream:
for raw in stream:
command = raw.decode().strip()
response = "200 OK\r\n"
if command == "HISTORY GET CLIENT_ID":
response = f"245-{clientId}\r\n245 OK\r\n"
elif command == "LIST OUTPUT_MODULES":
response = "200-echo-a\r\n200-echo-b\r\n200-main\r\n200 OK\r\n"
elif command == "LIST SYNTHESIS_VOICES":
voice = {"echo-a": "Echo A", "echo-b": "Echo B", "main": "Main"}[client["module"]]
response = f"200-{voice}\ten\tnone\r\n200 OK\r\n"
elif command.startswith("SET SELF OUTPUT_MODULE "):
client["module"] = command.removeprefix("SET SELF OUTPUT_MODULE ")
elif command.startswith("SET SELF SYNTHESIS_VOICE "):
client["voice"] = command.removeprefix("SET SELF SYNTHESIS_VOICE ")
elif command.startswith("SET SELF NOTIFICATION ALL "):
client["notifications"] = command.endswith(" on")
elif command.startswith("CANCEL "):
with self.lock:
targetId = int(command.split()[1])
target = self.clients[targetId]
if target["active"] is not None:
self.finish(targetId, target, target["active"], canceled=True)
elif command == "SPEAK":
parts = []
for line in stream:
if line == b".\r\n":
break
parts.append(line.decode().rstrip("\r\n"))
record = {"text": "\n".join(parts), "module": client["module"],
"voice": client["voice"], "finished": False, "canceled": False}
with self.lock:
self.spoken.append(record)
client["active"] = record
self.reply(client, "230 OK\r\n200 QUEUED\r\n")
if client["notifications"]:
self.reply(client, f"701-1\r\n701-{clientId}\r\n701 BEGIN\r\n")
timer = threading.Timer(0.25, self.finish, args=(clientId, client, record))
timer.daemon = True
timer.start()
continue
self.reply(client, response)
except (OSError, ValueError):
pass
def snapshot(self):
with self.lock:
return [dict(record) for record in self.spoken]
def close(self):
self.listener.close()
for client in self.clients.values():
client["socket"].close()
def check_runtime():
import pyatspi
directory = Path(tempfile.mkdtemp(prefix="cthulhu-echo-runtime-"))
binary = os.environ["CTHULHU_BINARY"]
wmConfig = directory / "i3.config"
wmConfig.write_text(f"font pango:monospace 10\nipc-socket {directory / 'i3.sock'}\n")
server = PreviewSpeechServer(directory / "speech.sock")
wm = subprocess.Popen(["i3", "-c", str(wmConfig)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
reader = None
try:
wait_for(lambda: "0x" in subprocess.check_output(["xprop", "-root", "_NET_SUPPORTING_WM_CHECK"], text=True), "private WM missing")
configPath = directory / "settings.toml"
configPath.write_text('''schema-version = 2
active-profile = "default"
[profiles.default.speech]
output-module = "main"
[profiles.default.braille]
enabled = false
[profiles.default.sound]
enabled = false
[profiles.default.key-echo]
enabled = false
custom-voice = true
custom-speech-server = true
speech-server = "echo-a"
[profiles.default.key-echo.voice]
rate = 50
average-pitch = 5
gain = 5
[profiles.default.key-echo.voice.family]
name = "Echo A"
lang = "en"
''')
reader = subprocess.Popen([binary, "--config", str(configPath), "--settings", "--no-tentacles",
"--speech-socket", str(directory / "speech.sock"),
"--debug-file", str(directory / "reader.log")],
stdout=subprocess.DEVNULL, stderr=(directory / "stderr.log").open("w"))
def find_window():
for application in pyatspi.Registry.getDesktop(0):
for window in application:
if window and window.name == "Cthulhu Preferences":
return window
window = wait_for(find_window, "reader's preferences did not open")
def walk(node):
yield node
for child in node:
if child is not None:
yield from walk(child)
controls = {node.name: node for node in walk(window) if node.name}
xid = subprocess.check_output(["xdotool", "search", "--onlyvisible", "--name", "^Cthulhu Preferences$"], text=True).splitlines()[0]
subprocess.run(["xdotool", "windowactivate", "--sync", xid], check=True)
tabs = next(node for node in walk(window) if node.getRole() == pyatspi.ROLE_PAGE_TAB_LIST)
assert tabs.querySelection().selectChild(4)
assert controls["Use custom echo voice"].queryComponent().grabFocus()
wait_for(lambda: any(record["text"] == "checked" and record["finished"]
for record in server.snapshot()), "initial checkbox announcement did not finish")
time.sleep(0.3)
def key(*keys):
subprocess.run(["xdotool", "key", "--clearmodifiers", *keys], check=True)
def check_output(keys, expected):
offset = len(server.snapshot())
key(*keys)
def completed():
records = server.snapshot()[offset:]
matching = [record for record in records if record["text"] in {text for text, _, _ in expected}]
return len(matching) >= len(expected) and all(record["finished"] for record in matching)
wait_for(completed, f"preview did not complete: {keys}")
# The original delayed menu-item event followed its preview by up
# to 160 ms. Require quiescence beyond that delay, then inspect all
# speech requests, including duplicates in the main voice.
time.sleep(0.25)
records = server.snapshot()[offset:]
got = [(record["text"], record["module"], record["voice"]) for record in records]
assert got == expected, (keys, got, expected)
assert not any(record["canceled"] for record in records), (keys, records)
check_output(("Tab",), [("Key echo speech synthesizer", "main", ""), ("echo-a", "echo-a", "Echo A")])
check_output(("Down",), [("echo-b", "echo-b", "")])
check_output(("Tab",), [("Key echo person", "main", ""), ("Default", "echo-b", "")])
check_output(("Down",), [("Echo B (en)", "echo-b", "Echo B")])
for control in ("rate", "pitch", "volume"):
value = "50.0" if control == "rate" else "5.0"
check_output(("Tab",), [("Key echo " + control, "main", ""), (value, "echo-b", "Echo B")])
for control in ("pitch", "rate", "person", "synthesizer"):
value = {"pitch": "5.0", "rate": "50.0", "person": "Echo B (en)", "synthesizer": "echo-b"}[control]
label = "Key echo speech synthesizer" if control == "synthesizer" else "Key echo " + control
check_output(("shift+Tab",), [(label, "main", ""), (value, "echo-b", "Echo B")])
print(f"PASS: real reader + GTK + SSIP focus/selection previews, voice completion, no duplicate menu-item speech; evidence: {directory}")
finally:
if reader is not None:
reader.terminate()
try:
reader.wait(timeout=5)
except subprocess.TimeoutExpired:
reader.kill()
reader.wait(timeout=5)
wm.terminate()
wm.wait(timeout=5)
server.close()
(directory / "speech.json").write_text(json.dumps(server.snapshot(), indent=2))
+203 -11
View File
@@ -13,7 +13,42 @@ sys.dont_write_bytecode = True
from native_x11 import wait_for
class ResponseReader:
"""Read complete JSON lines with one deadline, preserving read-ahead bytes."""
def __init__(self, stream):
self.stream = stream
self.pendingData = bytearray()
def request(self, timeout=5):
deadline = time.monotonic() + timeout
while b"\n" not in self.pendingData:
remaining = deadline - time.monotonic()
if remaining <= 0 or not select.select([self.stream], [], [], remaining)[0]:
raise TimeoutError("no complete preferences request within response timeout")
# Never mix buffered reads with select: TextIO can retain another
# complete reply even when the underlying pipe is empty.
chunk = os.read(self.stream.fileno(), 65536)
if not chunk:
raise EOFError("preferences helper closed stdout before a complete request")
self.pendingData.extend(chunk)
end = self.pendingData.index(b"\n") + 1
line = self.pendingData[:end]
del self.pendingData[:end]
return json.loads(line)
def read_remaining(self):
# Used only after helper exit; include any bytes read ahead by request.
remaining = bytes(self.pendingData) + self.stream.buffer.read()
self.pendingData.clear()
return remaining.decode("utf-8")
def inside():
if os.environ.get("CTHULHU_PREFS_ECHO_RUNTIME_ONLY") == "1":
from native_echo_preview import check_runtime
check_runtime()
return
if os.environ.get("CTHULHU_PREFS_ADAPTER_ONLY") == "1":
environment = dict(os.environ, CTHULHU_NATIVE_PREFERENCES="1")
environment.setdefault("GOCACHE", "/tmp/cthulhu-cache")
@@ -40,6 +75,7 @@ def inside():
binary = os.environ.get("CTHULHU_BINARY", str(Path(__file__).resolve().parents[1] / "cthulhu"))
process = subprocess.Popen([binary, "--preferences-ui"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, text=True)
responses = ResponseReader(process.stdout)
initial = {"Values": {"Rate": 50, "Pitch": 5, "Volume": 5,
"SpeechHistoryLimit": 50,
"Reading": {"AutomaticallyReadTitleChanges": True},
@@ -71,6 +107,17 @@ def inside():
"test-module": [{"Name": "English test voice", "Language": "en", "Variant": "none"},
{"Name": "Spanish test voice", "Language": "es", "Variant": "none"}]},
"CanSave": True, "Accepted": True, "Message": "Preferences test ready."}
echoFocusMode = os.environ.get("CTHULHU_PREFS_ECHO_PREVIEW_ONLY") == "1"
echo_mode = os.environ.get("CTHULHU_PREFS_KEY_ECHO_ONLY") or ("custom" if echoFocusMode else None)
if echo_mode:
initial["Catalog"]["echo-module"] = [
{"Name": "Echo test voice", "Language": "en", "Variant": "none"}]
initial["Values"].update(
SpeechOutputModule="test-module", EchoSpeechServer="echo-module",
UseCustomEchoVoice=echo_mode == "custom",
UseCustomEchoSpeechServer=echo_mode == "custom",
EnableEchoByCharacter=True, EnableEchoBySentence=True,
UseCustomEchoForCharacter=True)
if os.environ.get("CTHULHU_PREFS_SPEECH_ONLY") == "1":
initial["Catalog"]["espeak-ng"] = list(initial["Catalog"]["test-module"])
if os.environ.get("CTHULHU_PREFS_NUMBERS_ONLY") == "1":
@@ -129,8 +176,12 @@ def inside():
assert node.queryComponent().grabFocus(), ("cannot focus", node.name)
wait_for(lambda: any(child.getState().contains(pyatspi.STATE_FOCUSED) for child in walk(node)), "focus missing")
def request():
assert select.select([process.stdout], [], [], 5)[0], "no Apply request"
return json.loads(process.stdout.readline())
while True:
value = responses.request()
if value.get("EchoPreviewFocus") and not echoFocusMode:
send({"Preview": True, "Accepted": True})
continue
return value
try:
send_initial(initial)
window = wait_for(find_window, "preferences accessible window missing")
@@ -141,6 +192,141 @@ def inside():
xid = subprocess.check_output(["xdotool", "search", "--onlyvisible", "--name", "^" + window_name + "$"], text=True).splitlines()[0]
subprocess.run(["xdotool", "windowfocus", xid], check=True)
assert not any(node.name == "Profiles" for node in nodes), "removed profile controls remain in preferences"
if echoFocusMode:
tabs = next(n for n in nodes if n.getRole() == pyatspi.ROLE_PAGE_TAB_LIST)
assert tabs.querySelection().selectChild(4), "cannot select Key Echo tab"
def check_preview(control, isFocus):
value = request()
assert value["Preview"] and value.get("EchoPreview") == control, value
assert bool(value.get("EchoPreviewFocus")) == isFocus, value
send({"Preview": True, "Accepted": True})
return value["Values"]
focus(named("Use custom echo voice"))
key("Tab")
check_preview("synthesizer", True)
key("Down")
value = check_preview("synthesizer", False)
assert value["EchoSpeechServer"] == "test-module", value
key("Up")
value = check_preview("synthesizer", False)
assert value["EchoSpeechServer"] == "echo-module", value
key("Tab")
check_preview("person", True)
key("Down")
value = check_preview("person", False)
assert value["EchoVoice"]["Family"]["Name"] == "Echo test voice", value
for control in ("rate", "pitch", "volume"):
key("Tab")
check_preview(control, True)
key("Right")
check_preview(control, False)
for control in ("pitch", "rate", "person", "synthesizer"):
key("shift+Tab")
check_preview(control, True)
# Popup Escape restores the same combo without trapping focus.
key("alt+Down", "Escape", "Tab")
check_preview("person", True)
focus(named("Cancel")); key("space")
assert process.wait(timeout=5) == 0
print("PASS: all five echo controls preview their current values on Tab/Shift+Tab and changed values on arrows; popup Escape and Cancel")
return
if echo_mode:
assert "Use custom speech synthesizer for key echo" not in controls
assert "Use custom voice for key echo" not in controls
assert "Use the custom voice for:" in controls
tabs = next(n for n in nodes if n.getRole() == pyatspi.ROLE_PAGE_TAB_LIST)
assert tabs.querySelection().selectChild(4), "cannot select Key Echo tab"
custom = named("Use custom echo voice")
synth = named("Key echo speech synthesizer")
family = named("Key echo person")
rate = named("Key echo rate")
expected_module = "echo-module" if echo_mode == "custom" else "test-module"
assert synth.querySelection().getSelectedChild(0).name == expected_module
if echo_mode != "custom":
# An unused saved echo module must not override the main one.
assert not synth.getState().contains(pyatspi.STATE_SENSITIVE)
assert not family.getState().contains(pyatspi.STATE_SENSITIVE)
focus(custom); key("space")
wait_for(lambda: synth.getState().contains(pyatspi.STATE_SENSITIVE),
"custom echo did not enable the synthesizer directly")
def focused(node):
return any(child.getState().contains(pyatspi.STATE_FOCUSED) for child in walk(node))
# GTK's internal combo button does not consistently expose its
# focused state. Exercise the popup, value and following Tab stop.
focus(custom); key("Tab", "alt+Down", "Home", "Down")
if echo_mode != "custom":
key("Down")
key("Return")
wait_for(lambda: synth.description == expected_module, "Tab did not reach echo synthesizer")
key("Tab", "Tab")
wait_for(lambda: focused(rate), "voice selector trapped Tab")
key("shift+Tab", "shift+Tab")
key("shift+Tab")
wait_for(lambda: focused(custom), "synthesizer trapped Shift+Tab")
assert named("Key names").getState().contains(pyatspi.STATE_CHECKED)
assert named("Typed characters").getState().contains(pyatspi.STATE_CHECKED)
for name in ("Key names", "Typed characters", "Words", "Sentences"):
assert named(name).getRole() == pyatspi.ROLE_CHECK_BOX
assert named(name).getState().contains(pyatspi.STATE_SENSITIVE)
focus(named("Words")); key("space")
def apply_echo():
focus(named("Apply")); key("space")
while True:
applied = request()
if applied["Preview"]:
send({"Preview": True, "Accepted": True})
continue
assert applied["Save"] and not applied["Close"], applied
values = applied["Values"]
send(dict(initial, Values=values, Message="Echo settings saved."))
wait_for(lambda: named("Apply").getState().contains(pyatspi.STATE_SENSITIVE),
"echo Apply stayed busy")
return values
saved = apply_echo()
assert saved["SpeechOutputModule"] == "test-module", saved
assert saved["UseCustomEchoVoice"] and saved["UseCustomEchoSpeechServer"], saved
assert saved["EchoSpeechServer"] == expected_module, saved
assert saved["UseCustomEchoForKey"] and saved["UseCustomEchoForCharacter"], saved
assert saved["UseCustomEchoForWord"] and not saved["UseCustomEchoForSentence"], saved
# Select Default first to guarantee a change in either startup
# mode. Only the selected combo value gets an echo preview.
def accept_echo_preview(control, module):
preview = request()
assert preview["Preview"] and preview.get("EchoPreview") == control, preview
assert preview["Values"]["EchoSpeechServer"] == module, preview
send({"Preview": True, "Accepted": True})
return preview["Values"]
focus(custom); key("Tab", "alt+Down", "Home", "Return")
preview = accept_echo_preview("synthesizer", "")
assert preview["EchoVoice"]["Family"] is None, preview
# Change the synthesizer using its keyboard popup, then select a
# person and verify each sends its newly selected draft voice.
focus(custom); key("Tab", "alt+Down", "Home", "Down", "Return")
accept_echo_preview("synthesizer", "echo-module")
wait_for(lambda: synth.description == "echo-module", "echo synthesizer did not change")
wait_for(lambda: any(child.name == "Echo test voice (en)" for child in walk(family)),
"echo voices did not follow the selected synthesizer")
key("Tab", "alt+Down", "Home", "Down", "Return")
preview = accept_echo_preview("person", "echo-module")
assert preview["EchoVoice"]["Family"]["Name"] == "Echo test voice", preview
saved = apply_echo()
assert saved["EchoSpeechServer"] == "echo-module", saved
assert saved["EchoVoice"]["Family"]["Name"] == "Echo test voice", saved
assert synth.querySelection().getSelectedChild(0).name == "echo-module"
assert family.querySelection().getSelectedChild(0).name == "Echo test voice (en)"
focus(custom); key("space")
wait_for(lambda: not synth.getState().contains(pyatspi.STATE_SENSITIVE),
"custom echo off left the synthesizer enabled")
saved = apply_echo()
assert not saved["UseCustomEchoVoice"] and saved["EchoSpeechServer"] == "echo-module", saved
focus(custom); key("space")
saved = apply_echo()
assert saved["UseCustomEchoVoice"] and saved["EchoSpeechServer"] == "echo-module", saved
assert saved["EchoVoice"]["Family"]["Name"] == "Echo test voice", saved
focus(named("Cancel")); key("space")
assert process.wait(timeout=5) == 0
print("PASS: echo synthesizer initialization, keyboard navigation, synthesizer/person previews, routing choices, Apply/reload, disable/re-enable")
return
if os.environ.get("CTHULHU_PREFS_TENTACLE_SETTINGS_ONLY") == "1":
from native_tentacle_settings import check_page
check_page(pyatspi, window, nodes, named, walk, focus, key, request, send, initial)
@@ -190,7 +376,7 @@ def inside():
focus(automatic); key("space")
key("Escape")
assert process.wait(timeout=2) == 0, "Escape did not close OCR preferences"
assert process.stdout.read() == "", "cancel submitted changed OCR settings"
assert responses.read_remaining() == "", "cancel submitted changed OCR settings"
print("PASS: OCR layout Tab/Shift+Tab, popup selection, automatic reading checkbox, Apply, rollback, Cancel")
return
if os.environ.get("CTHULHU_PREFS_TEXT_ONLY") == "1":
@@ -240,9 +426,10 @@ def inside():
key("ctrl+Page_Down", "ctrl+Page_Down")
wait_for(lambda: named("Speech").getState().contains(pyatspi.STATE_SELECTED), "Speech page missing")
values = initial["Values"]
def accept_preview():
def accept_preview(echoPreview=""):
preview = request()
assert preview["Preview"], preview
assert preview.get("EchoPreview", "") == echoPreview, preview
send({"Preview": True, "Accepted": True})
return preview["Values"]
for name, field in (("Rate", "Rate"), ("Pitch", "Pitch"), ("Volume", "Volume")):
@@ -276,6 +463,7 @@ def inside():
for name, field in (("Key echo rate", "Rate"), ("Key echo pitch", "AveragePitch"), ("Key echo volume", "Gain")):
slider = named(name)
focus(slider)
echoPreview = {"Rate": "rate", "AveragePitch": "pitch", "Gain": "volume"}[field]
assert abs(slider.queryValue().minimumIncrement - 0.1) < 1e-8, (name, "accessible increment")
for arrow, expected in (("Right", 5.1 if field != "Rate" else 50.1),
("Up", 6.1 if field != "Rate" else 51.1),
@@ -283,15 +471,19 @@ def inside():
("Down", 5 if field != "Rate" else 50),
("Left", 4.9 if field != "Rate" else 49.9)):
key(arrow)
values = accept_preview(echoPreview)
wait_for(lambda: abs(slider.queryValue().currentValue - expected) < 1e-8,
f"{name}: {arrow} did not produce {expected}")
assert abs(values["EchoVoice"][field] - expected) < 1e-8, values
finalValue = expected
for bound, arrows in ((0, ("Left", "Down")),
(slider.queryValue().maximumValue, ("Right", "Up"))):
slider.queryValue().currentValue = bound
accept_preview(echoPreview)
key(*arrows)
assert slider.queryValue().currentValue == bound, (name, "boundary", bound)
slider.queryValue().currentValue = finalValue
accept_preview(echoPreview)
focus(named("Apply")); key("space")
applied = request()
assert applied["Save"], applied
@@ -494,7 +686,7 @@ def inside():
values = accept_preview()
assert values["Pitch"] == 5 and pitchScale.queryValue().currentValue == 8
focus(named("Cancel")); key("space")
assert process.wait(timeout=2) == 0 and process.stdout.read() == ""
assert process.wait(timeout=2) == 0 and responses.read_remaining() == ""
print("PASS: independent voice editors, inheritance, previews, indentation modes, Apply/reload, Cancel")
return
if os.environ.get("CTHULHU_PREFS_SPEECH_ONLY") == "1":
@@ -592,7 +784,7 @@ def inside():
assert process.poll() is None, "dropdown Escape closed the whole preferences window"
key("Escape")
assert process.wait(timeout=2) == 0, "Escape did not close preferences promptly"
assert process.stdout.read() == "", "Escape submitted changes"
assert responses.read_remaining() == "", "Escape submitted changes"
print("PASS: synthesizer and voice previews, locale filtering, language preserved across synthesizers, Apply/reload, dropdown and window Escape")
return
if os.environ.get("CTHULHU_PREFS_READING_ONLY") == "1":
@@ -672,7 +864,7 @@ def inside():
if readingTable.getAccessibleAt(row, 1).name == "Speak object under mouse"), 0).name == "checked"
focus(named("Cancel")); key("space")
assert process.wait(timeout=5) == 0
assert process.stdout.read() == "", "Cancel submitted reading changes"
assert responses.read_remaining() == "", "Cancel submitted reading changes"
print("PASS: reading table, Say All, tooltip and mouse choices, Space, arrows, Tab/Shift+Tab, Apply/reload, Cancel")
return
if os.environ.get("CTHULHU_PREFS_MODIFIERS_ONLY") == "1":
@@ -727,7 +919,7 @@ def inside():
assert_modifiers({"Insert", "Numpad Insert"})
focus(named("Cancel")); key("space")
assert process.wait(timeout=5) == 0
assert process.stdout.read() == "", "Cancel submitted modifier changes"
assert responses.read_remaining() == "", "Cancel submitted modifier changes"
print("PASS: modifier checkbox table, accessible states, Space, Tab/Shift+Tab, desktop/laptop defaults, multiple/empty selections, Apply/reload, Cancel")
return
if os.environ.get("CTHULHU_PREFS_BINDINGS_ONLY") == "1":
@@ -804,7 +996,7 @@ def inside():
set_binding("F9")
focus(named("Cancel")); key("space")
assert process.wait(timeout=5) == 0
assert process.stdout.read() == "", "Cancel submitted bindings"
assert responses.read_remaining() == "", "Cancel submitted bindings"
print("PASS: accessible binding editor, Tab/Shift+Tab, conflict, save/reload, clear, reset, laptop browse, reset all, Cancel")
return
if os.environ.get("CTHULHU_PREFS_BRAILLE_ONLY") == "1":
@@ -1095,7 +1287,7 @@ def inside():
focus(named("Key echo volume")); named("Key echo volume").queryValue().currentValue = 10
family = named("Key echo person")
family.querySelection().selectChild(1)
word_voice = named("Use custom voice for word echo")
word_voice = named("Words")
assert not word_voice.getState().contains(pyatspi.STATE_CHECKED)
focus(word_voice); key("space")
wait_for(lambda: word_voice.getState().contains(pyatspi.STATE_CHECKED),
@@ -1128,7 +1320,7 @@ def inside():
subprocess.run(["xdotool", "windowfocus", xid], check=True)
key("Escape")
assert process.wait(timeout=2) == 0, "Escape did not close preferences promptly"
assert process.stdout.read() == "", "Escape submitted extra settings"
assert responses.read_remaining() == "", "Escape submitted extra settings"
print("PASS: GTK notebook, roles, label buddies, Tab/Shift+Tab, Apply, failed apply, OK, Escape")
finally:
if reader_process is not None:
+59
View File
@@ -0,0 +1,59 @@
"""Pipe-level regressions for the native preferences harness response reader."""
import os
import select
import unittest
from unittest.mock import patch
from native_preferences import ResponseReader
class ResponseReaderTests(unittest.TestCase):
def setUp(self):
readFd, writeFd = os.pipe()
self.stream = os.fdopen(readFd, encoding="utf-8")
self.writer = os.fdopen(writeFd, "wb", buffering=0)
self.addCleanup(self.stream.close)
self.addCleanup(self.writer.close)
self.reader = ResponseReader(self.stream)
def test_batched_preview_and_save(self):
self.writer.write(b'{"Preview": true}\n{"Save": true}\n')
self.assertEqual(self.reader.request(), {"Preview": True})
self.assertFalse(select.select([self.stream], [], [], 0)[0])
self.assertEqual(self.reader.request(timeout=0), {"Save": True})
def test_missing_response_times_out(self):
with self.assertRaises(TimeoutError):
self.reader.request(timeout=0.01)
def test_partial_response_times_out_and_can_resume(self):
self.writer.write(b'{"Name": "\xc3')
with self.assertRaises(TimeoutError):
self.reader.request(timeout=0.01)
self.writer.write(b'\xa9"}\n')
self.assertEqual(self.reader.request(), {"Name": "\u00e9"})
def test_partial_reads_share_one_deadline(self):
self.writer.write(b'{"Save":')
with patch("native_preferences.time.monotonic", side_effect=[10, 10, 16]):
with self.assertRaises(TimeoutError):
self.reader.request(timeout=5)
def test_eof_is_reported_after_complete_responses(self):
self.writer.write(b'{"Save": true}\n{"Close":')
self.writer.close()
self.assertEqual(self.reader.request(), {"Save": True})
with self.assertRaises(EOFError):
self.reader.request()
def test_remaining_output_includes_read_ahead_and_pipe_bytes(self):
self.writer.write(b'{"Preview": true}\n{"Name": "\xc3')
self.assertEqual(self.reader.request(), {"Preview": True})
self.writer.write(b'\xa9"}\n')
self.writer.close()
self.assertEqual(self.reader.read_remaining(), '{"Name": "\u00e9"}\n')
self.assertEqual(self.reader.read_remaining(), "")
if __name__ == "__main__":
unittest.main()