Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwasmaccessibility.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6#include "qwasmscreen.h"
7#include "qwasmwindow.h"
9#include <QtCore/private/qwasmsuspendresumecontrol_p.h>
10#include <QtGui/qguiapplication.h>
11#include <QtGui/qwindow.h>
12
14{
15 QWasmAccessibility::enable();
16}
17
18#if QT_CONFIG(accessibility)
19
20#include <QtGui/private/qaccessiblebridgeutils_p.h>
21
22Q_LOGGING_CATEGORY(lcQpaAccessibility, "qt.qpa.accessibility")
23
24namespace {
25// Returns the focused element, descending into shadow roots.
26static emscripten::val getActiveElement()
27{
28 emscripten::val activeElement = emscripten::val::global("document")["activeElement"];
29 while (!activeElement.isNull() && !activeElement.isUndefined()) {
30 const emscripten::val shadowRoot = activeElement["shadowRoot"];
31 if (shadowRoot.isNull() || shadowRoot.isUndefined())
32 return activeElement;
33 activeElement = shadowRoot["activeElement"];
34 }
35 return emscripten::val::undefined();
36}
37
38#ifndef QT_NO_DEBUG
39static void logElement(emscripten::val element)
40{
41 emscripten::val::global("console").call<void>("log", element);
42}
43#endif
44
45}
46
47// Qt WebAssembly a11y backend
48//
49// This backend implements accessibility support by creating "shadowing" html
50// elements for each Qt UI element. We access the DOM by using Emscripten's
51// val.h API.
52//
53// Currently, html elements are created in response to notifyAccessibilityUpdate
54// events. In addition or alternatively, we could also walk the accessibility tree
55// from setRootObject().
56
57QWasmAccessibility::QWasmAccessibility()
58{
59 if (qEnvironmentVariableIntValue("QT_WASM_ENABLE_ACCESSIBILITY") == 1)
60 enableAccessibility();
61
62 // Register accessibility element event handler
63 QWasmSuspendResumeControl *suspendResume = QWasmSuspendResumeControl::get();
64
65 m_eventHandlerIndex = suspendResume->registerEventHandler([this](const emscripten::val event){
66 this->handleEventFromHtmlElement(event);
67 });
68}
69
70QWasmAccessibility::~QWasmAccessibility()
71{
72 // Remove accessibility element event handler
73 QWasmSuspendResumeControl *suspendResume = QWasmSuspendResumeControl::get();
74 suspendResume->removeEventHandler(m_eventHandlerIndex);
75}
76
77QWasmAccessibility *QWasmAccessibility::instance()
78{
79 QWasmIntegration *integration = QWasmIntegration::get();
80 return integration ? static_cast<QWasmAccessibility *>(integration->accessibility()) : nullptr;
81}
82
83void QWasmAccessibility::addAccessibilityEnableButton(QWindow *window)
84{
85 if (QWasmAccessibility *accessibility = instance(); accessibility && !accessibility->isActive())
86 accessibility->addEnableButton(window);
87}
88
89void QWasmAccessibility::onShowWindow(QWindow *window)
90{
91 if (QWasmAccessibility *accessibility = instance(); accessibility && accessibility->isActive())
92 accessibility->populateAccessibilityTree(window->accessibleRoot());
93}
94
95void QWasmAccessibility::onRemoveWindow(QWindow *window)
96{
97 if (QWasmAccessibility *accessibility = instance())
98 accessibility->removeWindow(window);
99}
100
101bool QWasmAccessibility::isEnabled()
102{
103 const QWasmAccessibility *accessibility = instance();
104 return accessibility && accessibility->isActive();
105}
106
107void QWasmAccessibility::enable()
108{
109 if (QWasmAccessibility *accessibility = instance(); accessibility && !accessibility->isActive())
110 accessibility->enableAccessibility();
111}
112
113bool QWasmAccessibility::setFocusObject(QObject *object)
114{
115 QWasmAccessibility *accessibility = instance();
116 return accessibility && accessibility->setFocusObjectImpl(object);
117}
118
119void QWasmAccessibility::addEnableButton(QWindow *window)
120{
121 emscripten::val container = getElementContainer(window);
122 if (container.isUndefined())
123 return;
124
125 emscripten::val document = getDocument(container);
126 emscripten::val button = document.call<emscripten::val>("createElement", std::string("button"));
127 setProperty(button, "innerText", "Enable Screen Reader");
128 button["classList"].call<void>("add", emscripten::val("hidden-visually-read-by-screen-reader"));
129 button.set("tabIndex", -1);
130 container.call<void>("appendChild", button);
131
132 auto enableContext = std::make_tuple(button, std::make_unique<qstdweb::EventCallback>
133 (button, std::string("click"), [this](emscripten::val) { enableAccessibility(); }));
134 m_enableButtons.insert(std::make_pair(window, std::move(enableContext)));
135}
136
137void QWasmAccessibility::removeWindow(QWindow *window)
138{
139 {
140 const auto it = m_enableButtons.find(window);
141 if (it != m_enableButtons.end()) {
142 // Remove button
143 auto [element, callback] = it->second;
144 Q_UNUSED(callback);
145 element["parentElement"].call<void>("removeChild", element);
146 m_enableButtons.erase(it);
147 }
148 }
149 const QWasmWindow *wasmWindow = QWasmWindow::fromWindow(window);
150 if (!isActive() || !wasmWindow)
151 return;
152
153 const emscripten::val a11yContainer = wasmWindow->a11yContainer();
154
155 // Forget the elements of the window, they go away with its container.
156 for (auto it = m_elements.begin(); it != m_elements.end();) {
157 if (a11yContainer.call<bool>("contains", it.value()))
158 it = m_elements.erase(it);
159 else
160 ++it;
161 }
162 getElementContainer(window).call<void>("replaceChildren");
163 getDescribedByContainer(window).call<void>("replaceChildren");
164}
165
166#ifndef QT_NO_DEBUG
167std::string QWasmAccessibility::logElementParentChain(emscripten::val element, QAccessibleInterface *iface, std::string tab)
168{
169 if (element.isUndefined())
170 element = getHtmlElement(iface);
171
172 QAccessibleInterface *parentIface = nullptr;
173 if (!element["parentElement"].isUndefined() &&
174 !element["parentElement"].isNull() &&
175 !element["parentElement"]["qtA11yId"].isUndefined()) {
176 parentIface = QAccessible::accessibleInterface(
177 element["parentElement"]["qtA11yId"].as<QAccessible::Id>());
178 }
179
180 emscripten::val parent = emscripten::val::undefined();
181 if (!element.isUndefined())
182 parent = element["parentElement"];
183 if (parent.isNull())
184 parent = emscripten::val::undefined();
185
186 if (!parent.isUndefined())
187 tab = logElementParentChain(parent, parentIface, tab);
188
189 QString outerHTML = QStringLiteral("No html");
190 if (!element.isUndefined())
191 outerHTML = QString::fromStdString(element["outerHTML"].as<std::string>()).left(40);
192
193 if (!iface)
194 qCDebug(lcQpaAccessibility) << tab << outerHTML << "No Role" << "No parent role"
195 << element.isUndefined() << parent.isUndefined();
196 else
197 qCDebug(lcQpaAccessibility) << tab << outerHTML << iface->role()
198 << (iface->parent() ? iface->parent()->role() : QAccessible::NoRole)
199 << element.isUndefined() << parent.isUndefined();
200 return tab + " ";
201}
202#endif
203
204void QWasmAccessibility::enableAccessibility()
205{
206 // Enable accessibility. Remove all "enable" buttons and populate the
207 // accessibility tree for each window.
208
209 Q_ASSERT(!isActive());
210 setActive(true);
211 for (const auto& [key, value] : m_enableButtons) {
212 const auto &[element, callback] = value;
213 Q_UNUSED(callback);
214 if (auto wasmWindow = QWasmWindow::fromWindow(key))
215 wasmWindow->onAccessibilityEnable();
216 populateAccessibilityTree(key->accessibleRoot());
217 element["parentElement"].call<void>("removeChild", element);
218 }
219 m_enableButtons.clear();
220}
221
222bool QWasmAccessibility::setFocusObjectImpl(QObject *object)
223{
224 auto iface = QAccessible::queryAccessibleInterface(object);
225 if (!iface)
226 return false;
227 return setHtmlElementFocus(iface);
228}
229
230bool QWasmAccessibility::isWindowNode(QAccessibleInterface *iface)
231{
232 return (iface && !getWindow(iface->parent()) && getWindow(iface));
233}
234
235emscripten::val QWasmAccessibility::getDescribedByContainer(QWindow *window)
236{
237 const QWasmWindow *wasmWindow = QWasmWindow::fromWindow(window);
238 return wasmWindow ? wasmWindow->a11yDescribedByContainer() : emscripten::val::undefined();
239}
240
241emscripten::val QWasmAccessibility::getDescribedByContainer(QAccessibleInterface *iface)
242{
243 return getDescribedByContainer(getWindow(iface));
244}
245
246emscripten::val QWasmAccessibility::getElementContainer(QWindow *window)
247{
248 const QWasmWindow *wasmWindow = QWasmWindow::fromWindow(window);
249 return wasmWindow ? wasmWindow->a11yElementContainer() : emscripten::val::undefined();
250}
251
252emscripten::val QWasmAccessibility::getElementContainer(QAccessibleInterface *iface)
253{
254 // Here we skip QWindow nodes, as they are already present. Such nodes
255 // has a parent window of null.
256 //
257 // The next node should return the a11y container.
258 // Further nodes should return the element of the parent.
259 if (!getWindow(iface))
260 return emscripten::val::undefined();
261
262 if (isWindowNode(iface))
263 return emscripten::val::undefined();
264
265 if (isWindowNode(iface->parent()))
266 return getElementContainer(getWindow(iface->parent()));
267
268 // Regular node
269 return getHtmlElement(iface->parent());
270}
271
272QWindow *QWasmAccessibility::getWindow(QAccessibleInterface *iface)
273{
274 if (!iface)
275 return nullptr;
276
277 QWindow *window = iface->window();
278 // this is needed to add tabs as the window is not available
279 if (!window && iface->parent())
280 window = iface->parent()->window();
281 return window;
282}
283
284// Returns whether the focus window is a child window of the window of iface,
285// for instance the window of a window container
286bool QWasmAccessibility::isFocusInChildWindow(QAccessibleInterface *iface)
287{
288 const QWindow *window = getWindow(iface);
289 const QWindow *focusWindow = QGuiApplication::focusWindow();
290 return window && focusWindow && focusWindow != window
291 && window->isAncestorOf(focusWindow, QWindow::ExcludeTransients);
292}
293
294emscripten::val QWasmAccessibility::getDocument(const emscripten::val &container)
295{
296 if (container.isUndefined())
297 return emscripten::val::global("document");
298 return container["ownerDocument"];
299}
300
301void QWasmAccessibility::setAttribute(emscripten::val element, const std::string &attr,
302 const std::string &val)
303{
304 if (val != "")
305 element.call<void>("setAttribute", attr, val);
306 else
307 element.call<void>("removeAttribute", attr);
308}
309
310void QWasmAccessibility::setAttribute(emscripten::val element, const std::string &attr,
311 const char *val)
312{
313 setAttribute(element, attr, std::string(val));
314}
315
316void QWasmAccessibility::setAttribute(emscripten::val element, const std::string &attr, bool val)
317{
318 if (val)
319 element.call<void>("setAttribute", attr, val);
320 else
321 element.call<void>("removeAttribute", attr);
322}
323
324void QWasmAccessibility::setProperty(emscripten::val element, const std::string &property,
325 const std::string &val)
326{
327 element.set(property, val);
328}
329
330void QWasmAccessibility::setProperty(emscripten::val element, const std::string &property, const char *val)
331{
332 setProperty(element, property, std::string(val));
333}
334
335void QWasmAccessibility::setProperty(emscripten::val element, const std::string &property, bool val)
336{
337 element.set(property, val);
338}
339
340void QWasmAccessibility::setNamedAttribute(QAccessibleInterface *iface, const std::string &attribute, QAccessible::Text text)
341{
342 const emscripten::val element = getHtmlElement(iface);
343 setAttribute(element, attribute, iface->text(text).toStdString());
344}
345void QWasmAccessibility::setNamedProperty(QAccessibleInterface *iface, const std::string &property, QAccessible::Text text)
346{
347 const emscripten::val element = getHtmlElement(iface);
348 setProperty(element, property, iface->text(text).toStdString());
349}
350
351void QWasmAccessibility::addEventListener(QAccessibleInterface *iface, emscripten::val element, const char *eventType)
352{
353 element.set("qtA11yId", QAccessible::uniqueId(iface));
354 element.call<void>("addEventListener", emscripten::val(eventType),
355 QWasmSuspendResumeControl::get()->jsEventHandlerAt(m_eventHandlerIndex),
356 true);
357}
358
359void QWasmAccessibility::sendEvent(QAccessibleInterface *iface, QAccessible::Event eventType)
360{
361 if (iface->object()) {
362 QAccessibleEvent event(iface->object(), eventType);
363 handleUpdateByInterfaceRole(&event);
364 } else {
365 QAccessibleEvent event(iface, eventType);
366 handleUpdateByInterfaceRole(&event);
367 }
368}
369
370emscripten::val QWasmAccessibility::createHtmlElement(QAccessibleInterface *iface)
371{
372 // Get the html container element for the interface; this depends on which
373 // QScreen it is on. If the interface is not on a screen yet we get an undefined
374 // container, and the code below handles that case as well.
375 emscripten::val container = getElementContainer(iface);
376
377 // Get the correct html document for the container, or fall back
378 // to the global document. TODO: Does using the correct document actually matter?
379 emscripten::val document = getDocument(container);
380
381 // Translate the Qt a11y elemen role into html element type + ARIA role.
382 // Here we can either create <div> elements with a spesific ARIA role,
383 // or create e.g. <button> elements which should have built-in accessibility.
384 emscripten::val element = [this, iface, document] {
385
386 emscripten::val element = emscripten::val::undefined();
387
388 switch (iface->role()) {
389
390 case QAccessible::Button: {
391 element = document.call<emscripten::val>("createElement", std::string("button"));
392 addEventListener(iface, element, "click");
393 } break;
394
395 case QAccessible::Grouping:
396 case QAccessible::CheckBox: {
397 // Three cases:
398 // 1) role=CheckBox, childCount() == 0 -> Checkbox
399 // 2) role=CheckBox, childCount() > 0 -> GroupBox w/checkbox
400 // 3) role=Grouping -> GroupBox w/label
401
402 emscripten::val checkbox = emscripten::val::undefined();
403 if (iface->role() == QAccessible::CheckBox) {
404 checkbox = document.call<emscripten::val>("createElement", std::string("input"));
405 setAttribute(checkbox, "type", "checkbox");
406 // The checked attribute is only the default, the browser stops reading
407 // it once the input is activated, so always write the property.
408 setProperty(checkbox, "checked", iface->state().checked);
409 setProperty(checkbox, "indeterminate", iface->state().checkStateMixed);
410 addEventListener(iface, checkbox, "change");
411 }
412
413 if (iface->childCount() > 0 || iface->role() == QAccessible::Grouping) {
414 auto label = document.call<emscripten::val>("createElement", std::string("span"));
415
416 const std::string id = "lbid_" + std::to_string(QAccessible::uniqueId(iface));
417 setAttribute(label, "id", id);
418
419 element = document.call<emscripten::val>("createElement", std::string("div"));
420 element.call<void>("appendChild", label);
421
422 setAttribute(element, "role", "group");
423 setAttribute(element, "aria-labelledby", id);
424
425 if (!checkbox.isUndefined()) {
426 element.call<void>("appendChild", checkbox);
427 addEventListener(iface, checkbox, "focus");
428 }
429 } else {
430 element = checkbox;
431 }
432 } break;
433
434 case QAccessible::Switch: {
435 element = document.call<emscripten::val>("createElement", std::string("button"));
436 setAttribute(element, "type", "button");
437 setAttribute(element, "role", "switch");
438 if (iface->state().checked)
439 setAttribute(element, "aria-checked", "true");
440 else
441 setAttribute(element, "aria-checked", "false");
442 addEventListener(iface, element, "click");
443 } break;
444
445 case QAccessible::RadioButton: {
446 element = document.call<emscripten::val>("createElement", std::string("input"));
447 setAttribute(element, "type", "radio");
448 setProperty(element, "checked", iface->state().checked);
449 // Qt makes sibling radio buttons exclusive, so group them by their parent.
450 // A shared name would merge every group in the window into one.
451 if (QAccessibleInterface *parentInterface = iface->parent()) {
452 setProperty(element, "name",
453 "qt-radio-group-" + std::to_string(QAccessible::uniqueId(parentInterface)));
454 }
455 addEventListener(iface, element, "change");
456 } break;
457
458 case QAccessible::Dial: {
459 // A dial is rotary and has no html counterpart, so use the slider role
460 // rather than a number input, which reads as a spin button.
461 element = document.call<emscripten::val>("createElement", std::string("div"));
462 setAttribute(element, "tabindex", "0");
463 setAttribute(element, "role", "slider");
464 if (QAccessibleValueInterface *valueInterface = iface->valueInterface()) {
465 setAttribute(element, "aria-valuemin",
466 valueInterface->minimumValue().toString().toStdString());
467 setAttribute(element, "aria-valuemax",
468 valueInterface->maximumValue().toString().toStdString());
469 setAttribute(element, "aria-valuenow",
470 valueInterface->currentValue().toString().toStdString());
471 }
472 // No aria-orientation, a dial turns rather than runs along an axis.
473 } break;
474
475 case QAccessible::SpinBox: {
476 // A number input is a text field, and writing its value while it has
477 // the focus is announced as a text edit, not as a new value.
478 element = document.call<emscripten::val>("createElement", std::string("div"));
479 setAttribute(element, "tabindex", "0");
480 setAttribute(element, "role", "spinbutton");
481 if (QAccessibleValueInterface *valueInterface = iface->valueInterface()) {
482 setAttribute(element, "aria-valuemin",
483 valueInterface->minimumValue().toString().toStdString());
484 setAttribute(element, "aria-valuemax",
485 valueInterface->maximumValue().toString().toStdString());
486 setAttribute(element, "aria-valuenow",
487 valueInterface->currentValue().toString().toStdString());
488 }
489 // The displayed text carries the prefix and suffix, the bare number does not.
490 setAttribute(element, "aria-valuetext",
491 iface->text(QAccessible::Value).toStdString());
492 } break;
493
494 case QAccessible::Slider: {
495 // A number input reads as a spin button, and writing its value while
496 // it has the focus is announced as a text edit, not as a new value.
497 element = document.call<emscripten::val>("createElement", std::string("div"));
498 setAttribute(element, "tabindex", "0");
499 setAttribute(element, "role", "slider");
500 if (QAccessibleValueInterface *valueInterface = iface->valueInterface()) {
501 setAttribute(element, "aria-valuemin",
502 valueInterface->minimumValue().toString().toStdString());
503 setAttribute(element, "aria-valuemax",
504 valueInterface->maximumValue().toString().toStdString());
505 setAttribute(element, "aria-valuenow",
506 valueInterface->currentValue().toString().toStdString());
507 }
508 setHtmlElementOrientation(element, iface);
509 } break;
510
511 case QAccessible::PageTabList:{
512 element = document.call<emscripten::val>("createElement", std::string("div"));
513 setAttribute(element, "role", "tablist");
514 setHtmlElementOrientation(element, iface);
515
516 m_elements[QAccessible::uniqueId(iface)] = element;
517
518 for (int i = 0; i < iface->childCount(); ++i)
519 createHtmlElement(iface->child(i));
520
521 } break;
522
523 case QAccessible::PageTab:{
524 const QString text = iface->text(QAccessible::Name);
525 element = document.call<emscripten::val>("createElement", std::string("button"));
526 setAttribute(element, "role", "tab");
527 setAttribute(element, "title", text.toStdString());
528 addEventListener(iface, element, "click");
529 } break;
530
531 case QAccessible::ScrollBar: {
532 // Events for scrollbars are handled by Qt, but setFocusPolicy must
533 // be called for this to happen.
534 element = document.call<emscripten::val>("createElement", std::string("div"));
535 setAttribute(element, "tabindex", "0");
536 setAttribute(element, "role", "scrollbar");
537 if (QAccessibleValueInterface *valueInterface = iface->valueInterface()) {
538 setAttribute(element, "aria-valuemin",
539 valueInterface->minimumValue().toString().toStdString());
540 setAttribute(element, "aria-valuemax",
541 valueInterface->maximumValue().toString().toStdString());
542 setAttribute(element, "aria-valuenow",
543 valueInterface->currentValue().toString().toStdString());
544 }
545 setHtmlElementOrientation(element, iface);
546 addEventListener(iface, element, "change");
547 } break;
548
549 case QAccessible::StaticText: {
550 element = document.call<emscripten::val>("createElement", std::string("div"));
551 } break;
552 case QAccessible::AlertMessage:
553 case QAccessible::Dialog: {
554 element = document.call<emscripten::val>("createElement", std::string("dialog"));
555 setAttribute(element, "open", true);
556 }break;
557 case QAccessible::ToolBar:{
558 const QString text = iface->text(QAccessible::Name);
559 element = document.call<emscripten::val>("createElement", std::string("div"));
560 setAttribute(element, "role", "toolbar");
561 setAttribute(element, "title", text.toStdString());
562 setHtmlElementOrientation(element, iface);
563 addEventListener(iface, element, "click");
564 }break;
565 case QAccessible::MenuItem:
566 case QAccessible::ButtonDropDown:
567 case QAccessible::ButtonMenu: {
568 const QString text = iface->text(QAccessible::Name);
569 element = document.call<emscripten::val>("createElement", std::string("button"));
570 setAttribute(element, "role", "menuitem");
571 setAttribute(element, "title", text.toStdString());
572 addEventListener(iface, element, "click");
573 element["classList"].call<void>("add", emscripten::val("menu-item"));
574 }break;
575 case QAccessible::MenuBar:
576 case QAccessible::PopupMenu: {
577 const QString text = iface->text(QAccessible::Name);
578 element = document.call<emscripten::val>("createElement", std::string("div"));
579 setAttribute(element, "role",
580 iface->role() == QAccessible::PopupMenu ? "menu" : "menubar");
581 setAttribute(element, "tabindex", "-1");
582 setAttribute(element, "title", text.toStdString());
583 setHtmlElementOrientation(element, iface);
584 m_elements[QAccessible::uniqueId(iface)] = element;
585
586 // The items are nested in the menu element, which already expresses
587 // ownership. aria-owns takes element ids, not the menu title.
588 for (int i = 0; i < iface->childCount(); ++i)
589 createHtmlElement(iface->child(i));
590 }break;
591 case QAccessible::EditableText: {
592 element = document.call<emscripten::val>("createElement", std::string("input"));
593 setAttribute(element, "type", "text");
594 setAttribute(element, "contenteditable", "true");
595 setAttribute(element, "readonly", iface->state().readOnly);
596 setAttribute(element, "autocorrect", "off");
597 setProperty(element, "inputMode", "text");
598 } break;
599 case QAccessible::List: {
600 element = document.call<emscripten::val>("createElement", std::string("div"));
601 setAttribute(element, "tabindex", "0");
602 setAttribute(element, "role", "list");
603 } break;
604 case QAccessible::ListItem: {
605 element = document.call<emscripten::val>("createElement", std::string("div"));
606 setAttribute(element, "tabindex", "0");
607 setAttribute(element, "role", "listitem");
608 // The name gets its own text node, so updating it keeps child elements.
609 emscripten::val nameTextNode = document.call<emscripten::val>("createTextNode", std::string());
610 element.call<void>("appendChild", nameTextNode);
611 element.set("qtA11yNameNode", nameTextNode);
612 } break;
613 case QAccessible::ProgressBar: {
614 element = document.call<emscripten::val>("createElement", std::string("div"));
615 setAttribute(element, "tabindex", "0");
616 setAttribute(element, "role", "progressbar");
617 setAttribute(element, "aria-live", "polite");
618 if (auto valueInterface = iface->valueInterface()) {
619 const auto name = iface->text(QAccessible::Name).toStdString();
620 const auto min = valueInterface->minimumValue().toInt();
621 const auto max = valueInterface->maximumValue().toInt();
622 const auto cur = valueInterface->currentValue().toInt();
623
624 // from qprogressbar.cpp
625 const auto totalSteps = qint64(max) - min;
626 const auto progress = (totalSteps == 0) ? 0 : static_cast<int>((qint64(cur) - min) * 100.0 / totalSteps);
627
628 if (cur <= min)
629 setAttribute(element, "aria-valuenow", "0");
630 else if (cur >= max)
631 setAttribute(element, "aria-valuenow", "100");
632 else
633 setAttribute(element, "aria-valuenow", std::to_string(progress));
634 setAttribute(element, "aria-valuemin", "0");
635 setAttribute(element, "aria-valuemax", "100");
636 setAttribute(element, "aria-label", name);
637 }
638 } break;
639 default:
640 qCDebug(lcQpaAccessibility) << "TODO: createHtmlElement() handle" << iface->role();
641 element = document.call<emscripten::val>("createElement", std::string("div"));
642 }
643
644 addEventListener(iface, element, "focus");
645 return element;
646
647 }();
648
649 m_elements[QAccessible::uniqueId(iface)] = element;
650
651 setHtmlElementGeometry(iface);
652 setHtmlElementDisabled(iface);
653 setHtmlElementVisibility(iface, !iface->state().invisible);
654 handleIdentifierUpdate(iface);
655 handleDescriptionChanged(iface);
656 sendEvent(iface, QAccessible::NameChanged);
657
658 // Remove from browser Tab order; a11y elements can be focused
659 // programmatically by Qt, but not by the browser
660 element.set("tabIndex", -1);
661
662 linkToParent(iface);
663 // Link in child elements
664 for (int i = 0; i < iface->childCount(); ++i) {
665 if (!getHtmlElement(iface->child(i)).isUndefined())
666 linkToParent(iface->child(i));
667 }
668
669 return element;
670}
671
672void QWasmAccessibility::destroyHtmlElement(QAccessibleInterface *iface)
673{
674 Q_UNUSED(iface);
675 qCDebug(lcQpaAccessibility) << "TODO destroyHtmlElement";
676}
677
678emscripten::val QWasmAccessibility::getHtmlElement(QAccessibleInterface *iface)
679{
680 if (!iface)
681 return emscripten::val::undefined();
682 return m_elements.value(QAccessible::uniqueId(iface), emscripten::val::undefined());
683}
684
685void QWasmAccessibility::repairLinks(QAccessibleInterface *iface)
686{
687 // relink any children that are linked to the wrong parent,
688 // This can be caused by a missing ParentChanged event.
689 bool moved = false;
690 for (int i = 0; i < iface->childCount(); ++i) {
691 const auto elementI = getHtmlElement(iface->child(i));
692 const auto containerI = getElementContainer(iface->child(i));
693
694 if (!elementI.isUndefined() &&
695 !containerI.isUndefined() &&
696 !elementI["parentElement"].isUndefined() &&
697 !elementI["parentElement"].isNull() &&
698 elementI["parentElement"] != containerI) {
699 moved = true;
700 break;
701 }
702 }
703 if (moved) {
704 for (int i = 0; i < iface->childCount(); ++i) {
705 const auto elementI = getHtmlElement(iface->child(i));
706 const auto containerI = getElementContainer(iface->child(i));
707 if (!elementI.isUndefined() && !containerI.isUndefined())
708 containerI.call<void>("appendChild", elementI);
709 }
710 }
711}
712
713void QWasmAccessibility::linkToParent(QAccessibleInterface *iface)
714{
715 emscripten::val element = getHtmlElement(iface);
716 emscripten::val container = getElementContainer(iface);
717
718 if (container.isUndefined() || element.isUndefined())
719 return;
720
721 // Make sure that we don't change the focused element
722 const auto activeElementBefore = getActiveElement();
723
724 repairLinks(iface->parent());
725
726 emscripten::val next = emscripten::val::undefined();
727 const int thisIndex = iface->parent()->indexOfChild(iface);
728 if (thisIndex >= 0) {
729 Q_ASSERT(thisIndex < iface->parent()->childCount());
730 for (int i = thisIndex + 1; i < iface->parent()->childCount(); ++i) {
731 const auto elementI = getHtmlElement(iface->parent()->child(i));
732 if (!elementI.isUndefined() &&
733 elementI["parentElement"] == container) {
734 next = elementI;
735 break;
736 }
737 }
738 if (next.isUndefined())
739 container.call<void>("appendChild", element);
740 else
741 container.call<void>("insertBefore", element, next);
742 }
743 const auto activeElementAfter = getActiveElement();
744 if (activeElementBefore != activeElementAfter) {
745 if (!activeElementBefore.isUndefined() && !activeElementBefore.isNull())
746 activeElementBefore.call<void>("focus");
747 }
748}
749
750void QWasmAccessibility::setHtmlElementVisibility(QAccessibleInterface *iface, bool visible)
751{
752 emscripten::val element = getHtmlElement(iface);
753 setAttribute(element, "inert", !visible);
754}
755
756void QWasmAccessibility::setHtmlElementGeometry(QAccessibleInterface *iface)
757{
758 const emscripten::val element = getHtmlElement(iface);
759
760 QRect windowGeometry = iface->rect();
761 if (iface->parent()) {
762 // Both iface and iface->parent returns geometry in screen coordinates
763 // We only want the relative coordinates, so the coordinate system does
764 // not matter as long as it is the same.
765 const QRect parentRect = iface->parent()->rect();
766 const QRect thisRect = iface->rect();
767 const QRect result(thisRect.topLeft() - parentRect.topLeft(), thisRect.size());
768 windowGeometry = result;
769 } else {
770 // Elements without a parent are not a part of the a11y tree, and don't
771 // have meaningful geometry.
772 Q_ASSERT(!getWindow(iface));
773 }
774 setHtmlElementGeometry(element, windowGeometry);
775}
776
777void QWasmAccessibility::setHtmlElementGeometry(emscripten::val element, QRect geometry)
778{
779 // Position the element using "position: absolute" in order to place
780 // it under the corresponding Qt element in the screen.
781 emscripten::val style = element["style"];
782 style.set("position", std::string("absolute"));
783 style.set("z-index", std::string("-1")); // FIXME: "0" should be sufficient to order beheind the
784 // screen element, but isn't
785 style.set("left", std::to_string(geometry.x()) + "px");
786 style.set("top", std::to_string(geometry.y()) + "px");
787 style.set("width", std::to_string(geometry.width()) + "px");
788 style.set("height", std::to_string(geometry.height()) + "px");
789}
790
791bool QWasmAccessibility::setHtmlElementFocus(QAccessibleInterface *iface)
792{
793 m_focusId = QAccessible::uniqueId(iface);
794 const auto element = getHtmlElement(iface);
795
796 if (element.isUndefined())
797 return false;
798
799 // To break focus loops
800 if (element == m_isSettingFocusIface)
801 return true;
802
803 m_isFollowingQtFocus = true;
804 element.call<void>("focus");
805 m_isFollowingQtFocus = false;
806
807#ifndef QT_NO_DEBUG
808 if (lcQpaAccessibility().isDebugEnabled()) {
809 const auto activeElementAfter = getActiveElement();
810
811 if (element != activeElementAfter) {
812 qCDebug(lcQpaAccessibility) << "Focus failed" << iface;
813 logElement(element);
814 logElement(activeElementAfter);
815 logElementParentChain(element, iface);
816 }
817 }
818#endif
819 // A detached or inert element does not take focus, let the caller fall back.
820 return element == getActiveElement();
821}
822
823void QWasmAccessibility::setHtmlElementDisabled(QAccessibleInterface *iface)
824{
825 auto element = getHtmlElement(iface);
826 setAttribute(element, "aria-disabled", iface->state().disabled);
827}
828
829void QWasmAccessibility::setHtmlElementOrientation(emscripten::val element, QAccessibleInterface *iface)
830{
831 Q_ASSERT(iface);
832 if (QAccessibleAttributesInterface *attributesIface = iface->attributesInterface()) {
833 const QVariant orientationVariant =
834 attributesIface->attributeValue(QAccessible::Attribute::Orientation);
835 if (orientationVariant.isValid()) {
836 Q_ASSERT(orientationVariant.canConvert<Qt::Orientation>());
837 const Qt::Orientation orientation = orientationVariant.value<Qt::Orientation>();
838 const std::string value = orientation == Qt::Horizontal ? "horizontal" : "vertical";
839 setAttribute(element, "aria-orientation", value);
840 }
841 }
842}
843
844void QWasmAccessibility::handleListItemUpdate(QAccessibleEvent *event)
845{
846 auto iface = event->accessibleInterface();
847
848 switch (event->type()) {
849 case QAccessible::NameChanged: {
850 // Update only the name's text node, leaving the item's child elements in place.
851 emscripten::val nameTextNode = getHtmlElement(iface)["qtA11yNameNode"];
852 nameTextNode.set("data", iface->text(QAccessible::Name).toStdString());
853 } break;
854 default:
855 qCDebug(lcQpaAccessibility) << "TODO: implement handleListItemUpdate for event" << event->type();
856 break;
857 }
858}
859
860void QWasmAccessibility::handleDialUpdate(QAccessibleEvent *event)
861{
862 switch (event->type()) {
863 case QAccessible::ObjectCreated:
864 case QAccessible::StateChanged: {
865 } break;
866 case QAccessible::Focus:
867 case QAccessible::NameChanged: {
868 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
869 } break;
870 case QAccessible::ValueChanged: {
871 QAccessibleInterface *accessible = event->accessibleInterface();
872 if (QAccessibleValueInterface *valueInterface = accessible->valueInterface()) {
873 setAttribute(getHtmlElement(accessible), "aria-valuenow",
874 valueInterface->currentValue().toString().toStdString());
875 }
876 } break;
877 default:
878 qCDebug(lcQpaAccessibility) << "TODO: implement handleDialUpdate for event" << event->type();
879 break;
880 }
881}
882
883void QWasmAccessibility::handleStaticTextUpdate(QAccessibleEvent *event)
884{
885 switch (event->type()) {
886 case QAccessible::NameChanged: {
887 // StaticText is a div
888 setNamedProperty(event->accessibleInterface(), "innerText", QAccessible::Name);
889 } break;
890 default:
891 qCDebug(lcQpaAccessibility) << "TODO: implement handleStaticTextUpdate for event" << event->type();
892 break;
893 }
894}
895
896void QWasmAccessibility::handleLineEditUpdate(QAccessibleEvent *event)
897{
898 switch (event->type()) {
899 case QAccessible::StateChanged: {
900 auto iface = event->accessibleInterface();
901 auto element = getHtmlElement(iface);
902 setAttribute(element, "readonly", iface->state().readOnly);
903 if (iface->state().passwordEdit)
904 setProperty(element, "type", "password");
905 else
906 setProperty(element, "type", "text");
907 } break;
908 case QAccessible::ValueChanged:
909 case QAccessible::NameChanged: {
910 setNamedProperty(event->accessibleInterface(), "value", QAccessible::Value);
911 } break;
912 case QAccessible::ObjectShow:
913 case QAccessible::Focus: {
914 auto iface = event->accessibleInterface();
915 auto element = getHtmlElement(iface);
916 if (!element.isUndefined()) {
917 setAttribute(element, "readonly", iface->state().readOnly);
918 if (iface->state().passwordEdit)
919 setProperty(element, "type", "password");
920 else
921 setProperty(element, "type", "text");
922 }
923 setNamedProperty(event->accessibleInterface(), "value", QAccessible::Value);
924 } break;
925 case QAccessible::TextRemoved:
926 case QAccessible::TextInserted:
927 case QAccessible::TextUpdated: {
928 setNamedProperty(event->accessibleInterface(), "value", QAccessible::Value);
929 } break;
930 case QAccessible::TextCaretMoved: {
931 // We lack ValueChanged event, sync on caret move instead
932 setNamedProperty(event->accessibleInterface(), "value", QAccessible::Value);
933 } break;
934 default:
935 qCDebug(lcQpaAccessibility) << "TODO: implement handleLineEditUpdate for event" << event->type();
936 break;
937 }
938}
939
940void QWasmAccessibility::handleEventFromHtmlElement(const emscripten::val event)
941{
942 const emscripten::val target = event["target"];
943 if (target.isNull() || target.isUndefined() || target["qtA11yId"].isUndefined())
944 return;
945
946 // Resolve the id, the interface may be gone by the time the event arrives.
947 QAccessibleInterface *iface =
948 QAccessible::accessibleInterface(target["qtA11yId"].as<QAccessible::Id>());
949 if (!iface || !iface->isValid())
950 return;
951
952 const auto eventType = QString::fromStdString(event["type"].as<std::string>());
953 const auto& actionNames = QAccessibleBridgeUtils::effectiveActionNames(iface);
954 bool handled = false;
955
956 if (eventType == "focus") {
957 // The dom focus follows Qt here, performing the focus action would take the
958 // keyboard focus from the item that has it, for instance a combo box with an open popup.
959 if (m_isFollowingQtFocus)
960 return;
961 m_isSettingFocusIface = event["target"];
962 if (actionNames.contains(QAccessibleActionInterface::setFocusAction()))
963 iface->actionInterface()->doAction(QAccessibleActionInterface::setFocusAction());
964 m_isSettingFocusIface = emscripten::val::undefined();
965 } else if (eventType == "click") {
966 handled = true;
967 if (actionNames.contains(QAccessibleActionInterface::pressAction()))
968 iface->actionInterface()->doAction(QAccessibleActionInterface::pressAction());
969 else if (actionNames.contains(QAccessibleActionInterface::showMenuAction()))
970 iface->actionInterface()->doAction(QAccessibleActionInterface::showMenuAction());
971 } else if (eventType == "change") {
972 handled = true;
973 // Checkboxes can have both toggle and press, in this case it is
974 // important to invoke press to handle tristate correctly
975 if (actionNames.contains(QAccessibleActionInterface::pressAction()))
976 iface->actionInterface()->doAction(QAccessibleActionInterface::pressAction());
977 else if (actionNames.contains(QAccessibleActionInterface::toggleAction()))
978 iface->actionInterface()->doAction(QAccessibleActionInterface::toggleAction());
979 } else {
980 qCDebug(lcQpaAccessibility) << "Unknown event" << eventType;
981 }
982
983 if (handled) {
984 event.call<void>("preventDefault");
985 event.call<void>("stopPropagation");
986 }
987}
988
989void QWasmAccessibility::handleButtonUpdate(QAccessibleEvent *event)
990{
991 switch (event->type()) {
992 case QAccessible::Focus:
993 case QAccessible::NameChanged: {
994 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
995 } break;
996 default:
997 qCDebug(lcQpaAccessibility) << "TODO: implement handleCheckBoxUpdate for event" << event->type();
998 break;
999 }
1000}
1001
1002void QWasmAccessibility::handleCheckBoxUpdate(QAccessibleEvent *event)
1003{
1004 switch (event->type()) {
1005 case QAccessible::Focus:
1006 case QAccessible::NameChanged: {
1007 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1008 } break;
1009 case QAccessible::StateChanged: {
1010 QAccessibleInterface *accessible = event->accessibleInterface();
1011 const emscripten::val element = getHtmlElement(accessible);
1012 setProperty(element, "checked", accessible->state().checked);
1013 setProperty(element, "indeterminate", accessible->state().checkStateMixed);
1014 } break;
1015 default:
1016 qCDebug(lcQpaAccessibility) << "TODO: implement handleCheckBoxUpdate for event" << event->type();
1017 break;
1018 }
1019}
1020
1021void QWasmAccessibility::handleGroupBoxUpdate(QAccessibleEvent *event)
1022{
1023 QAccessibleInterface *iface = event->accessibleInterface();
1024
1025 emscripten::val parent = getHtmlElement(iface);
1026 emscripten::val label = parent["children"][0];
1027 emscripten::val checkbox = emscripten::val::undefined();
1028 if (iface->role() == QAccessible::CheckBox)
1029 checkbox = parent["children"][1];
1030
1031 switch (event->type()) {
1032 case QAccessible::Focus:
1033 case QAccessible::NameChanged: {
1034 setProperty(label, "innerText", iface->text(QAccessible::Name).toStdString());
1035 if (!checkbox.isUndefined())
1036 setAttribute(checkbox, "aria-label", iface->text(QAccessible::Name).toStdString());
1037 } break;
1038 case QAccessible::StateChanged: {
1039 if (!checkbox.isUndefined()) {
1040 setProperty(checkbox, "checked", iface->state().checked);
1041 setProperty(checkbox, "indeterminate", iface->state().checkStateMixed);
1042 }
1043 } break;
1044 default:
1045 qCDebug(lcQpaAccessibility) << "TODO: implement handleCheckBoxUpdate for event" << event->type();
1046 break;
1047 }
1048}
1049
1050void QWasmAccessibility::handleSwitchUpdate(QAccessibleEvent *event)
1051{
1052 switch (event->type()) {
1053 case QAccessible::Focus:
1054 case QAccessible::NameChanged: {
1055 /* A switch is like a button in this regard */
1056 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1057 } break;
1058 case QAccessible::StateChanged: {
1059 QAccessibleInterface *accessible = event->accessibleInterface();
1060 const emscripten::val element = getHtmlElement(accessible);
1061 if (accessible->state().checked)
1062 setAttribute(element, "aria-checked", "true");
1063 else
1064 setAttribute(element, "aria-checked", "false");
1065 } break;
1066 default:
1067 qCDebug(lcQpaAccessibility) << "TODO: implement handleSwitchUpdate for event" << event->type();
1068 break;
1069 }
1070}
1071
1072void QWasmAccessibility::handleToolUpdate(QAccessibleEvent *event)
1073{
1074 QAccessibleInterface *iface = event->accessibleInterface();
1075 QString text = iface->text(QAccessible::Name);
1076 QString desc = iface->text(QAccessible::Description);
1077 switch (event->type()) {
1078 case QAccessible::NameChanged:
1079 case QAccessible::StateChanged:{
1080 const emscripten::val element = getHtmlElement(iface);
1081 setAttribute(element, "title", text.toStdString());
1082 } break;
1083 default:
1084 qCDebug(lcQpaAccessibility) << "TODO: implement handleToolUpdate for event" << event->type();
1085 break;
1086 }
1087}
1088void QWasmAccessibility::handleMenuUpdate(QAccessibleEvent *event)
1089{
1090 QAccessibleInterface *iface = event->accessibleInterface();
1091 QString text = iface->text(QAccessible::Name);
1092 QString desc = iface->text(QAccessible::Description);
1093 switch (event->type()) {
1094 case QAccessible::Focus:
1095 case QAccessible::NameChanged:
1096 case QAccessible::MenuStart ://"TODO: To implement later
1097 case QAccessible::StateChanged:{
1098 const emscripten::val element = getHtmlElement(iface);
1099 setAttribute(element, "title", text.toStdString());
1100 } break;
1101 case QAccessible::PopupMenuStart: {
1102 if (iface->childCount() > 0)
1103 setHtmlElementFocus(iface->child(0));
1104 } break;
1105 default:
1106 qCDebug(lcQpaAccessibility) << "TODO: implement handleMenuUpdate for event" << event->type();
1107 break;
1108 }
1109}
1110void QWasmAccessibility::handleDialogUpdate(QAccessibleEvent *event) {
1111
1112 switch (event->type()) {
1113 case QAccessible::ObjectShow:
1114 // We get focus before the dialog is visible, retry the focus operation
1115 if (QAccessibleInterface *focusInterface = QAccessible::accessibleInterface(m_focusId))
1116 setHtmlElementFocus(focusInterface);
1117 break;
1118
1119 case QAccessible::NameChanged:
1120 case QAccessible::Focus:
1121 case QAccessible::DialogStart:
1122 case QAccessible::StateChanged: {
1123 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1124 } break;
1125 default:
1126 qCDebug(lcQpaAccessibility) << "TODO: implement handleLineEditUpdate for event" << event->type();
1127 break;
1128 }
1129}
1130
1131void QWasmAccessibility::populateAccessibilityTree(QAccessibleInterface *iface)
1132{
1133 if (!iface)
1134 return;
1135
1136 // We ignore toplevel windows which is categorized
1137 // by getWindow(iface->parent()) != getWindow(iface)
1138 const QWindow *window1 = getWindow(iface);
1139 const QWindow *window0 = (iface->parent()) ? getWindow(iface->parent()) : nullptr;
1140
1141 if (window1 && window0 == window1) {
1142 // Create html element for the interface, sync up properties.
1143 bool exists = !getHtmlElement(iface).isUndefined();
1144 if (!exists)
1145 exists = !createHtmlElement(iface).isUndefined();
1146
1147 if (exists) {
1148 linkToParent(iface);
1149 setHtmlElementVisibility(iface, !iface->state().invisible);
1150 setHtmlElementGeometry(iface);
1151 setHtmlElementDisabled(iface);
1152 handleIdentifierUpdate(iface);
1153 handleDescriptionChanged(iface);
1154 sendEvent(iface, QAccessible::NameChanged);
1155 }
1156 }
1157 for (int i = 0; i < iface->childCount(); ++i)
1158 populateAccessibilityTree(iface->child(i));
1159}
1160
1161void QWasmAccessibility::handleRadioButtonUpdate(QAccessibleEvent *event)
1162{
1163 switch (event->type()) {
1164 case QAccessible::Focus:
1165 case QAccessible::NameChanged: {
1166 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1167 } break;
1168 case QAccessible::StateChanged: {
1169 QAccessibleInterface *accessible = event->accessibleInterface();
1170 const emscripten::val element = getHtmlElement(accessible);
1171 setProperty(element, "checked", accessible->state().checked);
1172 } break;
1173 default:
1174 qCDebug(lcQpaAccessibility) << "TODO: implement handleRadioButtonUpdate for event" << event->type();
1175 break;
1176 }
1177}
1178
1179void QWasmAccessibility::handleSpinBoxUpdate(QAccessibleEvent *event)
1180{
1181 switch (event->type()) {
1182 case QAccessible::ObjectCreated:
1183 case QAccessible::StateChanged: {
1184 } break;
1185 case QAccessible::Focus:
1186 case QAccessible::NameChanged: {
1187 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1188 } break;
1189 case QAccessible::ValueChanged: {
1190 QAccessibleInterface *accessible = event->accessibleInterface();
1191 if (QAccessibleValueInterface *valueInterface = accessible->valueInterface()) {
1192 setAttribute(getHtmlElement(accessible), "aria-valuenow",
1193 valueInterface->currentValue().toString().toStdString());
1194 }
1195 setNamedAttribute(accessible, "aria-valuetext", QAccessible::Value);
1196 } break;
1197 default:
1198 qCDebug(lcQpaAccessibility) << "TODO: implement handleSpinBoxUpdate for event" << event->type();
1199 break;
1200 }
1201}
1202
1203void QWasmAccessibility::handleSliderUpdate(QAccessibleEvent *event)
1204{
1205 switch (event->type()) {
1206 case QAccessible::ObjectCreated:
1207 case QAccessible::StateChanged: {
1208 } break;
1209 case QAccessible::Focus:
1210 case QAccessible::NameChanged: {
1211 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1212 } break;
1213 case QAccessible::ValueChanged: {
1214 QAccessibleInterface *accessible = event->accessibleInterface();
1215 if (QAccessibleValueInterface *valueInterface = accessible->valueInterface()) {
1216 setAttribute(getHtmlElement(accessible), "aria-valuenow",
1217 valueInterface->currentValue().toString().toStdString());
1218 }
1219 } break;
1220 default:
1221 qCDebug(lcQpaAccessibility) << "TODO: implement handleSliderUpdate for event" << event->type();
1222 break;
1223 }
1224}
1225
1226void QWasmAccessibility::handleScrollBarUpdate(QAccessibleEvent *event)
1227{
1228 switch (event->type()) {
1229 case QAccessible::Focus:
1230 case QAccessible::NameChanged: {
1231 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1232 } break;
1233 case QAccessible::ValueChanged: {
1234 QAccessibleInterface *accessible = event->accessibleInterface();
1235 if (QAccessibleValueInterface *valueInterface = accessible->valueInterface()) {
1236 setAttribute(getHtmlElement(accessible), "aria-valuenow",
1237 valueInterface->currentValue().toString().toStdString());
1238 }
1239 } break;
1240 default:
1241 qCDebug(lcQpaAccessibility) << "TODO: implement handleScrollBarUpdate for event" << event->type();
1242 break;
1243 }
1244}
1245
1246void QWasmAccessibility::handlePageTabUpdate(QAccessibleEvent *event)
1247{
1248 switch (event->type()) {
1249 case QAccessible::NameChanged: {
1250 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1251 } break;
1252 case QAccessible::Focus: {
1253 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1254 } break;
1255 default:
1256 qCDebug(lcQpaAccessibility) << "TODO: implement handlePageTabUpdate for event" << event->type();
1257 break;
1258 }
1259}
1260
1261void QWasmAccessibility::handlePageTabListUpdate(QAccessibleEvent *event)
1262{
1263 switch (event->type()) {
1264 case QAccessible::NameChanged: {
1265 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1266 } break;
1267 case QAccessible::Focus: {
1268 setNamedAttribute(event->accessibleInterface(), "aria-label", QAccessible::Name);
1269 } break;
1270 default:
1271 qCDebug(lcQpaAccessibility) << "TODO: implement handlePageTabListUpdate for event" << event->type();
1272 break;
1273 }
1274}
1275
1276void QWasmAccessibility::handleIdentifierUpdate(QAccessibleInterface *iface)
1277{
1278 // The tabs are nested in the tab list element, so they need no aria-owns
1279 // pointing back at it, which would also be the wrong direction.
1280 const emscripten::val element = getHtmlElement(iface);
1281 // Every element gets an id, so that other elements can refer to it.
1282 QString id = iface->text(QAccessible::Identifier).replace(" ", "_");
1283 if (id.isEmpty())
1284 id = QStringLiteral("qt-a11y-") + QString::number(QAccessible::uniqueId(iface));
1285 setAttribute(element, "id", id.toStdString());
1286}
1287
1288void QWasmAccessibility::handleDescriptionChanged(QAccessibleInterface *iface)
1289{
1290 // The element keeps a reference to its description, so that removeObject()
1291 // finds it without the interface.
1292 const auto desc = iface->text(QAccessible::Description).toStdString();
1293 auto element = getHtmlElement(iface);
1294 auto container = getDescribedByContainer(iface);
1295 if (element.isUndefined() || container.isUndefined())
1296 return;
1297
1298 auto describedBy = element["qtA11yDescribedBy"];
1299 if (desc.empty()) {
1300 if (!describedBy.isUndefined())
1301 describedBy.call<void>("remove");
1302 element.set("qtA11yDescribedBy", emscripten::val::undefined());
1303 setAttribute(element, "aria-describedby", "");
1304 } else {
1305 const std::string id = "dbid_" + std::to_string(QAccessible::uniqueId(iface));
1306 if (describedBy.isUndefined()) {
1307 describedBy = getDocument(container).call<emscripten::val>("createElement",
1308 std::string("p"));
1309 container.call<void>("appendChild", describedBy);
1310 element.set("qtA11yDescribedBy", describedBy);
1311 }
1312 setAttribute(describedBy, "id", id);
1313 setAttribute(describedBy, "inert", true);
1314 setAttribute(element, "aria-describedby", id);
1315 setProperty(describedBy, "innerText", desc);
1316 }
1317}
1318
1319void QWasmAccessibility::handleAnnouncement(QAccessibleInterface *iface,
1320 QAccessibleAnnouncementEvent *announcementEvent)
1321{
1322 emscripten::val element = getHtmlElement(iface);
1323 if (element["ariaNotify"].isUndefined())
1324 return;
1325
1326 const std::string message = announcementEvent->message().toStdString();
1327 const std::string prio(announcementEvent->politeness()
1328 == QAccessible::AnnouncementPoliteness::Assertive
1329 ? "high"
1330 : "normal");
1331 emscripten::val options = emscripten::val::object();
1332 options.set("priority", prio);
1333 element.call<void>("ariaNotify", message, options);
1334}
1335
1336void QWasmAccessibility::handleProgressBarUpdate(QAccessibleEvent *event)
1337{
1338 auto iface = event->accessibleInterface();
1339 auto valueInterface = iface->valueInterface();
1340 auto element = getHtmlElement(iface);
1341
1342 switch (event->type()) {
1343 case QAccessible::Focus:
1344 case QAccessible::NameChanged: {
1345 const auto name = iface->text(QAccessible::Name).toStdString();
1346 setAttribute(element, "aria-label", name);
1347 } // fallthrough
1348 case QAccessible::ValueChanged: {
1349 if (valueInterface) {
1350 const auto min = valueInterface->minimumValue().toInt();
1351 const auto max = valueInterface->maximumValue().toInt();
1352 const auto cur = valueInterface->currentValue().toInt();
1353
1354 // from qprogressbar.cpp
1355 const auto totalSteps = qint64(max) - min;
1356 const auto progress = (totalSteps == 0) ? 0 : static_cast<int>((qint64(cur) - min) * 100.0 / totalSteps);
1357
1358 if (cur <= min)
1359 setAttribute(element, "aria-valuenow", "0");
1360 else if (cur >= max)
1361 setAttribute(element, "aria-valuenow", "100");
1362 else
1363 setAttribute(element, "aria-valuenow", std::to_string(progress));
1364 }
1365 } break;
1366 default: {
1367 } break;
1368 } /* end-switch */
1369}
1370
1371void QWasmAccessibility::createObject(QAccessibleInterface *iface)
1372{
1373 if (getHtmlElement(iface).isUndefined())
1374 createHtmlElement(iface);
1375}
1376
1377void QWasmAccessibility::removeObject(QAccessible::Id id)
1378{
1379 // The interface may already be invalid, so work from the id and the element
1380 // alone. Objects are removed in no particular order, and remove() copes with
1381 // an element that is already detached.
1382 const auto it = m_elements.find(id);
1383 if (it == m_elements.end())
1384 return;
1385
1386 const emscripten::val element = it.value();
1387 if (!element["qtA11yDescribedBy"].isUndefined())
1388 element["qtA11yDescribedBy"].call<void>("remove");
1389 element.call<void>("remove");
1390 m_elements.erase(it);
1391}
1392
1393void QWasmAccessibility::unlinkParentForChildren(QAccessibleInterface *iface)
1394{
1395 auto element = getHtmlElement(iface);
1396 if (!element.isUndefined()) {
1397 auto oldContainer = element["parentElement"];
1398 auto newContainer = getElementContainer(iface);
1399 if (!oldContainer.isUndefined() &&
1400 !oldContainer.isNull() &&
1401 oldContainer != newContainer) {
1402 oldContainer.call<void>("removeChild", element);
1403 }
1404 }
1405 for (int i = 0; i < iface->childCount(); ++i)
1406 unlinkParentForChildren(iface->child(i));
1407}
1408
1409void QWasmAccessibility::relinkParentForChildren(QAccessibleInterface *iface)
1410{
1411 auto element = getHtmlElement(iface);
1412 if (!element.isUndefined()) {
1413 if (element["parentElement"].isUndefined() ||
1414 element["parentElement"].isNull()) {
1415 linkToParent(iface);
1416 }
1417 }
1418 for (int i = 0; i < iface->childCount(); ++i)
1419 relinkParentForChildren(iface->child(i));
1420}
1421
1422void QWasmAccessibility::notifyAccessibilityUpdate(QAccessibleEvent *event)
1423{
1424 if (handleUpdateByEventType(event))
1425 handleUpdateByInterfaceRole(event);
1426}
1427
1428bool QWasmAccessibility::handleUpdateByEventType(QAccessibleEvent *event)
1429{
1430 if (!isActive())
1431 return false;
1432
1433 QAccessibleInterface *iface = event->accessibleInterface();
1434 if (!iface) {
1435 // Expected for objects without an accessible interface, such as a Qt Quick Action
1436 qCDebug(lcQpaAccessibility) << "handleUpdateByEventType with null a11y interface" << event->type() << event->object();
1437 return false;
1438 }
1439
1440 // Handle event types that creates/removes objects.
1441 switch (event->type()) {
1442 case QAccessible::ObjectCreated:
1443 // Do nothing, there are too many changes to the interface
1444 // before ObjectShow is called
1445 return false;
1446
1447 case QAccessible::ObjectDestroyed:
1448 // The object might be under destruction, and the interface not valid.
1449 removeObject(event->uniqueId());
1450 return false;
1451
1452 case QAccessible::ObjectShow: // We do not get ObjectCreated from widgets, we get ObjectShow
1453 createObject(iface);
1454 break;
1455
1456 case QAccessible::ParentChanged:
1457 unlinkParentForChildren(iface);
1458 relinkParentForChildren(iface);
1459 break;
1460
1461 default:
1462 break;
1463 };
1464
1465 // Qt focuses widgets before the window is shown, so the element may not exist
1466 // yet. Remember the focus, ObjectShow applies it once the element is there.
1467 if (event->type() == QAccessible::Focus)
1468 m_focusId = event->uniqueId();
1469
1470 if (getHtmlElement(iface).isUndefined())
1471 return false;
1472
1473 // Handle some common event types. See
1474 // https://doc.qt.io/qt-6/qaccessible.html#Event-enum
1475 switch (event->type()) {
1476 case QAccessible::Announcement:
1477 handleAnnouncement(iface, static_cast<QAccessibleAnnouncementEvent *>(event));
1478 return false;
1479
1480 case QAccessible::StateChanged: {
1481 QAccessibleStateChangeEvent *stateChangeEvent = (QAccessibleStateChangeEvent *)event;
1482 if (stateChangeEvent->changedStates().disabled)
1483 setHtmlElementDisabled(iface);
1484 } break;
1485
1486 case QAccessible::DescriptionChanged:
1487 handleDescriptionChanged(iface);
1488 return false;
1489
1490 case QAccessible::Focus:
1491 // We do not get all callbacks for the geometry
1492 // hence we update here as well.
1493 setHtmlElementGeometry(iface);
1494 // The focus event may arrive after the focus has moved on to a child
1495 // window: QWidget::setFocus() sends it after the FocusIn event, which a
1496 // window container forwards to its child window. Moving the dom focus
1497 // back would take the focus from the child window.
1498 if (!isFocusInChildWindow(iface))
1499 setHtmlElementFocus(iface);
1500 break;
1501
1502 case QAccessible::IdentifierChanged:
1503 handleIdentifierUpdate(iface);
1504 return false;
1505
1506 case QAccessible::ObjectShow:
1507 linkToParent(iface);
1508 setHtmlElementVisibility(iface, true);
1509
1510 // Sync up properties on show;
1511 setHtmlElementGeometry(iface);
1512 sendEvent(iface, QAccessible::NameChanged);
1513
1514 // Qt focuses the element before it is shown, so apply the pending focus
1515 // once the element is in the dom.
1516 if (QAccessible::uniqueId(iface) == m_focusId)
1517 setHtmlElementFocus(iface);
1518 break;
1519
1520 case QAccessible::ObjectHide:
1521 // Do not call linkToParent, only set visibility to false
1522 setHtmlElementVisibility(iface, false);
1523 return false;
1524
1525 case QAccessible::LocationChanged:
1526 setHtmlElementGeometry(iface);
1527 return false;
1528
1529 // TODO: maybe handle more types here
1530 default:
1531 break;
1532 };
1533
1534 return true;
1535}
1536
1537void QWasmAccessibility::handleUpdateByInterfaceRole(QAccessibleEvent *event)
1538{
1539 if (!isActive())
1540 return;
1541
1542 QAccessibleInterface *iface = event->accessibleInterface();
1543 if (!iface) {
1544 qCDebug(lcQpaAccessibility) << "handleUpdateByInterfaceRole with null a11y interface" << event->type() << event->object();
1545 return;
1546 }
1547
1548 // Switch on interface role, see
1549 // https://doc.qt.io/qt-5/qaccessibleinterface.html#role
1550 switch (iface->role()) {
1551 case QAccessible::List:
1552 break;
1553 case QAccessible::ListItem:
1554 handleListItemUpdate(event);
1555 break;
1556 case QAccessible::StaticText:
1557 handleStaticTextUpdate(event);
1558 break;
1559 case QAccessible::Button:
1560 handleButtonUpdate(event);
1561 break;
1562 case QAccessible::CheckBox:
1563 if (iface->childCount() > 0)
1564 handleGroupBoxUpdate(event);
1565 else
1566 handleCheckBoxUpdate(event);
1567 break;
1568 case QAccessible::Switch:
1569 handleSwitchUpdate(event);
1570 break;
1571 case QAccessible::EditableText:
1572 handleLineEditUpdate(event);
1573 break;
1574 case QAccessible::Dialog:
1575 case QAccessible::AlertMessage:
1576 handleDialogUpdate(event);
1577 break;
1578 case QAccessible::MenuItem:
1579 case QAccessible::MenuBar:
1580 case QAccessible::PopupMenu:
1581 handleMenuUpdate(event);
1582 break;
1583 case QAccessible::ToolBar:
1584 case QAccessible::ButtonMenu:
1585 handleToolUpdate(event);
1586 break;
1587 case QAccessible::RadioButton:
1588 handleRadioButtonUpdate(event);
1589 break;
1590 case QAccessible::Dial:
1591 handleDialUpdate(event);
1592 break;
1593 case QAccessible::SpinBox:
1594 handleSpinBoxUpdate(event);
1595 break;
1596 case QAccessible::Slider:
1597 handleSliderUpdate(event);
1598 break;
1599 case QAccessible::PageTab:
1600 handlePageTabUpdate(event);
1601 break;
1602 case QAccessible::PageTabList:
1603 handlePageTabListUpdate(event);
1604 break;
1605 case QAccessible::ScrollBar:
1606 handleScrollBarUpdate(event);
1607 break;
1608 case QAccessible::Grouping:
1609 handleGroupBoxUpdate(event);
1610 break;
1611 case QAccessible::ProgressBar:
1612 handleProgressBarUpdate(event);
1613 break;
1614 default:
1615 qCDebug(lcQpaAccessibility) << "TODO: implement notifyAccessibilityUpdate for role" << iface->role();
1616 };
1617}
1618
1619#endif // QT_CONFIG(accessibility)
void QWasmAccessibilityEnable()