Files
wine-access/browser_worker.cpp
Storm Dragon 6bdd04cce1 Fix browser node lifetime and fail closed on unknown protection
Retire ATK nodes without accessing freed children or retaining dangling parent and ID pointers. Treat failed and malformed MSAA state queries as protected, and initialize worker logging before argument validation.

Add publisher lifetime and worker privacy regressions, correct the publisher build target dependency, and remove both browser artifacts during uninstall.

Validation: build, all 12 CTests, updated startup-error regression, AddressSanitizer lifetime check, shellcheck, and temporary-prefix removal check passed. Live speech and Braille acceptance remains separate.
2026-12-02 23:22:12 -05:00

1262 lines
47 KiB
C++

// SPDX-License-Identifier: LGPL-2.1-or-later
// Wine Access browser worker.
//
// Runs inside the browser's Wine prefix, owns every MSAA/IA2 call for one
// Chromium window, and talks to wine-access-browser-publisher over
// stdin/stdout with one JSON message per line. Protected (password) text and
// values never leave this process.
//
// Usage: wine-access-browser-worker.exe (--hwnd DECIMAL | --title TEXT) [--wait-window SECONDS]
// --title is for tests; the helper always passes --hwnd.
//
// Worker -> publisher:
// {"type":"hello","protocol":1,"hwnd":N,"windowsPid":N,"x11Window":N,"title":S,"foreground":BOOL}
// {"type":"tree","generation":N,"focusedId":N,"root":NODE} full tree
// {"type":"subtree","generation":N,"node":NODE} replace a node and its descendants
// {"type":"node","generation":N,"node":NODE-WITHOUT-CHILDREN} update one node's properties
// {"type":"focus","id":N}
// {"type":"caret","id":N,"caret":UTF16,"selection":[S,E]|null}
// {"type":"selection","id":N,"selection":[S,E]|null}
// {"type":"layout"} extents and line boundaries are stale
// {"type":"anchor","id":N} scrolled to an anchor (in-page link target)
// {"type":"flush"} end of one batch of changes
// {"type":"foreground","active":BOOL}
// {"type":"reply","requestId":N,"ok":BOOL,"hr":N,...}
// {"type":"gone"}
// Publisher -> worker (flat objects, integers only besides "type" and "op"):
// {"type":"request","requestId":N,"op":OP,...}
// OP: action(id,index) focus(id) setCaret(id,offset) setSelection(id,start,end)
// scrollTo(id,scrollType) scrollSubstring(id,start,end,scrollType)
// boundary(id,offset,granularity) extents(id) characterExtents(id,offset)
// characterExtentsAll(id) (every character, at most 4096)
// refresh(id)
// All offsets are UTF-16, as IA2 reports them.
#include <windows.h>
#include <ole2.h>
#include <oleacc.h>
#include <servprov.h>
#include "Accessible2.h"
#include "AccessibleAction.h"
#include "AccessibleEventID.h"
#include "AccessibleHyperlink.h"
#include "AccessibleHypertext.h"
#include "AccessibleRelation.h"
#include "AccessibleTable2.h"
#include "AccessibleTableCell.h"
#include "AccessibleText.h"
#include "IA2CommonTypes.h"
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <ctime>
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <vector>
namespace {
constexpr UINT WM_APP_REQUEST = WM_APP + 1;
constexpr UINT WM_APP_INPUT_CLOSED = WM_APP + 2;
constexpr int ProtocolVersion = 1;
constexpr size_t MaxQueuedEvents = 20000;
constexpr int MaxDepth = 80;
constexpr int MaxNodes = 20000;
HWND targetWindow;
DWORD targetProcessId;
DWORD mainThreadId;
DWORD queryThreadId;
IAccessible *windowRoot; // main thread's apartment only
CRITICAL_SECTION outputLock;
long generation;
std::map<long, long> parentOf; // uniqueID -> parent uniqueID, for everything sent
LARGE_INTEGER perfFrequency;
VARIANT self_child() {
VARIANT value;
VariantInit(&value);
value.vt = VT_I4;
value.lVal = CHILDID_SELF;
return value;
}
const VARIANT selfChild = self_child();
double now_ms() {
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
return counter.QuadPart * 1000.0 / perfFrequency.QuadPart;
}
// ------------------------------------------------------------------ output
void write_all(HANDLE handle, const std::string &data) {
size_t written = 0;
while (written < data.size()) {
DWORD chunk = 0;
if (!WriteFile(handle, data.data() + written, (DWORD)(data.size() - written), &chunk, nullptr) || chunk == 0)
ExitProcess(4); // the publisher went away
written += chunk;
}
}
// Both the main thread and the query thread write; one line at a time.
void send(const std::string &message) {
EnterCriticalSection(&outputLock);
write_all(GetStdHandle(STD_OUTPUT_HANDLE), message + "\n");
LeaveCriticalSection(&outputLock);
}
// Diagnostics go to stderr: message first, then the time.
void log_message(const std::string &message) {
char timeText[64];
time_t now = time(nullptr);
struct tm local {};
localtime_s(&local, &now); // both threads log
strftime(timeText, sizeof(timeText), "%a %b %e %H:%M:%S %Y", &local);
EnterCriticalSection(&outputLock);
write_all(GetStdHandle(STD_ERROR_HANDLE), "wine-access-browser-worker: " + message + " [" + timeText + "]\n");
LeaveCriticalSection(&outputLock);
}
std::string to_utf8(const wchar_t *text, size_t length) {
if (!length) return {};
int needed = WideCharToMultiByte(CP_UTF8, 0, text, (int)length, nullptr, 0, nullptr, nullptr);
std::string result(needed, '\0');
WideCharToMultiByte(CP_UTF8, 0, text, (int)length, result.data(), needed, nullptr, nullptr);
return result;
}
std::string json_quote_utf8(const std::string &utf8) {
std::string result = "\"";
for (unsigned char c : utf8) {
switch (c) {
case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break;
case '\n': result += "\\n"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
default:
if (c < 0x20) {
char escaped[8];
snprintf(escaped, sizeof(escaped), "\\u%04x", c);
result += escaped;
} else {
result += (char)c;
}
}
}
return result + "\"";
}
std::string json_bstr(BSTR value) {
std::string result = value ? json_quote_utf8(to_utf8(value, SysStringLen(value))) : "null";
SysFreeString(value);
return result;
}
// ------------------------------------------------------------------ COM helpers
IAccessible2 *get_ia2(IUnknown *unknown) {
if (!unknown) return nullptr;
IServiceProvider *provider = nullptr;
IAccessible2 *ia2 = nullptr;
if (SUCCEEDED(unknown->QueryInterface(IID_IServiceProvider, (void **)&provider)) && provider) {
provider->QueryService(IID_IAccessible, __uuidof(IAccessible2), (void **)&ia2);
provider->Release();
}
if (!ia2) unknown->QueryInterface(__uuidof(IAccessible2), (void **)&ia2);
return ia2;
}
template <typename T>
T *ia2_interface(IAccessible2 *ia2) {
T *result = nullptr;
if (ia2) ia2->QueryInterface(__uuidof(T), (void **)&result);
return result;
}
long unique_id_of(IUnknown *unknown) {
IAccessible2 *ia2 = get_ia2(unknown);
long uniqueId = 0;
if (ia2) {
ia2->get_uniqueID(&uniqueId);
ia2->Release();
}
return uniqueId;
}
// Roots that can resolve uniqueIDs: the top-level window resolves Chromium's
// views objects, and its child windows (Chrome_RenderWidgetHostHWND) resolve
// web content. get_accChild on the wrong root fails with E_INVALIDARG.
// Per thread: COM proxies belong to the apartment that created them.
thread_local std::vector<std::pair<HWND, IAccessible *>> resolutionRoots;
BOOL CALLBACK add_child_root(HWND hwnd, LPARAM) {
for (const auto &entry : resolutionRoots)
if (entry.first == hwnd) return TRUE;
IAccessible *root = nullptr;
if (SUCCEEDED(AccessibleObjectFromWindow(hwnd, (DWORD)OBJID_CLIENT, IID_IAccessible, (void **)&root)) && root)
resolutionRoots.push_back({hwnd, root});
return TRUE;
}
void refresh_resolution_roots() {
add_child_root(targetWindow, 0);
EnumChildWindows(targetWindow, add_child_root, 0);
}
IAccessible *resolve_with_roots(long id) {
VARIANT child;
VariantInit(&child);
child.vt = VT_I4;
child.lVal = id;
for (const auto &entry : resolutionRoots) {
IDispatch *dispatch = nullptr;
if (FAILED(entry.second->get_accChild(child, &dispatch)) || !dispatch) continue;
IAccessible *accessible = nullptr;
dispatch->QueryInterface(IID_IAccessible, (void **)&accessible);
dispatch->Release();
if (accessible) return accessible;
}
return nullptr;
}
// Resolve a uniqueID to its object. Returns an owned reference or null.
IAccessible *resolve(long id) {
IAccessible *accessible = resolve_with_roots(id);
if (accessible) return accessible;
size_t knownRoots = resolutionRoots.size();
refresh_resolution_roots(); // a render widget window may have appeared
return resolutionRoots.size() > knownRoots ? resolve_with_roots(id) : nullptr;
}
long msaa_state(IAccessible *accessible) {
VARIANT value;
VariantInit(&value);
// Unknown protection must never authorize value, text or boundary reads.
long state = STATE_SYSTEM_PROTECTED;
if (accessible->get_accState(selfChild, &value) == S_OK && value.vt == VT_I4) state = value.lVal;
VariantClear(&value);
return state;
}
bool is_protected(IAccessible *accessible) {
return (msaa_state(accessible) & STATE_SYSTEM_PROTECTED) != 0;
}
// ------------------------------------------------------------------ requests
struct PendingRequest {
std::string line;
double receivedMs;
};
void handle_request(const std::string &line);
std::set<long> pendingSubtreeRefreshes;
void handle_posted_request(LPARAM parameter);
// Answer queued requests while a long walk is in progress.
void service_requests() {
MSG message;
while (PeekMessageW(&message, nullptr, WM_APP_REQUEST, WM_APP_REQUEST, PM_REMOVE))
handle_posted_request(message.lParam);
}
// ------------------------------------------------------------------ node records
std::string id_array(IUnknown **items, long count) {
std::string result = "[";
for (long i = 0; i < count; i++) {
if (i) result += ",";
result += std::to_string(unique_id_of(items[i]));
if (items[i]) items[i]->Release();
}
CoTaskMemFree(items);
return result + "]";
}
int recordedNodes;
void node_record(IAccessible *accessible, long parentId, bool withChildren, int depth, std::string &json) {
// Answer pending requests between objects so a long walk never delays a
// reader's synchronous query by more than one object's worth of calls.
++recordedNodes;
service_requests();
long role = 0;
VARIANT value;
VariantInit(&value);
if (SUCCEEDED(accessible->get_accRole(selfChild, &value)) && value.vt == VT_I4) role = value.lVal;
VariantClear(&value);
long state = msaa_state(accessible);
bool isProtected = (state & STATE_SYSTEM_PROTECTED) != 0;
IAccessible2 *ia2 = get_ia2(accessible);
long uniqueId = 0;
if (ia2) ia2->get_uniqueID(&uniqueId);
if (parentId) parentOf[uniqueId] = parentId;
json += "{\"id\":" + std::to_string(uniqueId) + ",\"msaaRole\":" + std::to_string(role) +
",\"msaaStates\":" + std::to_string(state);
BSTR text = nullptr;
if (SUCCEEDED(accessible->get_accName(selfChild, &text))) json += ",\"name\":" + json_bstr(text);
text = nullptr;
if (SUCCEEDED(accessible->get_accDescription(selfChild, &text)) && text) json += ",\"description\":" + json_bstr(text);
text = nullptr;
if (!isProtected && SUCCEEDED(accessible->get_accValue(selfChild, &text)) && text)
json += ",\"value\":" + json_bstr(text);
text = nullptr;
if (SUCCEEDED(accessible->get_accDefaultAction(selfChild, &text)) && text)
json += ",\"defaultAction\":" + json_bstr(text);
long left = 0, top = 0, width = 0, height = 0;
if (SUCCEEDED(accessible->accLocation(&left, &top, &width, &height, selfChild)))
json += ",\"location\":[" + std::to_string(left) + "," + std::to_string(top) + "," + std::to_string(width) +
"," + std::to_string(height) + "]";
if (ia2) {
long ia2Role = 0;
AccessibleStates ia2States = 0;
ia2->role(&ia2Role);
ia2->get_states(&ia2States);
json += ",\"ia2Role\":" + std::to_string(ia2Role) + ",\"ia2States\":" + std::to_string((long)ia2States);
BSTR attributes = nullptr;
if (SUCCEEDED(ia2->get_attributes(&attributes)) && attributes) json += ",\"attributes\":" + json_bstr(attributes);
long level = 0, setSize = 0, position = 0;
if (SUCCEEDED(ia2->get_groupPosition(&level, &setSize, &position)) && (level || setSize || position))
json += ",\"groupPosition\":[" + std::to_string(level) + "," + std::to_string(setSize) + "," +
std::to_string(position) + "]";
long relationCount = 0;
if (SUCCEEDED(ia2->get_nRelations(&relationCount)) && relationCount > 0) {
json += ",\"relations\":[";
bool first = true;
for (long i = 0; i < relationCount; i++) {
IAccessibleRelation *relation = nullptr;
if (FAILED(ia2->get_relation(i, &relation)) || !relation) continue;
BSTR type = nullptr;
long targetCount = 0;
relation->get_relationType(&type);
relation->get_nTargets(&targetCount);
if (!first) json += ",";
first = false;
json += "{\"type\":" + json_bstr(type) + ",\"targets\":[";
for (long j = 0; j < targetCount; j++) {
IUnknown *target = nullptr;
if (j) json += ",";
if (SUCCEEDED(relation->get_target(j, &target)) && target) {
json += std::to_string(unique_id_of(target));
target->Release();
} else {
json += "0";
}
}
json += "]}";
relation->Release();
}
json += "]";
}
if (auto *textIface = ia2_interface<IAccessibleText>(ia2)) {
long characterCount = 0;
textIface->get_nCharacters(&characterCount);
json += ",\"textLength\":" + std::to_string(characterCount);
if (!isProtected) {
BSTR content = nullptr;
if (SUCCEEDED(textIface->get_text(0, IA2_TEXT_OFFSET_LENGTH, &content))) json += ",\"text\":" + json_bstr(content);
long caret = 0;
if (textIface->get_caretOffset(&caret) == S_OK) json += ",\"caret\":" + std::to_string(caret);
}
textIface->Release();
}
if (auto *hypertext = ia2_interface<IAccessibleHypertext>(ia2)) {
long linkCount = 0;
if (SUCCEEDED(hypertext->get_nHyperlinks(&linkCount)) && linkCount > 0) {
json += ",\"hyperlinks\":[";
for (long i = 0; i < linkCount; i++) {
IAccessibleHyperlink *link = nullptr;
if (i) json += ",";
long startIndex = -1, endIndex = -1;
if (SUCCEEDED(hypertext->get_hyperlink(i, &link)) && link) {
link->get_startIndex(&startIndex);
link->get_endIndex(&endIndex);
json += "[" + std::to_string(startIndex) + "," + std::to_string(endIndex) + "," +
std::to_string(unique_id_of(link)) + "]";
link->Release();
} else {
json += "null";
}
}
json += "]";
}
hypertext->Release();
}
if (auto *action = ia2_interface<IAccessibleAction>(ia2)) {
long actionCount = 0;
if (SUCCEEDED(action->nActions(&actionCount)) && actionCount > 0) {
json += ",\"actions\":[";
for (long i = 0; i < actionCount; i++) {
BSTR actionName = nullptr;
if (i) json += ",";
json += SUCCEEDED(action->get_name(i, &actionName)) ? json_bstr(actionName) : "null";
}
json += "]";
}
action->Release();
}
if (auto *table = ia2_interface<IAccessibleTable2>(ia2)) {
long rows = 0, columns = 0;
table->get_nRows(&rows);
table->get_nColumns(&columns);
json += ",\"table\":{\"rows\":" + std::to_string(rows) + ",\"columns\":" + std::to_string(columns) + "}";
table->Release();
}
if (auto *cell = ia2_interface<IAccessibleTableCell>(ia2)) {
long row = 0, column = 0, rowExtent = 1, columnExtent = 1;
cell->get_rowIndex(&row);
cell->get_columnIndex(&column);
cell->get_rowExtent(&rowExtent);
cell->get_columnExtent(&columnExtent);
json += ",\"cell\":{\"row\":" + std::to_string(row) + ",\"column\":" + std::to_string(column) +
",\"rowSpan\":" + std::to_string(rowExtent) + ",\"columnSpan\":" + std::to_string(columnExtent);
IUnknown **headers = nullptr;
long headerCount = 0;
if (SUCCEEDED(cell->get_columnHeaderCells(&headers, &headerCount)))
json += ",\"columnHeaders\":" + id_array(headers, headerCount);
headers = nullptr;
headerCount = 0;
if (SUCCEEDED(cell->get_rowHeaderCells(&headers, &headerCount)))
json += ",\"rowHeaders\":" + id_array(headers, headerCount);
json += "}";
cell->Release();
}
ia2->Release();
}
if (withChildren) {
json += ",\"children\":[";
long childCount = 0;
if (depth < MaxDepth && recordedNodes < MaxNodes && SUCCEEDED(accessible->get_accChildCount(&childCount)) &&
childCount > 0) {
std::vector<VARIANT> children(childCount);
long obtained = 0;
if (SUCCEEDED(AccessibleChildren(accessible, 0, childCount, children.data(), &obtained))) {
bool first = true;
for (long i = 0; i < obtained; i++) {
if (children[i].vt == VT_DISPATCH && children[i].pdispVal) {
IAccessible *child = nullptr;
if (SUCCEEDED(children[i].pdispVal->QueryInterface(IID_IAccessible, (void **)&child)) && child) {
if (!first) json += ",";
first = false;
node_record(child, uniqueId, true, depth + 1, json);
child->Release();
}
}
VariantClear(&children[i]);
}
}
}
json += "]";
if (recordedNodes >= MaxNodes) json += ",\"truncated\":true";
}
json += "}";
}
// Follow accFocus from the window root to the focused object.
long focused_unique_id() {
IAccessible *current = windowRoot;
current->AddRef();
for (int depth = 0; depth < 64; depth++) {
VARIANT focus;
VariantInit(&focus);
if (FAILED(current->get_accFocus(&focus))) break;
if (focus.vt != VT_DISPATCH || !focus.pdispVal) {
VariantClear(&focus);
break;
}
IAccessible *next = nullptr;
focus.pdispVal->QueryInterface(IID_IAccessible, (void **)&next);
VariantClear(&focus);
if (!next || next == current) {
if (next) next->Release();
break;
}
current->Release();
current = next;
}
long focusedId = unique_id_of(current);
current->Release();
return focusedId;
}
void send_tree() {
generation++;
parentOf.clear();
recordedNodes = 0;
double startMs = now_ms();
std::string json = "{\"type\":\"tree\",\"generation\":" + std::to_string(generation) +
",\"focusedId\":" + std::to_string(focused_unique_id()) + ",\"root\":";
node_record(windowRoot, 0, true, 0, json);
json += "}";
send(json);
log_message("sent tree generation " + std::to_string(generation) + ": " + std::to_string(recordedNodes) +
" nodes in " + std::to_string((long)(now_ms() - startMs)) + " ms");
}
void send_subtree(long id) {
IAccessible *accessible = resolve(id);
if (!accessible) {
log_message("subtree " + std::to_string(id) + " no longer resolves; sending the whole tree");
send_tree();
return;
}
recordedNodes = 0;
auto parent = parentOf.find(id);
std::string json = "{\"type\":\"subtree\",\"generation\":" + std::to_string(generation) + ",\"node\":";
node_record(accessible, parent == parentOf.end() ? 0 : parent->second, true, 0, json);
json += "}";
accessible->Release();
send(json);
}
void send_node(long id) {
IAccessible *accessible = resolve(id);
if (!accessible) return; // already gone; a structural event will follow
recordedNodes = 0;
auto parent = parentOf.find(id);
std::string json = "{\"type\":\"node\",\"generation\":" + std::to_string(generation) + ",\"node\":";
node_record(accessible, parent == parentOf.end() ? 0 : parent->second, false, 0, json);
json += "}";
accessible->Release();
send(json);
}
std::string selection_json(IAccessibleText *text) {
long selectionCount = 0, start = 0, end = 0;
if (SUCCEEDED(text->get_nSelections(&selectionCount)) && selectionCount > 0 &&
SUCCEEDED(text->get_selection(0, &start, &end)))
return "[" + std::to_string(start) + "," + std::to_string(end) + "]";
return "null";
}
void send_caret(long id, bool selectionOnly) {
IAccessible *accessible = resolve(id);
if (!accessible) return;
IAccessible2 *ia2 = get_ia2(accessible);
IAccessibleText *text = ia2_interface<IAccessibleText>(ia2);
if (text) {
std::string selection = selection_json(text);
if (selectionOnly) {
send("{\"type\":\"selection\",\"id\":" + std::to_string(id) + ",\"selection\":" + selection + "}");
} else {
long caret = -1;
if (text->get_caretOffset(&caret) != S_OK) caret = -1;
send("{\"type\":\"caret\",\"id\":" + std::to_string(id) + ",\"caret\":" + std::to_string(caret) +
",\"selection\":" + selection + "}");
}
text->Release();
}
if (ia2) ia2->Release();
accessible->Release();
}
// ------------------------------------------------------------------ request handling
// Requests are flat JSON objects written by the publisher; read one member.
bool member_long(const std::string &line, const char *key, long &value) {
std::string pattern = std::string("\"") + key + "\":";
size_t position = line.find(pattern);
if (position == std::string::npos) return false;
const char *start = line.c_str() + position + pattern.size();
char *end = nullptr;
long parsed = strtol(start, &end, 10);
if (end == start) return false;
value = parsed;
return true;
}
std::string member_string(const std::string &line, const char *key) {
std::string pattern = std::string("\"") + key + "\":\"";
size_t position = line.find(pattern);
if (position == std::string::npos) return {};
size_t start = position + pattern.size();
size_t end = line.find('"', start);
return end == std::string::npos ? std::string() : line.substr(start, end - start);
}
void reply(long requestId, HRESULT hr, const std::string &fields = "") {
send("{\"type\":\"reply\",\"requestId\":" + std::to_string(requestId) + ",\"ok\":" +
(SUCCEEDED(hr) ? "true" : "false") + ",\"hr\":" + std::to_string((long)hr) + fields + "}");
}
// Objects already resolved on the query thread. Resolving costs a
// get_accChild plus an IA2 QueryService (about 4-5 ms), and readers query the
// same objects repeatedly. A stale entry fails its call and is resolved again.
struct CachedObject {
IAccessible *accessible;
IAccessible2 *ia2;
};
thread_local std::map<long, CachedObject> objectCache;
constexpr size_t MaxCachedObjects = 2048;
constexpr long MaxExtentCharacters = 4096;
void release_cached(CachedObject &entry) {
if (entry.ia2) entry.ia2->Release();
entry.accessible->Release();
}
void forget_cached_object(long id) {
auto found = objectCache.find(id);
if (found == objectCache.end()) return;
release_cached(found->second);
objectCache.erase(found);
}
// Owned references, or false when the object no longer resolves.
bool cached_object(long id, IAccessible **accessible, IAccessible2 **ia2) {
auto found = objectCache.find(id);
if (found == objectCache.end()) {
IAccessible *resolved = resolve(id);
if (!resolved) return false;
if (objectCache.size() >= MaxCachedObjects) {
for (auto &entry : objectCache) release_cached(entry.second);
objectCache.clear();
}
found = objectCache.emplace(id, CachedObject{resolved, get_ia2(resolved)}).first;
}
*accessible = found->second.accessible;
(*accessible)->AddRef();
*ia2 = found->second.ia2;
if (*ia2) (*ia2)->AddRef();
return true;
}
bool is_stale_result(HRESULT hr) {
return hr == E_FAIL || hr == RPC_E_DISCONNECTED || hr == CO_E_OBJNOTCONNECTED || hr == RPC_E_SERVER_DIED ||
hr == RPC_E_SERVER_DIED_DNE;
}
bool is_read_only_op(const std::string &op) {
return op == "extents" || op == "boundary" || op == "characterExtents" || op == "characterExtentsAll";
}
HRESULT perform_request(const std::string &op, const std::string &line, IAccessible *accessible, IAccessible2 *ia2,
std::string &fields) {
HRESULT hr = E_NOTIMPL;
fields.clear();
long a = 0, b = 0, c = 0;
if (op == "action") {
member_long(line, "index", a);
IAccessibleAction *action = ia2_interface<IAccessibleAction>(ia2);
if (action) {
hr = action->doAction(a);
action->Release();
} else if (a == 0) {
hr = accessible->accDoDefaultAction(selfChild); // views objects have no IA2 actions
} else {
hr = E_INVALIDARG;
}
} else if (op == "focus") {
hr = accessible->accSelect(SELFLAG_TAKEFOCUS, selfChild);
} else if (op == "extents") {
long left = 0, top = 0, width = 0, height = 0;
hr = accessible->accLocation(&left, &top, &width, &height, selfChild);
fields = ",\"extents\":[" + std::to_string(left) + "," + std::to_string(top) + "," + std::to_string(width) +
"," + std::to_string(height) + "]";
} else if (op == "scrollTo") {
member_long(line, "scrollType", a);
hr = ia2 ? ia2->scrollTo((IA2ScrollType)a) : E_NOINTERFACE;
} else {
IAccessibleText *text = ia2_interface<IAccessibleText>(ia2);
bool protectedText = is_protected(accessible);
if (!text) {
hr = E_NOINTERFACE;
} else if (op == "setCaret" && member_long(line, "offset", a)) {
hr = text->setCaretOffset(a);
} else if (op == "setSelection" && member_long(line, "start", a) && member_long(line, "end", b)) {
long selectionCount = 0;
text->get_nSelections(&selectionCount);
hr = selectionCount > 0 ? text->setSelection(0, a, b) : text->addSelection(a, b);
} else if (op == "scrollSubstring" && member_long(line, "start", a) && member_long(line, "end", b)) {
member_long(line, "scrollType", c);
hr = text->scrollSubstringTo(a, b, (IA2ScrollType)c);
} else if (op == "boundary" && member_long(line, "offset", a) && member_long(line, "granularity", b)) {
if (protectedText) {
hr = E_ACCESSDENIED; // boundaries would reveal word lengths
} else {
long startOffset = -1, endOffset = -1;
BSTR segment = nullptr;
hr = text->get_textAtOffset(a, (IA2TextBoundaryType)b, &startOffset, &endOffset, &segment);
SysFreeString(segment);
if (hr != S_OK) startOffset = endOffset = -1;
fields = ",\"start\":" + std::to_string(startOffset) + ",\"end\":" + std::to_string(endOffset);
if (SUCCEEDED(hr)) hr = S_OK;
}
} else if (op == "characterExtentsAll") {
// Every character's screen rectangle in one round trip; readers ask for
// range extents, which would otherwise cost one request per character.
long characterCount = 0;
text->get_nCharacters(&characterCount);
if (characterCount > MaxExtentCharacters) {
hr = E_INVALIDARG;
} else {
hr = S_OK;
fields = ",\"extents\":[";
for (long offset = 0; offset < characterCount; offset++) {
long x = 0, y = 0, width = 0, height = 0;
if (FAILED(text->get_characterExtents(offset, IA2_COORDTYPE_SCREEN_RELATIVE, &x, &y, &width, &height)))
x = y = width = height = 0;
if (offset) fields += ",";
fields += "[" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(width) + "," +
std::to_string(height) + "]";
}
fields += "]";
}
} else if (op == "characterExtents" && member_long(line, "offset", a)) {
long x = 0, y = 0, width = 0, height = 0;
hr = text->get_characterExtents(a, IA2_COORDTYPE_SCREEN_RELATIVE, &x, &y, &width, &height);
fields = ",\"extents\":[" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(width) + "," +
std::to_string(height) + "]";
} else {
hr = E_INVALIDARG;
}
if (text) text->Release();
}
return hr;
}
void handle_request(const std::string &line) {
long requestId = 0, id = 0;
std::string op = member_string(line, "op");
if (member_string(line, "type") != "request" || !member_long(line, "requestId", requestId) || op.empty()) {
log_message("malformed request ignored");
return;
}
if (!member_long(line, "id", id)) {
reply(requestId, E_INVALIDARG);
return;
}
if (op == "refresh") {
pendingSubtreeRefreshes.insert(id); // performed with the next event batch
reply(requestId, S_OK);
return;
}
IAccessible *accessible = nullptr;
IAccessible2 *ia2 = nullptr;
if (!cached_object(id, &accessible, &ia2)) {
reply(requestId, E_FAIL, ",\"gone\":true");
return;
}
std::string fields;
HRESULT hr = perform_request(op, line, accessible, ia2, fields);
if (is_stale_result(hr)) {
// The cached object may have died; resolve it afresh. Only read-only
// queries are retried, so an action can never run twice.
if (ia2) ia2->Release();
accessible->Release();
ia2 = nullptr;
forget_cached_object(id);
if (!is_read_only_op(op)) {
reply(requestId, hr, fields);
return;
}
if (!cached_object(id, &accessible, &ia2)) {
reply(requestId, E_FAIL, ",\"gone\":true");
return;
}
hr = perform_request(op, line, accessible, ia2, fields);
}
if (ia2) ia2->Release();
accessible->Release();
reply(requestId, hr, fields);
}
// ------------------------------------------------------------------ events
struct QueuedEvent {
DWORD event;
HWND hwnd;
LONG idObject;
LONG idChild;
};
std::vector<QueuedEvent> eventQueue;
double firstEventMs, lastEventMs;
long droppedEvents;
bool belongs_to_target(HWND hwnd) {
return hwnd == targetWindow || IsChild(targetWindow, hwnd);
}
void CALLBACK win_event_proc(HWINEVENTHOOK, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD) {
if (event == EVENT_SYSTEM_FOREGROUND) {
eventQueue.push_back({event, hwnd, idObject, idChild});
lastEventMs = now_ms();
if (eventQueue.size() == 1) firstEventMs = lastEventMs;
return;
}
if (!hwnd || !belongs_to_target(hwnd)) return;
// Caret location changes flood while typing and navigating and say nothing
// about layout; drop them here.
if (event == EVENT_OBJECT_LOCATIONCHANGE && idObject != OBJID_CLIENT) return;
if (eventQueue.size() >= MaxQueuedEvents) {
droppedEvents++;
return;
}
if (eventQueue.empty()) firstEventMs = now_ms();
lastEventMs = now_ms();
eventQueue.push_back({event, hwnd, idObject, idChild});
}
bool is_property_event(DWORD event) {
switch (event) {
case EVENT_OBJECT_STATECHANGE: case EVENT_OBJECT_NAMECHANGE: case EVENT_OBJECT_VALUECHANGE:
case EVENT_OBJECT_DESCRIPTIONCHANGE: case IA2_EVENT_TEXT_INSERTED: case IA2_EVENT_TEXT_REMOVED:
case IA2_EVENT_TEXT_UPDATED: case IA2_EVENT_TEXT_CHANGED: case IA2_EVENT_OBJECT_ATTRIBUTE_CHANGED:
case IA2_EVENT_TEXT_ATTRIBUTE_CHANGED: case IA2_EVENT_HYPERTEXT_CHANGED: case IA2_EVENT_HYPERTEXT_NLINKS_CHANGED:
case IA2_EVENT_ACTION_CHANGED:
return true;
default:
return false;
}
}
// Events that move content on screen. A location change of the caret object
// (OBJID_CARET) only means the caret moved; treating it as layout would
// discard every cached boundary and position on each arrow press.
bool is_layout_event(const QueuedEvent &queued) {
if (queued.event == EVENT_OBJECT_LOCATIONCHANGE) return queued.idObject == OBJID_CLIENT;
return queued.event == EVENT_SYSTEM_SCROLLINGSTART || queued.event == EVENT_SYSTEM_SCROLLINGEND ||
queued.event == IA2_EVENT_VISIBLE_DATA_CHANGED || queued.event == 0x8015;
}
bool has_ancestor_in(long id, const std::set<long> &ids) {
for (int guard = 0; guard < MaxDepth; guard++) {
auto parent = parentOf.find(id);
if (parent == parentOf.end()) return false;
id = parent->second;
if (ids.count(id)) return true;
}
return false;
}
long parent_from_provider(long id) {
IAccessible *accessible = resolve(id);
if (!accessible) return 0;
IDispatch *parentDispatch = nullptr;
long parentId = 0;
if (SUCCEEDED(accessible->get_accParent(&parentDispatch)) && parentDispatch) {
parentId = unique_id_of(parentDispatch);
parentDispatch->Release();
}
accessible->Release();
return parentId;
}
// Translate one coalesced batch of events into messages, in an order the
// publisher can apply directly: structure, then properties, then focus,
// caret, selection, and layout.
void process_events_inner(std::vector<QueuedEvent> &batch);
void process_events() {
std::vector<QueuedEvent> batch;
batch.swap(eventQueue);
double startMs = now_ms();
size_t batchSize = batch.size();
std::map<DWORD, int> kinds;
for (const QueuedEvent &queued : batch) kinds[queued.event]++;
process_events_inner(batch);
double elapsedMs = now_ms() - startMs;
if (elapsedMs > 100) {
std::string summary;
for (const auto &entry : kinds) {
char item[48];
snprintf(item, sizeof(item), " 0x%lx:%d", (unsigned long)entry.first, entry.second);
summary += item;
}
log_message("slow event batch: " + std::to_string(batchSize) + " events in " + std::to_string((long)elapsedMs) +
" ms," + summary);
}
}
void process_events_inner(std::vector<QueuedEvent> &batch) {
if (droppedEvents) {
log_message("event queue overflowed (" + std::to_string(droppedEvents) + " dropped); resynchronizing");
droppedEvents = 0;
send_tree();
send("{\"type\":\"flush\"}");
return;
}
bool fullTree = false, layout = false;
std::set<long> subtrees = pendingSubtreeRefreshes;
pendingSubtreeRefreshes.clear();
std::vector<long> nodes, carets, selections, anchors;
long focusId = 0;
int foreground = -1;
for (const QueuedEvent &queued : batch) {
if (queued.event == EVENT_SYSTEM_FOREGROUND) {
foreground = belongs_to_target(queued.hwnd) ? 1 : 0;
continue;
}
if (queued.event == EVENT_OBJECT_DESTROY && queued.hwnd == targetWindow && queued.idObject == OBJID_WINDOW) {
send("{\"type\":\"gone\"}");
ExitProcess(0);
}
if (is_layout_event(queued)) {
layout = true;
// Chromium reports scrolling to an anchor as SCROLLINGSTART on the target.
if (queued.event == EVENT_SYSTEM_SCROLLINGSTART && queued.idObject == OBJID_CLIENT &&
queued.idChild != CHILDID_SELF)
anchors.push_back(queued.idChild);
continue;
}
if (queued.idObject != OBJID_CLIENT) continue;
long id = queued.idChild;
switch (queued.event) {
case IA2_EVENT_DOCUMENT_LOAD_COMPLETE: case IA2_EVENT_DOCUMENT_RELOAD:
// The event names the document; refresh just that subtree when it is
// known, otherwise resend everything.
if (parentOf.count(id)) subtrees.insert(id);
else fullTree = true;
break;
case EVENT_OBJECT_REORDER: case IA2_EVENT_ROLE_CHANGED:
subtrees.insert(queued.event == IA2_EVENT_ROLE_CHANGED && parentOf.count(id) ? parentOf[id] : id);
break;
case EVENT_OBJECT_SHOW: {
long parentId = parent_from_provider(id);
if (!parentId && parentOf.count(id)) parentId = parentOf[id];
if (parentId) subtrees.insert(parentId);
else fullTree = true;
break;
}
case EVENT_OBJECT_HIDE:
if (parentOf.count(id)) subtrees.insert(parentOf[id]);
break; // an object never sent needs no removal
case EVENT_OBJECT_FOCUS:
focusId = id;
nodes.push_back(id);
break;
case IA2_EVENT_TEXT_CARET_MOVED:
carets.push_back(id);
break;
case IA2_EVENT_TEXT_SELECTION_CHANGED: case 0x8014:
selections.push_back(id);
break;
default:
if (is_property_event(queued.event)) nodes.push_back(id);
break;
}
}
if (fullTree) {
send_tree();
} else {
for (long id : subtrees)
if (!has_ancestor_in(id, subtrees)) send_subtree(id);
}
// Native Chromium order: the newly focused object's caret, then focus, then
// property changes (such as checked); while typing, text changes before the
// caret. So: focus target's caret, focus, node updates, remaining carets.
std::set<long> sentCarets;
if (focusId) {
if (std::find(carets.begin(), carets.end(), focusId) != carets.end()) {
send_caret(focusId, false);
sentCarets.insert(focusId);
}
send("{\"type\":\"focus\",\"id\":" + std::to_string(focusId) + "}");
}
if (!fullTree) {
std::set<long> sentNodes;
for (long id : nodes) {
if (subtrees.count(id) || has_ancestor_in(id, subtrees) || !sentNodes.insert(id).second) continue;
send_node(id);
}
}
for (auto it = carets.rbegin(); it != carets.rend(); ++it)
if (sentCarets.insert(*it).second) send_caret(*it, false);
std::set<long> sentSelections;
for (long id : selections)
if (!sentCarets.count(id) && sentSelections.insert(id).second) send_caret(id, true);
if (layout) send("{\"type\":\"layout\"}");
for (long id : anchors) send("{\"type\":\"anchor\",\"id\":" + std::to_string(id) + "}");
if (foreground >= 0) send(std::string("{\"type\":\"foreground\",\"active\":") + (foreground ? "true" : "false") + "}");
send("{\"type\":\"flush\"}");
}
// Synchronous queries and actions run on their own COM apartment, so the main
// thread's event walks never delay a reader's query.
DWORD WINAPI query_thread(LPVOID ready) {
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
MSG message;
PeekMessageW(&message, nullptr, WM_USER, WM_USER, PM_NOREMOVE); // create the queue
refresh_resolution_roots();
SetEvent((HANDLE)ready);
while (GetMessageW(&message, nullptr, 0, 0) > 0) {
if (message.message == WM_APP_REQUEST) {
handle_posted_request(message.lParam);
} else {
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
for (auto &entry : objectCache) release_cached(entry.second);
objectCache.clear();
for (auto &entry : resolutionRoots) entry.second->Release();
resolutionRoots.clear();
CoUninitialize();
return 0;
}
// Handle one request posted by the input thread, logging slow ones: the time
// spent waiting in the queue and the time spent answering.
void handle_posted_request(LPARAM parameter) {
auto *request = reinterpret_cast<PendingRequest *>(parameter);
double startMs = now_ms();
handle_request(request->line);
double doneMs = now_ms();
if (doneMs - request->receivedMs > 100)
log_message("slow request: waited " + std::to_string((long)(startMs - request->receivedMs)) + " ms, answered in " +
std::to_string((long)(doneMs - startMs)) + " ms: op " + member_string(request->line, "op"));
delete request;
}
// ------------------------------------------------------------------ startup
DWORD WINAPI input_thread(LPVOID) {
HANDLE input = GetStdHandle(STD_INPUT_HANDLE);
std::string buffer;
char chunk[4096];
DWORD readBytes = 0;
while (ReadFile(input, chunk, sizeof(chunk), &readBytes, nullptr) && readBytes > 0) {
buffer.append(chunk, readBytes);
size_t newline;
while ((newline = buffer.find('\n')) != std::string::npos) {
auto *request = new PendingRequest{buffer.substr(0, newline), now_ms()};
buffer.erase(0, newline + 1);
// Refreshes change what the main thread sends; everything else is a
// query or an action for the query thread.
DWORD target = member_string(request->line, "op") == "refresh" ? mainThreadId : queryThreadId;
if (!PostThreadMessageW(target, WM_APP_REQUEST, 0, (LPARAM)request)) delete request;
}
if (buffer.size() > (1u << 20)) buffer.clear(); // never let a broken peer grow memory
}
PostThreadMessageW(queryThreadId, WM_QUIT, 0, 0);
PostThreadMessageW(mainThreadId, WM_APP_INPUT_CLOSED, 0, 0);
return 0;
}
struct FindWindowState {
std::wstring titlePart;
HWND found = nullptr;
};
BOOL CALLBACK find_window_proc(HWND hwnd, LPARAM param) {
auto *state = reinterpret_cast<FindWindowState *>(param);
wchar_t title[512] = {0}, className[256] = {0};
GetWindowTextW(hwnd, title, 512);
GetClassNameW(hwnd, className, 256);
if (wcsstr(className, L"Chrome_WidgetWin") && wcsstr(title, state->titlePart.c_str()) && IsWindowVisible(hwnd)) {
state->found = hwnd;
return FALSE;
}
return TRUE;
}
// Pump everything except publisher requests, which stay queued for the main loop.
void pump(double milliseconds) {
double endMs = now_ms() + milliseconds;
while (now_ms() < endMs) {
MSG message;
while (PeekMessageW(&message, nullptr, 0, WM_APP_REQUEST - 1, PM_REMOVE) ||
PeekMessageW(&message, nullptr, WM_APP_REQUEST + 1, 0xFFFFFFFF, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
MsgWaitForMultipleObjects(0, nullptr, FALSE, 20, QS_ALLINPUT);
}
}
bool document_has_content(IAccessible *accessible, int depth = 0) {
VARIANT roleValue;
VariantInit(&roleValue);
if (SUCCEEDED(accessible->get_accRole(selfChild, &roleValue)) && roleValue.vt == VT_I4 &&
roleValue.lVal == ROLE_SYSTEM_DOCUMENT) {
long childCount = 0;
accessible->get_accChildCount(&childCount);
return childCount > 0;
}
VariantClear(&roleValue);
long childCount = 0;
if (depth > 40 || FAILED(accessible->get_accChildCount(&childCount)) || childCount <= 0) return false;
std::vector<VARIANT> children(childCount);
long obtained = 0;
if (FAILED(AccessibleChildren(accessible, 0, childCount, children.data(), &obtained))) return false;
bool found = false;
for (long i = 0; i < obtained; i++) {
if (!found && children[i].vt == VT_DISPATCH && children[i].pdispVal) {
IAccessible *child = nullptr;
if (SUCCEEDED(children[i].pdispVal->QueryInterface(IID_IAccessible, (void **)&child)) && child) {
found = document_has_content(child, depth + 1);
child->Release();
}
}
VariantClear(&children[i]);
}
return found;
}
void default_action_sweep(IAccessible *accessible, int depth = 0) {
BSTR text = nullptr;
accessible->get_accDefaultAction(selfChild, &text);
SysFreeString(text);
long childCount = 0;
if (depth > 40 || FAILED(accessible->get_accChildCount(&childCount)) || childCount <= 0) return;
std::vector<VARIANT> children(childCount);
long obtained = 0;
if (FAILED(AccessibleChildren(accessible, 0, childCount, children.data(), &obtained))) return;
for (long i = 0; i < obtained; i++) {
if (children[i].vt == VT_DISPATCH && children[i].pdispVal) {
IAccessible *child = nullptr;
if (SUCCEEDED(children[i].pdispVal->QueryInterface(IID_IAccessible, (void **)&child)) && child) {
default_action_sweep(child, depth + 1);
child->Release();
}
}
VariantClear(&children[i]);
}
}
// Chromium exposes web content only after a client looks like a screen
// reader. The measured trigger is accDefaultAction on the pre-activation
// tree; verify the result instead of trusting it.
bool activate_web_content() {
if (document_has_content(windowRoot)) return true;
default_action_sweep(windowRoot);
double deadlineMs = now_ms() + 10000;
while (now_ms() < deadlineMs) {
pump(100);
if (document_has_content(windowRoot)) return true;
}
return false;
}
} // namespace
int wmain(int argc, wchar_t **argv) {
QueryPerformanceFrequency(&perfFrequency);
InitializeCriticalSection(&outputLock);
std::wstring titlePart;
HWND hwndArgument = nullptr;
double waitWindowSeconds = 30;
for (int i = 1; i < argc; i++) {
std::wstring arg = argv[i];
auto next = [&]() -> std::wstring { return i + 1 < argc ? argv[++i] : L""; };
if (arg == L"--title") titlePart = next();
else if (arg == L"--hwnd") hwndArgument = (HWND)(ULONG_PTR)_wcstoui64(next().c_str(), nullptr, 10);
else if (arg == L"--wait-window") waitWindowSeconds = _wtof(next().c_str());
else {
log_message("unknown argument");
return 2;
}
}
if (titlePart.empty() && !hwndArgument) {
log_message("usage: wine-access-browser-worker.exe (--hwnd DECIMAL | --title TEXT) [--wait-window SECONDS]");
return 2;
}
mainThreadId = GetCurrentThreadId();
MSG message;
PeekMessageW(&message, nullptr, WM_USER, WM_USER, PM_NOREMOVE); // create the queue before the input thread posts
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (hwndArgument) {
targetWindow = IsWindow(hwndArgument) ? hwndArgument : nullptr;
} else {
FindWindowState state;
state.titlePart = titlePart;
double deadlineMs = now_ms() + waitWindowSeconds * 1000.0;
while (!state.found && now_ms() < deadlineMs) {
EnumWindows(find_window_proc, (LPARAM)&state);
if (!state.found) pump(250);
}
targetWindow = state.found;
}
if (!targetWindow) {
log_message("browser window not found");
send("{\"type\":\"gone\"}");
return 3;
}
GetWindowThreadProcessId(targetWindow, &targetProcessId);
if (FAILED(AccessibleObjectFromWindow(targetWindow, (DWORD)OBJID_CLIENT, IID_IAccessible, (void **)&windowRoot)) ||
!windowRoot) {
log_message("AccessibleObjectFromWindow failed");
send("{\"type\":\"gone\"}");
return 3;
}
wchar_t title[512] = {0};
GetWindowTextW(targetWindow, title, 512);
HANDLE x11Window = GetPropW(targetWindow, L"__wine_x11_whole_window");
send("{\"type\":\"hello\",\"protocol\":" + std::to_string(ProtocolVersion) + ",\"hwnd\":" +
std::to_string((unsigned long long)(ULONG_PTR)targetWindow) + ",\"windowsPid\":" +
std::to_string(targetProcessId) + ",\"x11Window\":" + std::to_string((unsigned long long)(ULONG_PTR)x11Window) +
",\"title\":" + json_quote_utf8(to_utf8(title, wcslen(title))) +
",\"foreground\":" + (GetForegroundWindow() == targetWindow ? "true" : "false") + "}");
HWINEVENTHOOK objectHook = SetWinEventHook(EVENT_MIN, EVENT_MAX, nullptr, win_event_proc, targetProcessId, 0,
WINEVENT_OUTOFCONTEXT);
HWINEVENTHOOK foregroundHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr,
win_event_proc, 0, 0, WINEVENT_OUTOFCONTEXT);
if (!objectHook || !foregroundHook) log_message("SetWinEventHook failed");
if (!activate_web_content()) log_message("web content did not appear after activation; publishing what exists");
refresh_resolution_roots();
HANDLE queryReady = CreateEventW(nullptr, TRUE, FALSE, nullptr);
HANDLE queryThread = CreateThread(nullptr, 0, query_thread, queryReady, 0, &queryThreadId);
WaitForSingleObject(queryReady, 10000);
CloseHandle(queryReady);
{
std::string rootClasses;
for (const auto &entry : resolutionRoots) {
wchar_t className[256] = {0};
GetClassNameW(entry.first, className, 256);
rootClasses += " " + to_utf8(className, wcslen(className));
}
log_message("resolution roots:" + rootClasses);
}
send_tree();
CloseHandle(CreateThread(nullptr, 0, input_thread, nullptr, 0, nullptr));
bool running = true;
while (running) {
DWORD timeout = eventQueue.empty() && pendingSubtreeRefreshes.empty() ? 1000 : 10;
MsgWaitForMultipleObjects(0, nullptr, FALSE, timeout, QS_ALLINPUT);
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
if (message.message == WM_APP_REQUEST) {
handle_posted_request(message.lParam);
} else if (message.message == WM_APP_INPUT_CLOSED) {
running = false;
} else {
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
// Coalesce bursts: wait for 25 ms of quiet, but never longer than 150 ms.
double nowMs = now_ms();
if ((!eventQueue.empty() && (nowMs - lastEventMs >= 25 || nowMs - firstEventMs >= 150)) ||
(eventQueue.empty() && !pendingSubtreeRefreshes.empty()))
process_events();
if (!IsWindow(targetWindow)) {
send("{\"type\":\"gone\"}");
running = false;
}
}
PostThreadMessageW(queryThreadId, WM_QUIT, 0, 0);
WaitForSingleObject(queryThread, 5000);
CloseHandle(queryThread);
for (auto &entry : resolutionRoots) entry.second->Release();
if (objectHook) UnhookWinEvent(objectHook);
if (foregroundHook) UnhookWinEvent(foregroundHook);
windowRoot->Release();
CoUninitialize();
return 0;
}