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
qcocoaaccessibilityelement.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
10#include "qcocoawindow.h"
11#include "qcocoascreen.h"
12
13#include <QtCore/qlogging.h>
14#include <QtGui/private/qaccessiblecache_p.h>
15#include <QtGui/private/qaccessiblebridgeutils_p.h>
16#include <QtGui/qaccessible.h>
17
18QT_USE_NAMESPACE
19
20Q_STATIC_LOGGING_CATEGORY(lcAccessibilityTable, "qt.accessibility.table")
21
22using namespace Qt::StringLiterals;
23
24#if QT_CONFIG(accessibility)
25
26/**
27 * Converts between absolute character offsets and line numbers of a
28 * QAccessibleTextInterface. Works in exactly one of two modes:
29 *
30 * - Pass *line == -1 in order to get a line containing character at the given
31 * *offset
32 * - Pass *offset == -1 in order to get the offset of first character of the
33 * given *line
34 *
35 * You can optionally also pass non-NULL `start` and `end`, which will in both
36 * modes be filled with the offset of the first and last characters of the
37 * relevant line.
38 */
39static void convertLineOffset(QAccessibleTextInterface *text, int *line, int *offset, NSUInteger *start = 0, NSUInteger *end = 0)
40{
41 Q_ASSERT(*line == -1 || *offset == -1);
42 Q_ASSERT(*line != -1 || *offset != -1);
43 Q_ASSERT(*offset <= text->characterCount());
44
45 int curLine = -1;
46 int curStart = 0, curEnd = 0;
47
48 do {
49 curStart = curEnd;
50 text->textAtOffset(curStart, QAccessible::LineBoundary, &curStart, &curEnd);
51 // If the text is empty then we just return
52 if (curStart == -1 || curEnd == -1) {
53 if (start)
54 *start = 0;
55 if (end)
56 *end = 0;
57 return;
58 }
59 ++curLine;
60 {
61 // check for a case where a single word longer than the text edit's width and gets wrapped
62 // in the middle of the word; in this case curEnd will be an offset belonging to the next line
63 // and therefore nextEnd will not be equal to curEnd
64 int nextStart;
65 int nextEnd;
66 text->textAtOffset(curEnd, QAccessible::LineBoundary, &nextStart, &nextEnd);
67 if (nextEnd == curEnd)
68 ++curEnd;
69 }
70 } while ((*line == -1 || curLine < *line) && (*offset == -1 || (curEnd <= *offset)) && curEnd <= text->characterCount());
71
72 curEnd = qMin(curEnd, text->characterCount());
73
74 if (*line == -1)
75 *line = curLine;
76 if (*offset == -1)
77 *offset = curStart;
78
79 Q_ASSERT(curStart >= 0);
80 Q_ASSERT(curEnd >= 0);
81 if (start)
82 *start = curStart;
83 if (end)
84 *end = curEnd;
85}
86
87@implementation QMacAccessibilityElement {
88 QAccessible::Id axid;
89 int m_rowIndex;
90 int m_columnIndex;
91
92 // used by NSAccessibilityTable
93 NSMutableArray<QMacAccessibilityElement *> *rows; // corresponds to accessibilityRows
94 NSMutableArray<QMacAccessibilityElement *> *columns; // corresponds to accessibilityColumns
95
96 // If synthesizedRole is set, this means that this objects does not have a corresponding
97 // QAccessibleInterface, but it is synthesized by the cocoa plugin in order to meet the
98 // NSAccessibility requirements.
99 // The ownership is controlled by the parent object identified with the axid member variable.
100 // (Therefore, if this member is set, this objects axid member is the same as the parents axid
101 // member)
102 NSString *synthesizedRole;
103}
104
105- (instancetype)initWithId:(QAccessible::Id)anId
106{
107 return [self initWithId:anId role:nil];
108}
109
110- (instancetype)initWithId:(QAccessible::Id)anId role:(NSAccessibilityRole)role
111{
112 Q_ASSERT((int)anId < 0);
113 self = [super init];
114 if (self) {
115 axid = anId;
116 m_rowIndex = -1;
117 m_columnIndex = -1;
118 rows = nil;
119 columns = nil;
120 synthesizedRole = role;
121 // table: if this is not created as an element managed by the table, then
122 // it's either the table itself, or an element created for an already existing
123 // cell interface (or an element that's not at all related to a table).
124 if (!synthesizedRole) {
125 if (QAccessibleInterface *iface = QAccessible::accessibleInterface(axid)) {
126 if (iface->tableInterface()) {
127 [self updateTableModel];
128 } else if (const auto *cell = iface->tableCellInterface()) {
129 // If we create an element for a table cell, initialize it with row/column
130 // and insert it into the corresponding row's columns array.
131 m_rowIndex = cell->rowIndex();
132 m_columnIndex = cell->columnIndex();
133 QAccessibleInterface *table = cell->table();
134 Q_ASSERT(table);
135 QAccessibleTableInterface *tableInterface = table->tableInterface();
136 // Collapsed cells and pending relayouts can report a position of -1.
137 if (tableInterface && (m_rowIndex >= 0) && (m_columnIndex >= 0)) {
138 auto *tableElement = [QMacAccessibilityElement elementWithInterface:table];
139 Q_ASSERT(tableElement);
140 if (!tableElement->rows
141 || int(tableElement->rows.count) <= m_rowIndex
142 || int(tableElement->rows.count) != tableInterface->rowCount()) {
143 qCWarning(lcAccessibilityTable)
144 << "Cell requested for row" << m_rowIndex << "is out of"
145 << "bounds for table with" << (tableElement->rows ?
146 tableElement->rows.count : tableInterface->rowCount())
147 << "rows! Resizing table model.";
148 [tableElement updateTableModel];
149 }
150
151 Q_ASSERT(tableElement->rows);
152 Q_ASSERT(int(tableElement->rows.count) > m_rowIndex);
153
154 auto *rowElement = tableElement->rows[m_rowIndex];
155 if (!rowElement->columns || int(rowElement->columns.count) != tableInterface->columnCount()) {
156 if (rowElement->columns) {
157 qCWarning(lcAccessibilityTable)
158 << "Table representation column count is out of sync:"
159 << rowElement->columns.count << "!=" << tableInterface->columnCount();
160 [rowElement->columns autorelease];
161 rowElement->columns = nil;
162 }
163 rowElement->columns = [rowElement populateTableRow:tableInterface->columnCount()];
164 [rowElement->columns retain];
165 }
166
167 qCDebug(lcAccessibilityTable) << "Creating cell representation for"
168 << m_rowIndex << m_columnIndex
169 << "in table with"
170 << tableElement->rows.count << "rows and"
171 << rowElement->columns.count << "columns";
172
173 rowElement->columns[m_columnIndex] = self;
174 }
175 }
176 }
177 }
178 }
179
180 return self;
181}
182
183/*!
184 \internal
185
186 Constructs a new element with the ID \a anId and inserts it into the cache.
187
188 Elements representing table rows, columns, and cells are created directly
189 via initWithId (in populateTableArray and populateTableRow), as they don't
190 get added to the cache until later.
191*/
192+ (instancetype)elementWithId:(QAccessible::Id)anId
193{
194 Q_ASSERT(anId);
195 if (!anId)
196 return nil;
197
198 QAccessibleCache *cache = QAccessibleCache::instance();
199
200 QMacAccessibilityElement *element = cache->elementForId(anId);
201 if (!element) {
202 Q_ASSERT(QAccessible::accessibleInterface(anId));
203 element = [[self alloc] initWithId:anId];
204 if (cache->insertElement(anId, element))
205 [element release];
206 }
207 return element;
208}
209
210+ (instancetype)elementWithInterface:(QAccessibleInterface *)iface
211{
212 Q_ASSERT(iface);
213 if (!iface)
214 return nil;
215
216 const QAccessible::Id anId = QAccessible::uniqueId(iface);
217 return [self elementWithId:anId];
218}
219
220// called by QAccessibleCache after removing the element, which also releases
221- (void)invalidate {
222 axid = 0;
223 if (rows) {
224 [rows autorelease];
225 rows = nil;
226 }
227 if (columns) {
228 [columns autorelease];
229 columns = nil;
230 }
231 synthesizedRole = nil;
232
233 NSAccessibilityPostNotification(self, NSAccessibilityUIElementDestroyedNotification);
234}
235
236// The view and accessibility cache own the interfaces. Native element teardown
237// must not delete interfaces that the table still references.
238- (void)dealloc {
239 if (axid)
240 NSAccessibilityPostNotification(self, NSAccessibilityUIElementDestroyedNotification);
241 if (rows)
242 [rows release]; // will also release all entries first
243 if (columns)
244 [columns release]; // will also release all entries first
245 [super dealloc];
246}
247
248- (BOOL)isEqual:(id)object {
249 if ([object isKindOfClass:[QMacAccessibilityElement class]]) {
250 QMacAccessibilityElement *other = object;
251 // invalidated elements are only equal to themselves
252 if (!axid)
253 return other == self;
254 // synthesized rows, columns, and cells share the table's axid
255 return other->axid == axid && other->synthesizedRole == synthesizedRole
256 && (!synthesizedRole
257 || (other->m_rowIndex == m_rowIndex && other->m_columnIndex == m_columnIndex));
258 } else {
259 return NO;
260 }
261}
262
263- (NSUInteger)hash {
264 return axid;
265}
266
267- (BOOL)isManagedByParent {
268 return synthesizedRole != nil;
269}
270
271- (NSMutableArray *)populateTableArray:(NSAccessibilityRole)role count:(int)count
272{
273 if (self.qtInterface) {
274 auto *array = [NSMutableArray<QMacAccessibilityElement *> arrayWithCapacity:count];
275 Q_ASSERT(array);
276 for (int n = 0; n < count; ++n) {
277 // columns will have same axid as table (but not inserted in cache)
278 QMacAccessibilityElement *element =
279 [[QMacAccessibilityElement alloc] initWithId:axid role:role];
280 if (element) {
281 if (role == NSAccessibilityRowRole)
282 element->m_rowIndex = n;
283 else if (role == NSAccessibilityColumnRole)
284 element->m_columnIndex = n;
285 [array addObject:element];
286 [element release];
287 } else {
288 qWarning("QCocoaAccessibility: invalid child");
289 }
290 }
291 return array;
292 }
293 return nil;
294}
295
296- (NSMutableArray *)populateTableRow:(int)count
297{
298 Q_ASSERT(synthesizedRole == NSAccessibilityRowRole);
299 qCDebug(lcAccessibilityTable) << "Populating table row" << m_rowIndex
300 << "with" << count << "placeholder cells";
301 // When macOS asks for the children of a row, then we populate the row's column
302 // array with synthetic elements as place holders. This way, we don't have to
303 // create QAccessibleInterfaces for every cell before they are really needed.
304 // We don't add those synthetic elements into the cache, and we give them the
305 // same axid as the table. This way, we can get easily to the table, and from
306 // there to the QAccessibleInterface for the cell, when we have to eventually
307 // associate such an interface with the element (at which point it is no longer
308 // a placeholder).
309 auto *array = [NSMutableArray<QMacAccessibilityElement *> arrayWithCapacity:count];
310 Q_ASSERT(array);
311
312 for (int n = 0; n < count; ++n) {
313 // columns will have same axid as table (but not inserted in cache)
314 QMacAccessibilityElement *cell =
315 [[QMacAccessibilityElement alloc] initWithId:axid role:NSAccessibilityCellRole];
316 if (cell) {
317 cell->m_rowIndex = m_rowIndex;
318 cell->m_columnIndex = n;
319 [array addObject:cell];
320 [cell release];
321 }
322 }
323 return array;
324}
325
326- (void)updateTableModel
327{
328 if (QAccessibleInterface *iface = self.qtInterface) {
329 if (QAccessibleTableInterface *table = iface->tableInterface()) {
330 Q_ASSERT(!self.isManagedByParent);
331 qCDebug(lcAccessibilityTable) << "Updating table representation with"
332 << table->rowCount() << table->columnCount();
333 if (rows) {
334 [rows autorelease];
335 rows = nil;
336 }
337 rows = [self populateTableArray:NSAccessibilityRowRole count:table->rowCount()];
338 [rows retain];
339 if (columns) {
340 [columns autorelease];
341 columns = nil;
342 }
343 columns = [self populateTableArray:NSAccessibilityColumnRole count:table->columnCount()];
344 [columns retain];
345 }
346 }
347}
348
349- (QAccessibleInterface *)qtInterface
350{
351 QAccessibleInterface *iface = QAccessible::accessibleInterface(axid);
352 if (!iface || !iface->isValid())
353 return nullptr;
354
355 // If this is a placeholder element for a table cell, associate it with the
356 // cell interface (which will be created now, if needed). The current axid is
357 // for the table to which the cell belongs, so iface is pointing at the table.
358 if (synthesizedRole == NSAccessibilityCellRole) {
359 // get the cell interface - there must be a valid one
360 QAccessibleTableInterface *table = iface->tableInterface();
361 Q_ASSERT(table);
362 QAccessibleInterface *cell = table->cellAt(m_rowIndex, m_columnIndex);
363 if (!cell)
364 return nullptr;
365 Q_ASSERT(cell->isValid());
366 iface = cell;
367
368 // no longer a placeholder
369 axid = QAccessible::uniqueId(cell);
370 synthesizedRole = nil;
371
372 // If there already is another element for this cell in the cache, then
373 // the cache invalidates and releases it. That element might have been
374 // created for a different position, if rows or columns moved since.
375 QAccessibleCache *cache = QAccessibleCache::instance();
376 Q_ASSERT(!cache->elementForId(axid) || !cache->elementForId(axid)->synthesizedRole);
377 cache->insertElement(axid, self);
378 }
379 return iface;
380}
381
382//
383// accessibility protocol
384//
385
386- (BOOL)isAccessibilityFocused
387{
388 // Just check if the app thinks we're focused.
389 id focusedElement = NSApp.accessibilityApplicationFocusedUIElement;
390 return [focusedElement isEqual:self];
391}
392
393// attributes
394
395+ (id) lineNumberForIndex: (int)index forText:(const QString &)text
396{
397 auto textBefore = QStringView(text).left(index);
398 qsizetype newlines = textBefore.count(u'\n');
399 return @(newlines);
400}
401
402- (BOOL) accessibilityNotifiesWhenDestroyed {
403 return YES;
404}
405
406- (NSString *) accessibilityRole {
407 // shortcut for cells, rows, and columns in a table
408 if (synthesizedRole)
409 return synthesizedRole;
410 if (QAccessibleInterface *iface = self.qtInterface)
411 return QCocoaAccessible::macRole(iface);
412 return NSAccessibilityUnknownRole;
413}
414
415- (NSString *) accessibilitySubRole {
416 if (QAccessibleInterface *iface = self.qtInterface)
417 return QCocoaAccessible::macSubrole(iface);
418 return NSAccessibilityUnknownRole;
419}
420
421- (NSString *) accessibilityRoleDescription {
422 if (self.qtInterface)
423 return NSAccessibilityRoleDescription(self.accessibilityRole, self.accessibilitySubRole);
424 return NSAccessibilityUnknownRole;
425}
426
427- (NSArray *) accessibilityChildren {
428 // shortcut for cells
429 if (synthesizedRole == NSAccessibilityCellRole)
430 return nil;
431
432 QAccessibleInterface *iface = self.qtInterface;
433 if (!iface)
434 return nil;
435 if (QAccessibleTableInterface *table = iface->tableInterface()) {
436 // either a table or table rows/columns
437 if (!synthesizedRole) {
438 // This is the table element, parent of all rows and columns
439 /*
440 * Typical 2x2 table hierarchy as can be observed in a table found under
441 * Apple -> System Settings -> General -> Login Items (macOS 13)
442 *
443 * (AXTable)
444 * | Columns: NSArray* (2 items)
445 * | Rows: NSArray* (2 items)
446 * | Visible Columns: NSArray* (2 items)
447 * | Visible Rows: NSArray* (2 items)
448 * | Children: NSArray* (5 items)
449 +----<--| Header: (AXGroup)
450 | * +-- (AXRow)
451 | * | +-- (AXText)
452 | * | +-- (AXTextField)
453 | * +-- (AXRow)
454 | * | +-- (AXText)
455 | * | +-- (AXTextField)
456 | * +-- (AXColumn)
457 | * | Header: "Item" (sort button)
458 | * | Index: 0
459 | * | Rows: NSArray* (2 items)
460 | * | Visible Rows: NSArray* (2 items)
461 | * +-- (AXColumn)
462 | * | Header: "Kind" (sort button)
463 | * | Index: 1
464 | * | Rows: NSArray* (2 items)
465 | * | Visible Rows: NSArray* (2 items)
466 +----> +-- (AXGroup)
467 * +-- (AXButton/AXSortButton) Item [NSAccessibilityTableHeaderCellProxy]
468 * +-- (AXButton/AXSortButton) Kind [NSAccessibilityTableHeaderCellProxy]
469 */
470 NSArray *rs = [self accessibilityRows];
471 NSArray *cs = [self accessibilityColumns];
472 const int rCount = int([rs count]);
473 const int cCount = int([cs count]);
474 int childCount = rCount + cCount;
475 NSMutableArray<QMacAccessibilityElement *> *tableChildren =
476 [NSMutableArray<QMacAccessibilityElement *> arrayWithCapacity:childCount];
477 for (int i = 0; i < rCount; ++i) {
478 [tableChildren addObject:[rs objectAtIndex:i]];
479 }
480 for (int i = 0; i < cCount; ++i) {
481 [tableChildren addObject:[cs objectAtIndex:i]];
482 }
483 return NSAccessibilityUnignoredChildren(tableChildren);
484 } else if (synthesizedRole == NSAccessibilityColumnRole) {
485 return nil;
486 } else if (synthesizedRole == NSAccessibilityRowRole) {
487 // axid matches the parent table axid so that we can easily find the parent table
488 // children of row are cell/any items
489 Q_ASSERT(m_rowIndex >= 0);
490 Q_ASSERT(rows == nil);
491 const unsigned int numColumns = table->columnCount();
492 if (!columns || columns.count != numColumns) {
493 if (columns) {
494 [columns autorelease];
495 columns = nil;
496 }
497 columns = [self populateTableRow:numColumns];
498 [columns retain];
499 }
500 return NSAccessibilityUnignoredChildren(columns);
501 }
502 }
503 return QCocoaAccessible::unignoredChildren(iface);
504}
505
506- (NSArray *) accessibilitySelectedChildren {
507 QAccessibleInterface *iface = QAccessible::accessibleInterface(axid);
508 if (!iface || !iface->isValid())
509 return nil;
510
511 QAccessibleSelectionInterface *selection = iface->selectionInterface();
512 if (!selection)
513 return nil;
514
515 const QList<QAccessibleInterface *> selectedList = selection->selectedItems();
516 const qsizetype numSelected = selectedList.size();
517 NSMutableArray<QMacAccessibilityElement *> *selectedChildren =
518 [NSMutableArray<QMacAccessibilityElement *> arrayWithCapacity:numSelected];
519 for (QAccessibleInterface *selectedChild : selectedList) {
520 if (selectedChild && selectedChild->isValid()) {
521 QAccessible::Id id = QAccessible::uniqueId(selectedChild);
522 QMacAccessibilityElement *element = [QMacAccessibilityElement elementWithId:id];
523 if (element)
524 [selectedChildren addObject:element];
525 }
526 }
527 return NSAccessibilityUnignoredChildren(selectedChildren);
528}
529
530- (id) accessibilityWindow {
531 // Go up until we find a parent that is a window
532 NSAccessibilityElement *parent = self.accessibilityParent;
533 if (parent && parent.accessibilityRole == NSAccessibilityWindowRole)
534 return parent;
535 return [parent accessibilityWindow];
536}
537
538- (id) accessibilityTopLevelUIElementAttribute {
539 // We're in the same top level element as our parent.
540 return [self.accessibilityParent accessibilityTopLevelUIElementAttribute];
541}
542
543- (NSString *) accessibilityTitle {
544 if (QAccessibleInterface *iface = self.qtInterface) {
545 if (iface->role() == QAccessible::StaticText)
546 return nil;
547 if (self.isManagedByParent)
548 return nil;
549 return iface->text(QAccessible::Name).toNSString();
550 }
551 return nil;
552}
553
554- (id) accessibilityTitleUIElement {
555 QAccessibleInterface *iface = self.qtInterface;
556 if (!iface)
557 return nil;
558
559 const auto labelRelations = iface->relations(QAccessible::Label);
560 if (labelRelations.empty())
561 return nil;
562
563 QAccessibleInterface *label = labelRelations.first().first;
564 if (!label)
565 return nil;
566
567 QMacAccessibilityElement *accessibleElement = [QMacAccessibilityElement elementWithInterface:label];
568 if (!accessibleElement)
569 return nil;
570
571 return NSAccessibilityUnignoredAncestor(accessibleElement);
572}
573
574- (NSString*) accessibilityIdentifier {
575 if (QAccessibleInterface *iface = self.qtInterface)
576 return QAccessibleBridgeUtils::accessibleId(iface).toNSString();
577 return nil;
578}
579
580- (BOOL) isAccessibilityEnabled {
581 if (QAccessibleInterface *iface = self.qtInterface)
582 return !iface->state().disabled;
583 return false;
584}
585
586- (id)accessibilityParent {
587 if (synthesizedRole == NSAccessibilityCellRole) {
588 QAccessibleInterface *tableInterface = QAccessible::accessibleInterface(axid);
589 if (!tableInterface || !tableInterface->isValid())
590 return nil;
591 QMacAccessibilityElement *tableElement =
592 [QMacAccessibilityElement elementWithId:axid];
593 if (!tableElement->rows || m_rowIndex < 0
594 || m_rowIndex >= int(tableElement->rows.count))
595 return nil;
596 QMacAccessibilityElement *rowElement = tableElement->rows[m_rowIndex];
597 return rowElement;
598 }
599
600 QAccessibleInterface *iface = self.qtInterface;
601 if (!iface)
602 return nil;
603
604 if (self.isManagedByParent) {
605 // axid is the same for the parent element
606 return NSAccessibilityUnignoredAncestor([QMacAccessibilityElement elementWithId:axid]);
607 }
608
609 if (QAccessibleInterface *parent = iface->parent()) {
610 if (parent->tableInterface()) {
611 QMacAccessibilityElement *tableElement =
612 [QMacAccessibilityElement elementWithInterface:parent];
613
614 // parent of cell should be row; the row index we were created with
615 // is outdated if rows got inserted or removed since.
616 int rowIndex = -1;
617 if (QAccessibleTableCellInterface *cell = iface->tableCellInterface())
618 rowIndex = cell->rowIndex();
619 else if (m_rowIndex >= 0 && m_columnIndex >= 0)
620 rowIndex = m_rowIndex;
621 if (!tableElement->rows || rowIndex < 0 || rowIndex >= int(tableElement->rows.count))
622 return nil;
623 QMacAccessibilityElement *rowElement = tableElement->rows[rowIndex];
624 return NSAccessibilityUnignoredAncestor(rowElement);
625 }
626
627 // If AppKit reports the parent for us, fall through to the native
628 // view below, whose unignored ancestor is the NSWindow.
629 if (!QCocoaAccessible::isRepresentedByAppKit(parent))
630 return NSAccessibilityUnignoredAncestor([QMacAccessibilityElement elementWithInterface: parent]);
631 }
632
633 if (QWindow *window = iface->window()) {
634 QPlatformWindow *platformWindow = window->handle();
635 if (platformWindow) {
636 QCocoaWindow *win = static_cast<QCocoaWindow*>(platformWindow);
637 return NSAccessibilityUnignoredAncestor(qnsview_cast(win->view()));
638 }
639 }
640 return nil;
641}
642
643- (NSRect)accessibilityFrame {
644 QAccessibleInterface *iface = self.qtInterface;
645 if (!iface)
646 return NSZeroRect;
647
648 QRect rect;
649 if (self.isManagedByParent) {
650 if (QAccessibleTableInterface *table = iface->tableInterface()) {
651 // Construct the geometry of the Row/Column by looking at the individual table cells
652 // ### Assumes that cells logical coordinates have spatial ordering (e.g finds the
653 // rows width by taking the union between the leftmost item and the rightmost item in
654 // a row).
655 // Otherwise, we have to iterate over *all* cells in a row/columns to
656 // find out the Row/Column geometry
657 const bool isRow = synthesizedRole == NSAccessibilityRowRole;
658 QPoint cellPos;
659 int &row = isRow ? cellPos.ry() : cellPos.rx();
660 int &col = isRow ? cellPos.rx() : cellPos.ry();
661
662 NSUInteger trackIndex = self.accessibilityIndex;
663 if (trackIndex != NSNotFound) {
664 row = int(trackIndex);
665 if (QAccessibleInterface *firstCell = table->cellAt(cellPos.y(), cellPos.x())) {
666 rect = firstCell->rect();
667 col = isRow ? table->columnCount() : table->rowCount();
668 if (col > 1) {
669 --col;
670 if (QAccessibleInterface *lastCell =
671 table->cellAt(cellPos.y(), cellPos.x()))
672 rect = rect.united(lastCell->rect());
673 }
674 }
675 }
676 }
677 } else {
678 rect = iface->rect();
679 }
680
681 return QCocoaScreen::mapToNative(rect);
682}
683
684- (NSString*)accessibilityLabel {
685 if (QAccessibleInterface *iface = self.qtInterface)
686 return iface->text(QAccessible::Description).toNSString();
687 qWarning() << "Called accessibilityLabel on invalid object: " << axid;
688 return nil;
689}
690
691- (void)setAccessibilityLabel:(NSString*)label{
692 if (QAccessibleInterface *iface = self.qtInterface)
693 iface->setText(QAccessible::Description, QString::fromNSString(label));
694}
695
696- (NSAccessibilityOrientation)accessibilityOrientation {
697 QAccessibleInterface *iface = self.qtInterface;
698 if (!iface)
699 return NSAccessibilityOrientationUnknown;
700
701 NSAccessibilityOrientation nsOrientation = NSAccessibilityOrientationUnknown;
702 if (QAccessibleAttributesInterface *attributesIface = iface->attributesInterface()) {
703 const QVariant orientationVariant =
704 attributesIface->attributeValue(QAccessible::Attribute::Orientation);
705 if (orientationVariant.isValid()) {
706 Q_ASSERT(orientationVariant.canConvert<Qt::Orientation>());
707 const Qt::Orientation orientation = orientationVariant.value<Qt::Orientation>();
708 nsOrientation = orientation == Qt::Horizontal ? NSAccessibilityOrientationHorizontal
709 : NSAccessibilityOrientationVertical;
710 }
711 }
712 return nsOrientation;
713}
714
715- (id) accessibilityValue {
716 if (QAccessibleInterface *iface = self.qtInterface) {
717 // VoiceOver asks for the value attribute for all elements. Return nil
718 // if we don't want the element to have a value attribute.
719 if (QCocoaAccessible::hasValueAttribute(iface))
720 return QCocoaAccessible::getValueAttribute(iface);
721 }
722 return nil;
723}
724
725
726- (id) accessibilityMinValue {
727 if (QAccessibleInterface *iface = self.qtInterface) {
728 if (iface->valueInterface()) {
729 return QCocoaAccessible::valueAsNSObject(iface->valueInterface()->minimumValue());
730 }
731 }
732 return nil;
733}
734
735
736- (id) accessibilityMaxValue {
737 if (QAccessibleInterface *iface = self.qtInterface) {
738 if (iface->valueInterface()) {
739 return QCocoaAccessible::valueAsNSObject(iface->valueInterface()->maximumValue());
740 }
741 }
742 return nil;
743}
744
745- (NSInteger) accessibilityNumberOfCharacters {
746 if (QAccessibleInterface *iface = self.qtInterface) {
747 if (QAccessibleTextInterface *text = iface->textInterface())
748 return text->characterCount();
749 }
750 return 0;
751}
752
753- (NSString *) accessibilitySelectedText {
754 if (QAccessibleInterface *iface = self.qtInterface) {
755 if (QAccessibleTextInterface *text = iface->textInterface()) {
756 int start = 0;
757 int end = 0;
758 text->selection(0, &start, &end);
759 return text->text(start, end).toNSString();
760 }
761 }
762 return nil;
763}
764
765- (NSRange) accessibilitySelectedTextRange {
766 QAccessibleInterface *iface = self.qtInterface;
767 if (!iface)
768 return NSRange();
769 if (QAccessibleTextInterface *text = iface->textInterface()) {
770 int start = 0;
771 int end = 0;
772 if (text->selectionCount() > 0) {
773 text->selection(0, &start, &end);
774 } else {
775 start = text->cursorPosition();
776 end = start;
777 }
778 return NSMakeRange(quint32(start), quint32(end - start));
779 }
780 return NSMakeRange(0, 0);
781}
782
783- (NSInteger)accessibilityLineForIndex:(NSInteger)index {
784 QAccessibleInterface *iface = self.qtInterface;
785 if (!iface)
786 return 0;
787 if (QAccessibleTextInterface *text = iface->textInterface()) {
788 QString textToPos = text->text(0, index);
789 return textToPos.count('\n');
790 }
791 return 0;
792}
793
794- (NSRange)accessibilityVisibleCharacterRange {
795 QAccessibleInterface *iface = self.qtInterface;
796 if (!iface)
797 return NSRange();
798 // FIXME This is not correct and may impact performance for big texts
799 if (QAccessibleTextInterface *text = iface->textInterface())
800 return NSMakeRange(0, static_cast<uint>(text->characterCount()));
801 return NSMakeRange(0, static_cast<uint>(iface->text(QAccessible::Name).length()));
802}
803
804- (NSInteger) accessibilityInsertionPointLineNumber {
805 QAccessibleInterface *iface = self.qtInterface;
806 if (!iface)
807 return 0;
808 if (QAccessibleTextInterface *text = iface->textInterface()) {
809 int position = text->cursorPosition();
810 return [self accessibilityLineForIndex:position];
811 }
812 return 0;
813}
814
815- (NSArray *)accessibilityAttributeNames {
816 NSMutableArray *attributes = [[NSMutableArray new] autorelease];
817 QAccessibleInterface *iface = self.qtInterface;
818
819#if QT_APPLE_SDK_EQUAL_OR_ABOVE(MACOS(26))
820 if (@available(macOS 26, *)) {
821 [attributes addObject:NSAccessibilityLanguageAttribute];
822
823 if (iface && iface->role() == QAccessible::Heading) {
824 QAccessibleAttributesInterface *attributesIface = iface->attributesInterface();
825 if (attributesIface
826 && attributesIface->attributeKeys().contains(QAccessible::Attribute::Level))
827 [attributes addObject:NSAccessibilityHeadingLevelAttribute];
828 }
829 }
830#endif
831
832 if (iface && iface->state().expandable)
833 [attributes addObject:NSAccessibilityExpandedAttribute];
834
835 return attributes;
836}
837
838- (id)accessibilityAttributeValue:(NSString *)attribute {
839 QAccessibleInterface *iface = self.qtInterface;
840 if (!iface) {
841 qWarning() << "Called attribute on invalid object: " << axid;
842 return nil;
843 }
844
845#if QT_APPLE_SDK_EQUAL_OR_ABOVE(MACOS(26))
846 if (@available(macOS 26, *)) {
847 if ([attribute isEqualToString:NSAccessibilityLanguageAttribute]) {
848 QAccessibleAttributesInterface *attributesIface = iface->attributesInterface();
849 if (!attributesIface
850 || !attributesIface->attributeKeys().contains(QAccessible::Attribute::Locale))
851 return nil;
852
853 const auto &localeVariant =
854 attributesIface->attributeValue(QAccessible::Attribute::Locale);
855 return localeVariant.toLocale().bcp47Name().toNSString();
856 }
857
858 if ([attribute isEqualToString:NSAccessibilityHeadingLevelAttribute]) {
859 if (iface->role() != QAccessible::Heading)
860 return @(0);
861
862 auto attributesIface = iface->attributesInterface();
863 if (!attributesIface)
864 return @(0);
865
866 const QVariant levelVariant =
867 attributesIface->attributeValue(QAccessible::Attribute::Level);
868 if (!levelVariant.isValid() || !levelVariant.canConvert<int>())
869 return @(0);
870
871 const int level = levelVariant.toInt();
872 if (level < 1)
873 return @(0);
874
875 return @(level);
876 }
877 }
878#endif
879
880 if ([attribute isEqualToString:NSAccessibilityExpandedAttribute])
881 return iface->state().expanded ? @YES : @NO;
882
883 return nil;
884}
885
886- (NSArray *)accessibilityParameterizedAttributeNames {
887
888 QAccessibleInterface *iface = self.qtInterface;
889 if (!iface) {
890 qWarning() << "Called attribute on invalid object: " << axid;
891 return nil;
892 }
893
894 if (iface->textInterface()) {
895 return @[
896 NSAccessibilityStringForRangeParameterizedAttribute,
897 NSAccessibilityLineForIndexParameterizedAttribute,
898 NSAccessibilityRangeForLineParameterizedAttribute,
899 NSAccessibilityRangeForPositionParameterizedAttribute,
900// NSAccessibilityRangeForIndexParameterizedAttribute,
901 NSAccessibilityBoundsForRangeParameterizedAttribute,
902// NSAccessibilityRTFForRangeParameterizedAttribute,
903 NSAccessibilityStyleRangeForIndexParameterizedAttribute,
904 NSAccessibilityAttributedStringForRangeParameterizedAttribute
905 ];
906 }
907
908 return nil;
909}
910
911- (id)accessibilityAttributeValue:(NSString *)attribute forParameter:(id)parameter {
912 QAccessibleInterface *iface = self.qtInterface;
913 if (!iface) {
914 qWarning() << "Called attribute on invalid object: " << axid;
915 return nil;
916 }
917
918 if (!iface->textInterface())
919 return nil;
920
921 if ([attribute isEqualToString: NSAccessibilityStringForRangeParameterizedAttribute]) {
922 NSRange range = [parameter rangeValue];
923 QString text = iface->textInterface()->text(range.location, range.location + range.length);
924 return text.toNSString();
925 }
926 if ([attribute isEqualToString: NSAccessibilityLineForIndexParameterizedAttribute]) {
927 int index = [parameter intValue];
928 if (index < 0 || index > iface->textInterface()->characterCount())
929 return nil;
930 int line = 0; // true for all single line edits
931 if (iface->state().multiLine) {
932 line = -1;
933 convertLineOffset(iface->textInterface(), &line, &index);
934 }
935 return @(line);
936 }
937 if ([attribute isEqualToString: NSAccessibilityRangeForLineParameterizedAttribute]) {
938 int line = [parameter intValue];
939 if (line < 0)
940 return nil;
941 int lineOffset = -1;
942 NSUInteger startOffset = 0;
943 NSUInteger endOffset = 0;
944 convertLineOffset(iface->textInterface(), &line, &lineOffset, &startOffset, &endOffset);
945 return [NSValue valueWithRange:NSMakeRange(startOffset, endOffset - startOffset)];
946 }
947 if ([attribute isEqualToString: NSAccessibilityBoundsForRangeParameterizedAttribute]) {
948 NSRange range = [parameter rangeValue];
949 QRect firstRect = iface->textInterface()->characterRect(range.location);
950 QRectF rect;
951 if (range.length > 0) {
952 NSUInteger position = range.location + range.length - 1;
953 if (position > range.location && iface->textInterface()->text(position, position + 1) == "\n"_L1)
954 --position;
955 QRect lastRect = iface->textInterface()->characterRect(position);
956 rect = firstRect.united(lastRect);
957 } else {
958 rect = firstRect;
959 rect.setWidth(1);
960 }
961 return [NSValue valueWithRect:QCocoaScreen::mapToNative(rect)];
962 }
963 if ([attribute isEqualToString: NSAccessibilityAttributedStringForRangeParameterizedAttribute]) {
964 NSRange range = [parameter rangeValue];
965 QString text = iface->textInterface()->text(range.location, range.location + range.length);
966 return [[NSAttributedString alloc] initWithString:text.toNSString()];
967 } else if ([attribute isEqualToString: NSAccessibilityRangeForPositionParameterizedAttribute]) {
968 QPoint point = QCocoaScreen::mapFromNative([parameter pointValue]).toPoint();
969 int offset = iface->textInterface()->offsetAtPoint(point);
970 return [NSValue valueWithRange:NSMakeRange(static_cast<NSUInteger>(offset), 1)];
971 } else if ([attribute isEqualToString: NSAccessibilityStyleRangeForIndexParameterizedAttribute]) {
972 int start = 0;
973 int end = 0;
974 iface->textInterface()->attributes([parameter intValue], &start, &end);
975 return [NSValue valueWithRange:NSMakeRange(static_cast<NSUInteger>(start), static_cast<NSUInteger>(end - start))];
976 }
977 return nil;
978}
979
980- (BOOL)accessibilityIsAttributeSettable:(NSString *)attribute {
981 QAccessibleInterface *iface = self.qtInterface;
982 if (!iface)
983 return NO;
984
985 if ([attribute isEqualToString:NSAccessibilityFocusedAttribute]) {
986 return iface->state().focusable ? YES : NO;
987 } else if ([attribute isEqualToString:NSAccessibilityValueAttribute]) {
988 if (iface->textInterface() && iface->state().editable)
989 return YES;
990 if (iface->valueInterface())
991 return YES;
992 return NO;
993 } else if ([attribute isEqualToString:NSAccessibilitySelectedTextRangeAttribute]) {
994 return iface->textInterface() ? YES : NO;
995 }
996 return NO;
997}
998
999- (void)accessibilitySetValue:(id)value forAttribute:(NSString *)attribute {
1000 QAccessibleInterface *iface = self.qtInterface;
1001 if (!iface)
1002 return;
1003 if ([attribute isEqualToString:NSAccessibilityFocusedAttribute]) {
1004 if (QAccessibleActionInterface *action = iface->actionInterface())
1005 action->doAction(QAccessibleActionInterface::setFocusAction());
1006 } else if ([attribute isEqualToString:NSAccessibilityValueAttribute]) {
1007 if (iface->textInterface()) {
1008 QString text = QString::fromNSString((NSString *)value);
1009 iface->setText(QAccessible::Value, text);
1010 } else if (QAccessibleValueInterface *valueIface = iface->valueInterface()) {
1011 double val = [value doubleValue];
1012 valueIface->setCurrentValue(val);
1013 }
1014 } else if ([attribute isEqualToString:NSAccessibilitySelectedTextRangeAttribute]) {
1015 if (QAccessibleTextInterface *text = iface->textInterface()) {
1016 NSRange range = [value rangeValue];
1017 if (range.length > 0)
1018 text->setSelection(0, range.location, range.location + range.length);
1019 else
1020 text->setCursorPosition(range.location);
1021 }
1022 }
1023}
1024
1025// actions
1026
1027- (NSArray *)accessibilityActionNames {
1028 NSMutableArray *nsActions = [[NSMutableArray new] autorelease];
1029 QAccessibleInterface *iface = self.qtInterface;
1030 if (!iface)
1031 return nsActions;
1032
1033 const QStringList &supportedActionNames = QAccessibleBridgeUtils::effectiveActionNames(iface);
1034 for (const QString &qtAction : supportedActionNames) {
1035 NSString *nsAction = QCocoaAccessible::getTranslatedAction(qtAction);
1036 // Several Qt actions translate to the same NSAccessibility action
1037 // (press and toggle both are AXPress). List the action only once.
1038 if (nsAction && ![nsActions containsObject:nsAction])
1039 [nsActions addObject : nsAction];
1040 }
1041
1042 return nsActions;
1043}
1044
1045- (NSString *)accessibilityActionDescription:(NSString *)action {
1046 QAccessibleInterface *iface = self.qtInterface;
1047 if (!iface)
1048 return nil; // FIXME is that the right return type??
1049 QString qtAction = QCocoaAccessible::translateAction(action, iface);
1050 QString description;
1051 // Return a description from the action interface if this action is not known to the OS.
1052 if (qtAction.isEmpty()) {
1053 if (QAccessibleActionInterface *actionInterface = iface->actionInterface()) {
1054 qtAction = QString::fromNSString((NSString *)action);
1055 description = actionInterface->localizedActionDescription(qtAction);
1056 }
1057 } else {
1058 description = qAccessibleLocalizedActionDescription(qtAction);
1059 }
1060 return description.toNSString();
1061}
1062
1063- (void)accessibilityPerformAction:(NSString *)action {
1064 if (QAccessibleInterface *iface = self.qtInterface) {
1065 const QString qtAction = QCocoaAccessible::translateAction(action, iface);
1066 QAccessibleBridgeUtils::performEffectiveAction(iface, qtAction);
1067 }
1068}
1069
1070// misc
1071
1072- (BOOL)accessibilityIsIgnored {
1073 // Short-cut for placeholders and synthesized elements. Working around a bug
1074 // that corrups lists returned by NSAccessibilityUnignoredChildren, otherwise
1075 // we could ignore rows and columns that are outside the table.
1076 if (self.isManagedByParent)
1077 return false;
1078
1079 if (QAccessibleInterface *iface = self.qtInterface)
1080 return QCocoaAccessible::shouldBeIgnored(iface);
1081 return true;
1082}
1083
1084- (id)accessibilityHitTest:(NSPoint)point
1085{
1086 QAccessibleInterface *iface = self.qtInterface;
1087 if (!iface)
1088 return NSAccessibilityUnignoredAncestor(self);
1089
1090 QPointF screenPoint = QCocoaScreen::mapFromNative(point);
1091 QWindow *window = QAccessibleBridgeUtils::windowFor(iface);
1092
1093 // Find the deepest child at the point, stopping where a child lives in a
1094 // window of its own, as that window's view answers for its own content.
1095 QAccessibleInterface *childInterface = iface;
1096 while (QAccessibleInterface *child = childInterface->childAt(screenPoint.x(), screenPoint.y())) {
1097 if (!child->isValid())
1098 break;
1099
1100 QWindow *childWindow = QAccessibleBridgeUtils::windowFor(child, childInterface, window);
1101 if (childWindow != window) {
1102 if (auto *view = QCocoaAccessible::accessibleViewFor(childWindow))
1103 return [view accessibilityHitTest:point];
1104 }
1105
1106 childInterface = child;
1107 }
1108
1109 // No child found, meaning we hit this element.
1110 if (childInterface == iface)
1111 return NSAccessibilityUnignoredAncestor(self);
1112
1113 // hit a child, forward to child accessible interface.
1114 QMacAccessibilityElement *accessibleElement = [QMacAccessibilityElement elementWithInterface:childInterface];
1115 if (accessibleElement)
1116 return NSAccessibilityUnignoredAncestor(accessibleElement);
1117 return NSAccessibilityUnignoredAncestor(self);
1118}
1119
1120- (id)accessibilityFocusedUIElement {
1121 QAccessibleInterface *iface = self.qtInterface;
1122 if (!iface) {
1123 qWarning("FocusedUIElement for INVALID");
1124 return nil;
1125 }
1126
1127 QAccessibleInterface *focusInterface = iface->focusChild();
1128 if (focusInterface && focusInterface->isValid()) {
1129 // The focus may have moved into a window of its own, whose view answers
1130 // for its own content. QAccessibleWindow::focusChild() reports
1131 // the child window holding the focus, so this is the ordinary way for
1132 // the focus to leave our window. Note that focusChild() answers with
1133 // the deepest focused interface, which may be any depth below us, and
1134 // need not report a window of its own.
1135 QWindow *window = QAccessibleBridgeUtils::windowFor(iface);
1136 QWindow *focusWindow = QAccessibleBridgeUtils::windowFor(focusInterface, iface, window);
1137 if (focusWindow != window) {
1138 if (auto *view = QCocoaAccessible::accessibleViewFor(focusWindow))
1139 return [view accessibilityFocusedUIElement];
1140 }
1141
1142 QMacAccessibilityElement *accessibleElement = [QMacAccessibilityElement elementWithInterface:focusInterface];
1143 return NSAccessibilityUnignoredAncestor(accessibleElement);
1144 }
1145
1146 return NSAccessibilityUnignoredAncestor(self);
1147}
1148
1149- (NSString *) accessibilityHelp {
1150 if (QAccessibleInterface *iface = self.qtInterface) {
1151 const QString helpText = iface->text(QAccessible::Help);
1152 if (!helpText.isEmpty())
1153 return helpText.toNSString();
1154 }
1155 return nil;
1156}
1157
1158/*
1159 * Support for table
1160 */
1161- (NSInteger) accessibilityIndex {
1162 NSInteger index = 0;
1163 if (synthesizedRole == NSAccessibilityCellRole)
1164 return m_columnIndex;
1165 if (QAccessibleInterface *iface = self.qtInterface) {
1166 if (self.isManagedByParent) {
1167 // axid matches the parent table axid so that we can easily find the parent table
1168 // children of row are cell/any items
1169 if (iface->tableInterface()) {
1170 if (m_rowIndex >= 0)
1171 index = NSInteger(m_rowIndex);
1172 else if (m_columnIndex >= 0)
1173 index = NSInteger(m_columnIndex);
1174 }
1175 }
1176 }
1177 return index;
1178}
1179
1180- (NSArray *) accessibilityRows {
1181 if (!synthesizedRole && rows) {
1182 QAccessibleInterface *iface = self.qtInterface;
1183 QAccessibleTableInterface *tableInterface = iface ? iface->tableInterface() : nullptr;
1184 if (tableInterface) {
1185 const unsigned int rowCount = tableInterface->rowCount();
1186 if (rows.count != rowCount) {
1187 qCDebug(lcAccessibilityTable) << "Updating table rows with" << rowCount << "rows";
1188 if (rows) {
1189 [rows autorelease];
1190 rows = nil;
1191 }
1192 rows = [self populateTableArray:NSAccessibilityRowRole
1193 count:rowCount];
1194 [rows retain];
1195 }
1196 return NSAccessibilityUnignoredChildren(rows);
1197 }
1198 }
1199 return nil;
1200}
1201
1202- (NSArray *) accessibilityColumns {
1203 // we only implement this for a table, not for rows
1204 if (!synthesizedRole && columns) {
1205 QAccessibleInterface *iface = self.qtInterface;
1206 if (iface && iface->tableInterface())
1207 return NSAccessibilityUnignoredChildren(columns);
1208 }
1209 return nil;
1210}
1211
1212// tabs
1213
1214- (NSArray *) accessibilityTabs {
1215 QAccessibleInterface *iface = self.qtInterface;
1216 if (iface && iface->role() == QAccessible::PageTabList) {
1217 return QCocoaAccessible::unignoredChildren(iface, [](QAccessibleInterface *child){
1218 return QCocoaAccessible::defaultUnignored(child)
1219 && child->role() == QAccessible::PageTab;
1220 });
1221 }
1222 return nil;
1223}
1224
1225@end
1226
1227#endif // QT_CONFIG(accessibility)