Files
wine-access/browser_bridge.cpp
Storm DragonandClaude Opus 5.5 9c1fc644ba Add browser accessibility for Chromium windows
Chromium-based Windows applications under Wine (Electron, CEF) exposed only
what the legacy MSAA path could announce, one event at a time. The helper now
starts a publisher for each Chromium window: a PE worker reads the page
through MSAA and IAccessible2 inside the prefix, and a native ATK publisher
presents it on the accessibility bus as toolkit Chromium, matching native
Linux Chromium, so the reader's own browser support handles browse mode,
structural navigation, forms, tables and live regions. Once a window is
published, legacy announcements for it stop, so nothing is spoken twice; if
the publisher fails, the window returns to the legacy path and the helper
retries with backoff. Publishers follow the helper's lifetime.

The publisher marks itself with WINE_ACCESS_BROWSER_PUBLISHER=1 and gives each
frame a wine-access-x11-window attribute so readers can verify window
ownership. Password text, values and boundaries never leave the worker.
Design, mapping rules and verification are in docs/browser.md; the
IAccessible2 IDL is vendored in third_party/ia2.

Checked: xvfb-run ctest (all 10, including the new
browser-publisher-snapshot comparison with native Chromium 158 and Electron
42), menu_integration.py with the menu and edit fixtures, the Orca extension
unit tests, and tests/browser/live_checks.sh against Electron 45: worker
protocol, helper lifecycle (publish, no legacy announcements while typing,
restart, no orphans), and live tree, text boundaries and AT-SPI event
sequence matching native Chromium. A live test with Cthulhu on Electron 45
read the fixture page correctly.

Remaining live checks: Orca with the extension, Firefox, WebView2, 32-bit
browsers, iframes, and window switching under other window managers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:15:21 -05:00

248 lines
10 KiB
C++

