Bug Summary

File:root/firefox-clang/obj-x86_64-pc-linux-gnu/accessible/generic/./../../../accessible/generic/LocalAccessible.cpp
Warning:line 3247, column 11
Although the value stored to 'selected' is used in the enclosing expression, the value is never actually read from 'selected'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Unified_cpp_accessible_generic0.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/accessible/generic -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/accessible/generic -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -D _GLIBCXX_ASSERTIONS=1 -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D MOZ_SUPPORT_LEAKCHECKING -D STATIC_EXPORTABLE_JS_API -I /root/firefox-clang/accessible/generic -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/accessible/generic -I /root/firefox-clang/accessible/base -I /root/firefox-clang/accessible/html -I /root/firefox-clang/accessible/xpcom -I /root/firefox-clang/accessible/xul -I /root/firefox-clang/dom/base -I /root/firefox-clang/dom/xul -I /root/firefox-clang/layout/generic -I /root/firefox-clang/layout/xul -I /root/firefox-clang/accessible/atk -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /root/firefox-clang/ipc/chromium/src -I /root/firefox-clang/third_party/abseil-cpp -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=pessimizing-move -Wno-error=large-by-value-copy=128 -Wno-error=implicit-int-float-conversion -Wno-error=thread-safety-analysis -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -Wno-character-conversion -std=gnu++20 -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fno-implicit-modules -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-11-25-110557-2966600-1 -x c++ Unified_cpp_accessible_generic0.cpp
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5#include "AccEvent.h"
6#include "AccGroupInfo.h"
7#include "AccIterator.h"
8#include "ApplicationAccessible.h"
9#include "CachedTableAccessible.h"
10#include "DocAccessible-inl.h"
11#include "EmbeddedObjCollector.h"
12#include "EventTree.h"
13#include "HTMLElementAccessibles.h"
14#include "HTMLSelectAccessible.h"
15#include "HTMLTableAccessible.h"
16#include "ImageAccessible.h"
17#include "LocalAccessible-inl.h"
18#include "NotificationController.h"
19#include "OuterDocAccessible.h"
20#include "Pivot.h"
21#include "Relation.h"
22#include "RootAccessible.h"
23#include "States.h"
24#include "TextLeafAccessible.h"
25#include "TextLeafRange.h"
26#include "TextRange.h"
27#include "mozilla/Assertions.h"
28#include "mozilla/BasicEvents.h"
29#include "mozilla/ErrorResult.h"
30#include "mozilla/FloatingPoint.h"
31#include "mozilla/FocusModel.h"
32#include "mozilla/PerfStats.h"
33#include "mozilla/PresShell.h"
34#include "mozilla/ProfilerMarkers.h"
35#include "mozilla/ScrollContainerFrame.h"
36#include "mozilla/StaticPrefs_accessibility.h"
37#include "mozilla/StaticPrefs_dom.h"
38#include "mozilla/StaticPrefs_ui.h"
39#include "mozilla/a11y/AccAttributes.h"
40#include "mozilla/a11y/DocAccessibleChild.h"
41#include "mozilla/a11y/Platform.h"
42#include "mozilla/a11y/Role.h"
43#include "mozilla/dom/ContentList.h"
44#include "mozilla/dom/Document.h"
45#include "mozilla/dom/Element.h"
46#include "mozilla/dom/HTMLAnchorElement.h"
47#include "mozilla/dom/HTMLFormElement.h"
48#include "mozilla/dom/HTMLHeadingElement.h"
49#include "mozilla/dom/HTMLInputElement.h"
50#include "mozilla/dom/HTMLLabelElement.h"
51#include "mozilla/dom/KeyboardEventBinding.h"
52#include "mozilla/dom/NodeList.h"
53#include "mozilla/dom/PopoverData.h"
54#include "mozilla/dom/TreeWalker.h"
55#include "mozilla/dom/UserActivation.h"
56#include "mozilla/gfx/Matrix.h"
57#include "nsAccUtils.h"
58#include "nsAccessibilityService.h"
59#include "nsAtom.h"
60#include "nsComputedDOMStyle.h"
61#include "nsContainerFrame.h"
62#include "nsCoreUtils.h"
63#include "nsDisplayList.h"
64#include "nsEventShell.h"
65#include "nsFocusManager.h"
66#include "nsGenericHTMLElement.h"
67#include "nsGkAtoms.h"
68#include "nsIContent.h"
69#include "nsIDOMXULButtonElement.h"
70#include "nsIDOMXULSelectCntrlEl.h"
71#include "nsIDOMXULSelectCntrlItemEl.h"
72#include "nsIDocShellTreeItem.h"
73#include "nsIFormControl.h"
74#include "nsIFrame.h"
75#include "nsIMutationObserver.h"
76#include "nsLayoutUtils.h"
77#include "nsMenuPopupFrame.h"
78#include "nsPresContext.h"
79#include "nsString.h"
80#include "nsStyleStructInlines.h"
81#include "nsTextEquivUtils.h"
82#include "nsTextFrame.h"
83
84using namespace mozilla;
85using namespace mozilla::a11y;
86
87////////////////////////////////////////////////////////////////////////////////
88// LocalAccessible: nsISupports and cycle collection
89
90NS_IMPL_CYCLE_COLLECTION_CLASS(LocalAccessible)LocalAccessible::cycleCollection LocalAccessible::_cycleCollectorGlobal
;
91NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(LocalAccessible)void LocalAccessible::cycleCollection::Unlink(void* p) { LocalAccessible
* tmp = DowncastCCParticipant<LocalAccessible>(p);
92 tmp->Shutdown();
93NS_IMPL_CYCLE_COLLECTION_UNLINK_END(void)tmp; }
94NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(LocalAccessible)nsresult LocalAccessible::cycleCollection::TraverseNative( void
* p, nsCycleCollectionTraversalCallback& cb) { LocalAccessible
* tmp = DowncastCCParticipant<LocalAccessible>(p); cb.DescribeRefCountedNode
(tmp->mRefCnt.get(), "LocalAccessible");
95 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContent, mDoc)ImplCycleCollectionTraverse(cb, tmp->mContent, "mContent",
0); ImplCycleCollectionTraverse(cb, tmp->mDoc, "mDoc", 0)
;
96NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END(void)tmp; return NS_OK; }
97
98NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(LocalAccessible)nsresult LocalAccessible::QueryInterface(const nsIID& aIID
, void** aInstancePtr) { do { if (!(aInstancePtr)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "QueryInterface requires a non-NULL destination!"
, "aInstancePtr", "./../../../accessible/generic/LocalAccessible.cpp"
, 98); MOZ_PretendNoReturn(); } } while (0); nsISupports* foundInterface
; if (TopThreeWordsEquals( aIID, (nsXPCOMCycleCollectionParticipant
::kIID), (nsCycleCollectionISupports::kIID)) && (LowWordEquals
(aIID, (nsXPCOMCycleCollectionParticipant::kIID)) || LowWordEquals
(aIID, (nsCycleCollectionISupports::kIID)))) { if (LowWordEquals
(aIID, (nsXPCOMCycleCollectionParticipant::kIID))) { *aInstancePtr
= LocalAccessible::cycleCollection::GetParticipant(); return
NS_OK; } if (LowWordEquals(aIID, (nsCycleCollectionISupports
::kIID))) { *aInstancePtr = LocalAccessible::cycleCollection::
Upcast(this); return NS_OK; } foundInterface = nullptr; } else
99 NS_INTERFACE_MAP_ENTRY_CONCRETE(LocalAccessible)if (aIID.Equals(mozilla::detail::kImplementedIID<std::remove_reference_t
<decltype(*this)>, LocalAccessible>)) { *aInstancePtr
= do_AddRef(static_cast<LocalAccessible*>(this)).take(
); return NS_OK; } else
100 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, LocalAccessible)if (aIID.Equals(mozilla::detail::kImplementedIID<std::remove_reference_t
<decltype(*this)>, nsISupports>)) foundInterface = static_cast
<nsISupports*>(static_cast<LocalAccessible*>(this
)); else
101NS_INTERFACE_MAP_ENDfoundInterface = 0; nsresult status; if (!foundInterface) { do
{ static_assert( mozilla::detail::AssertionConditionType<
decltype(!aIID.Equals((nsISupports::kIID)))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aIID.Equals((nsISupports::kIID
))))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!aIID.Equals((nsISupports::kIID))", "./../../../accessible/generic/LocalAccessible.cpp"
, 101); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aIID.Equals((nsISupports::kIID))"
")"); do { MOZ_CrashSequence(__null, 101); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); status = NS_NOINTERFACE
; } else { (foundInterface)->AddRef(); status = NS_OK; } *
aInstancePtr = foundInterface; return status; }
102
103NS_IMPL_CYCLE_COLLECTING_ADDREF(LocalAccessible)MozExternalRefCountType LocalAccessible::AddRef(void) { static_assert
(!std::is_destructible_v<LocalAccessible>, "Reference-counted class "
"LocalAccessible" " should not have a public destructor. " "Make this class's destructor non-public"
); do { static_assert( mozilla::detail::AssertionConditionType
<decltype(int32_t(mRefCnt) >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) >= 0))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) >= 0"
" (" "illegal refcnt" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 103); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) >= 0"
") (" "illegal refcnt" ")"); do { MOZ_CrashSequence(__null, 103
); __attribute__((nomerge)) ::abort(); } while (false); } } while
(false); _mOwningThread.AssertOwnership("LocalAccessible" " not thread-safe"
); nsISupports* base = LocalAccessible::cycleCollection::Upcast
(this); nsrefcnt count = mRefCnt.incr(base); NS_LogAddRef((this
), (count), ("LocalAccessible"), (uint32_t)(sizeof(*this))); return
count; }
104NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_DESTROY(LocalAccessible, LastRelease())MozExternalRefCountType LocalAccessible::Release(void) { do {
static_assert( mozilla::detail::AssertionConditionType<decltype
(int32_t(mRefCnt) > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) > 0))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) > 0"
" (" "dup release" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 104); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) > 0"
") (" "dup release" ")"); do { MOZ_CrashSequence(__null, 104
); __attribute__((nomerge)) ::abort(); } while (false); } } while
(false); _mOwningThread.AssertOwnership("LocalAccessible" " not thread-safe"
); nsISupports* base = LocalAccessible::cycleCollection::Upcast
(this); nsrefcnt count = mRefCnt.decr(base); if (count == 0) {
NS_CycleCollectableHasRefCntZero(); } NS_LogRelease((this), (
count), ("LocalAccessible")); return count; } void LocalAccessible
::DeleteCycleCollectable(void) { LastRelease(); }
105
106LocalAccessible::LocalAccessible(nsIContent* aContent, DocAccessible* aDoc)
107 : mContent(aContent),
108 mDoc(aDoc),
109 mParent(nullptr),
110 mIndexInParent(-1),
111 mFirstLineStart(-1),
112 mStateFlags(0),
113 mContextFlags(0),
114 mReorderEventTarget(false),
115 mShowEventTarget(false),
116 mHideEventTarget(false),
117 mIndexOfEmbeddedChild(-1),
118 mGroupInfo(nullptr) {}
119
120LocalAccessible::~LocalAccessible() {
121 NS_ASSERTION(!mDoc, "LastRelease was never called!?!")do { if (!(!mDoc)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "LastRelease was never called!?!"
, "!mDoc", "./../../../accessible/generic/LocalAccessible.cpp"
, 121); MOZ_PretendNoReturn(); } } while (0)
;
122}
123
124ENameValueFlag LocalAccessible::DirectName(nsString& aName) const {
125 if (!HasOwnContent()) return eNameOK;
126
127 ENameValueFlag nameFlag = ARIAName(aName);
128 if (!aName.IsEmpty()) return nameFlag;
129
130 nameFlag = NativeName(aName);
131 aName.CompressWhitespace();
132
133 return nameFlag;
134}
135
136ENameValueFlag LocalAccessible::Name(nsString& aName) const {
137 aName.Truncate();
138
139 ENameValueFlag nameFlag = DirectName(aName);
140 if (!aName.IsEmpty()) return nameFlag;
141
142 nsTextEquivUtils::GetNameFromSubtree(this, aName);
143 if (!aName.IsEmpty()) return eNameFromSubtree;
144
145 // In the end get the name from tooltip.
146 if (Tooltip(aName)) {
147 return eNameFromTooltip;
148 }
149
150 if (Maybe<nsString> cssAlt = nsCoreUtils::GetCssAltContent(mContent)) {
151 // This covers two cases:
152 // 1. The CSS content property replaces the content of an element with an
153 // image plus alt text.
154 // 2. Alt text is provided for a pseudo-element image.
155 aName.Append(*cssAlt);
156 return eNameOK;
157 }
158
159 aName.SetIsVoid(true);
160
161 return eNameOK;
162}
163
164EDescriptionValueFlag LocalAccessible::Description(
165 nsString& aDescription) const {
166 // There are 4 conditions that make an accessible have no accDescription:
167 // 1. it's a text node; or
168 // 2. It has no ARIA describedby or description property
169 // 3. it doesn't have an accName; or
170 // 4. its title attribute already equals to its accName nsAutoString name;
171
172 EDescriptionValueFlag descFlag = eDescriptionOK;
173 aDescription.Truncate();
174
175 if (!HasOwnContent() || mContent->IsText()) {
176 return descFlag;
177 }
178
179 if (ARIADescription(aDescription)) {
180 descFlag = eDescriptionFromARIA;
181 }
182
183 if (aDescription.IsEmpty()) {
184 NativeDescription(aDescription);
185 aDescription.CompressWhitespace();
186 }
187
188 if (aDescription.IsEmpty()) {
189 Tooltip(aDescription);
190 }
191
192 if (!aDescription.IsEmpty()) {
193 nsAutoString name;
194 Name(name);
195 // Don't expose a description if it is the same as the name.
196 if (aDescription.Equals(name)) aDescription.Truncate();
197 }
198
199 return descFlag;
200}
201
202KeyBinding LocalAccessible::AccessKey() const {
203 if (!HasOwnContent()) return KeyBinding();
204
205 uint32_t key = nsCoreUtils::GetAccessKeyFor(mContent);
206 if (!key && mContent->IsElement()) {
207 LocalAccessible* label = nullptr;
208
209 // Copy access key from label node.
210 if (mContent->IsHTMLElement()) {
211 // Unless it is labeled via an ancestor <label>, in which case that would
212 // be redundant.
213 HTMLLabelIterator iter(Document(), this,
214 HTMLLabelIterator::eSkipAncestorLabel);
215 label = iter.Next();
216 }
217 if (!label) {
218 XULLabelIterator iter(Document(), mContent);
219 label = iter.Next();
220 }
221
222 if (label) key = nsCoreUtils::GetAccessKeyFor(label->GetContent());
223 }
224
225 if (!key) return KeyBinding();
226
227 // Get modifier mask. Use ui.key.generalAccessKey (unless it is -1).
228 switch (StaticPrefs::ui_key_generalAccessKey()) {
229 case -1:
230 break;
231 case dom::KeyboardEvent_Binding::DOM_VK_SHIFT:
232 return KeyBinding(key, KeyBinding::kShift);
233 case dom::KeyboardEvent_Binding::DOM_VK_CONTROL:
234 return KeyBinding(key, KeyBinding::kControl);
235 case dom::KeyboardEvent_Binding::DOM_VK_ALT:
236 return KeyBinding(key, KeyBinding::kAlt);
237 case dom::KeyboardEvent_Binding::DOM_VK_META:
238 return KeyBinding(key, KeyBinding::kMeta);
239 default:
240 return KeyBinding();
241 }
242
243 // Determine the access modifier used in this context.
244 dom::Document* document = mContent->GetComposedDoc();
245 if (!document) return KeyBinding();
246
247 nsCOMPtr<nsIDocShellTreeItem> treeItem(document->GetDocShell());
248 if (!treeItem) return KeyBinding();
249
250 nsresult rv = NS_ERROR_FAILURE;
251 int32_t modifierMask = 0;
252 switch (treeItem->ItemType()) {
253 case nsIDocShellTreeItem::typeChrome:
254 modifierMask = StaticPrefs::ui_key_chromeAccess();
255 rv = NS_OK;
256 break;
257 case nsIDocShellTreeItem::typeContent:
258 modifierMask = StaticPrefs::ui_key_contentAccess();
259 rv = NS_OK;
260 break;
261 }
262
263 return NS_SUCCEEDED(rv)((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1))) ? KeyBinding(key, modifierMask) : KeyBinding();
264}
265
266KeyBinding LocalAccessible::KeyboardShortcut() const { return KeyBinding(); }
267
268uint64_t LocalAccessible::VisibilityState() const {
269 if (IPCAccessibilityActive()) {
270 // Visibility states must be calculated by RemoteAccessible, so there's no
271 // point calculating them here.
272 return 0;
273 }
274 nsIFrame* frame = GetFrame();
275 if (!frame) {
276 // Element having display:contents is considered visible semantically,
277 // despite it doesn't have a visually visible box.
278 if (nsCoreUtils::IsDisplayContents(mContent)) {
279 return states::OFFSCREEN;
280 }
281 return states::INVISIBLE;
282 }
283
284 if (!frame->StyleVisibility()->IsVisible()) return states::INVISIBLE;
285
286 // It's invisible if the presshell is hidden by a visibility:hidden element in
287 // an ancestor document.
288 if (frame->PresShell()->IsUnderHiddenEmbedderElement()) {
289 return states::INVISIBLE;
290 }
291
292 // Offscreen state if the document's visibility state is not visible.
293 if (Document()->IsHidden()) return states::OFFSCREEN;
294
295 // Walk the parent frame chain to see if the frame is in background tab or
296 // scrolled out.
297 nsIFrame* curFrame = frame;
298 do {
299 if (nsMenuPopupFrame* popup = do_QueryFrame(curFrame)) {
300 return popup->IsOpen() ? 0 : states::INVISIBLE;
301 }
302
303 if (curFrame->StyleUIReset()->mMozSubtreeHiddenOnlyVisually) {
304 // Offscreen state for background tab content.
305 return states::OFFSCREEN;
306 }
307
308 nsIFrame* parentFrame = curFrame->GetParent();
309 // If contained by scrollable frame then check that at least 12 pixels
310 // around the object is visible, otherwise the object is offscreen.
311 const nscoord kMinPixels = nsPresContext::CSSPixelsToAppUnits(12);
312 if (ScrollContainerFrame* scrollContainerFrame =
313 do_QueryFrame(parentFrame)) {
314 nsRect scrollPortRect = scrollContainerFrame->GetScrollPortRect();
315 nsRect frameRect = nsLayoutUtils::TransformFrameRectToAncestor(
316 frame, frame->GetRectRelativeToSelf(), parentFrame);
317 if (!scrollPortRect.Contains(frameRect)) {
318 scrollPortRect.Deflate(kMinPixels, kMinPixels);
319 if (!scrollPortRect.Intersects(frameRect)) return states::OFFSCREEN;
320 }
321 }
322
323 if (!parentFrame) {
324 parentFrame = nsLayoutUtils::GetCrossDocParentFrameInProcess(curFrame);
325 // Even if we couldn't find the parent frame, it might mean we are in an
326 // out-of-process iframe, try to see if |frame| is scrolled out in an
327 // scrollable frame in a cross-process ancestor document.
328 if (!parentFrame &&
329 nsLayoutUtils::FrameIsMostlyScrolledOutOfViewInCrossProcess(
330 frame, kMinPixels)) {
331 return states::OFFSCREEN;
332 }
333 }
334
335 curFrame = parentFrame;
336 } while (curFrame);
337
338 // Zero area rects can occur in the first frame of a multi-frame text flow,
339 // in which case the rendered text is not empty and the frame should not be
340 // marked invisible.
341 // XXX Can we just remove this check? Why do we need to mark empty
342 // text invisible?
343 if (frame->IsTextFrame() && !frame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW) &&
344 frame->GetRect().IsEmpty()) {
345 nsIFrame::RenderedText text = frame->GetRenderedText(
346 0, UINT32_MAX(4294967295U), nsIFrame::TextOffsetType::OffsetsInContentText,
347 nsIFrame::TrailingWhitespace::DontTrim);
348 if (text.mString.IsEmpty()) {
349 return states::INVISIBLE;
350 }
351 }
352
353 return 0;
354}
355
356uint64_t LocalAccessible::NativeState() const {
357 uint64_t state = 0;
358
359 if (!IsInDocument()) state |= states::STALE;
360
361 if (HasOwnContent() && mContent->IsElement()) {
362 dom::ElementState elementState = mContent->AsElement()->State();
363
364 if (elementState.HasState(dom::ElementState::INVALID)) {
365 state |= states::INVALID;
366 }
367
368 if (elementState.HasState(dom::ElementState::REQUIRED)) {
369 state |= states::REQUIRED;
370 }
371
372 if (elementState.HasState(dom::ElementState::MODAL)) {
373 state |= states::MODAL;
374 }
375
376 state |= NativeInteractiveState();
377 }
378
379 // Gather states::INVISIBLE and states::OFFSCREEN flags for this object.
380 state |= VisibilityState();
381
382 nsIFrame* frame = GetFrame();
383 if (frame && frame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
384 state |= states::FLOATING;
385 }
386
387 // Check if a XUL element has the popup attribute (an attached popup menu).
388 if (HasOwnContent() && mContent->IsXULElement() &&
389 mContent->AsElement()->HasAttr(nsGkAtoms::popup)) {
390 state |= states::HASPOPUP;
391 }
392
393 // Bypass the link states specialization for non links.
394 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
395 if (!roleMapEntry || roleMapEntry->roleRule == kUseNativeRole ||
396 roleMapEntry->role == roles::LINK) {
397 state |= NativeLinkState();
398 }
399
400 return state;
401}
402
403uint64_t LocalAccessible::NativeInteractiveState() const {
404 if (!mContent->IsElement()) return 0;
405
406 if (NativelyUnavailable()) return states::UNAVAILABLE;
407
408 nsIFrame* frame = GetFrame();
409 auto flags = IsFocusableFlags(0);
410 // If we're caching this remote document in the parent process, we
411 // need to cache focusability irrespective of visibility. Otherwise,
412 // if this document is invisible when it first loads, we'll cache that
413 // all descendants are unfocusable and this won't get updated when the
414 // document becomes visible. Even if we did get notified when the
415 // document becomes visible, it would be wasteful to walk the entire
416 // tree to figure out what is now focusable and push cache updates.
417 // Although ignoring visibility means IsFocusable will return true for
418 // visibility: hidden, etc., this isn't a problem because we don't include
419 // those hidden elements in the a11y tree anyway.
420 if (mDoc->IPCDoc()) {
421 flags |= IsFocusableFlags::IgnoreVisibility;
422 }
423 if (frame && frame->IsFocusable(flags)) {
424 return states::FOCUSABLE;
425 }
426 return 0;
427}
428
429uint64_t LocalAccessible::NativeLinkState() const { return 0; }
430
431bool LocalAccessible::IsOnlyPlainContent() const {
432 if (!IsPlainContent()) {
433 return false;
434 }
435
436 uint32_t childCount = ChildCount();
437 for (uint32_t i = 0; i < childCount; i++) {
438 LocalAccessible* child = LocalChildAt(i);
439 if (!child) {
440 continue;
441 }
442
443 if (!child->IsOnlyPlainContent()) {
444 return false;
445 }
446 }
447
448 return true;
449}
450
451bool LocalAccessible::NativelyUnavailable() const {
452 if (mContent->IsHTMLElement()) return mContent->AsElement()->IsDisabled();
453
454 return mContent->IsElement() &&
455 mContent->AsElement()->GetBoolAttr(nsGkAtoms::disabled);
456}
457
458Accessible* LocalAccessible::ChildAtPoint(int32_t aX, int32_t aY,
459 EWhichChildAtPoint aWhichChild) {
460 Accessible* child = LocalChildAtPoint(aX, aY, aWhichChild);
461 if (aWhichChild != EWhichChildAtPoint::DirectChild && child &&
462 child->IsOuterDoc()) {
463 child = child->ChildAtPoint(aX, aY, aWhichChild);
464 }
465
466 return child;
467}
468
469LocalAccessible* LocalAccessible::LocalChildAtPoint(
470 int32_t aX, int32_t aY, EWhichChildAtPoint aWhichChild) {
471 // If we can't find the point in a child, we will return the fallback answer:
472 // we return |this| if the point is within it, otherwise nullptr.
473 LocalAccessible* fallbackAnswer = nullptr;
474 LayoutDeviceIntRect rect = Bounds();
475 if (rect.Contains(aX, aY)) fallbackAnswer = this;
476
477 if (nsAccUtils::MustPrune(this)) { // Do not dig any further
478 return fallbackAnswer;
479 }
480
481 // Search an accessible at the given point starting from accessible document
482 // because containing block (see CSS2) for out of flow element (for example,
483 // absolutely positioned element) may be different from its DOM parent and
484 // therefore accessible for containing block may be different from accessible
485 // for DOM parent but GetFrameForPoint() should be called for containing block
486 // to get an out of flow element.
487 DocAccessible* accDocument = Document();
488 NS_ENSURE_TRUE(accDocument, nullptr)do { if ((__builtin_expect(!!(!(accDocument)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "accDocument" ") failed"
, nullptr, "./../../../accessible/generic/LocalAccessible.cpp"
, 488); return nullptr; } } while (false)
;
489
490 nsIFrame* rootFrame = accDocument->GetFrame();
491 NS_ENSURE_TRUE(rootFrame, nullptr)do { if ((__builtin_expect(!!(!(rootFrame)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "rootFrame" ") failed", nullptr
, "./../../../accessible/generic/LocalAccessible.cpp", 491); return
nullptr; } } while (false)
;
492
493 nsIFrame* startFrame = rootFrame;
494
495 // Check whether the point is at popup content.
496 nsIWidget* rootWidget = rootFrame->GetNearestWidget();
497 NS_ENSURE_TRUE(rootWidget, nullptr)do { if ((__builtin_expect(!!(!(rootWidget)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "rootWidget" ") failed",
nullptr, "./../../../accessible/generic/LocalAccessible.cpp"
, 497); return nullptr; } } while (false)
;
498
499 LayoutDeviceIntRect rootRect = rootWidget->GetScreenBounds();
500
501 auto point = LayoutDeviceIntPoint(aX - rootRect.X(), aY - rootRect.Y());
502
503 nsIFrame* popupFrame = nsLayoutUtils::GetPopupFrameForPoint(
504 accDocument->PresContext()->GetRootPresContext(), rootWidget, point);
505 if (popupFrame) {
506 // If 'this' accessible is not inside the popup then ignore the popup when
507 // searching an accessible at point.
508 DocAccessible* popupDoc =
509 GetAccService()->GetDocAccessible(popupFrame->GetContent()->OwnerDoc());
510 LocalAccessible* popupAcc =
511 popupDoc->GetAccessibleOrContainer(popupFrame->GetContent());
512 LocalAccessible* popupChild = this;
513 while (popupChild && !popupChild->IsDoc() && popupChild != popupAcc) {
514 popupChild = popupChild->LocalParent();
515 }
516
517 if (popupChild == popupAcc) startFrame = popupFrame;
518 }
519
520 nsPresContext* presContext = startFrame->PresContext();
521 nsRect screenRect = startFrame->GetScreenRectInAppUnits();
522 nsPoint offset(presContext->DevPixelsToAppUnits(aX) - screenRect.X(),
523 presContext->DevPixelsToAppUnits(aY) - screenRect.Y());
524
525 nsIFrame* foundFrame = nsLayoutUtils::GetFrameForPoint(
526 RelativeTo{startFrame, ViewportType::Visual}, offset);
527
528 nsIContent* content = nullptr;
529 if (!foundFrame || !(content = foundFrame->GetContent())) {
530 return fallbackAnswer;
531 }
532
533 // Get accessible for the node with the point or the first accessible in
534 // the DOM parent chain.
535 DocAccessible* contentDocAcc =
536 GetAccService()->GetDocAccessible(content->OwnerDoc());
537
538 // contentDocAcc in some circumstances can be nullptr. See bug 729861
539 NS_ASSERTION(contentDocAcc, "could not get the document accessible")do { if (!(contentDocAcc)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "could not get the document accessible", "contentDocAcc", "./../../../accessible/generic/LocalAccessible.cpp"
, 539); MOZ_PretendNoReturn(); } } while (0)
;
540 if (!contentDocAcc) return fallbackAnswer;
541
542 LocalAccessible* accessible =
543 contentDocAcc->GetAccessibleOrContainer(content);
544 if (!accessible) return fallbackAnswer;
545
546 // Hurray! We have an accessible for the frame that layout gave us.
547 // Since DOM node of obtained accessible may be out of flow then we should
548 // ensure obtained accessible is a child of this accessible.
549 LocalAccessible* child = accessible;
550 while (child != this) {
551 LocalAccessible* parent = child->LocalParent();
552 if (!parent) {
553 // Reached the top of the hierarchy. These bounds were inside an
554 // accessible that is not a descendant of this one.
555 return fallbackAnswer;
556 }
557
558 // If we landed on a legitimate child of |this|, and we want the direct
559 // child, return it here.
560 if (parent == this && aWhichChild == EWhichChildAtPoint::DirectChild) {
561 return child;
562 }
563
564 child = parent;
565 }
566
567 // Manually walk through accessible children and see if the are within this
568 // point. Skip offscreen or invisible accessibles. This takes care of cases
569 // where layout won't walk into things for us, such as image map areas and
570 // sub documents (XXX: subdocuments should be handled by methods of
571 // OuterDocAccessibles).
572 uint32_t childCount = accessible->ChildCount();
573 if (childCount == 1 && accessible->IsOuterDoc() &&
574 accessible->FirstChild()->IsRemote()) {
575 // No local children.
576 return accessible;
577 }
578 for (uint32_t childIdx = 0; childIdx < childCount; childIdx++) {
579 LocalAccessible* child = accessible->LocalChildAt(childIdx);
580
581 LayoutDeviceIntRect childRect = child->Bounds();
582 if (childRect.Contains(aX, aY) &&
583 (child->State() & states::INVISIBLE) == 0) {
584 if (aWhichChild == EWhichChildAtPoint::DeepestChild) {
585 return child->LocalChildAtPoint(aX, aY,
586 EWhichChildAtPoint::DeepestChild);
587 }
588
589 return child;
590 }
591 }
592
593 return accessible;
594}
595
596nsIFrame* LocalAccessible::FindNearestAccessibleAncestorFrame() const {
597 nsIFrame* frame = GetFrame();
598 if (frame &&
599 frame->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
600 nsLayoutUtils::IsReallyFixedPos(frame)) {
601 return mDoc->PresShellPtr()->GetRootFrame();
602 }
603
604 if (IsDoc()) {
605 // We bound documents by their own frame, which is their PresShell's root
606 // frame. We cache the document offset elsewhere in BundleFieldsForCache
607 // using the nsGkAtoms::crossorigin attribute.
608 MOZ_ASSERT(frame, "DocAccessibles should always have a frame")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(frame)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(frame))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("frame" " (" "DocAccessibles should always have a frame"
")", "./../../../accessible/generic/LocalAccessible.cpp", 608
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "frame" ") (" "DocAccessibles should always have a frame"
")"); do { MOZ_CrashSequence(__null, 608); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
609 return frame;
610 }
611
612 // Iterate through accessible's ancestors to find one with a frame.
613 LocalAccessible* ancestor = mParent;
614 while (ancestor) {
615 if (nsIFrame* boundingFrame = ancestor->GetFrame()) {
616 return boundingFrame;
617 }
618 ancestor = ancestor->LocalParent();
619 }
620
621 return frame ? nsLayoutUtils::GetContainingBlockForClientRect(frame)
622 : nullptr;
623}
624
625nsRect LocalAccessible::ParentRelativeBounds() {
626 nsIFrame* frame = GetFrame();
627 if (frame && mContent) {
628 nsIFrame* boundingFrame = FindNearestAccessibleAncestorFrame();
629 nsRect result = nsLayoutUtils::GetAllInFlowRectsUnion(frame, boundingFrame);
630
631 if (result.IsEmpty()) {
632 // If we end up with a 0x0 rect from above (or one with negative
633 // height/width) we should try using the ink overflow rect instead. If we
634 // use this rect, our relative bounds will match the bounds of what
635 // appears visually. We do this because some web authors (icloud.com for
636 // example) employ things like 0x0 buttons with visual overflow. Without
637 // this, such frames aren't navigable by screen readers.
638 result = frame->InkOverflowRectRelativeToSelf();
639 result.MoveBy(frame->GetOffsetTo(boundingFrame));
640 }
641
642 if (boundingFrame->GetRect().IsEmpty() ||
643 nsLayoutUtils::GetNextContinuationOrIBSplitSibling(boundingFrame)) {
644 // Constructing a bounding box across a frame that has an IB split means
645 // the origin is likely be different from that of boundingFrame.
646 // Descendants will need their parent-relative bounds adjusted
647 // accordingly, since parent-relative bounds are constructed to the
648 // bounding box of the entire element and not each individual IB split
649 // frame. In the case that boundingFrame's rect is empty,
650 // GetAllInFlowRectsUnion might exclude its origin. For example, if
651 // boundingFrame is empty with an origin of (0, -840) but has a non-empty
652 // ib-split-sibling with (0, 0), the union rect will originate at (0, 0).
653 // This means the bounds returned for our parent Accessible might be
654 // offset from boundingFrame's rect. Since result is currently relative to
655 // boundingFrame's rect, we might need to adjust it to make it parent
656 // relative.
657 nsRect boundingUnion =
658 nsLayoutUtils::GetAllInFlowRectsUnion(boundingFrame, boundingFrame);
659 if (!boundingUnion.IsEmpty()) {
660 // The origin of boundingUnion is relative to boundingFrame, meaning
661 // when we call MoveBy on result with this value we're offsetting
662 // `result` by the distance boundingFrame's origin was moved to
663 // construct its bounding box.
664 result.MoveBy(-boundingUnion.TopLeft());
665 } else {
666 // Since GetAllInFlowRectsUnion returned an empty rect on our parent
667 // Accessible, we would have used the ink overflow rect. However,
668 // GetAllInFlowRectsUnion calculates relative to the bounding frame's
669 // main rect, not its ink overflow rect. We need to adjust for the ink
670 // overflow offset to make our result parent relative.
671 nsRect boundingOverflow =
672 boundingFrame->InkOverflowRectRelativeToSelf();
673 result.MoveBy(-boundingOverflow.TopLeft());
674 }
675 }
676
677 if (frame->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
678 nsLayoutUtils::IsReallyFixedPos(frame)) {
679 // If we're dealing with a fixed position frame, we've already made it
680 // relative to the document which should have gotten rid of its scroll
681 // offset.
682 return result;
683 }
684
685 if (!IsDoc()) {
686 if (ScrollContainerFrame* sf =
687 boundingFrame == mDoc->GetFrame()
688 ? mDoc->PresShellPtr()->GetRootScrollContainerFrame()
689 : boundingFrame->GetScrollTargetFrame()) {
690 // If boundingFrame has a scroll position, result is currently relative
691 // to that. Instead, we want result to remain the same regardless of
692 // scrolling. We then subtract the scroll position later when
693 // calculating absolute bounds. We do this because we don't want to push
694 // cache updates for the bounds of all descendants every time we scroll.
695 // We don't need to do this for the document because document bounds are
696 // always computed to be self-relative -- see
697 // FindNearestAccessibleAncestorFrame. However, if boundingFrame is the
698 // document's frame (e.g. mParent had no frame, and the document is the
699 // nearest frame-having ancestor), we have to account for any scroll
700 // offset between the doc and its content. This is tracked in the
701 // PresShell's root scroll container frame.
702 nsPoint scrollPos = sf->GetScrollPosition().ApplyResolution(
703 mDoc->PresShellPtr()->GetResolution());
704 result.MoveBy(scrollPos.x, scrollPos.y);
705 }
706 }
707
708 return result;
709 }
710
711 return nsRect();
712}
713
714nsRect LocalAccessible::RelativeBounds(nsIFrame** aBoundingFrame) const {
715 nsIFrame* frame = GetFrame();
716 if (frame && mContent) {
717 *aBoundingFrame = nsLayoutUtils::GetContainingBlockForClientRect(frame);
718 nsRect unionRect = nsLayoutUtils::GetAllInFlowRectsUnion(
719 frame, *aBoundingFrame,
720 nsLayoutUtils::GetAllInFlowRectsFlag::AccountForTransforms);
721
722 if (unionRect.IsEmpty()) {
723 // If we end up with a 0x0 rect from above (or one with negative
724 // height/width) we should try using the ink overflow rect instead. If we
725 // use this rect, our relative bounds will match the bounds of what
726 // appears visually. We do this because some web authors (icloud.com for
727 // example) employ things like 0x0 buttons with visual overflow. Without
728 // this, such frames aren't navigable by screen readers.
729 nsRect overflow = frame->InkOverflowRectRelativeToSelf();
730 nsLayoutUtils::TransformRect(frame, *aBoundingFrame, overflow);
731 return overflow;
732 }
733
734 return unionRect;
735 }
736
737 return nsRect();
738}
739
740nsRect LocalAccessible::BoundsInAppUnits() const {
741 nsIFrame* boundingFrame = nullptr;
742 nsRect unionRectTwips = RelativeBounds(&boundingFrame);
743 if (!boundingFrame) {
744 if (nsCoreUtils::IsDisplayContents(mContent)) {
745 nsRect result;
746 for (uint32_t i = 0, n = ChildCount(); i < n; i++) {
747 result.UnionRect(result, LocalChildAt(i)->BoundsInAppUnits());
748 }
749 return result;
750 }
751 return nsRect();
752 }
753
754 PresShell* presShell = mDoc->PresContext()->PresShell();
755
756 // We need to inverse translate with the offset of the edge of the visual
757 // viewport from top edge of the layout viewport.
758 nsPoint viewportOffset = presShell->GetVisualViewportOffset() -
759 presShell->GetLayoutViewportOffset();
760 unionRectTwips.MoveBy(-viewportOffset);
761
762 // We need to take into account a non-1 resolution set on the presshell.
763 // This happens with async pinch zooming. Here we scale the bounds before
764 // adding the screen-relative offset.
765 unionRectTwips.ScaleRoundOut(presShell->GetResolution());
766 // We have the union of the rectangle, now we need to put it in absolute
767 // screen coords.
768 nsRect orgRectPixels = boundingFrame->GetScreenRectInAppUnits();
769 unionRectTwips.MoveBy(orgRectPixels.X(), orgRectPixels.Y());
770
771 return unionRectTwips;
772}
773
774LayoutDeviceIntRect LocalAccessible::Bounds() const {
775 return LayoutDeviceIntRect::FromAppUnitsToNearest(
776 BoundsInAppUnits(), mDoc->PresContext()->AppUnitsPerDevPixel());
777}
778
779void LocalAccessible::SetSelected(bool aSelect) {
780 if (!HasOwnContent()) return;
781
782 if (nsAccUtils::GetSelectableContainer(this, State()) && aSelect) {
783 TakeFocus();
784 }
785}
786
787void LocalAccessible::TakeSelection() {
788 LocalAccessible* select = nsAccUtils::GetSelectableContainer(this, State());
789 if (select) {
790 if (select->State() & states::MULTISELECTABLE) select->UnselectAll();
791 SetSelected(true);
792 }
793}
794
795void LocalAccessible::TakeFocus() const {
796 nsIFrame* frame = GetFrame();
797 if (!frame) return;
798
799 nsIContent* focusContent = mContent;
800
801 // If the accessible focus is managed by container widget then focus the
802 // widget and set the accessible as its current item.
803 if (!frame->IsFocusable()) {
804 LocalAccessible* widget = ContainerWidget();
805 if (widget && widget->AreItemsOperable()) {
806 nsIContent* widgetElm = widget->GetContent();
807 nsIFrame* widgetFrame = widgetElm->GetPrimaryFrame();
808 if (widgetFrame && widgetFrame->IsFocusable()) {
809 focusContent = widgetElm;
810 widget->SetCurrentItem(this);
811 }
812 }
813 }
814
815 if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) {
816 dom::AutoHandlingUserInputStatePusher inputStatePusher(true);
817 // XXXbz: Can we actually have a non-element content here?
818 RefPtr<dom::Element> element = dom::Element::FromNodeOrNull(focusContent);
819 fm->SetFocus(element, 0);
820 }
821}
822
823void LocalAccessible::NameFromAssociatedXULLabel(DocAccessible* aDocument,
824 nsIContent* aElm,
825 nsString& aName) {
826 LocalAccessible* label = nullptr;
827 XULLabelIterator iter(aDocument, aElm);
828 while ((label = iter.Next())) {
829 // Check if label's value attribute is used
830 label->Elm()->GetAttr(nsGkAtoms::value, aName);
831 if (aName.IsEmpty()) {
832 // If no value attribute, a non-empty label must contain
833 // children that define its text -- possibly using HTML
834 nsTextEquivUtils::AppendTextEquivFromContent(label, label->Elm(), &aName);
835 }
836 }
837 aName.CompressWhitespace();
838}
839
840void LocalAccessible::XULElmName(DocAccessible* aDocument, nsIContent* aElm,
841 nsString& aName) {
842 /**
843 * 3 main cases for XUL Controls to be labeled
844 * 1 - control contains label="foo"
845 * 2 - non-child label contains control="controlID"
846 * - label has either value="foo" or children
847 * 3 - name from subtree; e.g. a child label element
848 * Cases 1 and 2 are handled here.
849 * Case 3 is handled by GetNameFromSubtree called in NativeName.
850 * Once a label is found, the search is discontinued, so a control
851 * that has a label attribute as well as having a label external to
852 * the control that uses the control="controlID" syntax will use
853 * the label attribute for its Name.
854 */
855
856 // CASE #1 (via label attribute) -- great majority of the cases
857 // Only do this if this is not a select control element, which uses label
858 // attribute to indicate, which option is selected.
859 nsCOMPtr<nsIDOMXULSelectControlElement> select =
860 aElm->AsElement()->AsXULSelectControl();
861 if (!select) {
862 aElm->AsElement()->GetAttr(nsGkAtoms::label, aName);
863 }
864
865 // CASE #2 -- label as <label control="id" ... ></label>
866 if (aName.IsEmpty()) {
867 NameFromAssociatedXULLabel(aDocument, aElm, aName);
868 }
869
870 aName.CompressWhitespace();
871}
872
873nsresult LocalAccessible::HandleAccEvent(AccEvent* aEvent) {
874 NS_ENSURE_ARG_POINTER(aEvent)do { if ((__builtin_expect(!!(!(aEvent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEvent" ") failed", nullptr
, "./../../../accessible/generic/LocalAccessible.cpp", 874); return
NS_ERROR_INVALID_POINTER; } } while (false)
;
875
876 if (profiler_thread_is_being_profiled_for_markers()) {
877 nsAutoCString strEventType;
878 GetAccService()->GetStringEventType(aEvent->GetEventType(), strEventType);
879 nsAutoCString strMarker;
880 strMarker.AppendLiteral("A11y Event - ");
881 strMarker.Append(strEventType);
882 PROFILER_MARKER_UNTYPED(strMarker, A11Y)do { ; do { if (profiler_is_collecting_markers()) { ::profiler_add_marker_impl
(strMarker, ::geckoprofiler::category::A11Y); } } while (false
); } while (false)
;
883 }
884
885 if (IPCAccessibilityActive() && Document()) {
886 DocAccessibleChild* ipcDoc = mDoc->IPCDoc();
887 // If ipcDoc is null, we can't fire the event to the client in the parent
888 // process. This could happen for two reasons:
889 // 1. There is no client in the parent process, so we didn't create a
890 // DocAccessibleChild.
891 // 2. A DocAccessibleChild would have been created, but we incorrectly fired
892 // an event before that happened. In this case, we shouldn't have fired the
893 // event in the first place, since this makes events inconsistent for local
894 // and remote documents. To avoid this, don't call nsEventShell::FireEvent
895 // on a DocAccessible for which HasLoadState(eTreeConstructed) is false.
896 MOZ_ASSERT(mDoc->HasLoadState(DocAccessible::eTreeConstructed))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mDoc->HasLoadState(DocAccessible::eTreeConstructed
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mDoc->HasLoadState(DocAccessible::eTreeConstructed
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mDoc->HasLoadState(DocAccessible::eTreeConstructed)", "./../../../accessible/generic/LocalAccessible.cpp"
, 896); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mDoc->HasLoadState(DocAccessible::eTreeConstructed)"
")"); do { MOZ_CrashSequence(__null, 896); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
897 if (ipcDoc) {
898 uint64_t id = aEvent->GetAccessible()->ID();
899
900 switch (aEvent->GetEventType()) {
901 case nsIAccessibleEvent::EVENT_SHOW:
902 ipcDoc->ShowEvent(downcast_accEvent(aEvent));
903 break;
904
905 case nsIAccessibleEvent::EVENT_HIDE:
906 ipcDoc->PushMutationEventData(
907 HideEventData{id, aEvent->IsFromUserInput()});
908 break;
909
910 case nsIAccessibleEvent::EVENT_INNER_REORDER:
911 case nsIAccessibleEvent::EVENT_REORDER:
912 if (IsTable()) {
913 SendCache(CacheDomain::Table, CacheUpdateType::Update,
914 /*aAppendEventData*/ true);
915 }
916
917#if defined(XP_WIN)
918 if (HasOwnContent() && mContent->IsMathMLElement()) {
919 // For any change in a MathML subtree, update the innerHTML cache on
920 // the root math element.
921 for (LocalAccessible* acc = this; acc; acc = acc->LocalParent()) {
922 if (acc->HasOwnContent() &&
923 acc->mContent->IsMathMLElement(nsGkAtoms::math)) {
924 mDoc->QueueCacheUpdate(acc, CacheDomain::InnerHTML);
925 }
926 }
927 }
928#endif // defined(XP_WIN)
929
930 // reorder events on the application acc aren't necessary to tell the
931 // parent about new top level documents.
932 if (!aEvent->GetAccessible()->IsApplication()) {
933 ipcDoc->PushMutationEventData(
934 ReorderEventData{id, aEvent->GetEventType()});
935 }
936 break;
937 case nsIAccessibleEvent::EVENT_STATE_CHANGE: {
938 AccStateChangeEvent* event = downcast_accEvent(aEvent);
939 ipcDoc->SendStateChangeEvent(id, event->GetState(),
940 event->IsStateEnabled());
941 break;
942 }
943 case nsIAccessibleEvent::EVENT_TEXT_CARET_MOVED: {
944 AccCaretMoveEvent* event = downcast_accEvent(aEvent);
945 ipcDoc->SendCaretMoveEvent(
946 id,
947 DocAccessibleChild::GetCaretRectForIPCEvent(
948 aEvent->GetAccessible()),
949 event->GetCaretOffset(), event->IsSelectionCollapsed(),
950 event->IsAtEndOfLine(), event->GetGranularity(),
951 event->IsFromUserInput(), /* aSuppressEvent */ false);
952 break;
953 }
954 case nsIAccessibleEvent::EVENT_TEXT_INSERTED:
955 case nsIAccessibleEvent::EVENT_TEXT_REMOVED: {
956 AccTextChangeEvent* event = downcast_accEvent(aEvent);
957 ipcDoc->PushMutationEventData(TextChangeEventData{
958 id, event->ModifiedText(), event->GetStartOffset(),
959 event->GetLength(), event->IsTextInserted(),
960 event->IsFromUserInput()});
961 break;
962 }
963 case nsIAccessibleEvent::EVENT_SELECTION:
964 case nsIAccessibleEvent::EVENT_SELECTION_ADD:
965 case nsIAccessibleEvent::EVENT_SELECTION_REMOVE: {
966 AccSelChangeEvent* selEvent = downcast_accEvent(aEvent);
967 ipcDoc->SendSelectionEvent(id, selEvent->Widget()->ID(),
968 aEvent->GetEventType());
969 break;
970 }
971 case nsIAccessibleEvent::EVENT_FOCUS:
972 ipcDoc->SendFocusEvent(id,
973 DocAccessibleChild::GetCaretRectForIPCEvent(
974 aEvent->GetAccessible()));
975 break;
976 case nsIAccessibleEvent::EVENT_SCROLLING_END:
977 case nsIAccessibleEvent::EVENT_SCROLLING: {
978 AccScrollingEvent* scrollingEvent = downcast_accEvent(aEvent);
979 ipcDoc->SendScrollingEvent(
980 id, aEvent->GetEventType(), scrollingEvent->ScrollX(),
981 scrollingEvent->ScrollY(), scrollingEvent->MaxScrollX(),
982 scrollingEvent->MaxScrollY());
983 break;
984 }
985 case nsIAccessibleEvent::EVENT_ANNOUNCEMENT: {
986 AccAnnouncementEvent* announcementEvent = downcast_accEvent(aEvent);
987 ipcDoc->SendAnnouncementEvent(id, announcementEvent->Announcement(),
988 announcementEvent->Priority());
989 break;
990 }
991 case nsIAccessibleEvent::EVENT_TEXT_SELECTION_CHANGED: {
992 AccTextSelChangeEvent* textSelChangeEvent = downcast_accEvent(aEvent);
993 AutoTArray<TextRange, 1> ranges;
994 textSelChangeEvent->SelectionRanges(&ranges);
995 nsTArray<TextRangeData> textRangeData(ranges.Length());
996 for (size_t i = 0; i < ranges.Length(); i++) {
997 const TextRange& range = ranges.ElementAt(i);
998 LocalAccessible* start = range.StartContainer()->AsLocal();
999 LocalAccessible* end = range.EndContainer()->AsLocal();
1000 textRangeData.AppendElement(TextRangeData(start->ID(), end->ID(),
1001 range.StartOffset(),
1002 range.EndOffset()));
1003 }
1004 ipcDoc->SendTextSelectionChangeEvent(id, textRangeData);
1005 break;
1006 }
1007 case nsIAccessibleEvent::EVENT_DESCRIPTION_CHANGE:
1008 case nsIAccessibleEvent::EVENT_NAME_CHANGE: {
1009 SendCache(CacheDomain::NameAndDescription, CacheUpdateType::Update);
1010 ipcDoc->SendEvent(id, aEvent->GetEventType());
1011 break;
1012 }
1013 case nsIAccessibleEvent::EVENT_TEXT_VALUE_CHANGE:
1014 case nsIAccessibleEvent::EVENT_VALUE_CHANGE: {
1015 SendCache(CacheDomain::Value, CacheUpdateType::Update);
1016 ipcDoc->SendEvent(id, aEvent->GetEventType());
1017 break;
1018 }
1019 default:
1020 ipcDoc->SendEvent(id, aEvent->GetEventType());
1021 }
1022 }
1023 }
1024
1025 if (nsCoreUtils::AccEventObserversExist()) {
1026 nsCoreUtils::DispatchAccEvent(MakeXPCEvent(aEvent));
1027 }
1028
1029 if (IPCAccessibilityActive()) {
1030 return NS_OK;
1031 }
1032
1033 if (IsDefunct()) {
1034 // This could happen if there is an XPCOM observer, since script might run
1035 // which mutates the tree.
1036 return NS_OK;
1037 }
1038
1039 LocalAccessible* target = aEvent->GetAccessible();
1040 switch (aEvent->GetEventType()) {
1041 case nsIAccessibleEvent::EVENT_SHOW: {
1042 // Scope for PerfStats
1043 AUTO_PROFILER_MARKER_TEXT("a11y::PlatformShowHideEvent", A11Y, {}, ""_ns)AutoProfilerTextMarker raiiObject1043( "a11y::PlatformShowHideEvent"
, ::mozilla::baseprofiler::category::A11Y, {}, ""_ns)
;
1044 PerfStats::AutoMetricRecording<
1045 PerfStats::Metric::A11Y_PlatformShowHideEvent>
1046 autoRecording;
1047 // WITHIN THIS SCOPE, DO NOT ADD CODE ABOVE THIS BLOCK:
1048 // THIS CODE IS MEASURING TIMINGS.
1049 PlatformShowHideEvent(target, target->LocalParent(), true,
1050 aEvent->IsFromUserInput());
1051 break;
1052 }
1053 case nsIAccessibleEvent::EVENT_HIDE: {
1054 // Scope for PerfStats
1055 AUTO_PROFILER_MARKER_TEXT("a11y::PlatformShowHideEvent", A11Y, {}, ""_ns)AutoProfilerTextMarker raiiObject1055( "a11y::PlatformShowHideEvent"
, ::mozilla::baseprofiler::category::A11Y, {}, ""_ns)
;
1056 PerfStats::AutoMetricRecording<
1057 PerfStats::Metric::A11Y_PlatformShowHideEvent>
1058 autoRecording;
1059 // WITHIN THIS SCOPE, DO NOT ADD CODE ABOVE THIS BLOCK:
1060 // THIS CODE IS MEASURING TIMINGS.
1061 PlatformShowHideEvent(target, target->LocalParent(), false,
1062 aEvent->IsFromUserInput());
1063 break;
1064 }
1065 case nsIAccessibleEvent::EVENT_STATE_CHANGE: {
1066 AccStateChangeEvent* event = downcast_accEvent(aEvent);
1067 PlatformStateChangeEvent(target, event->GetState(),
1068 event->IsStateEnabled());
1069 break;
1070 }
1071 case nsIAccessibleEvent::EVENT_TEXT_CARET_MOVED: {
1072 AccCaretMoveEvent* event = downcast_accEvent(aEvent);
1073 PlatformCaretMoveEvent(target, event->GetCaretOffset(),
1074 event->IsSelectionCollapsed(),
1075 event->GetGranularity(), event->IsFromUserInput());
1076 break;
1077 }
1078 case nsIAccessibleEvent::EVENT_TEXT_INSERTED:
1079 case nsIAccessibleEvent::EVENT_TEXT_REMOVED: {
1080 AccTextChangeEvent* event = downcast_accEvent(aEvent);
1081 const nsString& text = event->ModifiedText();
1082 PlatformTextChangeEvent(target, text, event->GetStartOffset(),
1083 event->GetLength(), event->IsTextInserted(),
1084 event->IsFromUserInput());
1085 break;
1086 }
1087 case nsIAccessibleEvent::EVENT_SELECTION:
1088 case nsIAccessibleEvent::EVENT_SELECTION_ADD:
1089 case nsIAccessibleEvent::EVENT_SELECTION_REMOVE: {
1090 AccSelChangeEvent* selEvent = downcast_accEvent(aEvent);
1091 PlatformSelectionEvent(target, selEvent->Widget(),
1092 aEvent->GetEventType());
1093 break;
1094 }
1095 case nsIAccessibleEvent::EVENT_FOCUS: {
1096 PlatformFocusEvent(target);
1097 break;
1098 }
1099#if defined(ANDROID)
1100 case nsIAccessibleEvent::EVENT_SCROLLING_END:
1101 case nsIAccessibleEvent::EVENT_SCROLLING: {
1102 AccScrollingEvent* scrollingEvent = downcast_accEvent(aEvent);
1103 PlatformScrollingEvent(
1104 target, aEvent->GetEventType(), scrollingEvent->ScrollX(),
1105 scrollingEvent->ScrollY(), scrollingEvent->MaxScrollX(),
1106 scrollingEvent->MaxScrollY());
1107 break;
1108 }
1109#endif // defined(ANDROID)
1110 case nsIAccessibleEvent::EVENT_ANNOUNCEMENT: {
1111 AccAnnouncementEvent* announcementEvent = downcast_accEvent(aEvent);
1112 PlatformAnnouncementEvent(target, announcementEvent->Announcement(),
1113 announcementEvent->Priority());
1114 break;
1115 }
1116#if defined(MOZ_WIDGET_COCOA)
1117 case nsIAccessibleEvent::EVENT_TEXT_SELECTION_CHANGED: {
1118 AccTextSelChangeEvent* textSelChangeEvent = downcast_accEvent(aEvent);
1119 AutoTArray<TextRange, 1> ranges;
1120 textSelChangeEvent->SelectionRanges(&ranges);
1121 PlatformTextSelectionChangeEvent(target, ranges);
1122 break;
1123 }
1124#endif // defined(MOZ_WIDGET_COCOA)
1125 default:
1126 PlatformEvent(target, aEvent->GetEventType());
1127 }
1128
1129 return NS_OK;
1130}
1131
1132already_AddRefed<AccAttributes> LocalAccessible::Attributes() {
1133 RefPtr<AccAttributes> attributes = NativeAttributes();
1134 if (!HasOwnContent() || !mContent->IsElement()) return attributes.forget();
1135
1136 // 'xml-roles' attribute coming from ARIA.
1137 nsString xmlRoles;
1138 if (nsAccUtils::GetARIAAttr(mContent->AsElement(), nsGkAtoms::role,
1139 xmlRoles) &&
1140 !xmlRoles.IsEmpty()) {
1141 attributes->SetAttribute(nsGkAtoms::xmlroles, std::move(xmlRoles));
1142 } else if (nsAtom* landmark = LandmarkRole()) {
1143 // 'xml-roles' attribute for landmark.
1144 attributes->SetAttribute(nsGkAtoms::xmlroles, landmark);
1145 }
1146
1147 // Expose object attributes from ARIA attributes.
1148 aria::AttrIterator attribIter(mContent);
1149 while (attribIter.Next()) {
1150 if (attribIter.AttrName() == nsGkAtoms::aria_placeholder &&
1151 attributes->HasAttribute(nsGkAtoms::placeholder)) {
1152 // If there is an HTML placeholder attribute exposed by
1153 // HTMLTextFieldAccessible::NativeAttributes, don't expose
1154 // aria-placeholder.
1155 continue;
1156 }
1157
1158 if ((attribIter.AttrName() == nsGkAtoms::aria_roledescription ||
1159 attribIter.AttrName() == nsGkAtoms::aria_brailleroledescription) &&
1160 IsGeneric()) {
1161 // We only expose these attributes in accessibles with non generic roles.
1162 // https://www.w3.org/TR/wai-aria-1.2/#aria-roledescription
1163 continue;
1164 }
1165
1166 attribIter.ExposeAttr(attributes);
1167 }
1168
1169 if (HasCustomActions()) {
1170 attributes->SetAttribute(nsGkAtoms::hasActions, true);
1171 }
1172
1173 // If there is no aria-live attribute then expose default value of 'live'
1174 // object attribute used for ARIA role of this accessible.
1175 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
1176 if (roleMapEntry) {
1177 if (roleMapEntry->Is(nsGkAtoms::searchbox)) {
1178 attributes->SetAttribute(nsGkAtoms::textInputType, nsGkAtoms::search);
1179 }
1180
1181 if (!attributes->HasAttribute(nsGkAtoms::aria_live)) {
1182 nsString live;
1183 if (nsAccUtils::GetLiveAttrValue(roleMapEntry->liveAttRule, live)) {
1184 attributes->SetAttribute(nsGkAtoms::aria_live, std::move(live));
1185 }
1186 }
1187 }
1188
1189 nsString detailsFrom;
1190 AssociatedElementsIterator iter(mDoc, Elm(), nsGkAtoms::aria_details);
1191 if (iter.Next()) {
1192 detailsFrom.AssignLiteral("aria-details");
1193 } else if (GetCommandForDetailsRelation()) {
1194 detailsFrom.AssignLiteral("command-for");
1195 } else if (GetPopoverTargetDetailsRelation()) {
1196 detailsFrom.AssignLiteral("popover-target");
1197 } else if (GetAnchorPositionTargetDetailsRelation()) {
1198 detailsFrom.AssignLiteral("css-anchor");
1199 }
1200
1201 if (!detailsFrom.IsEmpty()) {
1202 attributes->SetAttribute(nsGkAtoms::details_from, std::move(detailsFrom));
1203 }
1204
1205 return attributes.forget();
1206}
1207
1208already_AddRefed<AccAttributes> LocalAccessible::NativeAttributes() {
1209 auto attributes = MakeRefPtr<AccAttributes>();
1210
1211 // Expose checkable object attribute if the accessible has checkable state
1212 if (State() & states::CHECKABLE) {
1213 attributes->SetAttribute(nsGkAtoms::checkable, true);
1214 }
1215
1216 // Expose 'explicit-name' attribute.
1217 nsAutoString name;
1218 if (Name(name) != eNameFromSubtree && !name.IsVoid()) {
1219 attributes->SetAttribute(nsGkAtoms::explicit_name, true);
1220 }
1221
1222 bool hierarchical = false;
1223 uint32_t itemCount = AccGroupInfo::TotalItemCount(this, &hierarchical);
1224 if (itemCount) {
1225 attributes->SetAttribute(nsGkAtoms::child_item_count,
1226 static_cast<int32_t>(itemCount));
1227 }
1228
1229 if (hierarchical) {
1230 attributes->SetAttribute(nsGkAtoms::tree, true);
1231 }
1232
1233 // If the accessible doesn't have own content (such as list item bullet or
1234 // xul tree item) then don't calculate content based attributes.
1235 if (!HasOwnContent()) return attributes.forget();
1236
1237 // Get container-foo computed live region properties based on the closest
1238 // container with the live region attribute. Inner nodes override outer nodes
1239 // within the same document. The inner nodes can be used to override live
1240 // region behavior on more general outer nodes.
1241 nsAccUtils::SetLiveContainerAttributes(attributes, this);
1242
1243 if (!mContent->IsElement()) return attributes.forget();
1244
1245 nsString id;
1246 if (nsCoreUtils::GetID(mContent, id)) {
1247 attributes->SetAttribute(nsGkAtoms::id, std::move(id));
1248 }
1249
1250 // Expose class because it may have useful microformat information.
1251 nsString _class;
1252 if (mContent->AsElement()->GetAttr(nsGkAtoms::_class, _class)) {
1253 attributes->SetAttribute(nsGkAtoms::_class, std::move(_class));
1254 }
1255
1256 // Expose tag.
1257 attributes->SetAttribute(nsGkAtoms::tag, mContent->NodeInfo()->NameAtom());
1258
1259 if (auto htmlElement = nsGenericHTMLElement::FromNode(mContent)) {
1260 // Expose draggable object attribute.
1261 if (htmlElement->Draggable()) {
1262 attributes->SetAttribute(nsGkAtoms::draggable, true);
1263 }
1264 nsString popover;
1265 htmlElement->GetPopover(popover);
1266 if (!popover.IsEmpty()) {
1267 attributes->SetAttribute(nsGkAtoms::ispopup, std::move(popover));
1268 }
1269 }
1270
1271 // Don't calculate CSS-based object attributes when:
1272 // 1. There is no frame (e.g. the accessible is unattached from the tree).
1273 // 2. This is an image map area. CSS is irrelevant here. Furthermore, we won't
1274 // be able to get the computed style if the map is unslotted in a shadow host.
1275 nsIFrame* f = mContent->GetPrimaryFrame();
1276 if (!f || mContent->IsHTMLElement(nsGkAtoms::area)) {
1277 return attributes.forget();
1278 }
1279
1280 // Expose 'display' attribute.
1281 if (RefPtr<nsAtom> display = DisplayStyle()) {
1282 attributes->SetAttribute(nsGkAtoms::display, display);
1283 }
1284
1285 const ComputedStyle& style = *f->Style();
1286 auto Atomize = [&](NonCustomCSSPropertyId aId) -> RefPtr<nsAtom> {
1287 nsAutoCString value;
1288 style.GetComputedPropertyValue(aId, value);
1289 return NS_Atomize(value);
1290 };
1291
1292 // Expose 'text-align' attribute.
1293 attributes->SetAttribute(nsGkAtoms::textAlign,
1294 Atomize(eCSSProperty_text_align));
1295
1296 // Expose 'text-indent' attribute.
1297 attributes->SetAttribute(nsGkAtoms::textIndent,
1298 Atomize(eCSSProperty_text_indent));
1299
1300 auto GetMargin = [&](mozilla::Side aSide) -> CSSCoord {
1301 // This is here only to guarantee that we do the same as getComputedStyle
1302 // does, so that we don't hit precision errors in tests.
1303 const auto margin =
1304 f->StyleMargin()->GetMargin(aSide, AnchorPosResolutionParams::From(f));
1305 if (margin->ConvertsToLength()) {
1306 return margin->AsLengthPercentage().ToLengthInCSSPixels();
1307 }
1308
1309 nscoord coordVal = f->GetUsedMargin().Side(aSide);
1310 return CSSPixel::FromAppUnits(coordVal);
1311 };
1312
1313 // Expose 'margin-left' attribute.
1314 attributes->SetAttribute(nsGkAtoms::marginLeft, GetMargin(eSideLeft));
1315
1316 // Expose 'margin-right' attribute.
1317 attributes->SetAttribute(nsGkAtoms::marginRight, GetMargin(eSideRight));
1318
1319 // Expose 'margin-top' attribute.
1320 attributes->SetAttribute(nsGkAtoms::marginTop, GetMargin(eSideTop));
1321
1322 // Expose 'margin-bottom' attribute.
1323 attributes->SetAttribute(nsGkAtoms::marginBottom, GetMargin(eSideBottom));
1324
1325 // Expose data-at-shortcutkeys attribute for web applications and virtual
1326 // cursors. Currently mostly used by JAWS.
1327 nsString atShortcutKeys;
1328 if (mContent->AsElement()->GetAttr(
1329 kNameSpaceID_None, nsGkAtoms::dataAtShortcutkeys, atShortcutKeys)) {
1330 attributes->SetAttribute(nsGkAtoms::dataAtShortcutkeys,
1331 std::move(atShortcutKeys));
1332 }
1333
1334 return attributes.forget();
1335}
1336
1337bool LocalAccessible::AttributeChangesState(nsAtom* aAttribute) {
1338 return aAttribute == nsGkAtoms::aria_disabled ||
1339 // The HTML element disabled state gets handled in
1340 // DocAccessible::ElementStateChanged. This matches
1341 // LocalAccessible::NativelyUnavailable.
1342 (aAttribute == nsGkAtoms::disabled && !mContent->IsHTMLElement()) ||
1343 aAttribute == nsGkAtoms::tabindex ||
1344 aAttribute == nsGkAtoms::aria_required ||
1345 aAttribute == nsGkAtoms::aria_invalid ||
1346 aAttribute == nsGkAtoms::aria_expanded ||
1347 aAttribute == nsGkAtoms::aria_checked ||
1348 (aAttribute == nsGkAtoms::aria_pressed && IsButton()) ||
1349 aAttribute == nsGkAtoms::aria_readonly ||
1350 aAttribute == nsGkAtoms::aria_current ||
1351 aAttribute == nsGkAtoms::aria_haspopup ||
1352 aAttribute == nsGkAtoms::aria_busy ||
1353 aAttribute == nsGkAtoms::aria_multiline ||
1354 aAttribute == nsGkAtoms::aria_multiselectable ||
1355 // We track this for focusable state update
1356 aAttribute == nsGkAtoms::commandfor ||
1357 aAttribute == nsGkAtoms::contenteditable ||
1358 aAttribute == nsGkAtoms::popovertarget;
1359}
1360
1361void LocalAccessible::DOMAttributeChanged(int32_t aNameSpaceID,
1362 nsAtom* aAttribute,
1363 AttrModType aModType,
1364 const nsAttrValue* aOldValue,
1365 uint64_t aOldState) {
1366 // Fire accessible event after short timer, because we need to wait for
1367 // DOM attribute & resulting layout to actually change. Otherwise,
1368 // assistive technology will retrieve the wrong state/value/selection info.
1369
1370 // XXX todo
1371 // We still need to handle special HTML cases here
1372 // For example, if an <img>'s usemap attribute is modified
1373 // Otherwise it may just be a state change, for example an object changing
1374 // its visibility
1375 //
1376 // XXX todo: report aria state changes for "undefined" literal value changes
1377 // filed as bug 472142
1378 //
1379 // XXX todo: invalidate accessible when aria state changes affect exposed
1380 // role filed as bug 472143
1381
1382 if (AttributeChangesState(aAttribute)) {
1383 uint64_t currState = State();
1384 uint64_t diffState = currState ^ aOldState;
1385 if (diffState) {
1386 for (uint64_t state = 1; state <= states::LAST_ENTRY; state <<= 1) {
1387 if (diffState & state) {
1388 auto stateChangeEvent =
1389 MakeRefPtr<AccStateChangeEvent>(this, state, (currState & state));
1390 mDoc->FireDelayedEvent(stateChangeEvent);
1391 }
1392 }
1393 }
1394 }
1395
1396 if (aAttribute == nsGkAtoms::_class) {
1397 mDoc->QueueCacheUpdate(this, CacheDomain::DOMNodeIDAndClass);
1398 return;
1399 }
1400
1401 // When a details object has its open attribute changed
1402 // we should fire a state-change event on the accessible of
1403 // its main summary
1404 if (aAttribute == nsGkAtoms::open) {
1405 // FromDetails checks if the given accessible belongs to
1406 // a details frame and also locates the accessible of its
1407 // main summary.
1408 if (HTMLSummaryAccessible* summaryAccessible =
1409 HTMLSummaryAccessible::FromDetails(this)) {
1410 auto expandedChangeEvent =
1411 MakeRefPtr<AccStateChangeEvent>(summaryAccessible, states::EXPANDED);
1412 mDoc->FireDelayedEvent(expandedChangeEvent);
1413 return;
1414 }
1415 }
1416
1417 // Check for namespaced ARIA attribute
1418 if (aNameSpaceID == kNameSpaceID_None) {
1419 // Check for hyphenated aria-foo property?
1420 if (StringBeginsWith(nsDependentAtomString(aAttribute), u"aria-"_ns)) {
1421 uint8_t attrFlags = aria::AttrCharacteristicsFor(aAttribute);
1422 if (!(attrFlags & ATTR_BYPASSOBJ)) {
1423 mDoc->QueueCacheUpdate(this, CacheDomain::ARIA);
1424 // For aria attributes like drag and drop changes we fire a generic
1425 // attribute change event; at least until native API comes up with a
1426 // more meaningful event.
1427 auto event = MakeRefPtr<AccObjectAttrChangedEvent>(this, aAttribute);
1428 mDoc->FireDelayedEvent(event);
1429 }
1430 }
1431 }
1432
1433 if (aAttribute == nsGkAtoms::aria_actions && IsAdditionOrRemoval(aModType)) {
1434 // We only care about the presence of aria-actions, not its value.
1435 mDoc->QueueCacheUpdate(this, CacheDomain::ARIA);
1436 auto event =
1437 MakeRefPtr<AccObjectAttrChangedEvent>(this, nsGkAtoms::hasActions);
1438 mDoc->FireDelayedEvent(event);
1439 }
1440
1441 dom::Element* elm = Elm();
1442
1443 if (HasNumericValue() &&
1444 (aAttribute == nsGkAtoms::aria_valuemax ||
1445 aAttribute == nsGkAtoms::aria_valuemin || aAttribute == nsGkAtoms::min ||
1446 aAttribute == nsGkAtoms::max || aAttribute == nsGkAtoms::step)) {
1447 mDoc->QueueCacheUpdate(this, CacheDomain::Value);
1448 return;
1449 }
1450
1451 // Fire text value change event whenever aria-valuetext is changed.
1452 if (aAttribute == nsGkAtoms::aria_valuetext) {
1453 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_TEXT_VALUE_CHANGE, this);
1454 return;
1455 }
1456
1457 if (aAttribute == nsGkAtoms::aria_valuenow) {
1458 if (!nsAccUtils::HasARIAAttr(elm, nsGkAtoms::aria_valuetext) ||
1459 nsAccUtils::ARIAAttrValueIs(elm, nsGkAtoms::aria_valuetext,
1460 nsGkAtoms::_empty, eCaseMatters)) {
1461 // Fire numeric value change event when aria-valuenow is changed and
1462 // aria-valuetext is empty
1463 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_VALUE_CHANGE, this);
1464 } else {
1465 // We need to update the cache here since we won't get an event if
1466 // aria-valuenow is shadowed by aria-valuetext.
1467 mDoc->QueueCacheUpdate(this, CacheDomain::Value);
1468 }
1469 return;
1470 }
1471
1472 if (aAttribute == nsGkAtoms::aria_owns) {
1473 mDoc->Controller()->ScheduleRelocation(this);
1474 }
1475
1476 // Fire name change and description change events.
1477 if (aAttribute == nsGkAtoms::aria_label || aAttribute == nsGkAtoms::label) {
1478 // A valid aria-labelledby would take precedence over an aria-label or a xul
1479 // label attribute. So if that relation exists the name won't change.
1480 AssociatedElementsIterator iter(mDoc, elm, nsGkAtoms::aria_labelledby);
1481 if (!iter.NextElem()) {
1482 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
1483 }
1484 return;
1485 }
1486
1487 if (aAttribute == nsGkAtoms::aria_description) {
1488 // A valid aria-describedby would take precedence so an aria-description
1489 // change won't change the description.
1490 AssociatedElementsIterator iter(mDoc, elm, nsGkAtoms::aria_describedby);
1491 if (!iter.NextElem()) {
1492 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_DESCRIPTION_CHANGE,
1493 this);
1494 }
1495 return;
1496 }
1497
1498 if (aAttribute == nsGkAtoms::aria_describedby) {
1499 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
1500 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_DESCRIPTION_CHANGE, this);
1501 if (IsAdditionOrModification(aModType)) {
1502 // The subtrees of the new aria-describedby targets might be used to
1503 // compute the description for this. Therefore, we need to set
1504 // the eHasDescriptionDependent flag on all Accessibles in these subtrees.
1505 AssociatedElementsIterator iter(mDoc, elm, nsGkAtoms::aria_describedby);
1506 while (LocalAccessible* target = iter.Next()) {
1507 target->ModifySubtreeContextFlags(eHasDescriptionDependent, true);
1508 }
1509 }
1510 return;
1511 }
1512
1513 if (aAttribute == nsGkAtoms::aria_labelledby) {
1514 // We only queue cache updates for explicit relations. Implicit, reverse
1515 // relations are handled in ApplyCache and stored in a map on the remote
1516 // document itself.
1517 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
1518 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
1519 if (IsAdditionOrModification(aModType)) {
1520 // The subtrees of the new aria-labelledby targets might be used to
1521 // compute the name for this. Therefore, we need to set
1522 // the eHasNameDependent flag on all Accessibles in these subtrees.
1523 AssociatedElementsIterator iter(mDoc, elm, nsGkAtoms::aria_labelledby);
1524 while (LocalAccessible* target = iter.Next()) {
1525 target->ModifySubtreeContextFlags(eHasNameDependent, true);
1526 }
1527 }
1528 return;
1529 }
1530
1531 if ((aAttribute == nsGkAtoms::aria_expanded ||
1532 aAttribute == nsGkAtoms::href) &&
1533 IsAdditionOrRemoval(aModType)) {
1534 // The presence of aria-expanded adds an expand/collapse action.
1535 mDoc->QueueCacheUpdate(this, CacheDomain::Actions);
1536 }
1537
1538 if (aAttribute == nsGkAtoms::href || aAttribute == nsGkAtoms::src) {
1539 mDoc->QueueCacheUpdate(this, CacheDomain::Value);
1540 }
1541
1542 if (aAttribute == nsGkAtoms::aria_details) {
1543 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
1544 // If an aria-details attribute is added or removed from an anchored
1545 // accessible, it will change the validity of its anchor's relation.
1546 mDoc->RefreshAnchorRelationCacheForTarget(this);
1547 }
1548
1549 if (aAttribute == nsGkAtoms::aria_controls ||
1550 aAttribute == nsGkAtoms::aria_flowto ||
1551 aAttribute == nsGkAtoms::aria_errormessage ||
1552 aAttribute == nsGkAtoms::aria_actions) {
1553 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
1554 }
1555
1556 if (aAttribute == nsGkAtoms::popovertarget) {
1557 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
1558 return;
1559 }
1560
1561 if (aAttribute == nsGkAtoms::commandfor) {
1562 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
1563 return;
1564 }
1565
1566 if (aAttribute == nsGkAtoms::alt &&
1567 !nsAccUtils::HasARIAAttr(elm, nsGkAtoms::aria_label) &&
1568 !elm->HasAttr(nsGkAtoms::aria_labelledby)) {
1569 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
1570 return;
1571 }
1572
1573 if (aAttribute == nsGkAtoms::title) {
1574 nsAutoString name;
1575 if (Name(name) == eNameFromTooltip || name.IsVoid()) {
1576 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, this);
1577 return;
1578 }
1579
1580 if (!elm->HasAttr(nsGkAtoms::aria_describedby)) {
1581 mDoc->FireDelayedEvent(nsIAccessibleEvent::EVENT_DESCRIPTION_CHANGE,
1582 this);
1583 }
1584
1585 return;
1586 }
1587
1588 // ARIA or XUL selection
1589 if ((mContent->IsXULElement() && aAttribute == nsGkAtoms::selected) ||
1590 aAttribute == nsGkAtoms::aria_selected) {
1591 if (aAttribute == nsGkAtoms::aria_selected) {
1592 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
1593 if (!roleMapEntry && IsHTMLTableCell() && Role() == roles::GRID_CELL) {
1594 // This is a <td> inside a role="grid"; see the similar case in
1595 // ApplyARIAState.
1596 roleMapEntry = aria::GetRoleMap(nsGkAtoms::gridcell);
1597 }
1598 if (roleMapEntry && roleMapEntry->IsSelectableIfDefined()) {
1599 // For these roles, whether aria-selected is "defined" (present and
1600 // neither empty nor "undefined") determines the selectable state.
1601 // For other selectable roles (option, tab, treeitem, etc.), the
1602 // selectable state doesn't depend on aria-selected's definedness, so
1603 // don't fire this there.
1604 const bool wasDefined =
1605 aOldValue && !aOldValue->IsEmptyString() &&
1606 !aOldValue->Equals(nsGkAtoms::_undefined, eCaseMatters);
1607 const bool isDefined =
1608 nsAccUtils::HasDefinedARIAToken(elm, nsGkAtoms::aria_selected);
1609 if (wasDefined != isDefined) {
1610 auto stateChangeEvent = MakeRefPtr<AccStateChangeEvent>(
1611 this, states::SELECTABLE, isDefined);
1612 mDoc->FireDelayedEvent(stateChangeEvent);
1613 }
1614 }
1615 }
1616
1617 LocalAccessible* widget = nsAccUtils::GetSelectableContainer(this, State());
1618 if (widget) {
1619 AccSelChangeEvent::SelChangeType selChangeType;
1620 if (aAttribute == nsGkAtoms::selected) {
1621 // The condition above guarantees a XUL element here. In XUL, `selected`
1622 // is a boolean attribute whose mere presence indicates selection,
1623 // unlike aria-selected which is "true"/"false".
1624 selChangeType = elm->HasAttr(nsGkAtoms::selected)
1625 ? AccSelChangeEvent::eSelectionAdd
1626 : AccSelChangeEvent::eSelectionRemove;
1627 } else {
1628 selChangeType = nsAccUtils::ARIAAttrValueIs(
1629 elm, aAttribute, nsGkAtoms::_true, eCaseMatters)
1630 ? AccSelChangeEvent::eSelectionAdd
1631 : AccSelChangeEvent::eSelectionRemove;
1632 }
1633
1634 auto event = MakeRefPtr<AccSelChangeEvent>(widget, this, selChangeType);
1635 mDoc->FireDelayedEvent(event);
1636 if (aAttribute == nsGkAtoms::aria_selected) {
1637 mDoc->QueueCacheUpdate(this, CacheDomain::State);
1638 }
1639 }
1640
1641 return;
1642 }
1643
1644 if (aAttribute == nsGkAtoms::aria_level ||
1645 aAttribute == nsGkAtoms::aria_setsize ||
1646 aAttribute == nsGkAtoms::aria_posinset) {
1647 mDoc->QueueCacheUpdate(this, CacheDomain::GroupInfo);
1648 return;
1649 }
1650
1651 if (aAttribute == nsGkAtoms::accesskey) {
1652 mDoc->QueueCacheUpdate(this, CacheDomain::Actions);
1653 }
1654
1655 if (aAttribute == nsGkAtoms::name &&
1656 (mContent && mContent->IsHTMLElement(nsGkAtoms::a))) {
1657 // If an anchor's name changed, it's possible a LINKS_TO relation
1658 // also changed. Push a cache update for Relations.
1659 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
1660 }
1661}
1662
1663void LocalAccessible::ARIAGroupPosition(int32_t* aLevel, int32_t* aSetSize,
1664 int32_t* aPosInSet) const {
1665 if (!mContent) {
1666 return;
1667 }
1668
1669 if (aLevel) {
1670 nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_level, aLevel);
1671 }
1672 if (aSetSize) {
1673 nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_setsize, aSetSize);
1674 }
1675 if (aPosInSet) {
1676 nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_posinset, aPosInSet);
1677 }
1678}
1679
1680uint64_t LocalAccessible::ExplicitState() const {
1681 if (IsDefunct()) return states::DEFUNCT;
1682
1683 uint64_t state = NativeState();
1684 // Apply ARIA states to be sure accessible states will be overridden.
1685 ApplyARIAState(&state);
1686
1687 if (!(state & states::UNAVAILABLE)) {
1688 // If the object is a current item of container widget then mark it as
1689 // ACTIVE. This allows screen reader virtual buffer modes to know which
1690 // descendant is the current one that would get focus if the user navigates
1691 // to the container widget.
1692 LocalAccessible* widget = ContainerWidget();
1693 if (widget && widget->CurrentItem() == this) state |= states::ACTIVE;
1694 }
1695
1696 return state;
1697}
1698
1699uint64_t LocalAccessible::State() {
1700 uint64_t state = ExplicitState();
1701
1702 ApplyImplicitState(state);
1703 return state;
1704}
1705
1706void LocalAccessible::ApplyARIAState(uint64_t* aState) const {
1707 if (!mContent->IsElement()) return;
1708
1709 dom::Element* element = mContent->AsElement();
1710
1711 // Test for universal states first
1712 *aState |= aria::UniversalStatesFor(element);
1713
1714 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
1715 if (!roleMapEntry && IsHTMLTableCell() && Role() == roles::GRID_CELL) {
1716 // This is a <td> inside a role="grid", so it gets an implicit role of
1717 // GRID_CELL in ARIATransformRole. However, because it's implicit, we
1718 // don't have a role map entry, and without that, we can't apply ARIA states
1719 // below. Therefore, we get the role map entry here.
1720 roleMapEntry = aria::GetRoleMap(nsGkAtoms::gridcell);
1721 MOZ_ASSERT(roleMapEntry, "Should have role map entry for gridcell")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(roleMapEntry)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(roleMapEntry))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("roleMapEntry" " ("
"Should have role map entry for gridcell" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 1721); AnnotateMozCrashReason("MOZ_ASSERT" "(" "roleMapEntry"
") (" "Should have role map entry for gridcell" ")"); do { MOZ_CrashSequence
(__null, 1721); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1722 }
1723 if (roleMapEntry) {
1724 // We only force the readonly bit off if we have a real mapping for the aria
1725 // role. This preserves the ability for screen readers to use readonly
1726 // (primarily on the document) as the hint for creating a virtual buffer.
1727 // Avoid doing this on text fields, since the readonly state is useful
1728 // there.
1729 if (roleMapEntry->role != roles::NOTHING && !IsTextField())
1730 *aState &= ~states::READONLY;
1731
1732 if (mContent->HasID()) {
1733 // If has a role & ID and aria-activedescendant on the container, assume
1734 // focusable.
1735 const LocalAccessible* ancestor = this;
1736 while ((ancestor = ancestor->LocalParent()) && !ancestor->IsDoc()) {
1737 dom::Element* el = ancestor->Elm();
1738 if (el && el->HasAttr(nsGkAtoms::aria_activedescendant)) {
1739 *aState |= states::FOCUSABLE;
1740 break;
1741 }
1742 }
1743 }
1744 }
1745
1746 if (!(*aState & states::FOCUSABLE)) {
1747 // Sometimes, we use aria-activedescendant targeting something which isn't
1748 // actually a descendant. This is technically a spec violation, but it's a
1749 // useful hack which makes certain things much easier. For example, we use
1750 // this for "fake focus" for multi select browser tabs and Quantumbar
1751 // autocomplete suggestions.
1752 // In these cases, the aria-activedescendant code above won't make the
1753 // active item focusable. It doesn't make sense for something to have
1754 // focus when it isn't focusable, so fix that here.
1755 if (FocusMgr()->IsActiveItem(this)) {
1756 *aState |= states::FOCUSABLE;
1757 }
1758 }
1759
1760 if (!roleMapEntry) {
1761 if (nsStaticAtom* ariaRole = ComputedARIARole()) {
1762 const nsRoleMapEntry* computedRoleMapEntry = aria::GetRoleMap(ariaRole);
1763 aria::MapToStateIfInRoleMapEntry(computedRoleMapEntry,
1764 aria::eARIAExpanded, element, aState);
1765 aria::MapToStateIfInRoleMapEntry(computedRoleMapEntry, aria::eARIAPressed,
1766 element, aState);
1767 }
1768 }
1769
1770 if (!IsTextField() && IsEditableRoot()) {
1771 // HTML text fields will have their own multi/single line calcuation in
1772 // NativeState.
1773 aria::MapToState(aria::eARIAMultilineByDefault, element, aState);
1774 }
1775
1776 if (!roleMapEntry) return;
1777
1778 *aState |= roleMapEntry->state;
1779
1780 if (aria::MapToState(roleMapEntry->attributeMap1, element, aState) &&
1781 aria::MapToState(roleMapEntry->attributeMap2, element, aState) &&
1782 aria::MapToState(roleMapEntry->attributeMap3, element, aState)) {
1783 aria::MapToState(roleMapEntry->attributeMap4, element, aState);
1784 }
1785
1786 // ARIA gridcell inherits readonly state from the grid until it's overridden.
1787 if ((roleMapEntry->Is(nsGkAtoms::gridcell) ||
1788 roleMapEntry->Is(nsGkAtoms::columnheader) ||
1789 roleMapEntry->Is(nsGkAtoms::rowheader)) &&
1790 // Don't recurse infinitely for an authoring error like
1791 // <table role="gridcell">. Without this check, we'd call TableFor(this)
1792 // below, which would return this.
1793 !IsTable() &&
1794 !nsAccUtils::HasDefinedARIAToken(mContent, nsGkAtoms::aria_readonly)) {
1795 if (const LocalAccessible* grid = nsAccUtils::TableFor(this)) {
1796 uint64_t gridState = 0;
1797 grid->ApplyARIAState(&gridState);
1798 *aState |= gridState & states::READONLY;
1799 }
1800 }
1801}
1802
1803void LocalAccessible::Value(nsString& aValue) const {
1804 if (HasNumericValue()) {
1805 // aria-valuenow is a number, and aria-valuetext is the optional text
1806 // equivalent. For the string value, we will try the optional text
1807 // equivalent first.
1808 if (!mContent->IsElement()) {
1809 return;
1810 }
1811
1812 if (!nsAccUtils::GetARIAAttr(mContent->AsElement(),
1813 nsGkAtoms::aria_valuetext, aValue)) {
1814 if (!NativeHasNumericValue()) {
1815 double checkValue = CurValue();
1816 if (!std::isnan(checkValue)) {
1817 aValue.AppendFloat(checkValue);
1818 }
1819 }
1820 }
1821 return;
1822 }
1823
1824 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
1825
1826 // The value of a textbox is the text content from its subtree.
1827 if (IsTextField() || (roleMapEntry && roleMapEntry->Is(nsGkAtoms::textbox)) ||
1828 (IsGeneric() && IsEditableRoot())) {
1829 TextLeafRange::FromAccessible(const_cast<LocalAccessible*>(this))
1830 .GetFlattenedText(aValue);
1831 return;
1832 }
1833
1834 // Value of combobox is a text of current or selected item.
1835 if (roleMapEntry && roleMapEntry->Is(nsGkAtoms::combobox)) {
1836 LocalAccessible* option = CurrentItem();
1837 if (!option) {
1838 uint32_t childCount = ChildCount();
1839 for (uint32_t idx = 0; idx < childCount; idx++) {
1840 LocalAccessible* child = mChildren.ElementAt(idx);
1841 if (child->IsListControl()) {
1842 Accessible* acc = child->GetSelectedItem(0);
1843 option = acc ? acc->AsLocal() : nullptr;
1844 break;
1845 }
1846 }
1847 }
1848
1849 // If there's a selected item, get the value from it. Otherwise, determine
1850 // the value from descendant elements.
1851 nsTextEquivUtils::GetTextEquivFromSubtree(option ? option : this, aValue);
1852 }
1853}
1854
1855double LocalAccessible::MaxValue() const {
1856 double checkValue = AttrNumericValue(nsGkAtoms::aria_valuemax);
1857 if (std::isnan(checkValue) && !NativeHasNumericValue()) {
1858 // aria-valuemax isn't present and this element doesn't natively provide a
1859 // maximum value. Use the ARIA default.
1860 const nsRoleMapEntry* roleMap = ARIARoleMap();
1861 if (roleMap && roleMap->role == roles::SPINBUTTON) {
1862 return UnspecifiedNaN<double>();
1863 }
1864 return 100;
1865 }
1866 return checkValue;
1867}
1868
1869double LocalAccessible::MinValue() const {
1870 double checkValue = AttrNumericValue(nsGkAtoms::aria_valuemin);
1871 if (std::isnan(checkValue) && !NativeHasNumericValue()) {
1872 // aria-valuemin isn't present and this element doesn't natively provide a
1873 // minimum value. Use the ARIA default.
1874 const nsRoleMapEntry* roleMap = ARIARoleMap();
1875 if (roleMap && roleMap->role == roles::SPINBUTTON) {
1876 return UnspecifiedNaN<double>();
1877 }
1878 return 0;
1879 }
1880 return checkValue;
1881}
1882
1883double LocalAccessible::Step() const {
1884 return UnspecifiedNaN<double>(); // no mimimum increment (step) in ARIA.
1885}
1886
1887double LocalAccessible::CurValue() const {
1888 double checkValue = AttrNumericValue(nsGkAtoms::aria_valuenow);
1889 if (std::isnan(checkValue) && !NativeHasNumericValue()) {
1890 // aria-valuenow isn't present and this element doesn't natively provide a
1891 // current value. Use the ARIA default.
1892 const nsRoleMapEntry* roleMap = ARIARoleMap();
1893 if (roleMap && roleMap->role == roles::SPINBUTTON) {
1894 return UnspecifiedNaN<double>();
1895 }
1896 double minValue = MinValue();
1897 return minValue + ((MaxValue() - minValue) / 2);
1898 }
1899
1900 return checkValue;
1901}
1902
1903bool LocalAccessible::SetCurValue(double /*aValue*/) { return false; }
1904
1905role LocalAccessible::NativeRole() const { return roles::NOTHING; }
1906
1907uint8_t LocalAccessible::ActionCount() const {
1908 return HasPrimaryAction() || ActionAncestor() ? 1 : 0;
1909}
1910
1911void LocalAccessible::ActionNameAt(uint8_t aIndex, nsAString& aName) {
1912 aName.Truncate();
1913
1914 if (aIndex != 0) return;
1915
1916 uint32_t actionRule = GetActionRule();
1917
1918 switch (actionRule) {
1919 case eActivateAction:
1920 aName.AssignLiteral("activate");
1921 return;
1922
1923 case eClickAction:
1924 aName.AssignLiteral("click");
1925 return;
1926
1927 case ePressAction:
1928 aName.AssignLiteral("press");
1929 return;
1930
1931 case eCheckUncheckAction: {
1932 uint64_t state = State();
1933 if (state & states::CHECKED) {
1934 aName.AssignLiteral("uncheck");
1935 } else if (state & states::MIXED) {
1936 aName.AssignLiteral("cycle");
1937 } else {
1938 aName.AssignLiteral("check");
1939 }
1940 return;
1941 }
1942
1943 case eJumpAction:
1944 aName.AssignLiteral("jump");
1945 return;
1946
1947 case eOpenCloseAction:
1948 if (State() & states::EXPANDED) {
1949 aName.AssignLiteral("close");
1950 } else {
1951 aName.AssignLiteral("open");
1952 }
1953 return;
1954
1955 case eSelectAction:
1956 aName.AssignLiteral("select");
1957 return;
1958
1959 case eSwitchAction:
1960 aName.AssignLiteral("switch");
1961 return;
1962
1963 case eSortAction:
1964 aName.AssignLiteral("sort");
1965 return;
1966
1967 case eExpandAction:
1968 if (State() & states::EXPANDED) {
1969 aName.AssignLiteral("collapse");
1970 } else {
1971 aName.AssignLiteral("expand");
1972 }
1973 return;
1974 }
1975
1976 if (ActionAncestor()) {
1977 aName.AssignLiteral("clickAncestor");
1978 return;
1979 }
1980}
1981
1982bool LocalAccessible::DoAction(uint8_t aIndex) const {
1983 if (aIndex != 0) return false;
1984
1985 if (HasPrimaryAction() || ActionAncestor()) {
1986 DoCommand();
1987 return true;
1988 }
1989
1990 return false;
1991}
1992
1993bool LocalAccessible::HasPrimaryAction() const {
1994 return GetActionRule() != eNoAction;
1995}
1996
1997nsIContent* LocalAccessible::GetAtomicRegion() const {
1998 nsIContent* loopContent = mContent;
1999 nsAutoString atomic;
2000 while (loopContent &&
2001 (!loopContent->IsElement() ||
2002 !nsAccUtils::GetARIAAttr(loopContent->AsElement(),
2003 nsGkAtoms::aria_atomic, atomic))) {
2004 loopContent = loopContent->GetParent();
2005 }
2006
2007 return atomic.EqualsLiteral("true") ? loopContent : nullptr;
2008}
2009
2010static bool IsHintPopover(nsIContent* aContent) {
2011 auto* htmlEl = nsGenericHTMLElement::FromNode(aContent);
2012 return htmlEl &&
2013 htmlEl->GetPopoverAttributeState() == dom::PopoverAttributeState::Hint;
2014}
2015
2016static bool IsOpenHintPopover(nsIContent* aContent) {
2017 auto* htmlEl = nsGenericHTMLElement::FromNode(aContent);
2018 return htmlEl && htmlEl->PopoverOpen() &&
2019 htmlEl->GetPopoverAttributeState() == dom::PopoverAttributeState::Hint;
2020}
2021
2022// Returns true if targetEl is:
2023// - a non hint popover (these should always use details, not described by).
2024// - a hint popover that is not open (no relation should be established).
2025// - a hint popover with "rich" content (for non-rich content, desdcribed by
2026// should be established instead).
2027static bool ShouldHintPopoverEstablishDetailsRelation(
2028 dom::Element* aTargetEl, LocalAccessible* aTargetAcc) {
2029 if (!IsHintPopover(aTargetEl)) {
2030 return true;
2031 }
2032 if (!IsOpenHintPopover(aTargetEl)) {
2033 return false;
2034 }
2035 return !aTargetAcc->IsOnlyPlainContent();
2036}
2037
2038static bool ShouldHintPopoverEstablishDescribedByRelation(
2039 dom::Element* aTargetEl, LocalAccessible* aTargetAcc) {
2040 return IsOpenHintPopover(aTargetEl) && aTargetAcc->IsOnlyPlainContent();
2041}
2042
2043LocalAccessible* LocalAccessible::GetCommandForDetailsRelation() const {
2044 dom::Element* targetEl = mContent->GetEffectiveCommandForElement();
2045 if (!targetEl) {
2046 return nullptr;
2047 }
2048 LocalAccessible* targetAcc = mDoc->GetAccessible(targetEl);
2049 if (!targetAcc) {
2050 return nullptr;
2051 }
2052 // Relations on Command/CommandFor should only be for ShowPopover &
2053 // TogglePopover commands.
2054 if (const nsAttrValue* actionVal = Elm()->GetParsedAttr(nsGkAtoms::command)) {
2055 if (actionVal && actionVal->Type() != nsAttrValue::eEnum) {
2056 return nullptr;
2057 }
2058 auto command =
2059 static_cast<dom::Element::Command>(actionVal->GetEnumValue());
2060 if (command != dom::Element::Command::ShowPopover &&
2061 command != dom::Element::Command::TogglePopover) {
2062 return nullptr;
2063 }
2064 }
2065 if (targetAcc->NextSibling() == this || targetAcc->PrevSibling() == this) {
2066 return nullptr;
2067 }
2068 if (!ShouldHintPopoverEstablishDetailsRelation(targetEl, targetAcc)) {
2069 return nullptr;
2070 }
2071 return targetAcc;
2072}
2073
2074LocalAccessible* LocalAccessible::GetPopoverTargetDetailsRelation() const {
2075 dom::Element* targetEl = mContent->GetEffectivePopoverTargetElement();
2076 if (!targetEl) {
2077 return nullptr;
2078 }
2079 LocalAccessible* targetAcc = mDoc->GetAccessible(targetEl);
2080 if (!targetAcc) {
2081 return nullptr;
2082 }
2083 // Even if the popovertarget is valid, there are a few cases where we must not
2084 // expose it via the details relation.
2085 if (const nsAttrValue* actionVal =
2086 Elm()->GetParsedAttr(nsGkAtoms::popovertargetaction)) {
2087 if (static_cast<PopoverTargetAction>(actionVal->GetEnumValue()) ==
2088 PopoverTargetAction::Hide) {
2089 return nullptr;
2090 }
2091 }
2092 if (targetAcc->NextSibling() == this || targetAcc->PrevSibling() == this) {
2093 return nullptr;
2094 }
2095 if (!ShouldHintPopoverEstablishDetailsRelation(targetEl, targetAcc)) {
2096 return nullptr;
2097 }
2098 return targetAcc;
2099}
2100
2101LocalAccessible* LocalAccessible::GetAnchorPositionTargetDetailsRelation()
2102 const {
2103 if (!StaticPrefs::accessibility_anchorPositionedAsDetails_enabled()) {
2104 return nullptr;
2105 }
2106 nsIFrame* positionedFrame = nsCoreUtils::GetPositionedFrameForAnchor(
2107 mDoc->PresShellPtr(), GetFrame());
2108 if (!positionedFrame) {
2109 return nullptr;
2110 }
2111
2112 if (!nsCoreUtils::GetAnchorForPositionedFrame(mDoc->PresShellPtr(),
2113 positionedFrame)) {
2114 // There is no reciprocal, 1:1, anchor for this positioned frame.
2115 return nullptr;
2116 }
2117
2118 LocalAccessible* targetAcc =
2119 mDoc->GetAccessible(positionedFrame->GetContent());
2120
2121 if (!targetAcc) {
2122 return nullptr;
2123 }
2124
2125 if (targetAcc->Role() == roles::TOOLTIP) {
2126 // A tooltip is never a valid target for details relation.
2127 return nullptr;
2128 }
2129
2130 AssociatedElementsIterator describedby(mDoc, GetContent(),
2131 nsGkAtoms::aria_describedby);
2132 while (LocalAccessible* target = describedby.Next()) {
2133 if (target == targetAcc) {
2134 // An explicit description relation exists, so we don't want to create a
2135 // details relation.
2136 return nullptr;
2137 }
2138 }
2139
2140 AssociatedElementsIterator labelledby(mDoc, GetContent(),
2141 nsGkAtoms::aria_labelledby);
2142 while (LocalAccessible* target = labelledby.Next()) {
2143 if (target == targetAcc) {
2144 // An explicit label relation exists, so we don't want to create a details
2145 // relation.
2146 return nullptr;
2147 }
2148 }
2149
2150 dom::Element* anchorEl = targetAcc->Elm();
2151 if (anchorEl && anchorEl->HasAttr(nsGkAtoms::aria_details)) {
2152 // If the anchor has an explicit aria-details attribute, then we don't want
2153 // to create a details relation.
2154 return nullptr;
2155 }
2156
2157 dom::Element* targetEl = Elm();
2158 if (targetEl && targetEl->HasAttr(nsGkAtoms::aria_details)) {
2159 // If the target has an explicit aria-details attribute, then we don't want
2160 // to create a details relation.
2161 return nullptr;
2162 }
2163
2164 return targetAcc;
2165}
2166
2167LocalAccessible* LocalAccessible::GetPopoverTargetDescribedByRelation() const {
2168 dom::Element* targetEl = mContent->GetEffectivePopoverTargetElement();
2169 if (!targetEl) {
2170 return nullptr;
2171 }
2172 LocalAccessible* targetAcc = mDoc->GetAccessible(targetEl);
2173 if (!targetAcc) {
2174 return nullptr;
2175 }
2176 if (const nsAttrValue* actionVal =
2177 Elm()->GetParsedAttr(nsGkAtoms::popovertargetaction)) {
2178 if (static_cast<PopoverTargetAction>(actionVal->GetEnumValue()) ==
2179 PopoverTargetAction::Hide) {
2180 return nullptr;
2181 }
2182 }
2183 if (ShouldHintPopoverEstablishDescribedByRelation(targetEl, targetAcc)) {
2184 return targetAcc;
2185 }
2186 return nullptr;
2187}
2188
2189LocalAccessible* LocalAccessible::GetCommandForDescribedByRelation() const {
2190 dom::Element* targetEl = mContent->GetEffectiveCommandForElement();
2191 if (!targetEl) {
2192 return nullptr;
2193 }
2194 LocalAccessible* targetAcc = mDoc->GetAccessible(targetEl);
2195 if (!targetAcc) {
2196 return nullptr;
2197 }
2198 if (const nsAttrValue* actionVal = Elm()->GetParsedAttr(nsGkAtoms::command)) {
2199 if (actionVal && actionVal->Type() != nsAttrValue::eEnum) {
2200 return nullptr;
2201 }
2202 auto command =
2203 static_cast<dom::Element::Command>(actionVal->GetEnumValue());
2204 if (command != dom::Element::Command::ShowPopover &&
2205 command != dom::Element::Command::TogglePopover) {
2206 return nullptr;
2207 }
2208 }
2209 if (ShouldHintPopoverEstablishDescribedByRelation(targetEl, targetAcc)) {
2210 return targetAcc;
2211 }
2212 return nullptr;
2213}
2214
2215Relation LocalAccessible::RelationByType(RelationType aType) const {
2216 if (!HasOwnContent()) return Relation();
2217
2218 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
2219
2220 // Relationships are defined on the same content node that the role would be
2221 // defined on.
2222 switch (aType) {
2223 case RelationType::LABELLED_BY: {
2224 Relation rel(new AssociatedElementsIterator(mDoc, mContent,
2225 nsGkAtoms::aria_labelledby));
2226 if (mContent->IsHTMLElement()) {
2227 rel.AppendIter(new HTMLLabelIterator(mDoc, this));
2228 }
2229 rel.AppendIter(new XULLabelIterator(Document(), mContent));
2230
2231 return rel;
2232 }
2233
2234 case RelationType::LABEL_FOR: {
2235 Relation rel(new RelatedAccIterator(Document(), mContent,
2236 nsGkAtoms::aria_labelledby));
2237 if (mContent->IsXULElement(nsGkAtoms::label)) {
2238 rel.AppendIter(
2239 new AssociatedElementsIterator(mDoc, mContent, nsGkAtoms::control));
2240 }
2241
2242 return rel;
2243 }
2244
2245 case RelationType::DESCRIBED_BY: {
2246 Relation rel(new AssociatedElementsIterator(mDoc, mContent,
2247 nsGkAtoms::aria_describedby));
2248 if (mContent->IsXULElement()) {
2249 rel.AppendIter(new XULDescriptionIterator(Document(), mContent));
2250 }
2251 if (LocalAccessible* target = GetCommandForDescribedByRelation()) {
2252 rel.AppendTarget(target);
2253 }
2254 if (LocalAccessible* target = GetPopoverTargetDescribedByRelation()) {
2255 rel.AppendTarget(target);
2256 }
2257
2258 return rel;
2259 }
2260
2261 case RelationType::DESCRIPTION_FOR: {
2262 Relation rel(new RelatedAccIterator(Document(), mContent,
2263 nsGkAtoms::aria_describedby));
2264
2265 // This affectively adds an optional control attribute to xul:description,
2266 // which only affects accessibility, by allowing the description to be
2267 // tied to a control.
2268 if (mContent->IsXULElement(nsGkAtoms::description)) {
2269 rel.AppendIter(
2270 new AssociatedElementsIterator(mDoc, mContent, nsGkAtoms::control));
2271 }
2272
2273 RelatedAccIterator popoverInvokers(mDoc, mContent,
2274 nsGkAtoms::popovertarget);
2275 while (Accessible* invoker = popoverInvokers.Next()) {
2276 if (invoker->AsLocal()->GetPopoverTargetDescribedByRelation()) {
2277 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetPopoverTargetDescribedByRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetPopoverTargetDescribedByRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetPopoverTargetDescribedByRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2279);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetPopoverTargetDescribedByRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2279); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2278 invoker->AsLocal()->GetPopoverTargetDescribedByRelation() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetPopoverTargetDescribedByRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetPopoverTargetDescribedByRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetPopoverTargetDescribedByRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2279);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetPopoverTargetDescribedByRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2279); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2279 this)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetPopoverTargetDescribedByRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetPopoverTargetDescribedByRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetPopoverTargetDescribedByRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2279);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetPopoverTargetDescribedByRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2279); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2280 rel.AppendTarget(invoker);
2281 }
2282 }
2283 RelatedAccIterator commandInvokers(mDoc, mContent, nsGkAtoms::commandfor);
2284 while (Accessible* invoker = commandInvokers.Next()) {
2285 if (invoker->AsLocal()->GetCommandForDescribedByRelation()) {
2286 MOZ_ASSERT(invoker->AsLocal()->GetCommandForDescribedByRelation() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetCommandForDescribedByRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetCommandForDescribedByRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetCommandForDescribedByRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2287);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetCommandForDescribedByRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2287); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2287 this)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetCommandForDescribedByRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetCommandForDescribedByRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetCommandForDescribedByRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2287);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetCommandForDescribedByRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2287); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2288 rel.AppendTarget(invoker);
2289 }
2290 }
2291
2292 return rel;
2293 }
2294
2295 case RelationType::NODE_CHILD_OF: {
2296 Relation rel;
2297 // This is an ARIA tree or treegrid that doesn't use owns, so we need to
2298 // get the parent the hard way.
2299 if (roleMapEntry && (roleMapEntry->role == roles::OUTLINEITEM ||
2300 roleMapEntry->role == roles::LISTITEM ||
2301 roleMapEntry->role == roles::ROW)) {
2302 AccGroupInfo* groupInfo =
2303 const_cast<LocalAccessible*>(this)->GetOrCreateGroupInfo();
2304 if (groupInfo) {
2305 Accessible* parent = groupInfo->ConceptualParent();
2306 if (parent) {
2307 MOZ_ASSERT(parent->IsLocal())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->IsLocal())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(parent->IsLocal()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("parent->IsLocal()"
, "./../../../accessible/generic/LocalAccessible.cpp", 2307);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "parent->IsLocal()"
")"); do { MOZ_CrashSequence(__null, 2307); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2308 rel.AppendTarget(parent->AsLocal());
2309 }
2310 }
2311 }
2312
2313 // If this is an OOP iframe document, we can't support NODE_CHILD_OF
2314 // here, since the iframe resides in a different process. This is fine
2315 // because the client will then request the parent instead, which will be
2316 // correctly handled by platform code.
2317 if (XRE_IsContentProcess() && IsRoot()) {
2318 dom::Document* doc =
2319 const_cast<LocalAccessible*>(this)->AsDoc()->DocumentNode();
2320 dom::BrowsingContext* bc = doc->GetBrowsingContext();
2321 MOZ_ASSERT(bc)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(bc)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(bc))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("bc", "./../../../accessible/generic/LocalAccessible.cpp"
, 2321); AnnotateMozCrashReason("MOZ_ASSERT" "(" "bc" ")"); do
{ MOZ_CrashSequence(__null, 2321); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
2322 if (!bc->Top()->IsInProcess()) {
2323 return rel;
2324 }
2325 }
2326
2327 // If accessible is in its own Window, or is the root of a document,
2328 // then we should provide NODE_CHILD_OF relation so that MSAA clients
2329 // can easily get to true parent instead of getting to oleacc's
2330 // ROLE_WINDOW accessible which will prevent us from going up further
2331 // (because it is system generated and has no idea about the hierarchy
2332 // above it).
2333 if (nsIFrame* frame = GetFrame()) {
2334 ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(frame);
2335 if (scrollContainerFrame || frame->GetOwnWidget() ||
2336 !frame->GetParent()) {
2337 rel.AppendTarget(LocalParent());
2338 }
2339 }
2340
2341 return rel;
2342 }
2343
2344 case RelationType::NODE_PARENT_OF: {
2345 // ARIA tree or treegrid can do the hierarchy by @aria-level, ARIA trees
2346 // also can be organized by groups.
2347 if (roleMapEntry && (roleMapEntry->role == roles::OUTLINEITEM ||
2348 roleMapEntry->role == roles::LISTITEM ||
2349 roleMapEntry->role == roles::ROW ||
2350 roleMapEntry->role == roles::OUTLINE ||
2351 roleMapEntry->role == roles::LIST ||
2352 roleMapEntry->role == roles::TREE_TABLE)) {
2353 return Relation(new ItemIterator(this));
2354 }
2355
2356 return Relation();
2357 }
2358
2359 case RelationType::CONTROLLED_BY: {
2360 Relation rel(new RelatedAccIterator(Document(), mContent,
2361 nsGkAtoms::aria_controls));
2362
2363 RelatedAccIterator owners(Document(), mContent, nsGkAtoms::aria_owns);
2364 if (LocalAccessible* owner = owners.Next()) {
2365 if (nsAccUtils::IsEditableARIACombobox(owner)) {
2366 MOZ_ASSERT(!IsRelocated(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsRelocated())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsRelocated()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!IsRelocated()"
" (" "Child is not relocated to editable combobox" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 2367); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!IsRelocated()"
") (" "Child is not relocated to editable combobox" ")"); do
{ MOZ_CrashSequence(__null, 2367); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
2367 "Child is not relocated to editable combobox")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsRelocated())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsRelocated()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!IsRelocated()"
" (" "Child is not relocated to editable combobox" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 2367); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!IsRelocated()"
") (" "Child is not relocated to editable combobox" ")"); do
{ MOZ_CrashSequence(__null, 2367); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
2368 rel.AppendTarget(owner);
2369 }
2370 }
2371
2372 return rel;
2373 }
2374 case RelationType::CONTROLLER_FOR: {
2375 Relation rel(new AssociatedElementsIterator(mDoc, mContent,
2376 nsGkAtoms::aria_controls));
2377 rel.AppendIter(new HTMLOutputIterator(Document(), mContent));
2378 if (nsAccUtils::IsEditableARIACombobox(this)) {
2379 AssociatedElementsIterator iter(mDoc, mContent, nsGkAtoms::aria_owns);
2380 while (Accessible* owned_child = iter.Next()) {
2381 MOZ_ASSERT(!owned_child->AsLocal()->IsRelocated())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!owned_child->AsLocal()->IsRelocated())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(!owned_child->AsLocal()->IsRelocated()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!owned_child->AsLocal()->IsRelocated()"
, "./../../../accessible/generic/LocalAccessible.cpp", 2381);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "!owned_child->AsLocal()->IsRelocated()"
")"); do { MOZ_CrashSequence(__null, 2381); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2382 rel.AppendTarget(owned_child->AsLocal());
2383 }
2384 }
2385 return rel;
2386 }
2387
2388 case RelationType::FLOWS_TO:
2389 return Relation(new AssociatedElementsIterator(mDoc, mContent,
2390 nsGkAtoms::aria_flowto));
2391
2392 case RelationType::FLOWS_FROM:
2393 return Relation(
2394 new RelatedAccIterator(Document(), mContent, nsGkAtoms::aria_flowto));
2395
2396 case RelationType::MEMBER_OF: {
2397 if (Role() == roles::RADIOBUTTON) {
2398 /* If we see a radio button role here, we're dealing with an aria
2399 * radio button (because input=radio buttons are
2400 * HTMLRadioButtonAccessibles) */
2401 Relation rel = Relation();
2402 LocalAccessible* currParent = LocalParent();
2403 while (currParent && currParent->Role() != roles::RADIO_GROUP) {
2404 currParent = currParent->LocalParent();
2405 }
2406
2407 if (currParent && currParent->Role() == roles::RADIO_GROUP) {
2408 /* If we found a radiogroup parent, search for all
2409 * roles::RADIOBUTTON children and add them to our relation.
2410 * This search will include the radio button this method
2411 * was called from, which is expected. */
2412 Pivot p = Pivot(currParent);
2413 PivotRoleRule rule(roles::RADIOBUTTON);
2414 Accessible* match = p.Next(currParent, rule);
2415 while (match) {
2416 MOZ_ASSERT(match->IsLocal(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(match->IsLocal())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(match->IsLocal()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("match->IsLocal()"
" (" "We shouldn't find any remote accs while building our "
"relation!" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 2418); AnnotateMozCrashReason("MOZ_ASSERT" "(" "match->IsLocal()"
") (" "We shouldn't find any remote accs while building our "
"relation!" ")"); do { MOZ_CrashSequence(__null, 2418); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
2417 "We shouldn't find any remote accs while building our "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(match->IsLocal())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(match->IsLocal()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("match->IsLocal()"
" (" "We shouldn't find any remote accs while building our "
"relation!" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 2418); AnnotateMozCrashReason("MOZ_ASSERT" "(" "match->IsLocal()"
") (" "We shouldn't find any remote accs while building our "
"relation!" ")"); do { MOZ_CrashSequence(__null, 2418); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
2418 "relation!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(match->IsLocal())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(match->IsLocal()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("match->IsLocal()"
" (" "We shouldn't find any remote accs while building our "
"relation!" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 2418); AnnotateMozCrashReason("MOZ_ASSERT" "(" "match->IsLocal()"
") (" "We shouldn't find any remote accs while building our "
"relation!" ")"); do { MOZ_CrashSequence(__null, 2418); __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
2419 rel.AppendTarget(match->AsLocal());
2420 match = p.Next(match, rule);
2421 }
2422 }
2423
2424 /* By webkit's standard, aria radio buttons do not get grouped
2425 * if they lack a group parent, so we return an empty
2426 * relation here if the above check fails. */
2427
2428 return rel;
2429 }
2430
2431 return Relation(mDoc, GetAtomicRegion());
2432 }
2433
2434 case RelationType::LINKS_TO: {
2435 Relation rel = Relation();
2436 if (Role() == roles::LINK) {
2437 dom::HTMLAnchorElement* anchor =
2438 dom::HTMLAnchorElement::FromNode(mContent);
2439 if (!anchor) {
2440 return rel;
2441 }
2442 // If this node is an anchor element, query its hash to find the
2443 // target.
2444 nsAutoCString hash;
2445 anchor->GetHash(hash);
2446 if (hash.IsEmpty()) {
2447 return rel;
2448 }
2449
2450 // GetHash returns an ID or name with a leading '#', trim it so we can
2451 // search the doc by ID or name alone.
2452 NS_ConvertUTF8toUTF16 hash16(Substring(hash, 1));
2453 if (dom::Element* elm = mContent->OwnerDoc()->GetElementById(hash16)) {
2454 rel.AppendTarget(mDoc->GetAccessibleOrContainer(elm));
2455 } else if (RefPtr<dom::NodeList> list =
2456 mContent->OwnerDoc()->GetElementsByName(hash16)) {
2457 // Loop through the named nodes looking for the first anchor
2458 uint32_t length = list->Length();
2459 for (uint32_t i = 0; i < length; i++) {
2460 nsIContent* node = list->Item(i);
2461 if (node->IsHTMLElement(nsGkAtoms::a)) {
2462 rel.AppendTarget(mDoc->GetAccessibleOrContainer(node));
2463 break;
2464 }
2465 }
2466 }
2467 }
2468
2469 return rel;
2470 }
2471
2472 case RelationType::SUBWINDOW_OF:
2473 case RelationType::EMBEDS:
2474 case RelationType::EMBEDDED_BY:
2475 case RelationType::POPUP_FOR:
2476 case RelationType::PARENT_WINDOW_OF:
2477 return Relation();
2478
2479 case RelationType::DEFAULT_BUTTON: {
2480 if (mContent->IsHTMLElement()) {
2481 // HTML form controls implements nsIFormControl interface.
2482 if (auto* control = nsIFormControl::FromNode(mContent)) {
2483 if (dom::HTMLFormElement* form = control->GetFormInternal()) {
2484 return Relation(mDoc, form->GetDefaultSubmitElement());
2485 }
2486 }
2487 } else {
2488 // In XUL, use first <button default="true" .../> in the document
2489 dom::Document* doc = mContent->OwnerDoc();
2490 nsIContent* buttonEl = nullptr;
2491 if (doc->AllowXULXBL()) {
2492 RefPtr<dom::HTMLCollection> possibleDefaultButtons =
2493 doc->GetElementsByAttribute(u"default"_ns, u"true"_ns);
2494 if (possibleDefaultButtons) {
2495 uint32_t length = possibleDefaultButtons->Length();
2496 // Check for button in list of default="true" elements
2497 for (uint32_t count = 0; count < length && !buttonEl; count++) {
2498 nsIContent* item = possibleDefaultButtons->Item(count);
2499 RefPtr<nsIDOMXULButtonElement> button =
2500 item->IsElement() ? item->AsElement()->AsXULButton()
2501 : nullptr;
2502 if (button) {
2503 buttonEl = item;
2504 }
2505 }
2506 }
2507 return Relation(mDoc, buttonEl);
2508 }
2509 }
2510 return Relation();
2511 }
2512
2513 case RelationType::CONTAINING_DOCUMENT:
2514 return Relation(mDoc);
2515
2516 case RelationType::CONTAINING_TAB_PANE: {
2517 nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(GetNode());
2518 if (docShell) {
2519 // Walk up the parent chain without crossing the boundary at which item
2520 // types change, preventing us from walking up out of tab content.
2521 nsCOMPtr<nsIDocShellTreeItem> root;
2522 docShell->GetInProcessSameTypeRootTreeItem(getter_AddRefs(root));
2523 if (root) {
2524 // If the item type is typeContent, we assume we are in browser tab
2525 // content. Note, this includes content such as about:addons,
2526 // for consistency.
2527 if (root->ItemType() == nsIDocShellTreeItem::typeContent) {
2528 return Relation(nsAccUtils::GetDocAccessibleFor(root));
2529 }
2530 }
2531 }
2532 return Relation();
2533 }
2534
2535 case RelationType::CONTAINING_APPLICATION:
2536 return Relation(ApplicationAcc());
2537
2538 case RelationType::DETAILS: {
2539 if (mContent->IsElement() &&
2540 nsAccUtils::HasARIAAttr(mContent->AsElement(),
2541 nsGkAtoms::aria_details)) {
2542 return Relation(new AssociatedElementsIterator(
2543 mDoc, mContent, nsGkAtoms::aria_details));
2544 }
2545 if (LocalAccessible* target = GetCommandForDetailsRelation()) {
2546 return Relation(target);
2547 }
2548 if (LocalAccessible* target = GetPopoverTargetDetailsRelation()) {
2549 return Relation(target);
2550 }
2551 if (LocalAccessible* target = GetAnchorPositionTargetDetailsRelation()) {
2552 if (nsAccUtils::IsValidDetailsTargetForAnchor(target, this)) {
2553 return Relation(target);
2554 }
2555 }
2556
2557 return Relation();
2558 }
2559
2560 case RelationType::DETAILS_FOR: {
2561 Relation rel(
2562 new RelatedAccIterator(mDoc, mContent, nsGkAtoms::aria_details));
2563 RelatedAccIterator popover_invokers(mDoc, mContent,
2564 nsGkAtoms::popovertarget);
2565 while (Accessible* invoker = popover_invokers.Next()) {
2566 // We should only expose DETAILS_FOR if DETAILS was exposed on the
2567 // invoker. However, DETAILS exposure on popover invokers is
2568 // conditional.
2569 if (invoker->AsLocal()->GetPopoverTargetDetailsRelation()) {
2570 MOZ_ASSERT(invoker->AsLocal()->GetPopoverTargetDetailsRelation() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetPopoverTargetDetailsRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetPopoverTargetDetailsRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetPopoverTargetDetailsRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2571);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetPopoverTargetDetailsRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2571); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2571 this)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetPopoverTargetDetailsRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetPopoverTargetDetailsRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetPopoverTargetDetailsRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2571);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetPopoverTargetDetailsRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2571); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2572 rel.AppendTarget(invoker);
2573 }
2574 }
2575 RelatedAccIterator command_invokers(mDoc, mContent,
2576 nsGkAtoms::commandfor);
2577 while (Accessible* invoker = command_invokers.Next()) {
2578 // We should only expose DETAILS_FOR if DETAILS was exposed on the
2579 // invoker. However, DETAILS exposure on popover invokers is
2580 // conditional.
2581 if (invoker->AsLocal()->GetCommandForDetailsRelation()) {
2582 MOZ_ASSERT(invoker->AsLocal()->GetCommandForDetailsRelation() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetCommandForDetailsRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetCommandForDetailsRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetCommandForDetailsRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2583);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetCommandForDetailsRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2583); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2583 this)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(invoker->AsLocal()->GetCommandForDetailsRelation
() == this)>::isValid, "invalid assertion condition"); if (
(__builtin_expect(!!(!(!!(invoker->AsLocal()->GetCommandForDetailsRelation
() == this))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("invoker->AsLocal()->GetCommandForDetailsRelation() == this"
, "./../../../accessible/generic/LocalAccessible.cpp", 2583);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "invoker->AsLocal()->GetCommandForDetailsRelation() == this"
")"); do { MOZ_CrashSequence(__null, 2583); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2584 rel.AppendTarget(invoker);
2585 }
2586 }
2587
2588 // Check early if the accessible is a tooltip. If so, it can never be a
2589 // valid target for an anchor's details relation.
2590 if (StaticPrefs::accessibility_anchorPositionedAsDetails_enabled() &&
2591 Role() != roles::TOOLTIP) {
2592 if (const nsIFrame* anchorFrame =
2593 nsCoreUtils::GetAnchorForPositionedFrame(mDoc->PresShellPtr(),
2594 GetFrame())) {
2595 LocalAccessible* anchorAcc =
2596 mDoc->GetAccessible(anchorFrame->GetContent());
2597 if (anchorAcc &&
2598 anchorAcc->GetAnchorPositionTargetDetailsRelation() == this &&
2599 nsAccUtils::IsValidDetailsTargetForAnchor(this, anchorAcc)) {
2600 rel.AppendTarget(anchorAcc);
2601 }
2602 }
2603 }
2604
2605 return rel;
2606 }
2607
2608 case RelationType::ERRORMSG:
2609 if (!(ExplicitState() & states::INVALID)) {
2610 return Relation();
2611 }
2612 return Relation(new AssociatedElementsIterator(
2613 mDoc, mContent, nsGkAtoms::aria_errormessage));
2614
2615 case RelationType::ERRORMSG_FOR:
2616 return Relation(
2617 new RelatedAccIterator(mDoc, mContent, nsGkAtoms::aria_errormessage));
2618
2619 case RelationType::ACTION:
2620 return Relation(new AssociatedElementsIterator(mDoc, mContent,
2621 nsGkAtoms::aria_actions));
2622
2623 case RelationType::ACTION_FOR:
2624 return Relation(
2625 new RelatedAccIterator(mDoc, mContent, nsGkAtoms::aria_actions));
2626
2627 default:
2628 return Relation();
2629 }
2630}
2631
2632void LocalAccessible::GetNativeInterface(void** aNativeAccessible) {}
2633
2634void LocalAccessible::DoCommand(uint32_t aActionIndex) const {
2635 NS_DispatchToMainThread(NS_NewRunnableFunction(
2636 "LocalAccessible::DispatchClickEvent",
2637 [aActionIndex, acc = RefPtr{this}]() MOZ_CAN_RUN_SCRIPT_BOUNDARY {
2638 acc->DispatchClickEvent(aActionIndex);
2639 }));
2640}
2641
2642void LocalAccessible::DispatchClickEvent(uint32_t /*aActionIndex*/) const {
2643 if (IsDefunct()) return;
2644 MOZ_ASSERT(mContent)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mContent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mContent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mContent", "./../../../accessible/generic/LocalAccessible.cpp"
, 2644); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mContent" ")"
); do { MOZ_CrashSequence(__null, 2644); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2645
2646 RefPtr<PresShell> presShell = mDoc->PresShellPtr();
2647
2648 // Scroll into view.
2649 presShell->ScrollContentIntoView(mContent, AxisScrollParams(),
2650 AxisScrollParams(),
2651 ScrollFlags::ScrollOverflowHidden);
2652
2653 AutoWeakFrame frame = GetFrame();
2654 if (!frame) {
2655 return;
2656 }
2657
2658 // We use RelativeBounds rather than querying the frame directly because of
2659 // special cases like image map areas which don't have their own frame.
2660 // RelativeBounds overrides handle these special cases.
2661 nsIFrame* boundingFrame = nullptr;
2662 nsRect rect = RelativeBounds(&boundingFrame);
2663 MOZ_ASSERT(boundingFrame)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(boundingFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(boundingFrame))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("boundingFrame",
"./../../../accessible/generic/LocalAccessible.cpp", 2663); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "boundingFrame" ")"); do { MOZ_CrashSequence
(__null, 2663); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
2664
2665 // Compute x and y coordinates in dev pixels relative to the widget.
2666 nsPoint offsetToWidget;
2667 nsCOMPtr<nsIWidget> widget = boundingFrame->GetNearestWidget(offsetToWidget);
2668 if (!widget) {
2669 return;
2670 }
2671
2672 rect += offsetToWidget;
2673 RefPtr<nsPresContext> presContext = presShell->GetPresContext();
2674 int32_t x = presContext->AppUnitsToDevPixels(rect.x + rect.width / 2);
2675 int32_t y = presContext->AppUnitsToDevPixels(rect.y + rect.height / 2);
2676
2677 // Simulate a touch interaction by dispatching touch events with mouse events.
2678 // Even though we calculated x and y using the bounding frame, we must use the
2679 // primary frame for the event. In most cases, these two frames will be
2680 // different, but they are the same for special cases such as image map areas
2681 // which don't have their own frame.
2682 nsCoreUtils::DispatchTouchEvent(eTouchStart, x, y, mContent, frame, presShell,
2683 widget);
2684
2685 // This isn't needed once bug 1924790 is fixed.
2686 mContent->OwnerDoc()->NotifyUserGestureActivation();
2687
2688 nsCoreUtils::DispatchMouseEvent(eMouseDown, x, y, mContent, frame, presShell,
2689 widget);
2690 nsCoreUtils::DispatchTouchEvent(eTouchEnd, x, y, mContent, frame, presShell,
2691 widget);
2692 nsCoreUtils::DispatchMouseEvent(eMouseUp, x, y, mContent, frame, presShell,
2693 widget);
2694}
2695
2696void LocalAccessible::ScrollToPoint(uint32_t aCoordinateType, int32_t aX,
2697 int32_t aY) {
2698 nsIFrame* frame = GetFrame();
2699 if (!frame) return;
2700
2701 LayoutDeviceIntPoint coords =
2702 nsAccUtils::ConvertToScreenCoords(aX, aY, aCoordinateType, this);
2703
2704 nsIFrame* parentFrame = frame;
2705 while ((parentFrame = parentFrame->GetParent())) {
2706 nsCoreUtils::ScrollFrameToPoint(parentFrame, frame, coords);
2707 }
2708}
2709
2710bool LocalAccessible::IsScrollable() const {
2711 const auto [scrollPosition, scrollRange] = mDoc->ComputeScrollData(this);
2712 return scrollRange.width > 0 || scrollRange.height > 0;
2713}
2714
2715bool LocalAccessible::IsPopover() const {
2716 dom::Element* el = Elm();
2717 return el && el->IsHTMLElement() && el->HasAttr(nsGkAtoms::popover);
2718}
2719
2720bool LocalAccessible::IsEditable() const {
2721 dom::Element* el = Elm();
2722 return el && el->State().HasState(dom::ElementState::READWRITE);
2723}
2724
2725void LocalAccessible::AppendTextTo(nsAString& aText, uint32_t aStartOffset,
2726 uint32_t aLength) {
2727 // Return text representation of non-text accessible within hypertext
2728 // accessible. Text accessible overrides this method to return enclosed text.
2729 if (aStartOffset != 0 || aLength == 0) return;
2730
2731 MOZ_ASSERT(mParent,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mParent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mParent" " (" "Called on accessible unbound from tree. Result can be wrong."
")", "./../../../accessible/generic/LocalAccessible.cpp", 2732
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mParent" ") (" "Called on accessible unbound from tree. Result can be wrong."
")"); do { MOZ_CrashSequence(__null, 2732); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
2732 "Called on accessible unbound from tree. Result can be wrong.")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mParent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mParent" " (" "Called on accessible unbound from tree. Result can be wrong."
")", "./../../../accessible/generic/LocalAccessible.cpp", 2732
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mParent" ") (" "Called on accessible unbound from tree. Result can be wrong."
")"); do { MOZ_CrashSequence(__null, 2732); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2733 nsIFrame* frame = GetFrame();
2734 // We handle something becoming display: none async, which means we won't have
2735 // a frame when we're queuing text removed events. Thus, it's important that
2736 // we produce text here even if there's no frame. Otherwise, we won't fire a
2737 // text removed event at all, which might leave client caches (e.g. NVDA
2738 // virtual buffers) with dead nodes.
2739 if (IsHTMLBr() || (frame && frame->IsBrFrame())) {
2740 aText += kForcedNewLineChar;
2741 } else if (mParent && nsAccUtils::MustPrune(mParent)) {
2742 // Expose the embedded object accessible as imaginary embedded object
2743 // character if its parent hypertext accessible doesn't expose children to
2744 // AT.
2745 aText += kImaginaryEmbeddedObjectChar;
2746 } else {
2747 aText += kEmbeddedObjectChar;
2748 }
2749}
2750
2751void LocalAccessible::Shutdown() {
2752 // Mark the accessible as defunct, invalidate the child count and pointers to
2753 // other accessibles, also make sure none of its children point to this
2754 // parent
2755 mStateFlags |= eIsDefunct;
2756
2757 int32_t childCount = mChildren.Length();
2758 for (int32_t childIdx = 0; childIdx < childCount; childIdx++) {
2759 mChildren.ElementAt(childIdx)->UnbindFromParent();
2760 }
2761 mChildren.Clear();
2762
2763 mEmbeddedObjCollector = nullptr;
2764
2765 if (mParent) mParent->RemoveChild(this);
2766
2767 mContent = nullptr;
2768 mDoc = nullptr;
2769 if (SelectionMgr() && SelectionMgr()->AccessibleWithCaret(nullptr) == this) {
2770 SelectionMgr()->ResetCaretOffset();
2771 }
2772}
2773
2774// LocalAccessible protected
2775ENameValueFlag LocalAccessible::ARIAName(nsString& aName) const {
2776 // 'slot' elements should ignore aria-label and aria-labelledby.
2777 if (mContent->IsHTMLElement(nsGkAtoms::slot)) {
2778 return eNameOK;
2779 }
2780 // aria-labelledby now takes precedence over aria-label
2781 bool notSimpleRelation = nsTextEquivUtils::GetTextEquivFromIDRefs(
2782 this, nsGkAtoms::aria_labelledby, aName);
2783 aName.CompressWhitespace();
2784
2785 if (!aName.IsEmpty()) {
2786 return notSimpleRelation ? eNameOK : eNameFromRelations;
2787 }
2788
2789 if (mContent->IsElement() &&
2790 nsAccUtils::GetARIAAttr(mContent->AsElement(), nsGkAtoms::aria_label,
2791 aName)) {
2792 aName.CompressWhitespace();
2793 }
2794
2795 return eNameOK;
2796}
2797
2798// LocalAccessible protected
2799bool LocalAccessible::ARIADescription(nsString& aDescription) const {
2800 // aria-describedby takes precedence over aria-description
2801 nsTextEquivUtils::GetTextEquivFromIDRefs(this, nsGkAtoms::aria_describedby,
2802 aDescription);
2803 aDescription.CompressWhitespace();
2804
2805 if (aDescription.IsEmpty() && mContent->IsElement() &&
2806 nsAccUtils::GetARIAAttr(mContent->AsElement(),
2807 nsGkAtoms::aria_description, aDescription)) {
2808 aDescription.CompressWhitespace();
2809 }
2810
2811 return !aDescription.IsEmpty();
2812}
2813
2814// LocalAccessible protected
2815bool LocalAccessible::Tooltip(nsString& aTooltip) const {
2816 if (!HasOwnContent()) {
2817 return false;
2818 }
2819
2820 if (mContent->IsHTMLElement()) {
2821 mContent->AsElement()->GetAttr(nsGkAtoms::title, aTooltip);
2822 aTooltip.CompressWhitespace();
2823 return !aTooltip.IsEmpty();
2824 } else if (mContent->IsXULElement()) {
2825 mContent->AsElement()->GetAttr(nsGkAtoms::tooltiptext, aTooltip);
2826 aTooltip.CompressWhitespace();
2827 return !aTooltip.IsEmpty();
2828 } else if (mContent->IsSVGElement()) {
2829 // If user agents need to choose among multiple 'desc' or 'title'
2830 // elements for processing, the user agent shall choose the first one.
2831 for (nsIContent* childElm = mContent->GetFirstChild(); childElm;
2832 childElm = childElm->GetNextSibling()) {
2833 if (childElm->IsSVGElement(nsGkAtoms::desc)) {
2834 nsTextEquivUtils::AppendTextEquivFromContent(this, childElm, &aTooltip);
2835 aTooltip.CompressWhitespace();
2836 return !aTooltip.IsEmpty();
2837 }
2838 }
2839 }
2840 return false;
2841}
2842
2843// LocalAccessible protected
2844ENameValueFlag LocalAccessible::NativeName(nsString& aName) const {
2845 if (mContent->IsHTMLElement()) {
2846 LocalAccessible* label = nullptr;
2847 HTMLLabelIterator iter(Document(), this);
2848 bool notSimpleRelation = false;
2849 while ((label = iter.Next())) {
2850 notSimpleRelation |= nsTextEquivUtils::AppendTextEquivFromContent(
2851 this, label->GetContent(), &aName);
2852 aName.CompressWhitespace();
2853 }
2854
2855 if (!aName.IsEmpty()) {
2856 return notSimpleRelation ? eNameOK : eNameFromRelations;
2857 }
2858
2859 NameFromAssociatedXULLabel(mDoc, mContent, aName);
2860 if (!aName.IsEmpty()) {
2861 return eNameOK;
2862 }
2863
2864 // We return eNameFromSubtree here to indicate that if there is no native
2865 // name we will calculate the name from the subtree next. This is useful for
2866 // noting where the name will come from in cases like name change
2867 // notifications.
2868 return eNameFromSubtree;
2869 }
2870
2871 if (mContent->IsXULElement()) {
2872 XULElmName(mDoc, mContent, aName);
2873 if (!aName.IsEmpty()) return eNameOK;
2874
2875 // We return eNameFromSubtree here to indicate that if there is no native
2876 // name we will calculate the name from the subtree next. See above.
2877 return eNameFromSubtree;
2878 }
2879
2880 if (mContent->IsSVGElement()) {
2881 // If user agents need to choose among multiple 'desc' or 'title'
2882 // elements for processing, the user agent shall choose the first one.
2883 for (nsIContent* childElm = mContent->GetFirstChild(); childElm;
2884 childElm = childElm->GetNextSibling()) {
2885 if (childElm->IsSVGElement(nsGkAtoms::title)) {
2886 nsTextEquivUtils::AppendTextEquivFromContent(this, childElm, &aName);
2887 return eNameOK;
2888 }
2889 }
2890 }
2891
2892 return eNameOK;
2893}
2894
2895// LocalAccessible protected
2896void LocalAccessible::NativeDescription(nsString& aDescription) const {
2897 bool isXUL = mContent->IsXULElement();
2898 if (isXUL) {
2899 // Try XUL <description control="[id]">description text</description>
2900 XULDescriptionIterator iter(Document(), mContent);
2901 LocalAccessible* descr = nullptr;
2902 while ((descr = iter.Next())) {
2903 nsTextEquivUtils::AppendTextEquivFromContent(this, descr->GetContent(),
2904 &aDescription);
2905 }
2906 }
2907}
2908
2909// LocalAccessible protected
2910void LocalAccessible::BindToParent(LocalAccessible* aParent,
2911 uint32_t aIndexInParent) {
2912 MOZ_ASSERT(aParent, "This method isn't used to set null parent")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aParent" " (" "This method isn't used to set null parent"
")", "./../../../accessible/generic/LocalAccessible.cpp", 2912
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent" ") (" "This method isn't used to set null parent"
")"); do { MOZ_CrashSequence(__null, 2912); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2913 MOZ_ASSERT(!mParent, "The child was expected to be moved")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!mParent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!mParent" " (" "The child was expected to be moved"
")", "./../../../accessible/generic/LocalAccessible.cpp", 2913
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mParent" ") (" "The child was expected to be moved"
")"); do { MOZ_CrashSequence(__null, 2913); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2914
2915#ifdef A11Y_LOG1
2916 if (mParent) {
2917 logging::TreeInfo("BindToParent: stealing accessible", 0, "old parent",
2918 mParent, "new parent", aParent, "child", this, nullptr);
2919 }
2920#endif
2921
2922 mParent = aParent;
2923 mIndexInParent = aIndexInParent;
2924
2925 if (mParent->HasNameDependent() || mParent->IsXULListItem() ||
2926 RelationByType(RelationType::LABEL_FOR).Next() ||
2927 nsTextEquivUtils::HasNameRule(mParent, eNameFromSubtreeRule)) {
2928 mContextFlags |= eHasNameDependent;
2929 } else {
2930 mContextFlags &= ~eHasNameDependent;
2931 }
2932 if (mParent->HasDescriptionDependent() ||
2933 RelationByType(RelationType::DESCRIPTION_FOR).Next()) {
2934 mContextFlags |= eHasDescriptionDependent;
2935 } else {
2936 mContextFlags &= ~eHasDescriptionDependent;
2937 }
2938 if (mParent->HasValueDependent() ||
2939 nsAccUtils::ShouldFireValueChangeForDescendantChanges(mParent)) {
2940 mContextFlags |= eHasValueDependent;
2941 } else {
2942 mContextFlags &= ~eHasValueDependent;
2943 }
2944
2945 // Add name/description dependent flags for dependent content once
2946 // a name/description provider is added to doc.
2947 Relation rel = RelationByType(RelationType::LABELLED_BY);
2948 LocalAccessible* relTarget = nullptr;
2949 while ((relTarget = rel.LocalNext())) {
2950 if (!relTarget->HasNameDependent()) {
2951 relTarget->ModifySubtreeContextFlags(eHasNameDependent, true);
2952 }
2953 }
2954
2955 rel = RelationByType(RelationType::DESCRIBED_BY);
2956 while ((relTarget = rel.LocalNext())) {
2957 if (!relTarget->HasDescriptionDependent()) {
2958 relTarget->ModifySubtreeContextFlags(eHasDescriptionDependent, true);
2959 }
2960 }
2961
2962 if (mParent->IsAlert() || mParent->IsInsideAlert()) {
2963 mContextFlags |= eInsideAlert;
2964 }
2965
2966 if (IsTableRow() || IsTableCell()) {
2967 CachedTableAccessible::Invalidate(this);
2968 }
2969
2970 if (mContent && mContent->IsElement()) {
2971 // If this element is an open hint popover, queue cache updates for all its
2972 // invokers so they can recompute relations now that this popover and its
2973 // descendants are in the accessibility tree.
2974 if (IsOpenHintPopover(mContent)) {
2975 mDoc->QueueCacheUpdateForPopoverInvokers(mContent->AsElement());
2976 }
2977
2978 // If this element is being bound to a parent that is an open hint popover,
2979 // queue cache updates for that popover's invokers. This handles the case
2980 // where interactive descendants are added to the hint popover after it's
2981 // already been shown.
2982 if (aParent->Elm() && IsOpenHintPopover(aParent->Elm())) {
2983 mDoc->QueueCacheUpdateForPopoverInvokers(aParent->Elm());
2984 }
2985 }
2986}
2987
2988// LocalAccessible protected
2989void LocalAccessible::UnbindFromParent() {
2990 // We do this here to handle document shutdown and an Accessible being moved.
2991 // We do this for subtree removal in DocAccessible::UncacheChildrenInSubtree.
2992 if (IsTableRow() || IsTable() || IsTableCell()) {
2993 CachedTableAccessible::Invalidate(this);
2994 }
2995
2996 // If this element is a hint popover being hidden, queue cache updates for all
2997 // its invokers so they can clear the relations.
2998 if (mContent && mContent->IsElement() && IsHintPopover(mContent)) {
2999 mDoc->QueueCacheUpdateForPopoverInvokers(mContent->AsElement());
3000 }
3001
3002 mParent = nullptr;
3003 mIndexInParent = -1;
3004 mIndexOfEmbeddedChild = -1;
3005
3006 delete mGroupInfo;
3007 mGroupInfo = nullptr;
3008 mContextFlags &= ~eHasNameDependent & ~eHasValueDependent & ~eInsideAlert;
3009}
3010
3011////////////////////////////////////////////////////////////////////////////////
3012// LocalAccessible public methods
3013
3014RootAccessible* LocalAccessible::RootAccessible() const {
3015 nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(GetNode());
3016 NS_ASSERTION(docShell, "No docshell for mContent")do { if (!(docShell)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "No docshell for mContent"
, "docShell", "./../../../accessible/generic/LocalAccessible.cpp"
, 3016); MOZ_PretendNoReturn(); } } while (0)
;
3017 if (!docShell) {
3018 return nullptr;
3019 }
3020
3021 nsCOMPtr<nsIDocShellTreeItem> root;
3022 docShell->GetInProcessRootTreeItem(getter_AddRefs(root));
3023 NS_ASSERTION(root, "No root content tree item")do { if (!(root)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "No root content tree item"
, "root", "./../../../accessible/generic/LocalAccessible.cpp"
, 3023); MOZ_PretendNoReturn(); } } while (0)
;
3024 if (!root) {
3025 return nullptr;
3026 }
3027
3028 DocAccessible* docAcc = nsAccUtils::GetDocAccessibleFor(root);
3029 return docAcc ? docAcc->AsRoot() : nullptr;
3030}
3031
3032nsIFrame* LocalAccessible::GetFrame() const {
3033 return mContent ? nsLayoutUtils::GetPrimaryOrAreaImageFrame(mContent)
3034 : nullptr;
3035}
3036
3037nsINode* LocalAccessible::GetNode() const { return mContent; }
3038
3039dom::Element* LocalAccessible::Elm() const {
3040 return dom::Element::FromNodeOrNull(mContent);
3041}
3042
3043void LocalAccessible::Language(nsAString& aLanguage) {
3044 aLanguage.Truncate();
3045
3046 if (!mDoc) return;
3047
3048 nsCoreUtils::GetLanguageFor(mContent, nullptr, aLanguage);
3049 if (aLanguage.IsEmpty()) { // Nothing found, so use document's language
3050 mDoc->DocumentNode()->GetHeaderData(nsGkAtoms::headerContentLanguage,
3051 aLanguage);
3052 }
3053}
3054
3055bool LocalAccessible::InsertChildAt(uint32_t aIndex, LocalAccessible* aChild) {
3056 if (!aChild) return false;
3057
3058 if (aIndex == mChildren.Length()) {
3059 // XXX(Bug 1631371) Check if this should use a fallible operation as it
3060 // pretended earlier.
3061 mChildren.AppendElement(aChild);
3062 } else {
3063 // XXX(Bug 1631371) Check if this should use a fallible operation as it
3064 // pretended earlier.
3065 mChildren.InsertElementAt(aIndex, aChild);
3066
3067 MOZ_ASSERT(mStateFlags & eKidsMutating, "Illicit children change")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mStateFlags & eKidsMutating)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mStateFlags & eKidsMutating
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"mStateFlags & eKidsMutating" " (" "Illicit children change"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3067
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mStateFlags & eKidsMutating"
") (" "Illicit children change" ")"); do { MOZ_CrashSequence
(__null, 3067); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3068
3069 for (uint32_t idx = aIndex + 1; idx < mChildren.Length(); idx++) {
3070 mChildren[idx]->mIndexInParent = idx;
3071 }
3072 }
3073
3074 if (aChild->IsText()) {
3075 mStateFlags |= eHasTextKids;
3076 }
3077
3078 aChild->BindToParent(this, aIndex);
3079 return true;
3080}
3081
3082bool LocalAccessible::RemoveChild(LocalAccessible* aChild) {
3083 MOZ_DIAGNOSTIC_ASSERT(aChild, "No child was given")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(aChild))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aChild" " (" "No child was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3083
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild"
") (" "No child was given" ")"); do { MOZ_CrashSequence(__null
, 3083); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
3084 MOZ_DIAGNOSTIC_ASSERT(aChild->mParent, "No parent")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mParent))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("aChild->mParent"
" (" "No parent" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3084); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mParent"
") (" "No parent" ")"); do { MOZ_CrashSequence(__null, 3084)
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
;
3085 MOZ_DIAGNOSTIC_ASSERT(aChild->mParent == this, "Wrong parent")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mParent == this)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mParent == this))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("aChild->mParent == this"
" (" "Wrong parent" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3085); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mParent == this"
") (" "Wrong parent" ")"); do { MOZ_CrashSequence(__null, 3085
); __attribute__((nomerge)) ::abort(); } while (false); } } while
(false)
;
3086 MOZ_DIAGNOSTIC_ASSERT(aChild->mIndexInParent != -1,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mIndexInParent != -1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mIndexInParent !=
-1))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aChild->mIndexInParent != -1" " (" "Unbound child was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3087
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mIndexInParent != -1"
") (" "Unbound child was given" ")"); do { MOZ_CrashSequence
(__null, 3087); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
3087 "Unbound child was given")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mIndexInParent != -1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mIndexInParent !=
-1))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aChild->mIndexInParent != -1" " (" "Unbound child was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3087
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mIndexInParent != -1"
") (" "Unbound child was given" ")"); do { MOZ_CrashSequence
(__null, 3087); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3088 MOZ_DIAGNOSTIC_ASSERT((mStateFlags & eKidsMutating) || aChild->IsDefunct() ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype((mStateFlags & eKidsMutating) || aChild->IsDefunct
() || aChild->IsDoc() || IsApplication())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!((mStateFlags & eKidsMutating
) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("(mStateFlags & eKidsMutating) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication()"
" (" "Illicit children change" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3090); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "(mStateFlags & eKidsMutating) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication()"
") (" "Illicit children change" ")"); do { MOZ_CrashSequence
(__null, 3090); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
3089 aChild->IsDoc() || IsApplication(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype((mStateFlags & eKidsMutating) || aChild->IsDefunct
() || aChild->IsDoc() || IsApplication())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!((mStateFlags & eKidsMutating
) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("(mStateFlags & eKidsMutating) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication()"
" (" "Illicit children change" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3090); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "(mStateFlags & eKidsMutating) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication()"
") (" "Illicit children change" ")"); do { MOZ_CrashSequence
(__null, 3090); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
3090 "Illicit children change")do { static_assert( mozilla::detail::AssertionConditionType<
decltype((mStateFlags & eKidsMutating) || aChild->IsDefunct
() || aChild->IsDoc() || IsApplication())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!((mStateFlags & eKidsMutating
) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("(mStateFlags & eKidsMutating) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication()"
" (" "Illicit children change" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3090); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "(mStateFlags & eKidsMutating) || aChild->IsDefunct() || aChild->IsDoc() || IsApplication()"
") (" "Illicit children change" ")"); do { MOZ_CrashSequence
(__null, 3090); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3091
3092 int32_t index = static_cast<uint32_t>(aChild->mIndexInParent);
3093 if (mChildren.SafeElementAt(index) != aChild) {
3094 MOZ_ASSERT_UNREACHABLE("A wrong child index")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"A wrong child index" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3094); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "A wrong child index" ")"); do { MOZ_CrashSequence
(__null, 3094); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3095 index = mChildren.IndexOf(aChild);
3096 if (index == -1) {
3097 MOZ_ASSERT_UNREACHABLE("No child was found")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"No child was found" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3097); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "No child was found" ")"); do { MOZ_CrashSequence
(__null, 3097); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3098 return false;
3099 }
3100 }
3101
3102 aChild->UnbindFromParent();
3103 mChildren.RemoveElementAt(index);
3104
3105 for (uint32_t idx = index; idx < mChildren.Length(); idx++) {
3106 mChildren[idx]->mIndexInParent = idx;
3107 }
3108
3109 return true;
3110}
3111
3112void LocalAccessible::RelocateChild(uint32_t aNewIndex,
3113 LocalAccessible* aChild) {
3114 MOZ_DIAGNOSTIC_ASSERT(aChild, "No child was given")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(aChild))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aChild" " (" "No child was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3114
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild"
") (" "No child was given" ")"); do { MOZ_CrashSequence(__null
, 3114); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
3115 MOZ_DIAGNOSTIC_ASSERT(aChild->mParent == this,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mParent == this)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mParent == this))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("aChild->mParent == this"
" (" "A child from different subtree was given" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3116); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mParent == this"
") (" "A child from different subtree was given" ")"); do { MOZ_CrashSequence
(__null, 3116); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
3116 "A child from different subtree was given")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mParent == this)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mParent == this))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("aChild->mParent == this"
" (" "A child from different subtree was given" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3116); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mParent == this"
") (" "A child from different subtree was given" ")"); do { MOZ_CrashSequence
(__null, 3116); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3117 MOZ_DIAGNOSTIC_ASSERT(aChild->mIndexInParent != -1,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mIndexInParent != -1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mIndexInParent !=
-1))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aChild->mIndexInParent != -1" " (" "Unbound child was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3118
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mIndexInParent != -1"
") (" "Unbound child was given" ")"); do { MOZ_CrashSequence
(__null, 3118); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
3118 "Unbound child was given")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mIndexInParent != -1)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->mIndexInParent !=
-1))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aChild->mIndexInParent != -1" " (" "Unbound child was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3118
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mIndexInParent != -1"
") (" "Unbound child was given" ")"); do { MOZ_CrashSequence
(__null, 3118); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3119 MOZ_DIAGNOSTIC_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mParent->LocalChildAt(aChild->mIndexInParent
) == aChild)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(aChild->mParent->LocalChildAt
(aChild->mIndexInParent) == aChild))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aChild->mParent->LocalChildAt(aChild->mIndexInParent) == aChild"
" (" "Wrong index in parent" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3121); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mParent->LocalChildAt(aChild->mIndexInParent) == aChild"
") (" "Wrong index in parent" ")"); do { MOZ_CrashSequence(__null
, 3121); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
3120 aChild->mParent->LocalChildAt(aChild->mIndexInParent) == aChild,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mParent->LocalChildAt(aChild->mIndexInParent
) == aChild)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(aChild->mParent->LocalChildAt
(aChild->mIndexInParent) == aChild))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aChild->mParent->LocalChildAt(aChild->mIndexInParent) == aChild"
" (" "Wrong index in parent" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3121); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mParent->LocalChildAt(aChild->mIndexInParent) == aChild"
") (" "Wrong index in parent" ")"); do { MOZ_CrashSequence(__null
, 3121); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
3121 "Wrong index in parent")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->mParent->LocalChildAt(aChild->mIndexInParent
) == aChild)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(aChild->mParent->LocalChildAt
(aChild->mIndexInParent) == aChild))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aChild->mParent->LocalChildAt(aChild->mIndexInParent) == aChild"
" (" "Wrong index in parent" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3121); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aChild->mParent->LocalChildAt(aChild->mIndexInParent) == aChild"
") (" "Wrong index in parent" ")"); do { MOZ_CrashSequence(__null
, 3121); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
3122 MOZ_DIAGNOSTIC_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<uint32_t>(aChild->mIndexInParent
) != aNewIndex)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(static_cast<uint32_t>(aChild
->mIndexInParent) != aNewIndex))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex"
" (" "No move, same index" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3124); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex"
") (" "No move, same index" ")"); do { MOZ_CrashSequence(__null
, 3124); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
3123 static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<uint32_t>(aChild->mIndexInParent
) != aNewIndex)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(static_cast<uint32_t>(aChild
->mIndexInParent) != aNewIndex))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex"
" (" "No move, same index" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3124); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex"
") (" "No move, same index" ")"); do { MOZ_CrashSequence(__null
, 3124); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
3124 "No move, same index")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(static_cast<uint32_t>(aChild->mIndexInParent
) != aNewIndex)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(static_cast<uint32_t>(aChild
->mIndexInParent) != aNewIndex))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex"
" (" "No move, same index" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3124); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex"
") (" "No move, same index" ")"); do { MOZ_CrashSequence(__null
, 3124); __attribute__((nomerge)) ::abort(); } while (false);
} } while (false)
;
3125 MOZ_DIAGNOSTIC_ASSERT(aNewIndex <= mChildren.Length(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewIndex <= mChildren.Length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewIndex <= mChildren.Length
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewIndex <= mChildren.Length()" " (" "Wrong new index was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3126
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewIndex <= mChildren.Length()"
") (" "Wrong new index was given" ")"); do { MOZ_CrashSequence
(__null, 3126); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
3126 "Wrong new index was given")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aNewIndex <= mChildren.Length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aNewIndex <= mChildren.Length
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aNewIndex <= mChildren.Length()" " (" "Wrong new index was given"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3126
); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "aNewIndex <= mChildren.Length()"
") (" "Wrong new index was given" ")"); do { MOZ_CrashSequence
(__null, 3126); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
3127
3128 // Don't queue events while we're still building the initial tree.
3129 if (mDoc->HasLoadState(DocAccessible::eTreeConstructed)) {
3130 auto hideEvent = MakeRefPtr<AccHideEvent>(aChild, false);
3131 if (mDoc->Controller()->QueueMutationEvent(hideEvent)) {
3132 aChild->SetHideEventTarget(true);
3133 }
3134 }
3135
3136 mEmbeddedObjCollector = nullptr;
3137 mChildren.RemoveElementAt(aChild->mIndexInParent);
3138
3139 uint32_t startIdx = aNewIndex, endIdx = aChild->mIndexInParent;
3140
3141 // If the child is moved after its current position.
3142 if (static_cast<uint32_t>(aChild->mIndexInParent) < aNewIndex) {
3143 startIdx = aChild->mIndexInParent;
3144 if (aNewIndex == mChildren.Length() + 1) {
3145 // The child is moved to the end.
3146 mChildren.AppendElement(aChild);
3147 endIdx = mChildren.Length() - 1;
3148 } else {
3149 mChildren.InsertElementAt(aNewIndex - 1, aChild);
3150 endIdx = aNewIndex;
3151 }
3152 } else {
3153 // The child is moved prior its current position.
3154 mChildren.InsertElementAt(aNewIndex, aChild);
3155 }
3156
3157 for (uint32_t idx = startIdx; idx <= endIdx; idx++) {
3158 mChildren[idx]->mIndexInParent = idx;
3159 mChildren[idx]->mIndexOfEmbeddedChild = -1;
3160 }
3161
3162 for (uint32_t idx = 0; idx < mChildren.Length(); idx++) {
3163 mChildren[idx]->mStateFlags |= eGroupInfoDirty;
3164 }
3165
3166 if (mDoc->HasLoadState(DocAccessible::eTreeConstructed)) {
3167 auto showEvent = MakeRefPtr<AccShowEvent>(aChild);
3168 DebugOnly<bool> added = mDoc->Controller()->QueueMutationEvent(showEvent);
3169 MOZ_ASSERT(added)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(added)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(added))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("added", "./../../../accessible/generic/LocalAccessible.cpp"
, 3169); AnnotateMozCrashReason("MOZ_ASSERT" "(" "added" ")")
; do { MOZ_CrashSequence(__null, 3169); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3170 aChild->SetShowEventTarget(true);
3171 }
3172}
3173
3174LocalAccessible* LocalAccessible::LocalChildAt(uint32_t aIndex) const {
3175 LocalAccessible* child = mChildren.SafeElementAt(aIndex, nullptr);
3176 if (!child) return nullptr;
3177
3178#ifdef DEBUG1
3179 LocalAccessible* realParent = child->mParent;
3180 NS_ASSERTION(!realParent || realParent == this,do { if (!(!realParent || realParent == this)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Two accessibles have the same first child accessible!"
, "!realParent || realParent == this", "./../../../accessible/generic/LocalAccessible.cpp"
, 3181); MOZ_PretendNoReturn(); } } while (0)
3181 "Two accessibles have the same first child accessible!")do { if (!(!realParent || realParent == this)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Two accessibles have the same first child accessible!"
, "!realParent || realParent == this", "./../../../accessible/generic/LocalAccessible.cpp"
, 3181); MOZ_PretendNoReturn(); } } while (0)
;
3182#endif
3183
3184 return child;
3185}
3186
3187uint32_t LocalAccessible::ChildCount() const { return mChildren.Length(); }
3188
3189int32_t LocalAccessible::IndexInParent() const { return mIndexInParent; }
3190
3191uint32_t LocalAccessible::EmbeddedChildCount() {
3192 if (mStateFlags & eHasTextKids) {
3193 if (!mEmbeddedObjCollector) {
3194 mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this));
3195 }
3196 return mEmbeddedObjCollector->Count();
3197 }
3198
3199 return ChildCount();
3200}
3201
3202Accessible* LocalAccessible::EmbeddedChildAt(uint32_t aIndex) {
3203 if (mStateFlags & eHasTextKids) {
3204 if (!mEmbeddedObjCollector) {
3205 mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this));
3206 }
3207 return mEmbeddedObjCollector->GetAccessibleAt(aIndex);
3208 }
3209
3210 return ChildAt(aIndex);
3211}
3212
3213int32_t LocalAccessible::IndexOfEmbeddedChild(Accessible* aChild) {
3214 MOZ_ASSERT(aChild->IsLocal())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aChild->IsLocal())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aChild->IsLocal()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("aChild->IsLocal()"
, "./../../../accessible/generic/LocalAccessible.cpp", 3214);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "aChild->IsLocal()"
")"); do { MOZ_CrashSequence(__null, 3214); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3215 if (mStateFlags & eHasTextKids) {
3216 if (!mEmbeddedObjCollector) {
3217 mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this));
3218 }
3219 return mEmbeddedObjCollector->GetIndexAt(aChild->AsLocal());
3220 }
3221
3222 return GetIndexOf(aChild->AsLocal());
3223}
3224
3225////////////////////////////////////////////////////////////////////////////////
3226// HyperLinkAccessible methods
3227
3228bool LocalAccessible::IsLink() const {
3229 // Every embedded accessible within hypertext accessible implements
3230 // hyperlink interface.
3231 return mParent && mParent->IsHyperText() && !IsText();
3232}
3233
3234////////////////////////////////////////////////////////////////////////////////
3235// SelectAccessible
3236
3237void LocalAccessible::SelectedItems(nsTArray<Accessible*>* aItems) {
3238 AccIterator iter(this, filters::GetSelected);
3239 LocalAccessible* selected = nullptr;
3240 while ((selected = iter.Next())) aItems->AppendElement(selected);
3241}
3242
3243uint32_t LocalAccessible::SelectedItemCount() {
3244 uint32_t count = 0;
3245 AccIterator iter(this, filters::GetSelected);
3246 LocalAccessible* selected = nullptr;
3247 while ((selected = iter.Next())) ++count;
Although the value stored to 'selected' is used in the enclosing expression, the value is never actually read from 'selected'
3248
3249 return count;
3250}
3251
3252Accessible* LocalAccessible::GetSelectedItem(uint32_t aIndex) {
3253 AccIterator iter(this, filters::GetSelected);
3254 LocalAccessible* selected = nullptr;
3255
3256 uint32_t index = 0;
3257 while ((selected = iter.Next()) && index < aIndex) index++;
3258
3259 return selected;
3260}
3261
3262bool LocalAccessible::IsItemSelected(uint32_t aIndex) {
3263 uint32_t index = 0;
3264 AccIterator iter(this, filters::GetSelectable);
3265 LocalAccessible* selected = nullptr;
3266 while ((selected = iter.Next()) && index < aIndex) index++;
3267
3268 return selected && selected->State() & states::SELECTED;
3269}
3270
3271bool LocalAccessible::AddItemToSelection(uint32_t aIndex) {
3272 uint32_t index = 0;
3273 AccIterator iter(this, filters::GetSelectable);
3274 LocalAccessible* selected = nullptr;
3275 while ((selected = iter.Next()) && index < aIndex) index++;
3276
3277 if (selected) selected->SetSelected(true);
3278
3279 return static_cast<bool>(selected);
3280}
3281
3282bool LocalAccessible::RemoveItemFromSelection(uint32_t aIndex) {
3283 uint32_t index = 0;
3284 AccIterator iter(this, filters::GetSelectable);
3285 LocalAccessible* selected = nullptr;
3286 while ((selected = iter.Next()) && index < aIndex) index++;
3287
3288 if (selected) selected->SetSelected(false);
3289
3290 return static_cast<bool>(selected);
3291}
3292
3293bool LocalAccessible::SelectAll() {
3294 bool success = false;
3295 LocalAccessible* selectable = nullptr;
3296
3297 AccIterator iter(this, filters::GetSelectable);
3298 while ((selectable = iter.Next())) {
3299 success = true;
3300 selectable->SetSelected(true);
3301 }
3302 return success;
3303}
3304
3305bool LocalAccessible::UnselectAll() {
3306 bool success = false;
3307 LocalAccessible* selected = nullptr;
3308
3309 AccIterator iter(this, filters::GetSelected);
3310 while ((selected = iter.Next())) {
3311 success = true;
3312 selected->SetSelected(false);
3313 }
3314 return success;
3315}
3316
3317////////////////////////////////////////////////////////////////////////////////
3318// Widgets
3319
3320bool LocalAccessible::IsWidget() const { return false; }
3321
3322bool LocalAccessible::IsActiveWidget() const {
3323 if (FocusMgr()->HasDOMFocus(mContent)) return true;
3324
3325 // If text entry of combobox widget has a focus then the combobox widget is
3326 // active.
3327 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
3328 if (roleMapEntry && roleMapEntry->Is(nsGkAtoms::combobox)) {
3329 uint32_t childCount = ChildCount();
3330 for (uint32_t idx = 0; idx < childCount; idx++) {
3331 LocalAccessible* child = mChildren.ElementAt(idx);
3332 if (child->Role() == roles::ENTRY) {
3333 return FocusMgr()->HasDOMFocus(child->GetContent());
3334 }
3335 }
3336 }
3337
3338 return false;
3339}
3340
3341bool LocalAccessible::AreItemsOperable() const {
3342 return HasOwnContent() && mContent->IsElement() &&
3343 mContent->AsElement()->HasAttr(nsGkAtoms::aria_activedescendant);
3344}
3345
3346LocalAccessible* LocalAccessible::CurrentItem() const {
3347 // Check for aria-activedescendant, which changes which element has focus.
3348 // For activedescendant, the ARIA spec does not require that the user agent
3349 // checks whether pointed node is actually a DOM descendant of the element
3350 // with the aria-activedescendant attribute.
3351 if (HasOwnContent() && mContent->IsElement()) {
3352 if (dom::Element* activeDescendantElm =
3353 nsCoreUtils::GetAriaActiveDescendantElement(
3354 mContent->AsElement())) {
3355 if (mContent->IsInclusiveDescendantOf(activeDescendantElm)) {
3356 // Don't want a cyclical descendant relationship. That would be bad.
3357 return nullptr;
3358 }
3359
3360 DocAccessible* document = Document();
3361 if (document) return document->GetAccessible(activeDescendantElm);
3362 }
3363 }
3364 return nullptr;
3365}
3366
3367void LocalAccessible::SetCurrentItem(const LocalAccessible* aItem) {}
3368
3369LocalAccessible* LocalAccessible::ContainerWidget() const {
3370 if (HasARIARole() && mContent->HasID()) {
3371 for (LocalAccessible* parent = LocalParent(); parent;
3372 parent = parent->LocalParent()) {
3373 nsIContent* parentContent = parent->GetContent();
3374 if (parentContent && parentContent->IsElement() &&
3375 nsCoreUtils::GetAriaActiveDescendantElement(
3376 parentContent->AsElement())) {
3377 return parent;
3378 }
3379
3380 // Don't cross DOM document boundaries.
3381 if (parent->IsDoc()) break;
3382 }
3383 }
3384 return nullptr;
3385}
3386
3387bool LocalAccessible::IsActiveDescendant(LocalAccessible** aWidget) const {
3388 RelatedAccIterator widgets(mDoc, mContent, nsGkAtoms::aria_activedescendant);
3389 if (LocalAccessible* widget = widgets.Next()) {
3390 if (aWidget) {
3391 *aWidget = widget;
3392 }
3393 return true;
3394 }
3395
3396 return false;
3397}
3398
3399void LocalAccessible::Announce(const nsAString& aAnnouncement,
3400 uint16_t aPriority) {
3401 // Don't fire announcement events if the document is in the background (not
3402 // active).
3403 if (!mDoc) {
3404 return;
3405 }
3406 dom::Document* docNode = mDoc->DocumentNode();
3407 if (!docNode) {
3408 return;
3409 }
3410 dom::BrowsingContext* bc = docNode->GetBrowsingContext();
3411 if (!bc || !bc->IsActive()) {
3412 return;
3413 }
3414 auto event = MakeRefPtr<AccAnnouncementEvent>(this, aAnnouncement, aPriority);
3415 nsEventShell::FireEvent(event);
3416}
3417
3418////////////////////////////////////////////////////////////////////////////////
3419// LocalAccessible protected methods
3420
3421void LocalAccessible::LastRelease() {
3422 // First cleanup if needed...
3423 if (mDoc) {
3424 Shutdown();
3425 NS_ASSERTION(!mDoc,do { if (!(!mDoc)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "A Shutdown() impl forgot to call its parent's Shutdown?"
, "!mDoc", "./../../../accessible/generic/LocalAccessible.cpp"
, 3426); MOZ_PretendNoReturn(); } } while (0)
3426 "A Shutdown() impl forgot to call its parent's Shutdown?")do { if (!(!mDoc)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "A Shutdown() impl forgot to call its parent's Shutdown?"
, "!mDoc", "./../../../accessible/generic/LocalAccessible.cpp"
, 3426); MOZ_PretendNoReturn(); } } while (0)
;
3427 }
3428 // ... then die.
3429 delete this;
3430}
3431
3432LocalAccessible* LocalAccessible::GetSiblingAtOffset(int32_t aOffset,
3433 nsresult* aError) const {
3434 if (!mParent || mIndexInParent == -1) {
3435 if (aError) *aError = NS_ERROR_UNEXPECTED;
3436
3437 return nullptr;
3438 }
3439
3440 if (aError &&
3441 mIndexInParent + aOffset >= static_cast<int32_t>(mParent->ChildCount())) {
3442 *aError = NS_OK; // fail peacefully
3443 return nullptr;
3444 }
3445
3446 LocalAccessible* child = mParent->LocalChildAt(mIndexInParent + aOffset);
3447 if (aError && !child) *aError = NS_ERROR_UNEXPECTED;
3448
3449 return child;
3450}
3451
3452void LocalAccessible::ModifySubtreeContextFlags(uint32_t aContextFlags,
3453 bool aAdd) {
3454 Pivot pivot(this);
3455 LocalAccInSameDocRule rule;
3456 for (Accessible* anchor = this; anchor; anchor = pivot.Next(anchor, rule)) {
3457 MOZ_ASSERT(anchor->IsLocal())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(anchor->IsLocal())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(anchor->IsLocal()))), 0))
) { do { } while (false); MOZ_ReportAssertionFailure("anchor->IsLocal()"
, "./../../../accessible/generic/LocalAccessible.cpp", 3457);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "anchor->IsLocal()"
")"); do { MOZ_CrashSequence(__null, 3457); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3458 LocalAccessible* acc = anchor->AsLocal();
3459 if (aAdd) {
3460 acc->mContextFlags |= aContextFlags;
3461 } else {
3462 acc->mContextFlags &= ~aContextFlags;
3463 }
3464 }
3465}
3466
3467double LocalAccessible::AttrNumericValue(nsAtom* aAttr) const {
3468 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
3469 if (!roleMapEntry || roleMapEntry->valueRule == eNoValue) {
3470 return UnspecifiedNaN<double>();
3471 }
3472
3473 nsAutoString attrValue;
3474 if (!mContent->IsElement() ||
3475 !nsAccUtils::GetARIAAttr(mContent->AsElement(), aAttr, attrValue)) {
3476 return UnspecifiedNaN<double>();
3477 }
3478
3479 nsresult error = NS_OK;
3480 double value = attrValue.ToDouble(&error);
3481 return NS_FAILED(error)((bool)(__builtin_expect(!!(NS_FAILED_impl(error)), 0))) ? UnspecifiedNaN<double>() : value;
3482}
3483
3484uint32_t LocalAccessible::GetActionRule() const {
3485 if (!HasOwnContent() || (InteractiveState() & states::UNAVAILABLE)) {
3486 return eNoAction;
3487 }
3488
3489 // Return "click" action on elements that have an attached popup menu.
3490 if (mContent->IsXULElement()) {
3491 if (mContent->AsElement()->HasAttr(nsGkAtoms::popup)) {
3492 return eClickAction;
3493 }
3494 }
3495
3496 // Has registered 'click' event handler.
3497 bool isOnclick = nsCoreUtils::HasClickListener(mContent);
3498
3499 if (isOnclick) return eClickAction;
3500
3501 // Get an action based on ARIA role.
3502 const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
3503 if (roleMapEntry && roleMapEntry->actionRule != eNoAction) {
3504 return roleMapEntry->actionRule;
3505 }
3506
3507 // Get an action based on ARIA attribute.
3508 if (nsAccUtils::HasDefinedARIAToken(mContent, nsGkAtoms::aria_expanded)) {
3509 return eExpandAction;
3510 }
3511
3512 return eNoAction;
3513}
3514
3515AccGroupInfo* LocalAccessible::GetGroupInfo() const {
3516 if (mGroupInfo && !(mStateFlags & eGroupInfoDirty)) {
3517 return mGroupInfo;
3518 }
3519
3520 return nullptr;
3521}
3522
3523AccGroupInfo* LocalAccessible::GetOrCreateGroupInfo() {
3524 if (mGroupInfo) {
3525 if (mStateFlags & eGroupInfoDirty) {
3526 mGroupInfo->Update();
3527 mStateFlags &= ~eGroupInfoDirty;
3528 }
3529
3530 return mGroupInfo;
3531 }
3532
3533 mGroupInfo = AccGroupInfo::CreateGroupInfo(this);
3534 mStateFlags &= ~eGroupInfoDirty;
3535 return mGroupInfo;
3536}
3537
3538void LocalAccessible::SendCache(uint64_t aCacheDomain,
3539 CacheUpdateType aUpdateType,
3540 bool aAppendEventData) {
3541 PerfStats::AutoMetricRecording<PerfStats::Metric::A11Y_SendCache>
3542 autoRecording;
3543 // DO NOT ADD CODE ABOVE THIS BLOCK: THIS CODE IS MEASURING TIMINGS.
3544
3545 if (!IPCAccessibilityActive() || !Document()) {
3546 return;
3547 }
3548
3549 // Only send cache updates for domains that are active.
3550 const uint64_t domainsToSend = mDoc->EffectiveCacheDomains() & aCacheDomain;
3551
3552 // Avoid sending cache updates if we have no domains to update.
3553 if (domainsToSend == CacheDomain::None) {
3554 return;
3555 }
3556
3557 DocAccessibleChild* ipcDoc = mDoc->IPCDoc();
3558 if (!ipcDoc) {
3559 // This means DocAccessible::DoInitialUpdate hasn't been called yet, which
3560 // means the a11y tree hasn't been built yet. Therefore, this should only
3561 // be possible if this is a DocAccessible.
3562 MOZ_ASSERT(IsDoc(), "Called on a non-DocAccessible but IPCDoc is null")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsDoc())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(IsDoc()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("IsDoc()" " (" "Called on a non-DocAccessible but IPCDoc is null"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3562
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsDoc()" ") (" "Called on a non-DocAccessible but IPCDoc is null"
")"); do { MOZ_CrashSequence(__null, 3562); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3563 return;
3564 }
3565
3566 RefPtr<AccAttributes> fields =
3567 BundleFieldsForCache(domainsToSend, aUpdateType);
3568 if (!fields->Count()) {
3569 return;
3570 }
3571 nsTArray<CacheData> data;
3572 data.AppendElement(CacheData(ID(), fields));
3573 if (aAppendEventData) {
3574 ipcDoc->PushMutationEventData(
3575 CacheEventData{std::move(aUpdateType), std::move(data)});
3576 } else {
3577 ipcDoc->SendCache(aUpdateType, data);
3578 }
3579
3580 if (profiler_thread_is_being_profiled_for_markers()) {
3581 nsAutoCString updateTypeStr;
3582 if (aUpdateType == CacheUpdateType::Initial) {
3583 updateTypeStr = "Initial";
3584 } else if (aUpdateType == CacheUpdateType::Update) {
3585 updateTypeStr = "Update";
3586 } else {
3587 updateTypeStr = "Other";
3588 }
3589 PROFILER_MARKER_TEXT("LocalAccessible::SendCache", A11Y, {}, updateTypeStr)do { ; do { if (profiler_is_collecting_markers()) { ::profiler_add_marker_impl
("LocalAccessible::SendCache", ::geckoprofiler::category::A11Y
, {}, ::geckoprofiler::markers::TextMarker{}, updateTypeStr);
} } while (false); } while (false)
;
3590 }
3591}
3592
3593already_AddRefed<AccAttributes> LocalAccessible::BundleFieldsForCache(
3594 uint64_t aCacheDomain, CacheUpdateType aUpdateType,
3595 uint64_t aInitialDomains) {
3596 MOZ_ASSERT((~aCacheDomain & aInitialDomains) == CacheDomain::None,do { static_assert( mozilla::detail::AssertionConditionType<
decltype((~aCacheDomain & aInitialDomains) == CacheDomain
::None)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!((~aCacheDomain & aInitialDomains) == CacheDomain
::None))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("(~aCacheDomain & aInitialDomains) == CacheDomain::None"
" (" "Initial domain pushes without domains requested!" ")",
"./../../../accessible/generic/LocalAccessible.cpp", 3597); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "(~aCacheDomain & aInitialDomains) == CacheDomain::None"
") (" "Initial domain pushes without domains requested!" ")"
); do { MOZ_CrashSequence(__null, 3597); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
3597 "Initial domain pushes without domains requested!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype((~aCacheDomain & aInitialDomains) == CacheDomain
::None)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!((~aCacheDomain & aInitialDomains) == CacheDomain
::None))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("(~aCacheDomain & aInitialDomains) == CacheDomain::None"
" (" "Initial domain pushes without domains requested!" ")",
"./../../../accessible/generic/LocalAccessible.cpp", 3597); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "(~aCacheDomain & aInitialDomains) == CacheDomain::None"
") (" "Initial domain pushes without domains requested!" ")"
); do { MOZ_CrashSequence(__null, 3597); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3598 auto fields = MakeRefPtr<AccAttributes>();
3599
3600 if (aUpdateType == CacheUpdateType::Initial) {
3601 aInitialDomains = CacheDomain::All;
3602 }
3603 // Pass a single cache domain in to query whether this is the initial push for
3604 // this domain.
3605 auto IsInitialPush = [aInitialDomains](uint64_t aCacheDomain) {
3606 return (aCacheDomain & aInitialDomains) == aCacheDomain;
3607 };
3608 auto IsUpdatePush = [aInitialDomains](uint64_t aCacheDomain) {
3609 return (aCacheDomain & aInitialDomains) == CacheDomain::None;
3610 };
3611
3612 // Caching name for text leaf Accessibles is redundant, since their name is
3613 // always their text. Text gets handled below.
3614 if (aCacheDomain & CacheDomain::NameAndDescription && !IsText()) {
3615 nsString name;
3616 ENameValueFlag nameFlag = DirectName(name);
3617
3618 if (IsTextField()) {
3619 MOZ_ASSERT(mContent)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mContent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mContent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mContent", "./../../../accessible/generic/LocalAccessible.cpp"
, 3619); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mContent" ")"
); do { MOZ_CrashSequence(__null, 3619); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3620 nsString placeholder;
3621 // Only cache the placeholder separately if it isn't used as the name.
3622 if (Elm()->GetAttr(nsGkAtoms::placeholder, placeholder) &&
3623 name != placeholder) {
3624 fields->SetAttribute(CacheKey::HTMLPlaceholder, std::move(placeholder));
3625 } else if (IsUpdatePush(CacheDomain::NameAndDescription)) {
3626 fields->SetAttribute(CacheKey::HTMLPlaceholder, DeleteEntry());
3627 }
3628 }
3629
3630 if (nameFlag != eNameFromRelations && !name.IsEmpty()) {
3631 fields->SetAttribute(CacheKey::Name, std::move(name));
3632 } else if (IsUpdatePush(CacheDomain::NameAndDescription)) {
3633 fields->SetAttribute(CacheKey::Name, DeleteEntry());
3634 }
3635
3636 nsString tooltip;
3637 if (Tooltip(tooltip)) {
3638 fields->SetAttribute(CacheKey::Tooltip, std::move(tooltip));
3639 } else if (IsUpdatePush(CacheDomain::NameAndDescription)) {
3640 fields->SetAttribute(CacheKey::Tooltip, DeleteEntry());
3641 }
3642
3643 if (Maybe<nsString> cssAlt = nsCoreUtils::GetCssAltContent(mContent)) {
3644 fields->SetAttribute(CacheKey::CssAltContent, std::move(*cssAlt));
3645 } else if (IsUpdatePush(CacheDomain::NameAndDescription)) {
3646 fields->SetAttribute(CacheKey::CssAltContent, DeleteEntry());
3647 }
3648
3649 nsString description;
3650 int32_t descFlag = Description(description);
3651 if (!description.IsEmpty()) {
3652 fields->SetAttribute(CacheKey::Description, std::move(description));
3653 } else if (IsUpdatePush(CacheDomain::NameAndDescription)) {
3654 fields->SetAttribute(CacheKey::Description, DeleteEntry());
3655 }
3656
3657 if (descFlag != eDescriptionOK) {
3658 fields->SetAttribute(CacheKey::DescriptionValueFlag, descFlag);
3659 } else if (IsUpdatePush(CacheDomain::NameAndDescription)) {
3660 fields->SetAttribute(CacheKey::DescriptionValueFlag, DeleteEntry());
3661 }
3662 }
3663
3664 if (aCacheDomain & CacheDomain::Value) {
3665 // We cache the text value in 4 cases:
3666 // 1. Accessible is an HTML input type that holds a number.
3667 // 2. Accessible has a numeric value and an aria-valuetext.
3668 // 3. Accessible is a link, in which case value is the target URL.
3669 // 4. Accessible is an HTML input type that holds a color.
3670 // ... for all other cases we divine the value remotely.
3671 bool cacheValueText = false;
3672 if (HasNumericValue()) {
3673 fields->SetAttribute(CacheKey::NumericValue, CurValue());
3674 fields->SetAttribute(CacheKey::MaxValue, MaxValue());
3675 fields->SetAttribute(CacheKey::MinValue, MinValue());
3676 fields->SetAttribute(CacheKey::Step, Step());
3677 cacheValueText = NativeHasNumericValue() ||
3678 (mContent->IsElement() &&
3679 nsAccUtils::HasARIAAttr(mContent->AsElement(),
3680 nsGkAtoms::aria_valuetext));
3681 } else if (IsHTMLLink()) {
3682 cacheValueText = true;
3683 } else if (auto* input = dom::HTMLInputElement::FromNodeOrNull(mContent)) {
3684 cacheValueText = input->IsInputColor();
3685 } else if (IsHTMLCombobox()) {
3686 cacheValueText = true;
3687 }
3688
3689 if (cacheValueText) {
3690 nsString value;
3691 Value(value);
3692 if (!value.IsEmpty()) {
3693 fields->SetAttribute(CacheKey::TextValue, std::move(value));
3694 } else if (IsUpdatePush(CacheDomain::Value)) {
3695 fields->SetAttribute(CacheKey::TextValue, DeleteEntry());
3696 }
3697 }
3698
3699 if (IsImage()) {
3700 // Cache the src of images. This is used by some clients to help remediate
3701 // inaccessible images.
3702 MOZ_ASSERT(mContent, "Image must have mContent")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mContent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mContent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mContent" " (" "Image must have mContent"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3702
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mContent" ") (" "Image must have mContent"
")"); do { MOZ_CrashSequence(__null, 3702); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3703 nsString src;
3704 mContent->AsElement()->GetAttr(nsGkAtoms::src, src);
3705 if (!src.IsEmpty()) {
3706 fields->SetAttribute(CacheKey::SrcURL, std::move(src));
3707 } else if (IsUpdatePush(CacheDomain::Value)) {
3708 fields->SetAttribute(CacheKey::SrcURL, DeleteEntry());
3709 }
3710 }
3711
3712 if (TagName() == nsGkAtoms::meter) {
3713 // We should only cache value region for HTML meter elements. A meter
3714 // should always have a value region, so this attribute should never
3715 // be empty (i.e. there is no DeleteEntry() clause here).
3716 HTMLMeterAccessible* meter = static_cast<HTMLMeterAccessible*>(this);
3717 fields->SetAttribute(CacheKey::ValueRegion, meter->ValueRegion());
3718 }
3719 }
3720
3721 if (aCacheDomain & CacheDomain::Viewport && IsDoc()) {
3722 // Construct the viewport cache for this document. This cache domain will
3723 // only be requested after we finish painting.
3724 DocAccessible* doc = AsDoc();
3725 PresShell* presShell = doc->PresShellPtr();
3726
3727 if (nsIFrame* rootFrame = presShell->GetRootFrame()) {
3728 nsTArray<nsIFrame*> frames;
3729 ScrollContainerFrame* sf = presShell->GetRootScrollContainerFrame();
3730 nsRect scrollPort = sf ? sf->GetScrollPortRect() : rootFrame->GetRect();
3731
3732 nsLayoutUtils::GetFramesForArea(
3733 RelativeTo{rootFrame}, scrollPort, frames,
3734 {{// We don't add the ::OnlyVisible option here, because
3735 // it means we always consider frames with pointer-events: none.
3736 // See usage of HitTestIsForVisibility in nsDisplayList::HitTest.
3737 // This flag ensures the display lists are built, even if
3738 // the page hasn't finished loading.
3739 nsLayoutUtils::FrameForPointOption::IgnorePaintSuppression,
3740 // Each doc should have its own viewport cache, so we can
3741 // ignore cross-doc content as an optimization.
3742 nsLayoutUtils::FrameForPointOption::IgnoreCrossDoc}});
3743
3744 nsTHashSet<LocalAccessible*> inViewAccs;
3745 nsTArray<uint64_t> viewportCache(frames.Length());
3746 // Layout considers table rows fully occluded by their containing cells.
3747 // This means they don't have their own display list items, and they won't
3748 // show up in the list returned from GetFramesForArea. To prevent table
3749 // rows from appearing offscreen, we manually add any rows for which we
3750 // have on-screen cells.
3751 LocalAccessible* prevParentRow = nullptr;
3752 for (nsIFrame* frame : frames) {
3753 if (frame->IsInlineFrame() && !frame->IsPrimaryFrame()) {
3754 // This is a line other than the first line in an inline element. Even
3755 // though there are multiple frames for this element (one per line),
3756 // there is only a single Accessible with bounds encompassing all the
3757 // frames. We don't have any additional information about the
3758 // individual continuation frames in our cache. Thus, we don't want
3759 // this Accessible to appear before leaves on other lines which are
3760 // later in the `frames` array. Otherwise, when hit testing, this
3761 // Accessible will match instead of those leaves. We will add this
3762 // Accessible when we get to its primary frame later.
3763 continue;
3764 }
3765 nsIContent* content = frame->GetContent();
3766 if (!content) {
3767 continue;
3768 }
3769
3770 LocalAccessible* acc = doc->GetAccessible(content);
3771 // The document should always be present at the end of the list, so
3772 // including it is unnecessary and wasteful. We skip the document here
3773 // and handle it as a fallback when hit testing.
3774 if (!acc || acc == mDoc) {
3775 continue;
3776 }
3777
3778 if (acc->IsTextLeaf() && nsAccUtils::MustPrune(acc->LocalParent())) {
3779 acc = acc->LocalParent();
3780 }
3781 if (acc->IsTableCell()) {
3782 LocalAccessible* parent = acc->LocalParent();
3783 if (parent && parent->IsTableRow() && parent != prevParentRow) {
3784 // If we've entered a new row since the last cell we saw, add the
3785 // previous parent row to our viewport cache here to maintain
3786 // hittesting order. Keep track of the current parent row.
3787 if (prevParentRow && inViewAccs.EnsureInserted(prevParentRow)) {
3788 viewportCache.AppendElement(prevParentRow->ID());
3789 }
3790 prevParentRow = parent;
3791 }
3792 } else if (acc->IsTable()) {
3793 // If we've encountered a table, we know we've already
3794 // handled all of this table's content (because we're traversing
3795 // in hittesting order). Add our table's final row to the viewport
3796 // cache before adding the table itself. Reset our marker for the next
3797 // table.
3798 if (prevParentRow && inViewAccs.EnsureInserted(prevParentRow)) {
3799 viewportCache.AppendElement(prevParentRow->ID());
3800 }
3801 prevParentRow = nullptr;
3802 } else if (acc->IsImageMap()) {
3803 // Layout doesn't walk image maps, so we do that
3804 // manually here. We do this before adding the map itself
3805 // so the children come earlier in the hittesting order.
3806 for (uint32_t i = 0; i < acc->ChildCount(); i++) {
3807 LocalAccessible* child = acc->LocalChildAt(i);
3808 MOZ_ASSERT(child)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(child)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(child))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("child", "./../../../accessible/generic/LocalAccessible.cpp"
, 3808); AnnotateMozCrashReason("MOZ_ASSERT" "(" "child" ")")
; do { MOZ_CrashSequence(__null, 3808); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3809 if (inViewAccs.EnsureInserted(child)) {
3810 MOZ_ASSERT(!child->IsDoc())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!child->IsDoc())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!child->IsDoc()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("!child->IsDoc()"
, "./../../../accessible/generic/LocalAccessible.cpp", 3810);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "!child->IsDoc()"
")"); do { MOZ_CrashSequence(__null, 3810); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3811 viewportCache.AppendElement(child->ID());
3812 }
3813 }
3814 } else if (acc->IsHTMLCombobox()) {
3815 // Layout doesn't consider combobox lists (or their
3816 // currently selected items) to be onscreen, but we do.
3817 // Add those things manually here.
3818 HTMLComboboxAccessible* combobox =
3819 static_cast<HTMLComboboxAccessible*>(acc);
3820 HTMLComboboxListAccessible* list = combobox->List();
3821 LocalAccessible* currItem = combobox->SelectedOption();
3822 // Preserve hittesting order by adding the item, then
3823 // the list, and finally the combobox itself.
3824 if (currItem && inViewAccs.EnsureInserted(currItem)) {
3825 viewportCache.AppendElement(currItem->ID());
3826 }
3827 if (list && inViewAccs.EnsureInserted(list)) {
3828 viewportCache.AppendElement(list->ID());
3829 }
3830 }
3831
3832 if (inViewAccs.EnsureInserted(acc)) {
3833 MOZ_ASSERT(!acc->IsDoc())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!acc->IsDoc())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!acc->IsDoc()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!acc->IsDoc()"
, "./../../../accessible/generic/LocalAccessible.cpp", 3833);
AnnotateMozCrashReason("MOZ_ASSERT" "(" "!acc->IsDoc()" ")"
); do { MOZ_CrashSequence(__null, 3833); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3834 viewportCache.AppendElement(acc->ID());
3835 }
3836 }
3837
3838 // Always send the viewport cache, even if we have no accessibles
3839 // in it. We don't want to send a delete entry because the viewport
3840 // cache _does_ exist, it is simply representing an empty screen.
3841 fields->SetAttribute(CacheKey::Viewport, std::move(viewportCache));
3842 }
3843 }
3844
3845 if (aCacheDomain & CacheDomain::APZ && IsDoc()) {
3846 PresShell* presShell = AsDoc()->PresShellPtr();
3847 MOZ_ASSERT(presShell, "Can't get APZ factor for null presShell")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(presShell)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(presShell))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("presShell" " (" "Can't get APZ factor for null presShell"
")", "./../../../accessible/generic/LocalAccessible.cpp", 3847
); AnnotateMozCrashReason("MOZ_ASSERT" "(" "presShell" ") (" "Can't get APZ factor for null presShell"
")"); do { MOZ_CrashSequence(__null, 3847); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3848 nsPoint viewportOffset =
3849 presShell->GetVisualViewportOffsetRelativeToLayoutViewport();
3850 if (viewportOffset.x || viewportOffset.y) {
3851 nsTArray<int32_t> offsetArray(2);
3852 offsetArray.AppendElement(viewportOffset.x);
3853 offsetArray.AppendElement(viewportOffset.y);
3854 fields->SetAttribute(CacheKey::VisualViewportOffset,
3855 std::move(offsetArray));
3856 } else if (IsUpdatePush(CacheDomain::APZ)) {
3857 fields->SetAttribute(CacheKey::VisualViewportOffset, DeleteEntry());
3858 }
3859 }
3860
3861 bool boundsChanged = false;
3862 nsIFrame* frame = GetFrame();
3863 if (aCacheDomain & CacheDomain::Bounds) {
3864 nsRect newBoundsRect = ParentRelativeBounds();
3865
3866 // 1. Layout might notify us of a possible bounds change when the bounds
3867 // haven't really changed. Therefore, we cache the last bounds we sent
3868 // and don't send an update if they haven't changed.
3869 // 2. For an initial cache push, we ignore 1) and always send the bounds.
3870 // This handles the case where this LocalAccessible was moved (but not
3871 // re-created). In that case, we will have cached bounds, but we currently
3872 // do an initial cache push.
3873 MOZ_ASSERT(IsInitialPush(CacheDomain::Bounds) || mBounds.isSome(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsInitialPush(CacheDomain::Bounds) || mBounds.isSome
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(IsInitialPush(CacheDomain::Bounds) || mBounds.isSome
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("IsInitialPush(CacheDomain::Bounds) || mBounds.isSome()" " ("
"Incremental cache push but mBounds is not set!" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3874); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsInitialPush(CacheDomain::Bounds) || mBounds.isSome()"
") (" "Incremental cache push but mBounds is not set!" ")");
do { MOZ_CrashSequence(__null, 3874); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
3874 "Incremental cache push but mBounds is not set!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(IsInitialPush(CacheDomain::Bounds) || mBounds.isSome
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(IsInitialPush(CacheDomain::Bounds) || mBounds.isSome
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("IsInitialPush(CacheDomain::Bounds) || mBounds.isSome()" " ("
"Incremental cache push but mBounds is not set!" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 3874); AnnotateMozCrashReason("MOZ_ASSERT" "(" "IsInitialPush(CacheDomain::Bounds) || mBounds.isSome()"
") (" "Incremental cache push but mBounds is not set!" ")");
do { MOZ_CrashSequence(__null, 3874); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
3875
3876 if (OuterDocAccessible* doc = AsOuterDoc()) {
3877 if (nsIFrame* docFrame = doc->GetFrame()) {
3878 const nsMargin& newOffset = docFrame->GetUsedBorderAndPadding();
3879 Maybe<nsMargin> currOffset = doc->GetCrossDocOffset();
3880 if (!currOffset || *currOffset != newOffset) {
3881 // OOP iframe docs can't compute their position within their
3882 // cross-proc parent, so we have to manually cache that offset
3883 // on the parent (outer doc) itself. For simplicity and consistency,
3884 // we do this here for both OOP and in-process iframes. For in-process
3885 // iframes, this also avoids the need to push a cache update for the
3886 // embedded document when the iframe changes its padding, gets
3887 // re-created, etc. Similar to bounds, we maintain a local cache and a
3888 // remote cache to avoid sending redundant updates.
3889 doc->SetCrossDocOffset(newOffset);
3890 nsTArray<int32_t> offsetArray(2);
3891 offsetArray.AppendElement(newOffset.Side(eSideLeft)); // X offset
3892 offsetArray.AppendElement(newOffset.Side(eSideTop)); // Y offset
3893 fields->SetAttribute(CacheKey::CrossDocOffset,
3894 std::move(offsetArray));
3895 }
3896 }
3897 }
3898
3899 // mBounds should never be Nothing, but sometimes it is (see Bug 1922691).
3900 // We null check mBounds here to avoid a crash while we figure out how this
3901 // can happen.
3902 boundsChanged = IsInitialPush(CacheDomain::Bounds) || !mBounds ||
3903 !newBoundsRect.IsEqualEdges(mBounds.value());
3904 if (boundsChanged) {
3905 mBounds = Some(newBoundsRect);
3906
3907 auto ptr = std::make_unique<nsRect>(newBoundsRect);
3908 fields->SetAttribute(CacheKey::ParentRelativeBounds, std::move(ptr));
3909 }
3910
3911 if (frame && frame->ScrollableOverflowRect().IsEmpty()) {
3912 fields->SetAttribute(CacheKey::IsClipped, true);
3913 } else if (IsUpdatePush(CacheDomain::Bounds)) {
3914 fields->SetAttribute(CacheKey::IsClipped, DeleteEntry());
3915 }
3916 }
3917
3918 if (aCacheDomain & CacheDomain::Text) {
3919 if (!HasChildren()) {
3920 // We only cache text and line offsets on leaf Accessibles.
3921 // Only text Accessibles can have actual text.
3922 if (IsText()) {
3923 nsString text;
3924 AppendTextTo(text);
3925 fields->SetAttribute(CacheKey::Text, std::move(text));
3926 TextLeafPoint point(this, 0);
3927 RefPtr<AccAttributes> attrs = point.GetTextAttributesLocalAcc(
3928 /* aIncludeDefaults */ false);
3929 if (attrs->Count()) {
3930 fields->SetAttribute(CacheKey::TextAttributes, std::move(attrs));
3931 } else if (IsUpdatePush(CacheDomain::Text)) {
3932 fields->SetAttribute(CacheKey::TextAttributes, DeleteEntry());
3933 }
3934 }
3935 }
3936 if (HyperTextAccessible* ht = AsHyperText()) {
3937 RefPtr<AccAttributes> attrs = ht->DefaultTextAttributes();
3938 LocalAccessible* parent = LocalParent();
3939 if (HyperTextAccessible* htParent =
3940 parent ? parent->AsHyperText() : nullptr) {
3941 if (RefPtr<AccAttributes> parentAttrs =
3942 htParent->DefaultTextAttributes()) {
3943 // Discard any entries that our parent already has.
3944 attrs->RemoveIdentical(parentAttrs);
3945 }
3946 }
3947 if (attrs->Count()) {
3948 fields->SetAttribute(CacheKey::TextAttributes, std::move(attrs));
3949 } else if (IsUpdatePush(CacheDomain::Text)) {
3950 fields->SetAttribute(CacheKey::TextAttributes, DeleteEntry());
3951 }
3952 } else if (!IsText()) {
3953 // Language is normally cached in text attributes, but Accessibles that
3954 // aren't HyperText or Text (e.g. <img>, <input type="radio">) don't have
3955 // text attributes. The Text domain isn't a great fit, but the kinds of
3956 // clients (e.g. screen readers) that care about language are likely to
3957 // care about text as well.
3958 nsString language;
3959 Language(language);
3960 if (!language.IsEmpty()) {
3961 fields->SetAttribute(CacheKey::Language, std::move(language));
3962 } else if (IsUpdatePush(CacheDomain::Text)) {
3963 fields->SetAttribute(CacheKey::Language, DeleteEntry());
3964 }
3965 }
3966 }
3967
3968 // If text changes, we must also update text offset attributes.
3969 if (aCacheDomain & (CacheDomain::TextOffsetAttributes | CacheDomain::Text) &&
3970 IsTextLeaf()) {
3971 auto offsetAttrs = TextLeafPoint::GetTextOffsetAttributes(this);
3972 if (!offsetAttrs.IsEmpty()) {
3973 fields->SetAttribute(CacheKey::TextOffsetAttributes,
3974 std::move(offsetAttrs));
3975 } else if (IsUpdatePush(CacheDomain::TextOffsetAttributes) ||
3976 IsUpdatePush(CacheDomain::Text)) {
3977 fields->SetAttribute(CacheKey::TextOffsetAttributes, DeleteEntry());
3978 }
3979 }
3980
3981 if (aCacheDomain & (CacheDomain::TextBounds) && !HasChildren()) {
3982 // We cache line start offsets for both text and non-text leaf Accessibles
3983 // because non-text leaf Accessibles can still start a line.
3984 TextLeafPoint lineStart =
3985 TextLeafPoint(this, 0).FindNextLineStartSameLocalAcc(
3986 /* aIncludeOrigin */ true);
3987 int32_t lineStartOffset = lineStart ? lineStart.mOffset : -1;
3988 // We push line starts and text bounds in two cases:
3989 // 1. TextBounds is pushed initially.
3990 // 2. CacheDomain::Bounds was requested (indicating that the frame was
3991 // reflowed) but the bounds didn't actually change. This can happen when
3992 // the spanned text is non-rectangular. For example, an Accessible might
3993 // cover two characters on one line and a single character on another line.
3994 // An insertion in a previous text node might cause it to shift such that it
3995 // now covers a single character on the first line and two characters on the
3996 // second line. Its bounding rect will be the same both before and after the
3997 // insertion. In this case, we use the first line start to determine whether
3998 // there was a change. This should be safe because the text didn't change in
3999 // this Accessible, so if the first line start doesn't shift, none of them
4000 // should shift.
4001 if (IsInitialPush(CacheDomain::TextBounds) ||
4002 aCacheDomain & CacheDomain::Text || boundsChanged ||
4003 mFirstLineStart != lineStartOffset) {
4004 mFirstLineStart = lineStartOffset;
4005 nsTArray<int32_t> lineStarts;
4006 for (; lineStart;
4007 lineStart = lineStart.FindNextLineStartSameLocalAcc(false)) {
4008 lineStarts.AppendElement(lineStart.mOffset);
4009 }
4010 if (!lineStarts.IsEmpty()) {
4011 fields->SetAttribute(CacheKey::TextLineStarts, std::move(lineStarts));
4012 } else if (IsUpdatePush(CacheDomain::TextBounds)) {
4013 fields->SetAttribute(CacheKey::TextLineStarts, DeleteEntry());
4014 }
4015
4016 if (frame && frame->IsTextFrame()) {
4017 if (nsTextFrame* currTextFrame = do_QueryFrame(frame)) {
4018 nsTArray<int32_t> charData(nsAccUtils::TextLength(this) *
4019 kNumbersInRect);
4020 // Continuation offsets are calculated relative to the primary frame.
4021 // However, the acc's bounds are calculated using
4022 // GetAllInFlowRectsUnion. For wrapped text which starts part way
4023 // through a line, this might mean the top left of the acc is
4024 // different to the top left of the primary frame. This also happens
4025 // when the primary frame is empty (e.g. a blank line at the start of
4026 // pre-formatted text), since the union rect will exclude the origin
4027 // in that case. Calculate the offset from the acc's rect to the
4028 // primary frame's rect.
4029 nsRect accOffset =
4030 nsLayoutUtils::GetAllInFlowRectsUnion(frame, frame);
4031 while (currTextFrame) {
4032 nsPoint contOffset = currTextFrame->GetOffsetTo(frame);
4033 contOffset -= accOffset.TopLeft();
4034 int32_t length = currTextFrame->GetContentLength();
4035 nsTArray<nsRect> charBounds(length);
4036 currTextFrame->GetCharacterRectsInRange(
4037 currTextFrame->GetContentOffset(), length, charBounds);
4038 for (nsRect& charRect : charBounds) {
4039 if (charRect.width == 0 &&
4040 !currTextFrame->StyleText()->WhiteSpaceIsSignificant()) {
4041 // GetCharacterRectsInRange gives us one rect per content
4042 // offset. However, TextLeafAccessibles use rendered offsets;
4043 // e.g. they might exclude some content white space. If we get
4044 // a 0 width rect and it's white space, skip this rect, since
4045 // this character isn't in the rendered text. We do have
4046 // a way to convert between content and rendered offsets, but
4047 // doing this for every character is expensive.
4048 const char16_t contentChar =
4049 mContent->GetCharacterDataBuffer()->CharAt(
4050 charData.Length() / kNumbersInRect);
4051 if (contentChar == u' ' || contentChar == u'\t' ||
4052 contentChar == u'\n') {
4053 continue;
4054 }
4055 }
4056 // We expect each char rect to be relative to the text leaf
4057 // acc this text lives in. Unfortunately, GetCharacterRectsInRange
4058 // returns rects relative to their continuation. Add the
4059 // continuation's relative position here to make our final
4060 // rect relative to the text leaf acc.
4061 charRect.MoveBy(contOffset);
4062 charData.AppendElement(charRect.x);
4063 charData.AppendElement(charRect.y);
4064 charData.AppendElement(charRect.width);
4065 charData.AppendElement(charRect.height);
4066 }
4067 currTextFrame = currTextFrame->GetNextContinuation();
4068 }
4069 if (charData.Length()) {
4070 fields->SetAttribute(CacheKey::TextBounds, std::move(charData));
4071 }
4072 }
4073 }
4074 }
4075 }
4076
4077 if (aCacheDomain & CacheDomain::TransformMatrix) {
4078 bool transformed = false;
4079 if (frame && frame->IsTransformed()) {
4080 // This matrix is only valid when applied to CSSPixel points/rects
4081 // in the coordinate space of `frame`.
4082 gfx::Matrix4x4 mtx = nsDisplayTransform::GetResultingTransformMatrix(
4083 frame, nsPoint(0, 0), AppUnitsPerCSSPixel(),
4084 nsDisplayTransform::INCLUDE_PERSPECTIVE);
4085 // We might get back the identity matrix. This can happen if there is no
4086 // actual transform. For example, if an element has
4087 // will-change: transform, nsIFrame::IsTransformed will return true, but
4088 // this doesn't necessarily mean there is a transform right now.
4089 // Applying the identity matrix is effectively a no-op, so there's no
4090 // point caching it.
4091 transformed = !mtx.IsIdentity();
4092 if (transformed) {
4093 auto ptr = std::make_unique<gfx::Matrix4x4>(mtx);
4094 fields->SetAttribute(CacheKey::TransformMatrix, std::move(ptr));
4095 }
4096 }
4097 if (!transformed && IsUpdatePush(CacheDomain::TransformMatrix)) {
4098 // Otherwise, if we're bundling a transform update but this
4099 // frame isn't transformed (or doesn't exist), we need
4100 // to send a DeleteEntry() to remove any
4101 // transform that was previously cached for this frame.
4102 fields->SetAttribute(CacheKey::TransformMatrix, DeleteEntry());
4103 }
4104 }
4105
4106 if (aCacheDomain & CacheDomain::ScrollPosition && frame) {
4107 // We request these values unscaled when caching because the scaled values
4108 // have resolution multiplied in. We can encounter a race condition when
4109 // using APZ where the resolution is not propogated back to content in time
4110 // for it to be multipled into the scroll position calculation. Even if we
4111 // end up with the correct resolution cached in parent, our final bounds
4112 // will be incorrect. Instead of scaling here, we scale in parent with our
4113 // cached resolution so any incorrectness will be consistent and dependent
4114 // on a single cache update (Resolution) instead of two (Resolution and
4115 // ScrollPosition).
4116 const auto [scrollPosition, scrollRange] =
4117 mDoc->ComputeScrollData(this, /* aShouldScaleByResolution */ false);
4118 if (scrollRange.width || scrollRange.height) {
4119 // If the scroll range is 0 by 0, this acc is not scrollable. We
4120 // can't simply check scrollPosition != 0, since it's valid for scrollable
4121 // frames to have a (0, 0) position. We also can't check IsEmpty or
4122 // ZeroArea because frames with only one scrollable dimension will return
4123 // a height/width of zero for the non-scrollable dimension, yielding zero
4124 // area even if the width/height for the scrollable dimension is nonzero.
4125 // We also cache (0, 0) for accs with overflow:auto or overflow:scroll,
4126 // even if the content is not currently large enough to be scrollable
4127 // right now -- these accs have a non-zero scroll range.
4128 nsTArray<int32_t> positionArr(2);
4129 positionArr.AppendElement(scrollPosition.x);
4130 positionArr.AppendElement(scrollPosition.y);
4131 fields->SetAttribute(CacheKey::ScrollPosition, std::move(positionArr));
4132 } else if (IsUpdatePush(CacheDomain::ScrollPosition)) {
4133 fields->SetAttribute(CacheKey::ScrollPosition, DeleteEntry());
4134 }
4135 }
4136
4137 if (aCacheDomain & CacheDomain::DOMNodeIDAndClass && mContent) {
4138 nsAtom* id = mContent->GetID();
4139 if (id) {
4140 fields->SetAttribute(CacheKey::DOMNodeID, id);
4141 } else if (IsUpdatePush(CacheDomain::DOMNodeIDAndClass)) {
4142 fields->SetAttribute(CacheKey::DOMNodeID, DeleteEntry());
4143 }
4144
4145 if (dom::Element* el = Elm()) {
4146 nsTArray<RefPtr<nsAtom>> classes;
4147 if (const nsAttrValue* attr = el->GetClasses()) {
4148 for (uint32_t i = 0; i < attr->GetAtomCount(); i++) {
4149 classes.AppendElement(attr->AtomAt(i));
4150 }
4151 }
4152 if (!classes.IsEmpty()) {
4153 fields->SetAttribute(CacheKey::DOMNodeClass, std::move(classes));
4154 } else if (IsUpdatePush(CacheDomain::DOMNodeIDAndClass)) {
4155 fields->SetAttribute(CacheKey::DOMNodeClass, DeleteEntry());
4156 }
4157 }
4158 }
4159
4160 // State is only included in the initial push. Thereafter, cached state is
4161 // updated via events.
4162 if (aCacheDomain & CacheDomain::State) {
4163 if (IsInitialPush(CacheDomain::State)) {
4164 // Most states are updated using state change events, so we only send
4165 // these for the initial cache push.
4166 uint64_t state = ExplicitState();
4167 // Exclude states which must be calculated by RemoteAccessible.
4168 state &= ~kRemoteCalculatedStates;
4169 fields->SetAttribute(CacheKey::State, state);
4170 }
4171 // If aria-selected isn't specified, there may be no SELECTED state.
4172 // However, aria-selected can be implicit in some cases when an item is
4173 // focused. We don't want to do this if aria-selected is explicitly
4174 // set to "false", so we need to differentiate between false and unset.
4175 if (auto ariaSelected = ARIASelected()) {
4176 fields->SetAttribute(CacheKey::ARIASelected, *ariaSelected);
4177 } else if (IsUpdatePush(CacheDomain::State)) {
4178 fields->SetAttribute(CacheKey::ARIASelected, DeleteEntry()); // Unset.
4179 }
4180 }
4181
4182 if (aCacheDomain & CacheDomain::GroupInfo && mContent) {
4183 for (nsAtom* attr : {nsGkAtoms::aria_level, nsGkAtoms::aria_setsize,
4184 nsGkAtoms::aria_posinset}) {
4185 int32_t value = 0;
4186 if (nsCoreUtils::GetUIntAttr(mContent, attr, &value)) {
4187 fields->SetAttribute(attr, value);
4188 } else if (IsUpdatePush(CacheDomain::GroupInfo)) {
4189 fields->SetAttribute(attr, DeleteEntry());
4190 }
4191 }
4192
4193 int32_t headingLevel = HeadingLevel();
4194 if (headingLevel > 0) {
4195 fields->SetAttribute(CacheKey::HeadingLevel, headingLevel);
4196 } else if (IsUpdatePush(CacheDomain::GroupInfo)) {
4197 fields->SetAttribute(CacheKey::HeadingLevel, DeleteEntry());
4198 }
4199 }
4200
4201 if (aCacheDomain & CacheDomain::Actions) {
4202 if (HasPrimaryAction()) {
4203 // Here we cache the primary action.
4204 nsAutoString actionName;
4205 ActionNameAt(0, actionName);
4206 RefPtr<nsAtom> actionAtom = NS_Atomize(actionName);
4207 fields->SetAttribute(CacheKey::PrimaryAction, actionAtom);
4208 } else if (IsUpdatePush(CacheDomain::Actions)) {
4209 fields->SetAttribute(CacheKey::PrimaryAction, DeleteEntry());
4210 }
4211
4212 if (ImageAccessible* imgAcc = AsImage()) {
4213 // Here we cache the showlongdesc action.
4214 if (imgAcc->HasLongDesc()) {
4215 fields->SetAttribute(CacheKey::HasLongdesc, true);
4216 } else if (IsUpdatePush(CacheDomain::Actions)) {
4217 fields->SetAttribute(CacheKey::HasLongdesc, DeleteEntry());
4218 }
4219 }
4220
4221 KeyBinding accessKey = AccessKey();
4222 if (!accessKey.IsEmpty()) {
4223 fields->SetAttribute(CacheKey::AccessKey, accessKey.Serialize());
4224 } else if (IsUpdatePush(CacheDomain::Actions)) {
4225 fields->SetAttribute(CacheKey::AccessKey, DeleteEntry());
4226 }
4227 }
4228
4229 if (aCacheDomain & CacheDomain::Style) {
4230 if (RefPtr<nsAtom> display = DisplayStyle()) {
4231 fields->SetAttribute(CacheKey::CSSDisplay, display);
4232 }
4233
4234 float opacity = Opacity();
4235 if (opacity != 1.0f) {
4236 fields->SetAttribute(CacheKey::Opacity, opacity);
4237 } else if (IsUpdatePush(CacheDomain::Style)) {
4238 fields->SetAttribute(CacheKey::Opacity, DeleteEntry());
4239 }
4240
4241 WritingMode wm = GetWritingMode();
4242 if (wm.GetBits()) {
4243 fields->SetAttribute(CacheKey::WritingMode, wm);
4244 } else if (IsUpdatePush(CacheDomain::Style)) {
4245 fields->SetAttribute(CacheKey::WritingMode, DeleteEntry());
4246 }
4247
4248 if (frame &&
4249 frame->StyleDisplay()->mPosition == StylePositionProperty::Fixed &&
4250 nsLayoutUtils::IsReallyFixedPos(frame)) {
4251 fields->SetAttribute(CacheKey::CssPosition, nsGkAtoms::fixed);
4252 } else if (IsUpdatePush(CacheDomain::Style)) {
4253 fields->SetAttribute(CacheKey::CssPosition, DeleteEntry());
4254 }
4255
4256 if (frame) {
4257 nsAutoCString overflow;
4258 frame->Style()->GetComputedPropertyValue(eCSSProperty_overflow, overflow);
4259 RefPtr<nsAtom> overflowAtom = NS_Atomize(overflow);
4260 if (overflowAtom == nsGkAtoms::hidden) {
4261 fields->SetAttribute(CacheKey::CSSOverflow, nsGkAtoms::hidden);
4262 } else if (IsUpdatePush(CacheDomain::Style)) {
4263 fields->SetAttribute(CacheKey::CSSOverflow, DeleteEntry());
4264 }
4265 }
4266 }
4267
4268 if (aCacheDomain & CacheDomain::Table) {
4269 if (auto* table = HTMLTableAccessible::GetFrom(this)) {
4270 if (table->IsProbablyLayoutTable()) {
4271 fields->SetAttribute(CacheKey::TableLayoutGuess, true);
4272 } else if (IsUpdatePush(CacheDomain::Table)) {
4273 fields->SetAttribute(CacheKey::TableLayoutGuess, DeleteEntry());
4274 }
4275 } else if (auto* cell = HTMLTableCellAccessible::GetFrom(this)) {
4276 // For HTML table cells, we must use the HTMLTableCellAccessible
4277 // GetRow/ColExtent methods rather than using the DOM attributes directly.
4278 // This is because of things like rowspan="0" which depend on knowing
4279 // about thead, tbody, etc., which is info we don't have in the a11y tree.
4280 int32_t value = static_cast<int32_t>(cell->RowExtent());
4281 MOZ_ASSERT(value > 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(value > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(value > 0))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("value > 0", "./../../../accessible/generic/LocalAccessible.cpp"
, 4281); AnnotateMozCrashReason("MOZ_ASSERT" "(" "value > 0"
")"); do { MOZ_CrashSequence(__null, 4281); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4282 if (value > 1) {
4283 fields->SetAttribute(CacheKey::RowSpan, value);
4284 } else if (IsUpdatePush(CacheDomain::Table)) {
4285 fields->SetAttribute(CacheKey::RowSpan, DeleteEntry());
4286 }
4287 value = static_cast<int32_t>(cell->ColExtent());
4288 MOZ_ASSERT(value > 0)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(value > 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(value > 0))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("value > 0", "./../../../accessible/generic/LocalAccessible.cpp"
, 4288); AnnotateMozCrashReason("MOZ_ASSERT" "(" "value > 0"
")"); do { MOZ_CrashSequence(__null, 4288); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
4289 if (value > 1) {
4290 fields->SetAttribute(CacheKey::ColSpan, value);
4291 } else if (IsUpdatePush(CacheDomain::Table)) {
4292 fields->SetAttribute(CacheKey::ColSpan, DeleteEntry());
4293 }
4294 if (mContent->AsElement()->HasAttr(nsGkAtoms::headers)) {
4295 nsTArray<uint64_t> headers;
4296 AssociatedElementsIterator iter(mDoc, mContent, nsGkAtoms::headers);
4297 while (LocalAccessible* cell = iter.Next()) {
4298 if (cell->IsTableCell()) {
4299 headers.AppendElement(cell->ID());
4300 }
4301 }
4302 fields->SetAttribute(CacheKey::CellHeaders, std::move(headers));
4303 } else if (IsUpdatePush(CacheDomain::Table)) {
4304 fields->SetAttribute(CacheKey::CellHeaders, DeleteEntry());
4305 }
4306 }
4307 }
4308
4309 if (aCacheDomain & CacheDomain::ARIA && mContent && mContent->IsElement()) {
4310 // We use a nested AccAttributes to make cache updates simpler. Rather than
4311 // managing individual removals, we just replace or remove the entire set of
4312 // ARIA attributes.
4313 RefPtr<AccAttributes> ariaAttrs;
4314 aria::AttrIterator attrIt(mContent);
4315 while (attrIt.Next()) {
4316 if (!ariaAttrs) {
4317 ariaAttrs = MakeRefPtr<AccAttributes>();
4318 }
4319 attrIt.ExposeAttr(ariaAttrs);
4320 }
4321 if (ariaAttrs) {
4322 fields->SetAttribute(CacheKey::ARIAAttributes, std::move(ariaAttrs));
4323 } else if (IsUpdatePush(CacheDomain::ARIA)) {
4324 fields->SetAttribute(CacheKey::ARIAAttributes, DeleteEntry());
4325 }
4326
4327 if (HasCustomActions()) {
4328 fields->SetAttribute(CacheKey::HasActions, true);
4329 } else if (IsUpdatePush(CacheDomain::ARIA)) {
4330 fields->SetAttribute(CacheKey::HasActions, DeleteEntry());
4331 }
4332 }
4333
4334 if (aCacheDomain & CacheDomain::Relations && mContent) {
4335 if (IsHTMLRadioButton() ||
4336 (mContent->IsElement() &&
4337 mContent->AsElement()->IsHTMLElement(nsGkAtoms::a))) {
4338 // HTML radio buttons with the same name should be grouped
4339 // and returned together when their MEMBER_OF relation is
4340 // requested. Computing LINKS_TO also requires we cache `name` on
4341 // anchor elements.
4342 nsString name;
4343 mContent->AsElement()->GetAttr(nsGkAtoms::name, name);
4344 if (!name.IsEmpty()) {
4345 fields->SetAttribute(CacheKey::DOMName, std::move(name));
4346 } else if (IsUpdatePush(CacheDomain::Relations)) {
4347 // It's possible we used to have a name and it's since been
4348 // removed. Send a delete entry.
4349 fields->SetAttribute(CacheKey::DOMName, DeleteEntry());
4350 }
4351 }
4352
4353 // Track whether aria-details/aria-describedby have targets, so that
4354 // commandfor/popovertarget can respect their precedence.
4355 bool hasAriaDetails = false;
4356 bool hasAriaDescribedby = false;
4357
4358 for (auto const& data : kRelationTypeAtoms) {
4359 nsTArray<uint64_t> ids;
4360 nsStaticAtom* const relAtom = data.mAtom;
4361 if (data.mValidTag && !mContent->IsHTMLElement(data.mValidTag)) {
4362 continue;
4363 }
4364
4365 Relation rel;
4366 if (data.mType == RelationType::LABEL_FOR) {
4367 // Labels are a special case -- we need to validate that the target of
4368 // their `for` attribute is in fact labelable. DOM checks this when we
4369 // call GetLabeledElementInternal(). If a label contains an element we
4370 // will return it here.
4371 if (dom::HTMLLabelElement* labelEl =
4372 dom::HTMLLabelElement::FromNode(mContent)) {
4373 rel.AppendTarget(mDoc, labelEl->GetLabeledElementInternal());
4374 }
4375 } else if (data.mType == RelationType::DETAILS) {
4376 if (relAtom == nsGkAtoms::aria_details) {
4377 rel.AppendIter(
4378 new AssociatedElementsIterator(mDoc, mContent, relAtom));
4379 } else if (relAtom == nsGkAtoms::commandfor) {
4380 // aria-details takes precedence; skip if it has targets.
4381 if (!hasAriaDetails) {
4382 if (LocalAccessible* target = GetCommandForDetailsRelation()) {
4383 rel.AppendTarget(target);
4384 fields->SetAttribute(CacheKey::PopoverInvokerIsDetails, true);
4385 }
4386 }
4387 } else if (relAtom == nsGkAtoms::popovertarget) {
4388 // aria-details takes precedence; skip if it has targets.
4389 if (!hasAriaDetails) {
4390 if (LocalAccessible* target = GetPopoverTargetDetailsRelation()) {
4391 rel.AppendTarget(target);
4392 fields->SetAttribute(CacheKey::PopoverInvokerIsDetails, true);
4393 }
4394 }
4395 } else if (relAtom == nsGkAtoms::target) {
4396 if (LocalAccessible* target =
4397 GetAnchorPositionTargetDetailsRelation()) {
4398 rel.AppendTarget(target);
4399 }
4400 } else {
4401 MOZ_ASSERT_UNREACHABLE("Unknown details relAtom")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Unknown details relAtom" ")", "./../../../accessible/generic/LocalAccessible.cpp"
, 4401); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unknown details relAtom" ")"); do
{ MOZ_CrashSequence(__null, 4401); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
4402 }
4403 } else if (data.mType == RelationType::DESCRIBED_BY) {
4404 if (relAtom == nsGkAtoms::aria_describedby) {
4405 rel.AppendIter(
4406 new AssociatedElementsIterator(mDoc, mContent, relAtom));
4407 } else if (relAtom == nsGkAtoms::commandfor) {
4408 // aria-describedby takes precedence; skip if it has targets.
4409 if (!hasAriaDescribedby) {
4410 if (LocalAccessible* target = GetCommandForDescribedByRelation()) {
4411 rel.AppendTarget(target);
4412 }
4413 }
4414 } else if (relAtom == nsGkAtoms::popovertarget) {
4415 // aria-describedby takes precedence; skip if it has targets.
4416 if (!hasAriaDescribedby) {
4417 if (LocalAccessible* target =
4418 GetPopoverTargetDescribedByRelation()) {
4419 rel.AppendTarget(target);
4420 }
4421 }
4422 }
4423 } else if (data.mType == RelationType::CONTROLLER_FOR) {
4424 // We need to use RelationByType for controls because it might include
4425 // failed aria-owned relocations or it may be an output element.
4426 // Nothing exposes an implicit reverse controls relation, so using
4427 // RelationByType here is fine.
4428 rel = RelationByType(data.mType);
4429 } else {
4430 // We use an AssociatedElementsIterator here instead of calling
4431 // RelationByType directly because we only want to cache explicit
4432 // relations. Implicit relations (e.g. LABEL_FOR exposed on the target
4433 // of aria-labelledby) will be computed and stored separately in the
4434 // parent process.
4435 rel.AppendIter(new AssociatedElementsIterator(mDoc, mContent, relAtom));
4436 }
4437
4438 while (LocalAccessible* acc = rel.LocalNext()) {
4439 ids.AppendElement(acc->ID());
4440 }
4441 if (ids.Length()) {
4442 fields->SetAttribute(relAtom, std::move(ids));
4443 // Track that aria-details/aria-describedby have targets for precedence.
4444 if (relAtom == nsGkAtoms::aria_details) {
4445 hasAriaDetails = true;
4446 } else if (relAtom == nsGkAtoms::aria_describedby) {
4447 hasAriaDescribedby = true;
4448 }
4449 } else if (IsUpdatePush(CacheDomain::Relations) &&
4450 !fields->HasAttribute(relAtom)) {
4451 // Only send DeleteEntry if we haven't already cached a value for this
4452 // atom in an earlier iteration. This handles atoms that appear multiple
4453 // times in kRelationTypeAtoms (e.g., popovertarget/commandfor appear
4454 // for both DETAILS and DESCRIBED_BY).
4455 fields->SetAttribute(relAtom, DeleteEntry());
4456 }
4457 }
4458 }
4459
4460#if defined(XP_WIN)
4461 if (aCacheDomain & CacheDomain::InnerHTML && HasOwnContent() &&
4462 mContent->IsMathMLElement(nsGkAtoms::math)) {
4463 nsString innerHTML;
4464 mContent->AsElement()->GetInnerHTML(innerHTML, IgnoreErrors());
4465 fields->SetAttribute(CacheKey::InnerHTML, std::move(innerHTML));
4466 }
4467#endif // defined(XP_WIN)
4468
4469 if (aUpdateType == CacheUpdateType::Initial) {
4470 // Add fields which never change and thus only need to be included in the
4471 // initial cache push.
4472 if (mContent && mContent->IsElement()) {
4473 fields->SetAttribute(CacheKey::TagName, mContent->NodeInfo()->NameAtom());
4474
4475 dom::Element* el = mContent->AsElement();
4476 if (IsTextField() || IsDateTimeField()) {
4477 // Cache text input types. Accessible is recreated if this changes,
4478 // so it is considered immutable.
4479 if (const nsAttrValue* attr = el->GetParsedAttr(nsGkAtoms::type)) {
4480 RefPtr<nsAtom> inputType = attr->GetAsAtom();
4481 if (inputType) {
4482 fields->SetAttribute(CacheKey::InputType, inputType);
4483 }
4484 }
4485 }
4486
4487 // Changing the role attribute currently re-creates the Accessible, so
4488 // it's immutable in the cache.
4489 if (const nsRoleMapEntry* roleMap = ARIARoleMap()) {
4490 // Most of the time, the role attribute is a single, known role. We
4491 // already send the map index, so we don't need to double up.
4492 if (!nsAccUtils::ARIAAttrValueIs(el, nsGkAtoms::role, roleMap->roleAtom,
4493 eIgnoreCase)) {
4494 // Multiple roles or unknown roles are rare, so just send them as a
4495 // string.
4496 nsAutoString role;
4497 nsAccUtils::GetARIAAttr(el, nsGkAtoms::role, role);
4498 fields->SetAttribute(CacheKey::ARIARole, std::move(role));
4499 }
4500 }
4501
4502 if (auto* htmlEl = nsGenericHTMLElement::FromNode(mContent)) {
4503 // Changing popover recreates the Accessible, so it's immutable in the
4504 // cache.
4505 nsAutoString popover;
4506 htmlEl->GetPopover(popover);
4507 if (!popover.IsEmpty()) {
4508 fields->SetAttribute(CacheKey::PopupType,
4509 RefPtr{NS_Atomize(popover)});
4510 }
4511 }
4512 }
4513
4514 if (frame) {
4515 // Note our frame's current computed style so we can track style changes
4516 // later on.
4517 mOldComputedStyle = frame->Style();
4518 if (frame->IsTransformed()) {
4519 mStateFlags |= eOldFrameHasValidTransformStyle;
4520 } else {
4521 mStateFlags &= ~eOldFrameHasValidTransformStyle;
4522 }
4523 }
4524
4525 if (IsDoc()) {
4526 if (PresShell* presShell = AsDoc()->PresShellPtr()) {
4527 // Send the initial resolution of the document. When this changes, we
4528 // will ne notified via nsAS::NotifyOfResolutionChange
4529 float resolution = presShell->GetResolution();
4530 fields->SetAttribute(CacheKey::Resolution, resolution);
4531 int32_t appUnitsPerDevPixel =
4532 presShell->GetPresContext()->AppUnitsPerDevPixel();
4533 fields->SetAttribute(CacheKey::AppUnitsPerDevPixel,
4534 appUnitsPerDevPixel);
4535 }
4536
4537 nsString mimeType;
4538 AsDoc()->MimeType(mimeType);
4539 fields->SetAttribute(CacheKey::MimeType, std::move(mimeType));
4540 }
4541 }
4542
4543 if ((aCacheDomain & (CacheDomain::Text | CacheDomain::ScrollPosition |
4544 CacheDomain::APZ) ||
4545 boundsChanged) &&
4546 mDoc) {
4547 mDoc->SetViewportCacheDirty(true);
4548 }
4549
4550 return fields.forget();
4551}
4552
4553void LocalAccessible::MaybeQueueCacheUpdateForStyleChanges() {
4554 // mOldComputedStyle might be null if the initial cache hasn't been sent yet.
4555 // In that case, there is nothing to do here.
4556 if (!IPCAccessibilityActive() || !mOldComputedStyle) {
4557 return;
4558 }
4559
4560 if (nsIFrame* frame = GetFrame()) {
4561 const ComputedStyle* newStyle = frame->Style();
4562
4563 const auto overflowProps =
4564 nsCSSPropertyIDSet({eCSSProperty_overflow_x, eCSSProperty_overflow_y});
4565
4566 for (NonCustomCSSPropertyId overflowProp : overflowProps) {
4567 nsAutoCString oldOverflow, newOverflow;
4568 mOldComputedStyle->GetComputedPropertyValue(overflowProp, oldOverflow);
4569 newStyle->GetComputedPropertyValue(overflowProp, newOverflow);
4570
4571 if (oldOverflow != newOverflow) {
4572 if (oldOverflow.Equals("hidden"_ns) ||
4573 newOverflow.Equals("hidden"_ns)) {
4574 mDoc->QueueCacheUpdate(this, CacheDomain::Style);
4575 }
4576 if (oldOverflow.Equals("auto"_ns) || newOverflow.Equals("auto"_ns) ||
4577 oldOverflow.Equals("scroll"_ns) ||
4578 newOverflow.Equals("scroll"_ns)) {
4579 // We cache a (0,0) scroll position for frames that have overflow
4580 // styling which means they _could_ become scrollable, even if the
4581 // content within them doesn't currently scroll.
4582 mDoc->QueueCacheUpdate(this, CacheDomain::ScrollPosition);
4583 }
4584 } else {
4585 ScrollContainerFrame* scrollContainerFrame = do_QueryFrame(frame);
4586 if (!scrollContainerFrame && (newOverflow.Equals("auto"_ns) ||
4587 newOverflow.Equals("scroll"_ns))) {
4588 // A document's body element can lose its scroll frame if the root
4589 // element (eg. <html>) is restyled to overflow scroll/auto. In that
4590 // case we will not get any useful notifications for the body element
4591 // except for a reframe to a non-scrolling frame.
4592 mDoc->QueueCacheUpdate(this, CacheDomain::ScrollPosition);
4593 }
4594 }
4595 }
4596
4597 nsAutoCString oldDisplay, newDisplay;
4598 mOldComputedStyle->GetComputedPropertyValue(eCSSProperty_display,
4599 oldDisplay);
4600 newStyle->GetComputedPropertyValue(eCSSProperty_display, newDisplay);
4601
4602 nsAutoCString oldOpacity, newOpacity;
4603 mOldComputedStyle->GetComputedPropertyValue(eCSSProperty_opacity,
4604 oldOpacity);
4605 newStyle->GetComputedPropertyValue(eCSSProperty_opacity, newOpacity);
4606
4607 if (oldDisplay != newDisplay || oldOpacity != newOpacity) {
4608 // CacheDomain::Style covers both display and opacity, so if
4609 // either property has changed, send an update for the entire domain.
4610 mDoc->QueueCacheUpdate(this, CacheDomain::Style);
4611 }
4612
4613 if (mOldComputedStyle->StyleDisplay()->mAnchorName !=
4614 newStyle->StyleDisplay()->mAnchorName) {
4615 // Anchor name changes can affect the result of
4616 // details relations.
4617 mDoc->QueueCacheUpdate(this, CacheDomain::Relations);
4618 }
4619
4620 if (mOldComputedStyle->MaybeAnchorPosReferencesDiffer(newStyle)) {
4621 // Refresh the cache for details on current target (ie. the old style)
4622 mDoc->RefreshAnchorRelationCacheForTarget(this);
4623 // Refresh the cache for details on new target asynchronously after the
4624 // next layout tick for new style.
4625 mDoc->Controller()->ScheduleNotification<DocAccessible>(
4626 mDoc, &DocAccessible::RefreshAnchorRelationCacheForTarget, this);
4627 }
4628
4629 nsAutoCString oldPosition, newPosition;
4630 mOldComputedStyle->GetComputedPropertyValue(eCSSProperty_position,
4631 oldPosition);
4632 newStyle->GetComputedPropertyValue(eCSSProperty_position, newPosition);
4633
4634 if (oldPosition != newPosition) {
4635 RefPtr<nsAtom> oldAtom = NS_Atomize(oldPosition);
4636 RefPtr<nsAtom> newAtom = NS_Atomize(newPosition);
4637 if (oldAtom == nsGkAtoms::fixed || newAtom == nsGkAtoms::fixed) {
4638 mDoc->QueueCacheUpdate(this, CacheDomain::Style);
4639 }
4640 }
4641
4642 bool newHasValidTransformStyle =
4643 newStyle->StyleDisplay()->HasTransform(frame);
4644 bool oldHasValidTransformStyle =
4645 (mStateFlags & eOldFrameHasValidTransformStyle) != 0;
4646
4647 // We should send a transform update if we're adding or
4648 // removing transform styling altogether.
4649 bool sendTransformUpdate =
4650 newHasValidTransformStyle || oldHasValidTransformStyle;
4651
4652 if (newHasValidTransformStyle && oldHasValidTransformStyle) {
4653 // If we continue to have transform styling, verify
4654 // our transform has actually changed.
4655 nsChangeHint transformHint =
4656 newStyle->StyleDisplay()->CalcTransformPropertyDifference(
4657 *mOldComputedStyle->StyleDisplay());
4658 // If this hint exists, it implies we found a property difference
4659 sendTransformUpdate = !!transformHint;
4660 }
4661
4662 if (sendTransformUpdate) {
4663 // If our transform matrix has changed, it's possible our
4664 // viewport cache has also changed.
4665 mDoc->SetViewportCacheDirty(true);
4666 // Queuing a cache update for the TransformMatrix domain doesn't
4667 // necessarily mean we'll send the matrix itself, we may
4668 // send a DeleteEntry() instead. See BundleFieldsForCache for
4669 // more information.
4670 mDoc->QueueCacheUpdate(this, CacheDomain::TransformMatrix);
4671 }
4672
4673 mOldComputedStyle = newStyle;
4674 if (newHasValidTransformStyle) {
4675 mStateFlags |= eOldFrameHasValidTransformStyle;
4676 } else {
4677 mStateFlags &= ~eOldFrameHasValidTransformStyle;
4678 }
4679 }
4680}
4681
4682nsAtom* LocalAccessible::TagName() const {
4683 return mContent && mContent->IsElement() ? mContent->NodeInfo()->NameAtom()
4684 : nullptr;
4685}
4686
4687already_AddRefed<nsAtom> LocalAccessible::DisplayStyle() const {
4688 dom::Element* elm = Elm();
4689 if (!elm) {
4690 return nullptr;
4691 }
4692 if (elm->IsHTMLElement(nsGkAtoms::area)) {
4693 // This is an image map area. CSS is irrelevant here.
4694 return nullptr;
4695 }
4696 static const dom::Element::AttrValuesArray presentationRoles[] = {
4697 nsGkAtoms::none, nsGkAtoms::presentation, nullptr};
4698 if (nsAccUtils::FindARIAAttrValueIn(elm, nsGkAtoms::role, presentationRoles,
4699 eIgnoreCase) != AttrArray::ATTR_MISSING &&
4700 IsGeneric()) {
4701 // This Accessible has been marked presentational, but we forced a generic
4702 // Accessible for some reason; e.g. CSS transform. Don't expose display in
4703 // this case, as the author might be explicitly trying to avoid said
4704 // exposure.
4705 return nullptr;
4706 }
4707 RefPtr<const ComputedStyle> style =
4708 nsComputedDOMStyle::GetComputedStyleNoFlush(elm);
4709 if (!style) {
4710 // The element is not styled, maybe not in the flat tree?
4711 return nullptr;
4712 }
4713 nsAutoCString value;
4714 style->GetComputedPropertyValue(eCSSProperty_display, value);
4715 return NS_Atomize(value);
4716}
4717
4718float LocalAccessible::Opacity() const {
4719 if (nsIFrame* frame = GetFrame()) {
4720 return frame->StyleEffects()->mOpacity;
4721 }
4722
4723 return 1.0f;
4724}
4725
4726WritingMode LocalAccessible::GetWritingMode() const {
4727 if (nsIFrame* frame = GetFrame()) {
4728 return WritingMode(frame->Style());
4729 }
4730
4731 return WritingMode();
4732}
4733
4734void LocalAccessible::DOMNodeID(nsString& aID) const {
4735 aID.Truncate();
4736 if (mContent) {
4737 if (nsAtom* id = mContent->GetID()) {
4738 id->ToString(aID);
4739 }
4740 }
4741}
4742
4743void LocalAccessible::DOMNodeClass(nsString& aClass) const {
4744 aClass.Truncate();
4745 if (auto* el = dom::Element::FromNodeOrNull(mContent)) {
4746 el->GetClassName(aClass);
4747 }
4748}
4749
4750int32_t LocalAccessible::HeadingLevel() const {
4751 if (auto* el = dom::HTMLHeadingElement::FromNodeOrNull(mContent)) {
4752 return static_cast<int32_t>(el->ComputedLevel());
4753 }
4754 return 0;
4755}
4756
4757void LocalAccessible::LiveRegionAttributes(nsAString* aLive,
4758 nsAString* aRelevant,
4759 Maybe<bool>* aAtomic,
4760 nsAString* aBusy) const {
4761 dom::Element* el = Elm();
4762 if (!el) {
4763 return;
4764 }
4765 if (aLive) {
4766 nsAccUtils::GetARIAAttr(el, nsGkAtoms::aria_live, *aLive);
4767 }
4768 if (aRelevant) {
4769 nsAccUtils::GetARIAAttr(el, nsGkAtoms::aria_relevant, *aRelevant);
4770 }
4771 if (aAtomic) {
4772 // XXX We ignore aria-atomic="false", but this probably doesn't conform to
4773 // the spec.
4774 if (nsAccUtils::ARIAAttrValueIs(el, nsGkAtoms::aria_atomic,
4775 nsGkAtoms::_true, eCaseMatters)) {
4776 *aAtomic = Some(true);
4777 }
4778 }
4779 if (aBusy) {
4780 nsAccUtils::GetARIAAttr(el, nsGkAtoms::aria_busy, *aBusy);
4781 }
4782}
4783
4784Maybe<bool> LocalAccessible::ARIASelected() const {
4785 if (dom::Element* el = Elm()) {
4786 nsStaticAtom* atom =
4787 nsAccUtils::NormalizeARIAToken(el, nsGkAtoms::aria_selected);
4788 if (atom == nsGkAtoms::_true) {
4789 return Some(true);
4790 }
4791 if (atom == nsGkAtoms::_false) {
4792 return Some(false);
4793 }
4794 }
4795 return Nothing();
4796}
4797
4798void LocalAccessible::StaticAsserts() const {
4799 static_assert(
4800 eLastStateFlag <= (1 << kStateFlagsBits) - 1,
4801 "LocalAccessible::mStateFlags was oversized by eLastStateFlag!");
4802 static_assert(
4803 eLastContextFlag <= (1 << kContextFlagsBits) - 1,
4804 "LocalAccessible::mContextFlags was oversized by eLastContextFlag!");
4805}
4806
4807TableAccessible* LocalAccessible::AsTable() {
4808 if (IsTable() && !IsCustomTable()) {
4809 return CachedTableAccessible::GetFrom(this);
4810 }
4811 return nullptr;
4812}
4813
4814TableCellAccessible* LocalAccessible::AsTableCell() {
4815 if (IsTableCell()) {
4816 return CachedTableCellAccessible::GetFrom(this);
4817 }
4818 return nullptr;
4819}
4820
4821Maybe<int32_t> LocalAccessible::GetIntARIAAttr(nsAtom* aAttrName) const {
4822 if (mContent) {
4823 int32_t val;
4824 if (nsCoreUtils::GetUIntAttr(mContent, aAttrName, &val)) {
4825 return Some(val);
4826 }
4827 // XXX Handle attributes that allow -1; e.g. aria-row/colcount.
4828 }
4829 return Nothing();
4830}
4831
4832bool LocalAccessible::GetStringARIAAttr(nsAtom* aAttrName,
4833 nsAString& aAttrValue) const {
4834 if (dom::Element* elm = Elm()) {
4835 return nsAccUtils::GetARIAAttr(elm, aAttrName, aAttrValue);
4836 }
4837 return false;
4838}
4839
4840bool LocalAccessible::ARIAAttrValueIs(nsAtom* aAttrName,
4841 nsAtom* aAttrValue) const {
4842 if (dom::Element* elm = Elm()) {
4843 return nsAccUtils::ARIAAttrValueIs(elm, aAttrName, aAttrValue,
4844 eCaseMatters);
4845 }
4846 return false;
4847}
4848
4849bool LocalAccessible::HasARIAAttr(nsAtom* aAttrName) const {
4850 return mContent ? nsAccUtils::HasDefinedARIAToken(mContent, aAttrName)
4851 : false;
4852}
4853
4854bool LocalAccessible::HasCustomActions() const {
4855 dom::Element* el = Elm();
4856 return el && nsAccUtils::HasARIAAttr(el, nsGkAtoms::aria_actions);
4857}