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
qcocoaaccessibility.mm
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <AppKit/AppKit.h>
6
9#include "qcocoawindow.h"
10#include <QtGui/qaccessible.h>
11#include <QtGui/private/qaccessiblebridgeutils_p.h>
12#include <QtCore/qmap.h>
13#include <private/qcore_mac_p.h>
14
16
17using namespace Qt::StringLiterals;
18
19#if QT_CONFIG(accessibility)
20
21QCocoaAccessibility::QCocoaAccessibility()
22{
23
24}
25
26QCocoaAccessibility::~QCocoaAccessibility()
27{
28
29}
30
31void QCocoaAccessibility::notifyAccessibilityUpdate(QAccessibleEvent *event)
32{
33 if (!isActive() || !event->accessibleInterface() || !event->accessibleInterface()->isValid())
34 return;
35
36 // The cache invalidates the native element after this event.
37 if (event->type() == QAccessible::ObjectDestroyed)
38 return;
39
40 QMacAccessibilityElement *element = [QMacAccessibilityElement elementWithId: event->uniqueId()];
41 if (!element) {
42 qWarning("QCocoaAccessibility::notifyAccessibilityUpdate: invalid element");
43 return;
44 }
45
46 switch (event->type()) {
47 case QAccessible::Announcement: {
48 auto *announcementEvent = static_cast<QAccessibleAnnouncementEvent *>(event);
49 auto priorityLevel = (announcementEvent->politeness() == QAccessible::AnnouncementPoliteness::Assertive)
50 ? NSAccessibilityPriorityHigh
51 : NSAccessibilityPriorityMedium;
52 NSDictionary *announcementInfo = @{
53 NSAccessibilityPriorityKey: [NSNumber numberWithInt:priorityLevel],
54 NSAccessibilityAnnouncementKey: announcementEvent->message().toNSString()
55 };
56 // post event for application element, as the comment for
57 // NSAccessibilityAnnouncementRequestedNotification in the
58 // NSAccessibilityConstants.h header says
59 NSAccessibilityPostNotificationWithUserInfo(NSApp,
60 NSAccessibilityAnnouncementRequestedNotification,
61 announcementInfo);
62 break;
63 }
64 case QAccessible::Focus: {
65 NSAccessibilityPostNotification(element, NSAccessibilityFocusedUIElementChangedNotification);
66 break;
67 }
68 case QAccessible::PopupMenuStart:
69 NSAccessibilityPostNotification(element, NSAccessibilityFocusedUIElementChangedNotification);
70 break;
71 case QAccessible::StateChanged:
72 case QAccessible::ValueChanged:
73 case QAccessible::TextInserted:
74 case QAccessible::TextRemoved:
75 case QAccessible::TextUpdated:
76 NSAccessibilityPostNotification(element, NSAccessibilityValueChangedNotification);
77 break;
78 case QAccessible::TextCaretMoved:
79 case QAccessible::TextSelectionChanged:
80 NSAccessibilityPostNotification(element, NSAccessibilitySelectedTextChangedNotification);
81 break;
82 case QAccessible::NameChanged:
83 NSAccessibilityPostNotification(element, NSAccessibilityTitleChangedNotification);
84 break;
85 case QAccessible::TableModelChanged:
86 // ### Could NSAccessibilityRowCountChangedNotification be relevant here?
87 [element updateTableModel];
88 break;
89 default:
90 break;
91 }
92}
93
94void QCocoaAccessibility::setRootObject(QObject *o)
95{
96 Q_UNUSED(o);
97}
98
99void QCocoaAccessibility::initialize()
100{
101
102}
103
104void QCocoaAccessibility::cleanup()
105{
106
107}
108
109namespace QCocoaAccessible {
110
111typedef QMap<QAccessible::Role, NSString *> QMacAccessibiltyRoleMap;
112Q_GLOBAL_STATIC(QMacAccessibiltyRoleMap, qMacAccessibiltyRoleMap);
113
114static void populateRoleMap()
115{
116 QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap();
117 roleMap[QAccessible::MenuItem] = NSAccessibilityMenuItemRole;
118 roleMap[QAccessible::MenuBar] = NSAccessibilityMenuBarRole;
119 roleMap[QAccessible::ScrollBar] = NSAccessibilityScrollBarRole;
120 roleMap[QAccessible::Grip] = NSAccessibilityGrowAreaRole;
121 roleMap[QAccessible::Window] = NSAccessibilityWindowRole;
122 roleMap[QAccessible::Dialog] = NSAccessibilityWindowRole;
123 roleMap[QAccessible::AlertMessage] = NSAccessibilityWindowRole;
124 roleMap[QAccessible::ToolTip] = NSAccessibilityWindowRole;
125 roleMap[QAccessible::HelpBalloon] = NSAccessibilityWindowRole;
126 roleMap[QAccessible::PopupMenu] = NSAccessibilityMenuRole;
127 roleMap[QAccessible::Application] = NSAccessibilityApplicationRole;
128 roleMap[QAccessible::Pane] = NSAccessibilityGroupRole;
129 roleMap[QAccessible::Grouping] = NSAccessibilityGroupRole;
130 roleMap[QAccessible::Separator] = NSAccessibilitySplitterRole;
131 roleMap[QAccessible::ToolBar] = NSAccessibilityToolbarRole;
132 roleMap[QAccessible::PageTab] = NSAccessibilityRadioButtonRole;
133 roleMap[QAccessible::PageTabList] = NSAccessibilityTabGroupRole;
134 roleMap[QAccessible::ButtonMenu] = NSAccessibilityMenuButtonRole;
135 roleMap[QAccessible::ButtonDropDown] = NSAccessibilityPopUpButtonRole;
136 roleMap[QAccessible::SpinBox] = NSAccessibilityIncrementorRole;
137 roleMap[QAccessible::Slider] = NSAccessibilitySliderRole;
138 // AppKit has no rotary role, and its own circular NSSlider reports as a slider.
139 roleMap[QAccessible::Dial] = NSAccessibilitySliderRole;
140 roleMap[QAccessible::ProgressBar] = NSAccessibilityProgressIndicatorRole;
141 roleMap[QAccessible::ComboBox] = NSAccessibilityComboBoxRole;
142 roleMap[QAccessible::RadioButton] = NSAccessibilityRadioButtonRole;
143 roleMap[QAccessible::CheckBox] = NSAccessibilityCheckBoxRole;
144 roleMap[QAccessible::Switch] = NSAccessibilityCheckBoxRole;
145 roleMap[QAccessible::StaticText] = NSAccessibilityStaticTextRole;
146 roleMap[QAccessible::Table] = NSAccessibilityTableRole;
147 roleMap[QAccessible::StatusBar] = NSAccessibilityStaticTextRole;
148 roleMap[QAccessible::Column] = NSAccessibilityColumnRole;
149 roleMap[QAccessible::ColumnHeader] = NSAccessibilityColumnRole;
150 roleMap[QAccessible::Row] = NSAccessibilityRowRole;
151 roleMap[QAccessible::RowHeader] = NSAccessibilityRowRole;
152 roleMap[QAccessible::Button] = NSAccessibilityButtonRole;
153 roleMap[QAccessible::EditableText] = NSAccessibilityTextFieldRole;
154 roleMap[QAccessible::Link] = NSAccessibilityLinkRole;
155 roleMap[QAccessible::Indicator] = NSAccessibilityValueIndicatorRole;
156 roleMap[QAccessible::Splitter] = NSAccessibilitySplitGroupRole;
157 roleMap[QAccessible::List] = NSAccessibilityListRole;
158 roleMap[QAccessible::ListItem] = NSAccessibilityStaticTextRole;
159 roleMap[QAccessible::Cell] = NSAccessibilityCellRole;
160 roleMap[QAccessible::Client] = NSAccessibilityGroupRole;
161 roleMap[QAccessible::Paragraph] = NSAccessibilityGroupRole;
162 roleMap[QAccessible::Section] = NSAccessibilityGroupRole;
163 roleMap[QAccessible::WebDocument] = NSAccessibilityGroupRole;
164 roleMap[QAccessible::ColorChooser] = NSAccessibilityColorWellRole;
165 roleMap[QAccessible::Footer] = NSAccessibilityGroupRole;
166 roleMap[QAccessible::Form] = NSAccessibilityGroupRole;
167 roleMap[QAccessible::Heading] = @"AXHeading";
168 roleMap[QAccessible::Note] = NSAccessibilityGroupRole;
169 roleMap[QAccessible::ComplementaryContent] = NSAccessibilityGroupRole;
170 roleMap[QAccessible::Graphic] = NSAccessibilityImageRole;
171 roleMap[QAccessible::Tree] = NSAccessibilityOutlineRole;
172 roleMap[QAccessible::BlockQuote] = NSAccessibilityGroupRole;
173 roleMap[QAccessible::LayeredPane] = NSAccessibilityGroupRole;
174}
175
176/*
177 Returns a Cocoa accessibility role for the given interface, or
178 NSAccessibilityUnknownRole if no role mapping is found.
179*/
180NSString *macRole(QAccessibleInterface *interface)
181{
182 QAccessible::Role qtRole = interface->role();
183 QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap();
184
185 if (roleMap.isEmpty())
186 populateRoleMap();
187
188 // MAC_ACCESSIBILTY_DEBUG() << "role for" << interface.object() << "interface role" << Qt::hex << qtRole;
189
190 if (roleMap.contains(qtRole)) {
191 // MAC_ACCESSIBILTY_DEBUG() << "return" << roleMap[qtRole];
192 if (roleMap[qtRole] == NSAccessibilityComboBoxRole && !interface->state().editable)
193 return NSAccessibilityMenuButtonRole;
194 if (roleMap[qtRole] == NSAccessibilityTextFieldRole && interface->state().multiLine)
195 return NSAccessibilityTextAreaRole;
196 if (roleMap[qtRole] == NSAccessibilityButtonRole && interface->state().expandable)
197 return NSAccessibilityDisclosureTriangleRole;
198 return roleMap[qtRole];
199 }
200
201 // Treat unknown Qt roles as generic group container items. Returning
202 // NSAccessibilityUnknownRole is also possible but makes the screen
203 // reader focus on the item instead of passing focus to child items.
204 // MAC_ACCESSIBILTY_DEBUG() << "return NSAccessibilityGroupRole for unknown Qt role";
205 return NSAccessibilityGroupRole;
206}
207
208/*
209 Returns a Cocoa sub role for the given interface.
210*/
211NSString *macSubrole(QAccessibleInterface *interface)
212{
213 QAccessible::State s = interface->state();
214 if (s.searchEdit)
215 return NSAccessibilitySearchFieldSubrole;
216 if (s.passwordEdit)
217 return NSAccessibilitySecureTextFieldSubrole;
218 if (interface->role() == QAccessible::PageTab)
219 return NSAccessibilityTabButtonSubrole;
220 if (interface->role() == QAccessible::Switch)
221 return NSAccessibilitySwitchSubrole;
222 return nil;
223}
224
225/*
226 Cocoa accessibility supports ignoring elements, which means that
227 the elements are still present in the accessibility tree but is
228 not used by the screen reader.
229*/
230bool shouldBeIgnored(QAccessibleInterface *interface)
231{
232 // Cocoa accessibility does not have an attribute that corresponds to the Invisible/Offscreen
233 // state. Ignore interfaces with those flags set.
234 const QAccessible::State state = interface->state();
235 if (state.invisible || state.offscreen || state.invalid)
236 return true;
237
238 // Some roles are not interesting. In particular, container roles should be
239 // ignored in order to flatten the accessibility tree as seen by the user.
240 switch (interface->role()) {
241 case QAccessible::Border: // QFrame
242 case QAccessible::Application: // We use the system-provided application element.
243 case QAccessible::ToolBar: // Access the tool buttons directly.
244 case QAccessible::Pane: // Scroll areas.
245 case QAccessible::Client: // The default for QWidget.
246 case QAccessible::PopupMenu: // Access the menu items directly
247 return true;
248 default:
249 break;
250 }
251
252 NSString *mac_role = macRole(interface);
253 if (mac_role == NSAccessibilityWindowRole || // We use the system-provided window elements.
254 mac_role == NSAccessibilityUnknownRole) {
255 return true;
256 }
257
258 if (const QObject *object = interface->object()) {
259 const QByteArrayView className = object->metaObject()->className();
260
261 // VoiceOver focusing on tool tips can be confusing. The contents of the
262 // tool tip is available through the description attribute anyway, so
263 // we disable accessibility for tool tips.
264 if (className == "QTipLabel"_ba)
265 return true;
266 }
267
268 return false;
269}
270
271bool defaultUnignored(QAccessibleInterface *child)
272{
273 if (child && child->isValid()) {
274 const auto state = child->state();
275 return !state.invalid && !state.invisible;
276 }
277 return false;
278}
279
280/*
281 Returns whether AppKit reports \a interface on our behalf.
282
283 macOS expects the hierarchy App -> Window -> Children, and takes the first
284 two from NSApp and the NSWindow, so an element of ours for either of them
285 would double up on a node AppKit already provides.
286*/
287bool isRepresentedByAppKit(QAccessibleInterface *interface)
288{
289 const QAccessible::Role role = interface->role();
290 return role == QAccessible::Application || role == QAccessible::Window;
291}
292
293/*
294 Returns the view backing \a window, with its accessible parent up to date.
295
296 A Qt view resolves its parent when asked, via [QNSView accessibilityParent],
297 but foreign views have no getter, so the parent has to be pushed onto it.
298 The parent we push is the unignored ancestor of the window container hosting
299 the window, which can change whenever anything above the container moves in
300 the hierarchy, or stops being ignored.
301
302 Rather than tracking those changes we resolve the parent here, on every path
303 by which a client reaches a foreign view. The parent is then correct as of
304 the last query that touched the view, and a query is the only thing that can
305 observe it.
306
307 Any stale parent relationships held by accessibility clients will either be
308 reflected as invalidated accessibility handles as a result of us emitting
309 layout changes, or be refreshed on the next walk of the a11y herarchy.
310*/
311NSView *accessibleViewFor(QWindow *window)
312{
313 // Opt-out, in case this regresses some use-cases
314 const bool disable = qEnvironmentVariableIsSet("QT_MAC_A11Y_NO_SPLIT_ON_VIEW_BOUNDARY");
315 if (disable)
316 return nil;
317
318 auto *platformWindow = static_cast<QCocoaWindow *>(window->handle());
319 if (!platformWindow)
320 return nil;
321 if (platformWindow->isForeignWindow())
322 platformWindow->updateAccessibleParent();
323 return platformWindow->view();
324}
325
326NSArray<id> *unignoredChildren(QAccessibleInterface *interface,
327 const std::function<bool(QAccessibleInterface *child)> &pred)
328{
329 QWindow *window = QAccessibleBridgeUtils::windowFor(interface);
330
331 int numKids = interface->childCount();
332 NSMutableArray<id> *kids = [NSMutableArray<id> arrayWithCapacity:numKids];
333 for (int i = 0; i < numKids; ++i) {
334 QAccessibleInterface *child = interface->child(i);
335
336 if (!pred(child))
337 continue;
338
339 // A child that lives in a window of its own is represented by that
340 // window's view, which then vends the a11y subtree.
341 QWindow *childWindow = QAccessibleBridgeUtils::windowFor(child, interface, window);
342 if (childWindow != window) {
343 if (auto *view = QCocoaAccessible::accessibleViewFor(childWindow)) {
344 [kids addObject:view];
345 continue;
346 }
347 }
348
349 QAccessible::Id childId = QAccessible::uniqueId(child);
350
351 QMacAccessibilityElement *element = [QMacAccessibilityElement elementWithId: childId];
352 if (element)
353 [kids addObject: element];
354 else
355 qWarning("QCocoaAccessibility: invalid child");
356 }
357 return NSAccessibilityUnignoredChildren(kids);
358}
359
360/*
361 Translates a predefined QAccessibleActionInterface action to a Mac action constant.
362 Returns 0 if the Qt Action has no mac equivalent. Ownership of the NSString is
363 not transferred.
364*/
365NSString *getTranslatedAction(const QString &qtAction)
366{
367 if (qtAction == QAccessibleActionInterface::pressAction())
368 return NSAccessibilityPressAction;
369 else if (qtAction == QAccessibleActionInterface::increaseAction())
370 return NSAccessibilityIncrementAction;
371 else if (qtAction == QAccessibleActionInterface::decreaseAction())
372 return NSAccessibilityDecrementAction;
373 else if (qtAction == QAccessibleActionInterface::showMenuAction())
374 return NSAccessibilityShowMenuAction;
375 else if (qtAction == QAccessibleActionInterface::setFocusAction()) // Not 100% sure on this one
376 return NSAccessibilityRaiseAction;
377 else if (qtAction == QAccessibleActionInterface::toggleAction())
378 return NSAccessibilityPressAction;
379
380 // Not translated:
381 //
382 // Qt:
383 // static const QString &checkAction();
384 // static const QString &uncheckAction();
385 //
386 // Cocoa:
387 // NSAccessibilityConfirmAction;
388 // NSAccessibilityPickAction;
389 // NSAccessibilityCancelAction;
390 // NSAccessibilityDeleteAction;
391
392 return nil;
393}
394
395
396/*
397 Translates between a Mac action constant and a QAccessibleActionInterface action
398 Returns an empty QString if there is no Qt predefined equivalent.
399*/
400QString translateAction(NSString *nsAction, QAccessibleInterface *interface)
401{
402 if ([nsAction compare: NSAccessibilityPressAction] == NSOrderedSame) {
403 if (interface->role() == QAccessible::CheckBox
404 || interface->role() == QAccessible::RadioButton
405 || interface->role() == QAccessible::Switch) {
406 return QAccessibleActionInterface::toggleAction();
407 }
408 return QAccessibleActionInterface::pressAction();
409 } else if ([nsAction compare: NSAccessibilityIncrementAction] == NSOrderedSame)
410 return QAccessibleActionInterface::increaseAction();
411 else if ([nsAction compare: NSAccessibilityDecrementAction] == NSOrderedSame)
412 return QAccessibleActionInterface::decreaseAction();
413 else if ([nsAction compare: NSAccessibilityShowMenuAction] == NSOrderedSame)
414 return QAccessibleActionInterface::showMenuAction();
415 else if ([nsAction compare: NSAccessibilityRaiseAction] == NSOrderedSame)
416 return QAccessibleActionInterface::setFocusAction();
417
418 // See getTranslatedAction for not matched translations.
419
420 return QString();
421}
422
423bool hasValueAttribute(QAccessibleInterface *interface)
424{
425 Q_ASSERT(interface);
426 const QAccessible::Role qtrole = interface->role();
427 if (qtrole == QAccessible::EditableText
428 || qtrole == QAccessible::StaticText
429 || interface->valueInterface()
430 || interface->state().checkable
431 || macRole(interface) == NSAccessibilityDisclosureTriangleRole) {
432 return true;
433 }
434
435 return false;
436}
437
438// Converts a QVariant value to the corresponding Cocoa type
439id valueAsNSObject(const QVariant &value)
440{
441 bool ok = false;
442 const double d = value.toDouble(&ok);
443 if (ok)
444 return @(d);
445 return value.toString().toNSString();
446}
447
448id getValueAttribute(QAccessibleInterface *interface)
449{
450 const QAccessible::Role qtrole = interface->role();
451 if (qtrole == QAccessible::StaticText) {
452 return interface->text(QAccessible::Name).toNSString();
453 }
454 if (qtrole == QAccessible::EditableText) {
455 if (QAccessibleTextInterface *textInterface = interface->textInterface()) {
456
457 int begin = 0;
458 int end = textInterface->characterCount();
459 QString text;
460 if (interface->state().passwordEdit) {
461 // return round password replacement chars
462 text = QString(end, QChar(0x2022));
463 } else {
464 // VoiceOver will read out the entire text string at once when returning
465 // text as a value. For large text edits the size of the returned string
466 // needs to be limited and text range attributes need to be used instead.
467 // NSTextEdit returns the first sentence as the value, Do the same here:
468 // ### call to textAfterOffset hangs. Booo!
469 //if (textInterface->characterCount() > 0)
470 // textInterface->textAfterOffset(0, QAccessible2::SentenceBoundary, &begin, &end);
471 text = textInterface->text(begin, end);
472 }
473 return text.toNSString();
474 }
475 }
476
477 if (QAccessibleValueInterface *valueInterface = interface->valueInterface())
478 return valueAsNSObject(valueInterface->currentValue());
479
480 if (interface->state().checkable) {
481 if (interface->state().checkStateMixed)
482 return @(2);
483 return interface->state().checked ? @(1) : @(0);
484 }
485
486 if (macRole(interface) == NSAccessibilityDisclosureTriangleRole) {
487 return interface->state().expanded ? @(1) : @(0);
488 }
489
490 return nil;
491}
492
493} // namespace QCocoaAccessible
494
495#endif // QT_CONFIG(accessibility)
496
497QT_END_NAMESPACE
Combined button and popup list for selecting options.