// SPDX-License-Identifier: LGPL-2.1-or-later
#include "browser_bridge.h"
#include <glib-unix.h>
#include <glib.h>
#include <signal.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <unistd.h>
#include <bit>
#include <cerrno>
#include <cstdio>
#include <string>
#include <vector>
namespace {
constexpr int MaxFailures = 3;
constexpr ULONGLONG BaseRetryMs = 2000;
std::string to_utf8(const wchar_t *text) {
if (!text || !*text) return {};
const int size = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
if (size <= 1) return {};
std::string result(size - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, text, -1, result.data(), size, nullptr, nullptr);
return result;
}
bool has_class(HWND window, const wchar_t *expected) {
wchar_t name[64] = {};
return GetClassNameW(window, name, 64) > 0 && lstrcmpW(name, expected) == 0;
}
BOOL CALLBACK find_render_widget(HWND window, LPARAM found) {
if (!has_class(window, L"Chrome_RenderWidgetHostHWND")) return TRUE;
*reinterpret_cast<bool *>(found) = true;
return FALSE;
}
// A Chromium top-level window that hosts web content. Popups and windows
// without a renderer (menus, tooltips) stay on the legacy path.
bool is_chromium_content_window(HWND root) {
if (!root || !IsWindowVisible(root) || !has_class(root, L"Chrome_WidgetWin_1")) return false;
bool found = false;
EnumChildWindows(root, find_render_widget, reinterpret_cast<LPARAM>(&found));
return found;
}
// Unix path of a file next to this helper (Winelib converts the Windows path).
std::string sibling_unix_path(const char *name) {
wchar_t module[4096] = {};
const DWORD length = GetModuleFileNameW(nullptr, module, std::size(module));
if (length == 0 || length >= std::size(module)) return {};
using UnixPath = char *(CDECL *)(LPCWSTR);
auto unixPath = std::bit_cast<UnixPath>(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "wine_get_unix_file_name"));
if (!unixPath) return {};
char *converted = unixPath(module);
if (!converted) return {};
std::string path = converted;
HeapFree(GetProcessHeap(), 0, converted);
const auto separator = path.rfind('/');
if (separator == std::string::npos) return {};
return path.substr(0, separator + 1) + name;
}
// The Wine loader of this prefix: readers pass WINELOADER; otherwise derive it
// from this process's preloader, so the worker joins the same wineserver.
std::string wine_loader() {
if (const char *configured = getenv("WINELOADER"); configured && *configured) return configured;
char self[4096] = {};
const ssize_t length = readlink("/proc/self/exe", self, sizeof(self) - 1);
if (length <= 0) return {};
std::string path(self, static_cast<size_t>(length));
const std::string suffix = "-preloader";
if (path.size() > suffix.size() && path.compare(path.size() - suffix.size(), suffix.size(), suffix) == 0)
path.erase(path.size() - suffix.size());
return access(path.c_str(), X_OK) == 0 ? path : std::string();
}
// Lowercase image name without ".exe", like native application names.
std::string application_name(HWND window) {
DWORD process = 0;
GetWindowThreadProcessId(window, &process);
HANDLE handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process);
wchar_t image[MAX_PATH] = {};
DWORD size = MAX_PATH;
const bool known = handle && QueryFullProcessImageNameW(handle, 0, image, &size);
if (handle) CloseHandle(handle);
if (!known) return "browser";
const wchar_t *base = image;
for (const wchar_t *cursor = image; *cursor; ++cursor)
if (*cursor == L'\\' || *cursor == L'/') base = cursor + 1;
std::string name = to_utf8(base);
for (char &c : name) c = static_cast<char>(g_ascii_tolower(c));
if (name.size() > 4 && name.compare(name.size() - 4, 4, ".exe") == 0) name.erase(name.size() - 4);
return name.empty() ? "browser" : name;
}
// Runs in the publisher between fork and exec. Readers stop the helper with a
// signal, which ends a Wine process without running its shutdown code, so the
// publisher must follow its parent on its own. The parent's PID is passed
// because it may already have gone before the death signal was armed.
void follow_parent(gpointer parentPid) {
prctl(PR_SET_PDEATHSIG, SIGTERM);
if (getppid() != static_cast<pid_t>(GPOINTER_TO_INT(parentPid))) _exit(0);
}
} // namespace
BrowserBridge::~BrowserBridge() { stop(); }
bool BrowserBridge::start() {
publisherPath_ = sibling_unix_path("wine-access-browser-publisher");
workerPath_ = sibling_unix_path("wine-access-browser-worker.exe");
loader_ = wine_loader();
running_ = !publisherPath_.empty() && access(publisherPath_.c_str(), X_OK) == 0 && !workerPath_.empty() &&
access(workerPath_.c_str(), R_OK) == 0 && !loader_.empty();
if (!running_)
std::fprintf(stderr, "wine-access: browser bridge unavailable (publisher %s, worker %s, Wine loader %s)\n",
publisherPath_.empty() ? "unknown" : publisherPath_.c_str(),
workerPath_.empty() ? "unknown" : workerPath_.c_str(), loader_.empty() ? "unknown" : loader_.c_str());
return running_;
}
void BrowserBridge::window_event(HWND window, DWORD event) {
if (!running_) return;
if (event == EVENT_SYSTEM_FOREGROUND || event == EVENT_OBJECT_SHOW || event == EVENT_OBJECT_FOCUS)
consider(window);
}
void BrowserBridge::consider(HWND window) {
HWND root = window ? GetAncestor(window, GA_ROOT) : nullptr;
if (!root || publishers_.count(root) || !is_chromium_content_window(root)) return;
Attempts &attempts = attempts_[root];
if (attempts.failures >= MaxFailures || GetTickCount64() < attempts.retryAfter) return;
if (!launch(root)) {
++attempts.failures;
attempts.retryAfter = GetTickCount64() + (BaseRetryMs << attempts.failures);
}
}
bool BrowserBridge::launch(HWND window) {
const std::string name = application_name(window);
const std::string handle = std::to_string(static_cast<unsigned long long>(reinterpret_cast<UINT_PTR>(window)));
std::vector<char *> argv = {
const_cast<char *>(publisherPath_.c_str()), const_cast<char *>("--app-name"), const_cast<char *>(name.c_str()),
const_cast<char *>("--worker"), const_cast<char *>(loader_.c_str()),
const_cast<char *>(workerPath_.c_str()), const_cast<char *>("--hwnd"),
const_cast<char *>(handle.c_str()), nullptr};
GPid pid = 0;
int output = -1;
GError *error = nullptr;
// stderr is inherited, so publisher and worker diagnostics reach the
// reader's helper log.
if (!g_spawn_async_with_pipes(nullptr, argv.data(), nullptr, G_SPAWN_DO_NOT_REAP_CHILD, follow_parent,
GINT_TO_POINTER(getpid()), &pid, nullptr, &output, nullptr, &error)) {
std::fprintf(stderr, "wine-access: browser publisher for %s did not start: %s\n", name.c_str(),
error ? error->message : "unknown error");
if (error) g_error_free(error);
return false;
}
g_unix_set_fd_nonblocking(output, TRUE, nullptr);
Publisher publisher;
publisher.pid = pid;
publisher.output = output;
publishers_[window] = publisher;
std::fprintf(stderr, "wine-access: browser publisher started for %s (pid %d)\n", name.c_str(), pid);
return true;
}
void BrowserBridge::read_output(Publisher &publisher) {
char chunk[256];
for (;;) {
const ssize_t count = read(publisher.output, chunk, sizeof(chunk));
if (count <= 0) break;
publisher.buffered.append(chunk, static_cast<size_t>(count));
if (publisher.buffered.size() > 4096) publisher.buffered.erase(0, publisher.buffered.size() - 64);
}
if (!publisher.published && publisher.buffered.find("published\n") != std::string::npos) {
publisher.published = true;
std::fprintf(stderr, "wine-access: browser publisher %d published; legacy announcements retired for its window\n",
publisher.pid);
}
}
void BrowserBridge::poll() {
if (!running_) return;
for (auto entry = publishers_.begin(); entry != publishers_.end();) {
Publisher &publisher = entry->second;
read_output(publisher);
int status = 0;
const pid_t result = waitpid(publisher.pid, &status, WNOHANG);
if (result == 0 || (result < 0 && errno == EINTR)) {
++entry;
continue;
}
close(publisher.output);
const HWND window = entry->first;
const bool windowAlive = IsWindow(window);
const int code = result > 0 && WIFEXITED(status) ? WEXITSTATUS(status) : -1;
std::fprintf(stderr, "wine-access: browser publisher %d exited (%s %d)%s\n", publisher.pid,
result > 0 && WIFSIGNALED(status) ? "signal" : "status",
result > 0 && WIFSIGNALED(status) ? WTERMSIG(status) : code,
windowAlive ? "; its window returns to legacy announcements" : "");
if (windowAlive) {
// A publisher should outlive its window; anything else is a failure.
Attempts &attempts = attempts_[window];
++attempts.failures;
attempts.retryAfter = GetTickCount64() + (BaseRetryMs << attempts.failures);
if (attempts.failures >= MaxFailures)
std::fprintf(stderr, "wine-access: browser bridge gave up on this window after %d failures\n",
attempts.failures);
}
entry = publishers_.erase(entry);
}
for (auto entry = attempts_.begin(); entry != attempts_.end();)
entry = IsWindow(entry->first) ? std::next(entry) : attempts_.erase(entry);
consider(GetForegroundWindow());
}
bool BrowserBridge::owns(HWND window) const {
if (!window) return false;
const auto found = publishers_.find(GetAncestor(window, GA_ROOT));
return found != publishers_.end() && found->second.published;
}
void BrowserBridge::stop() {
if (publishers_.empty()) return;
// Publishers close their worker's input as they exit; the worker follows.
for (auto &entry : publishers_) kill(entry.second.pid, SIGTERM);
const ULONGLONG deadline = GetTickCount64() + 2000;
for (auto &entry : publishers_) {
int status = 0;
while (waitpid(entry.second.pid, &status, WNOHANG) == 0) {
if (GetTickCount64() >= deadline) {
kill(entry.second.pid, SIGKILL);
waitpid(entry.second.pid, &status, 0);
break;
}
Sleep(20);
}
close(entry.second.output);
}
publishers_.clear();
}