File: AXLiveRegionManager.cpp

package info (click to toggle)
webkit2gtk 2.51.3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 477,912 kB
  • sloc: cpp: 3,898,343; javascript: 198,215; ansic: 165,229; python: 50,371; asm: 21,819; ruby: 18,095; perl: 16,953; xml: 4,623; sh: 2,398; yacc: 2,356; java: 2,019; lex: 1,358; pascal: 372; makefile: 197
file content (406 lines) | stat: -rw-r--r-- 15,541 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
 * Copyright (C) 2025 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "AXLiveRegionManager.h"

#if PLATFORM(COCOA)

#include "AXNotifications.h"
#include "AXObjectCache.h"
#include "AccessibilityObject.h"
#include "LocalizedStrings.h"
#include <wtf/TZoneMallocInlines.h>

namespace WebCore {

WTF_MAKE_TZONE_ALLOCATED_IMPL(AXLiveRegionManager);

#if PLATFORM(MAC)
static constexpr ASCIILiteral accessibilityLanguageAttributeKey = "AXLanguage"_s;
#else
static constexpr ASCIILiteral accessibilityLanguageAttributeKey = "UIAccessibilitySpeechAttributeLanguage"_s;
#endif

struct LiveRegionObjectMetadata {
    String text;
    String language;
    HashSet<AXID> descendants;
};

AXLiveRegionManager::AXLiveRegionManager(AXObjectCache& cache)
    : m_cache(cache)
{
}

static UNUSED_FUNCTION String debugDescriptionForSnapshot(LiveRegionSnapshot snapshot)
{
    StringBuilder result;
    result.append("SNAPSHOT:\n"_s);
    result.append("\tStatus: "_s);

    switch (snapshot.liveRegionStatus) {
    case LiveRegionStatus::Off:
        result.append("Off"_s);
        break;
    case LiveRegionStatus::Polite:
        result.append("Polite"_s);
        break;
    case LiveRegionStatus::Assertive:
        result.append("Assertive"_s);
        break;
    }
    result.append('\n');

    result.append("\tRelevant: "_s);
    if (snapshot.liveRegionRelevant.isEmpty())
        result.append("(default: additions text)"_s);
    else {
        bool isFirst = true;
        if (snapshot.liveRegionRelevant.contains(LiveRegionRelevant::Additions)) {
            result.append("additions"_s);
            isFirst = false;
        }
        if (snapshot.liveRegionRelevant.contains(LiveRegionRelevant::Removals)) {
            if (!isFirst)
                result.append(' ');
            result.append("removals"_s);
            isFirst = false;
        }
        if (snapshot.liveRegionRelevant.contains(LiveRegionRelevant::Text)) {
            if (!isFirst)
                result.append(' ');
            result.append("text"_s);
            isFirst = false;
        }
        if (snapshot.liveRegionRelevant.contains(LiveRegionRelevant::All)) {
            if (!isFirst)
                result.append(' ');
            result.append("all"_s);
        }
    }
    result.append('\n');

    result.append("\tObjects: "_s);
    result.append(snapshot.objects.size());
    result.append('\n');

    for (size_t i = 0; i < snapshot.objects.size(); ++i) {
        const auto& object = snapshot.objects[i];
        result.append("\t\t["_s);
        result.append(i);
        result.append("] AXID="_s);
        result.append(object.objectID.loggingString());
        result.append(" text=\""_s);
        result.append(object.text);
        result.append("\"\n"_s);
    }

    return result.toString();
}

void AXLiveRegionManager::registerLiveRegion(AccessibilityObject& object, bool speakIfNecessary)
{
    m_liveRegions.set(object.objectID(), buildLiveRegionSnapshot(object));
    // Alerts should speak when added to the page (or initialized for the first time), unlike all other live regions.
    bool isAlertOrAlertDialog = speakIfNecessary && (object.role() == AccessibilityRole::ApplicationAlert || object.role() == AccessibilityRole::ApplicationAlertDialog);
    if (isAlertOrAlertDialog)
        handleLiveRegionChange(object, AnnouncementContents::All);
}

static LiveRegionStatus stringToLiveRegionStatus(const String& string)
{
    String lowercaseString = string.convertToASCIILowercase();
    if (lowercaseString == "assertive")
        return LiveRegionStatus::Assertive;
    if (lowercaseString == "polite")
        return LiveRegionStatus::Polite;

    return LiveRegionStatus::Off;
}

static OptionSet<LiveRegionRelevant> stringToLiveRegionRelevant(const String& string)
{
    Vector<String> strings = string.convertToASCIILowercase().split(" "_s);
    OptionSet<LiveRegionRelevant> result;
    for (const auto& attribute : strings) {
        if (attribute == "additions")
            result.add(LiveRegionRelevant::Additions);
        else if (attribute == "all")
            result.add(LiveRegionRelevant::All);
        else if (attribute == "removals")
            result.add(LiveRegionRelevant::Removals);
        else if (attribute == "text")
            result.add(LiveRegionRelevant::Text);
    }
    return result;
}

void AXLiveRegionManager::handleLiveRegionChange(AccessibilityObject& object, AnnouncementContents contents)
{
    // If this is a new live region, don't speak it upon registering.
    auto iterator = m_liveRegions.find(object.objectID());
    if (iterator == m_liveRegions.end()) {
        registerLiveRegion(object);
        return;
    }

    LiveRegionSnapshot oldSnapshot = contents == AnnouncementContents::All ? LiveRegionSnapshot { } : iterator->value;
    LiveRegionSnapshot newSnapshot = buildLiveRegionSnapshot(object);

    iterator->value = newSnapshot;

    postAnnouncementForChange(object, oldSnapshot, newSnapshot);
}

LiveRegionSnapshot AXLiveRegionManager::buildLiveRegionSnapshot(AccessibilityObject& object) const
{
    LiveRegionSnapshot snapshot;
    snapshot.liveRegionStatus = stringToLiveRegionStatus(object.liveRegionStatus());
    snapshot.liveRegionRelevant = stringToLiveRegionRelevant(object.liveRegionRelevant());

    std::function<void(AccessibilityObject&)> buildObjectList = [this, &buildObjectList, &snapshot] (AccessibilityObject& object) {
        // Treat atomic objects as one object, so when they change the entire subtree is announced.
        if (object.liveRegionAtomic()) {
            HashSet<AXID> descendants;

            // Collect all atomic-region descendants to detect when nodes are added/removed within the atomic region.
            std::function<void(AccessibilityObject&)> collectDescendants = [&collectDescendants, &descendants] (AccessibilityObject& descendant) {
                descendants.add(descendant.objectID());
                for (auto& child : descendant.unignoredChildren())
                    collectDescendants(downcast<AccessibilityObject>(child.get()));
            };

            for (auto& child : object.unignoredChildren())
                collectDescendants(downcast<AccessibilityObject>(child.get()));

            snapshot.objects.append({ object.objectID(), textForObject(object), object.languageIncludingAncestors(), WTFMove(descendants) });
            return;
        }

        if (shouldIncludeInSnapshot(object))
            snapshot.objects.append({ object.objectID(), textForObject(object), object.languageIncludingAncestors(), { } });

        for (auto& child : object.unignoredChildren())
            buildObjectList(downcast<AccessibilityObject>(child.get()));
    };

    buildObjectList(object);

    return snapshot;
}

bool AXLiveRegionManager::shouldIncludeInSnapshot(AccessibilityObject& object) const
{
    if (object.isStaticText())
        return true;

    // If an object has unignored children, there isn't a need to include it in the snapshot since the children will return YES.
    if (object.hasUnignoredChild())
        return false;

    // For leaf objects, include if they have a value (e.g., form controls).
    if (!object.stringValue().isEmpty())
        return true;

#if PLATFORM(COCOA)
    // For leaf objects, include if they have accessible description text (e.g., images with alt text).
    if (!object.descriptionAttributeValue().isEmpty())
        return true;
#endif

    return false;
}

String AXLiveRegionManager::textForObject(AccessibilityObject& object) const
{
    return object.textMarkerRange().toString(IncludeListMarkerText::Yes, IncludeImageAltText::Yes);
}

AXLiveRegionManager::LiveRegionDiff AXLiveRegionManager::computeChanges(const Vector<LiveRegionObject>& oldObjects, const Vector<LiveRegionObject>& newObjects) const
{
    // Here we compare the old and new live region to compute:
    // - Additions: New objects, or atomic regions where nodes were added AND text changed.
    // - Deletions: Objects that were removed from the region, or atomic regions where nodes were removed AND text changed.
    // - Changes: Text content/values that changed between the same object (without node additions/removals).

    LiveRegionDiff diff;

    // Build a map of old objects for lookup. As we match them with new objects, we'll remove them.
    // Whatever remains unmatched at the end represents removals.
    HashMap<AXID, LiveRegionObjectMetadata> unmatchedOldObjects;
    unmatchedOldObjects.reserveInitialCapacity(oldObjects.size());

    for (auto& object : oldObjects)
        unmatchedOldObjects.set(object.objectID, LiveRegionObjectMetadata { object.text, object.language, object.descendants });

    for (auto& newObject : newObjects) {
        auto iterator = unmatchedOldObjects.find(newObject.objectID);
        if (iterator == unmatchedOldObjects.end())
            diff.added.append(newObject);
        else {
            bool textChanged = iterator->value.text != newObject.text;

            if (!newObject.descendants.isEmpty()) {
                // This is an atomic region, indicated by the presence of children.
                HashSet oldDescendantsCopy = iterator->value.descendants;
                HashSet newDescendantsCopy = newObject.descendants;

                newDescendantsCopy.removeAll(oldDescendantsCopy);
                oldDescendantsCopy.removeAll(newObject.descendants);
                bool nodesAdded = newDescendantsCopy.size();
                bool nodesRemoved = oldDescendantsCopy.size();

                if (nodesAdded && textChanged)
                    diff.added.append(newObject);
                else if (nodesRemoved && textChanged)
                    diff.removed.append(newObject);

                if (textChanged)
                    diff.changed.append(newObject);
            } else if (textChanged)
                diff.changed.append(newObject);

            unmatchedOldObjects.remove(iterator);
        }
    }

    // Anything left in unmatchedOldObjects is a removal.
    for (auto& entry : unmatchedOldObjects)
        diff.removed.append({ entry.key, entry.value.text, entry.value.language, { } });

    return diff;
}

static const size_t maximumAnnouncementLength = 2500;

AttributedString AXLiveRegionManager::computeAnnouncement(const LiveRegionSnapshot& newSnapshot, const LiveRegionDiff& diff) const
{
    bool hasAll = newSnapshot.liveRegionRelevant.contains(LiveRegionRelevant::All);
    bool hasAdditions = hasAll || newSnapshot.liveRegionRelevant.contains(LiveRegionRelevant::Additions);
    bool hasRemovals = hasAll || newSnapshot.liveRegionRelevant.contains(LiveRegionRelevant::Removals);
    bool hasText = hasAll || newSnapshot.liveRegionRelevant.contains(LiveRegionRelevant::Text);

    StringBuilder stringBuilder;
    Vector<std::pair<AttributedString::Range, HashMap<String, AttributedString::AttributeValue>>> attributes;

    bool reachedCharacterLimit = false;
    size_t characterCount = 0;

    HashSet<AXID> spokenObjects = { };

    // Determines whether we should add a space before adding the next object. Should only be false the first call.
    bool needsSpace = false;

    auto appendStringAndLanguage = [&](const LiveRegionObject& object) {
        if (object.text.isEmpty() || spokenObjects.contains(object.objectID))
            return;

        if (needsSpace) {
            stringBuilder.append(' ');
            characterCount++;
        }

        uint64_t startLocation = stringBuilder.length();
        stringBuilder.append(object.text);
        characterCount += object.text.length();

        if (!object.language.isEmpty()) {
            HashMap<String, AttributedString::AttributeValue> languageAttribute;
            languageAttribute.set(accessibilityLanguageAttributeKey, AttributedString::AttributeValue { object.language });
            attributes.append({ { startLocation, object.text.length() }, WTFMove(languageAttribute) });
        }

        needsSpace = true;
        spokenObjects.add(object.objectID);
    };

    if (hasAdditions && !diff.added.isEmpty()) {
        for (auto& object : diff.added) {
            appendStringAndLanguage(object);

            if (characterCount > maximumAnnouncementLength) {
                reachedCharacterLimit = true;
                break;
            }
        }
    }

    if (!reachedCharacterLimit && hasRemovals && !diff.removed.isEmpty()) {
        if (needsSpace) {
            stringBuilder.append(' ');
            characterCount++;
        }

        String removalPrefix = AXRemovedText();
        characterCount += removalPrefix.length();
        stringBuilder.append(WTFMove(removalPrefix));
        needsSpace = true;

        for (auto& object : diff.removed) {
            appendStringAndLanguage(object);

            if (characterCount > maximumAnnouncementLength) {
                reachedCharacterLimit = true;
                break;
            }
        }
    }

    if (!reachedCharacterLimit && hasText && !diff.changed.isEmpty()) {
        for (auto& object : diff.changed) {
            appendStringAndLanguage(object);

            if (characterCount > maximumAnnouncementLength) {
                reachedCharacterLimit = true;
                break;
            }
        }
    }

    auto string = stringBuilder.toString();
    return AttributedString { WTFMove(string), WTFMove(attributes), std::nullopt };
}

void AXLiveRegionManager::postAnnouncementForChange(AccessibilityObject& object, const LiveRegionSnapshot& oldSnapshot, const LiveRegionSnapshot& newSnapshot)
{
    auto diff = computeChanges(oldSnapshot.objects, newSnapshot.objects);
    if (diff.added.isEmpty() && diff.removed.isEmpty() && diff.changed.isEmpty())
        return;

    AttributedString announcement = computeAnnouncement(newSnapshot, diff);
    if (announcement.isNull())
        return;

    if (CheckedPtr cache = m_cache)
        cache->postLiveRegionNotification(object, newSnapshot.liveRegionStatus, announcement);
}

} // namespace WebCore

#endif // PLATFORM(COCOA)