Bug 1869043 allow a device to be specified with MediaTrackGraph::NotifyWhenDeviceStar...
[gecko.git] / layout / base / nsCounterManager.cpp
blob7c2e9bb7765c7611cae4dc178c1c5b06f5c3409e
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* implementation of CSS counters (for numbering things) */
9 #include "nsCounterManager.h"
11 #include "mozilla/AutoRestore.h"
12 #include "mozilla/ContainStyleScopeManager.h"
13 #include "mozilla/IntegerRange.h"
14 #include "mozilla/Likely.h"
15 #include "mozilla/PresShell.h"
16 #include "mozilla/StaticPrefs_layout.h"
17 #include "mozilla/WritingModes.h"
18 #include "mozilla/dom/Element.h"
19 #include "mozilla/dom/Text.h"
20 #include "nsContainerFrame.h"
21 #include "nsContentUtils.h"
22 #include "nsIContent.h"
23 #include "nsIContentInlines.h"
24 #include "nsIFrame.h"
25 #include "nsTArray.h"
27 using namespace mozilla;
29 bool nsCounterUseNode::InitTextFrame(nsGenConList* aList,
30 nsIFrame* aPseudoFrame,
31 nsIFrame* aTextFrame) {
32 nsCounterNode::InitTextFrame(aList, aPseudoFrame, aTextFrame);
34 auto* counterList = static_cast<nsCounterList*>(aList);
35 counterList->Insert(this);
36 aPseudoFrame->AddStateBits(NS_FRAME_HAS_CSS_COUNTER_STYLE);
37 // If the list is already dirty, or the node is not at the end, just start
38 // with an empty string for now and when we recalculate the list we'll change
39 // the value to the right one.
40 if (counterList->IsDirty()) {
41 return false;
43 if (!counterList->IsLast(this)) {
44 counterList->SetDirty();
45 return true;
47 Calc(counterList, /* aNotify = */ false);
48 return false;
51 // assign the correct |mValueAfter| value to a node that has been inserted
52 // Should be called immediately after calling |Insert|.
53 void nsCounterUseNode::Calc(nsCounterList* aList, bool aNotify) {
54 NS_ASSERTION(aList->IsRecalculatingAll() || !aList->IsDirty(),
55 "Why are we calculating with a dirty list?");
57 mValueAfter = nsCounterList::ValueBefore(this);
59 if (mText) {
60 nsAutoString contentString;
61 GetText(contentString);
62 mText->SetText(contentString, aNotify);
66 // assign the correct |mValueAfter| value to a node that has been inserted
67 // Should be called immediately after calling |Insert|.
68 void nsCounterChangeNode::Calc(nsCounterList* aList) {
69 NS_ASSERTION(aList->IsRecalculatingAll() || !aList->IsDirty(),
70 "Why are we calculating with a dirty list?");
71 if (IsContentBasedReset()) {
72 // RecalcAll takes care of this case.
73 } else if (mType == RESET || mType == SET) {
74 mValueAfter = mChangeValue;
75 } else {
76 NS_ASSERTION(mType == INCREMENT, "invalid type");
77 mValueAfter = nsCounterManager::IncrementCounter(
78 nsCounterList::ValueBefore(this), mChangeValue);
82 void nsCounterUseNode::GetText(nsString& aResult) {
83 CounterStyle* style =
84 mPseudoFrame->PresContext()->CounterStyleManager()->ResolveCounterStyle(
85 mCounterStyle);
86 GetText(mPseudoFrame->GetWritingMode(), style, aResult);
89 void nsCounterUseNode::GetText(WritingMode aWM, CounterStyle* aStyle,
90 nsString& aResult) {
91 const bool isBidiRTL = aWM.IsBidiRTL();
92 auto AppendCounterText = [&aResult, isBidiRTL](const nsAutoString& aText,
93 bool aIsRTL) {
94 if (MOZ_LIKELY(isBidiRTL == aIsRTL)) {
95 aResult.Append(aText);
96 } else {
97 // RLM = 0x200f, LRM = 0x200e
98 const char16_t mark = aIsRTL ? 0x200f : 0x200e;
99 aResult.Append(mark);
100 aResult.Append(aText);
101 aResult.Append(mark);
105 if (mForLegacyBullet) {
106 nsAutoString prefix;
107 aStyle->GetPrefix(prefix);
108 aResult.Assign(prefix);
111 AutoTArray<nsCounterNode*, 8> stack;
112 stack.AppendElement(static_cast<nsCounterNode*>(this));
114 if (mAllCounters && mScopeStart) {
115 for (nsCounterNode* n = mScopeStart; n->mScopePrev; n = n->mScopeStart) {
116 stack.AppendElement(n->mScopePrev);
120 for (nsCounterNode* n : Reversed(stack)) {
121 nsAutoString text;
122 bool isTextRTL;
123 aStyle->GetCounterText(n->mValueAfter, aWM, text, isTextRTL);
124 if (!mForLegacyBullet || aStyle->IsBullet()) {
125 aResult.Append(text);
126 } else {
127 AppendCounterText(text, isTextRTL);
129 if (n == this) {
130 break;
132 aResult.Append(mSeparator);
135 if (mForLegacyBullet) {
136 nsAutoString suffix;
137 aStyle->GetSuffix(suffix);
138 aResult.Append(suffix);
142 static const nsIContent* GetParentContentForScope(nsIFrame* frame) {
143 // We do not want elements with `display: contents` to establish scope for
144 // counters. We'd like to do something like
145 // `nsIFrame::GetClosestFlattenedTreeAncestorPrimaryFrame()` above, but this
146 // may be called before the primary frame is set on frames.
147 nsIContent* content = frame->GetContent()->GetFlattenedTreeParent();
148 while (content && content->IsElement() &&
149 content->AsElement()->IsDisplayContents()) {
150 content = content->GetFlattenedTreeParent();
153 return content;
156 bool nsCounterList::IsDirty() const {
157 return mScope->GetScopeManager().CounterDirty(mCounterName);
160 void nsCounterList::SetDirty() {
161 mScope->GetScopeManager().SetCounterDirty(mCounterName);
164 void nsCounterList::SetScope(nsCounterNode* aNode) {
165 // This function is responsible for setting |mScopeStart| and
166 // |mScopePrev| (whose purpose is described in nsCounterManager.h).
167 // We do this by starting from the node immediately preceding
168 // |aNode| in content tree order, which is reasonably likely to be
169 // the previous element in our scope (or, for a reset, the previous
170 // element in the containing scope, which is what we want). If
171 // we're not in the same scope that it is, then it's too deep in the
172 // frame tree, so we walk up parent scopes until we find something
173 // appropriate.
175 auto setNullScopeFor = [](nsCounterNode* aNode) {
176 aNode->mScopeStart = nullptr;
177 aNode->mScopePrev = nullptr;
178 aNode->mCrossesContainStyleBoundaries = false;
179 if (aNode->IsUnitializedIncrementNode()) {
180 aNode->ChangeNode()->mChangeValue = 1;
184 if (aNode == First() && aNode->mType != nsCounterNode::USE) {
185 setNullScopeFor(aNode);
186 return;
189 auto didSetScopeFor = [this](nsCounterNode* aNode) {
190 if (aNode->mType == nsCounterNode::USE) {
191 return;
193 if (aNode->mScopeStart->IsContentBasedReset()) {
194 SetDirty();
196 if (aNode->IsUnitializedIncrementNode()) {
197 aNode->ChangeNode()->mChangeValue =
198 aNode->mScopeStart->IsReversed() ? -1 : 1;
202 // If there exist an explicit RESET scope created by an ancestor or
203 // the element itself, then we use that scope.
204 // Otherwise, fall through to consider scopes created by siblings (and
205 // their descendants) in reverse document order.
206 if (aNode->mType != nsCounterNode::USE &&
207 StaticPrefs::layout_css_counter_ancestor_scope_enabled()) {
208 for (auto* p = aNode->mPseudoFrame; p; p = p->GetParent()) {
209 // This relies on the fact that a RESET node is always the first
210 // CounterNode for a frame if it has any.
211 auto* counter = GetFirstNodeFor(p);
212 if (!counter || counter->mType != nsCounterNode::RESET) {
213 continue;
215 if (p == aNode->mPseudoFrame) {
216 break;
218 aNode->mScopeStart = counter;
219 aNode->mScopePrev = counter;
220 aNode->mCrossesContainStyleBoundaries = false;
221 for (nsCounterNode* prev = Prev(aNode); prev; prev = prev->mScopePrev) {
222 if (prev->mScopeStart == counter) {
223 aNode->mScopePrev =
224 prev->mType == nsCounterNode::RESET ? prev->mScopePrev : prev;
225 break;
227 if (prev->mType != nsCounterNode::RESET) {
228 prev = prev->mScopeStart;
229 if (!prev) {
230 break;
234 didSetScopeFor(aNode);
235 return;
239 // Get the content node for aNode's rendering object's *parent*,
240 // since scope includes siblings, so we want a descendant check on
241 // parents. Note here that mPseudoFrame is a bit of a misnomer, as it
242 // might not be a pseudo element at all, but a normal element that
243 // happens to increment a counter. We want to respect the flat tree
244 // here, but skipping any <slot> element that happens to contain
245 // mPseudoFrame. That's why this uses GetInFlowParent() instead
246 // of GetFlattenedTreeParent().
247 const nsIContent* nodeContent = GetParentContentForScope(aNode->mPseudoFrame);
248 if (SetScopeByWalkingBackwardThroughList(aNode, nodeContent, Prev(aNode))) {
249 aNode->mCrossesContainStyleBoundaries = false;
250 didSetScopeFor(aNode);
251 return;
254 // If this is a USE node there's a possibility that its counter scope starts
255 // in a parent `contain: style` scope. Look upward in the `contain: style`
256 // scope tree to find an appropriate node with which this node shares a
257 // counter scope.
258 if (aNode->mType == nsCounterNode::USE && aNode == First()) {
259 for (auto* scope = mScope->GetParent(); scope; scope = scope->GetParent()) {
260 if (auto* counterList =
261 scope->GetCounterManager().GetCounterList(mCounterName)) {
262 if (auto* node = static_cast<nsCounterNode*>(
263 mScope->GetPrecedingElementInGenConList(counterList))) {
264 if (SetScopeByWalkingBackwardThroughList(aNode, nodeContent, node)) {
265 aNode->mCrossesContainStyleBoundaries = true;
266 didSetScopeFor(aNode);
267 return;
274 setNullScopeFor(aNode);
277 bool nsCounterList::SetScopeByWalkingBackwardThroughList(
278 nsCounterNode* aNodeToSetScopeFor, const nsIContent* aNodeContent,
279 nsCounterNode* aNodeToBeginLookingAt) {
280 for (nsCounterNode *prev = aNodeToBeginLookingAt, *start; prev;
281 prev = start->mScopePrev) {
282 // There are two possibilities here:
283 // 1. |prev| starts a new counter scope. This happens when:
284 // a. It's a reset node.
285 // b. It's an implied reset node which we know because mScopeStart is null.
286 // c. It follows one or more USE nodes at the start of the list which have
287 // a scope that starts in a parent `contain: style` context.
288 // In all of these cases, |prev| should be the start of this node's counter
289 // scope.
290 // 2. |prev| does not start a new counter scope and this node should share a
291 // counter scope start with |prev|.
292 start =
293 (prev->mType == nsCounterNode::RESET || !prev->mScopeStart ||
294 (prev->mScopePrev && prev->mScopePrev->mCrossesContainStyleBoundaries))
295 ? prev
296 : prev->mScopeStart;
298 const nsIContent* startContent =
299 GetParentContentForScope(start->mPseudoFrame);
300 NS_ASSERTION(aNodeContent || !startContent,
301 "null check on startContent should be sufficient to "
302 "null check aNodeContent as well, since if aNodeContent "
303 "is for the root, startContent (which is before it) "
304 "must be too");
306 // A reset's outer scope can't be a scope created by a sibling.
307 if (!(aNodeToSetScopeFor->mType == nsCounterNode::RESET &&
308 aNodeContent == startContent) &&
309 // everything is inside the root (except the case above,
310 // a second reset on the root)
311 (!startContent ||
312 aNodeContent->IsInclusiveFlatTreeDescendantOf(startContent))) {
313 // If this node is a USE node and the previous node was also a USE node
314 // which has a scope that starts in a parent `contain: style` context,
315 // this node's scope shares the same scope and crosses `contain: style`
316 // scope boundaries.
317 if (aNodeToSetScopeFor->mType == nsCounterNode::USE) {
318 aNodeToSetScopeFor->mCrossesContainStyleBoundaries =
319 prev->mCrossesContainStyleBoundaries;
322 aNodeToSetScopeFor->mScopeStart = start;
323 aNodeToSetScopeFor->mScopePrev = prev;
324 return true;
328 return false;
331 void nsCounterList::RecalcAll() {
332 AutoRestore<bool> restoreRecalculatingAll(mRecalculatingAll);
333 mRecalculatingAll = true;
335 // Setup the scope and calculate the default start value for content-based
336 // reversed() counters. We need to track the last increment for each of
337 // those scopes so that we can add it in an extra time at the end.
338 // https://drafts.csswg.org/css-lists/#instantiating-counters
339 nsTHashMap<nsPtrHashKey<nsCounterChangeNode>, int32_t> scopes;
340 for (nsCounterNode* node = First(); node; node = Next(node)) {
341 SetScope(node);
342 if (node->IsContentBasedReset()) {
343 node->ChangeNode()->mSeenSetNode = false;
344 node->mValueAfter = 0;
345 scopes.InsertOrUpdate(node->ChangeNode(), 0);
346 } else if (node->mScopeStart && node->mScopeStart->IsContentBasedReset() &&
347 !node->mScopeStart->ChangeNode()->mSeenSetNode) {
348 if (node->mType == nsCounterChangeNode::INCREMENT) {
349 auto incrementNegated = -node->ChangeNode()->mChangeValue;
350 if (auto entry = scopes.Lookup(node->mScopeStart->ChangeNode())) {
351 entry.Data() = incrementNegated;
353 auto* next = Next(node);
354 if (next && next->mPseudoFrame == node->mPseudoFrame &&
355 next->mType == nsCounterChangeNode::SET) {
356 continue;
358 node->mScopeStart->mValueAfter += incrementNegated;
359 } else if (node->mType == nsCounterChangeNode::SET) {
360 node->mScopeStart->mValueAfter += node->ChangeNode()->mChangeValue;
361 // We have a 'counter-set' for this scope so we're done.
362 // The counter is incremented from that value for the remaining nodes.
363 node->mScopeStart->ChangeNode()->mSeenSetNode = true;
368 // For all the content-based reversed() counters we found, add in the
369 // incrementNegated from its last counter-increment.
370 for (auto iter = scopes.ConstIter(); !iter.Done(); iter.Next()) {
371 iter.Key()->mValueAfter += iter.Data();
374 for (nsCounterNode* node = First(); node; node = Next(node)) {
375 node->Calc(this, /* aNotify = */ true);
379 static bool AddCounterChangeNode(nsCounterManager& aManager, nsIFrame* aFrame,
380 int32_t aIndex,
381 const nsStyleContent::CounterPair& aPair,
382 nsCounterNode::Type aType) {
383 auto* node = new nsCounterChangeNode(aFrame, aType, aPair.value, aIndex,
384 aPair.is_reversed);
385 nsCounterList* counterList =
386 aManager.GetOrCreateCounterList(aPair.name.AsAtom());
387 counterList->Insert(node);
388 if (!counterList->IsLast(node)) {
389 // Tell the caller it's responsible for recalculating the entire list.
390 counterList->SetDirty();
391 return true;
394 // Don't call Calc() if the list is already dirty -- it'll be recalculated
395 // anyway, and trying to calculate with a dirty list doesn't work.
396 if (MOZ_LIKELY(!counterList->IsDirty())) {
397 node->Calc(counterList);
399 return counterList->IsDirty();
402 static bool HasCounters(const nsStyleContent& aStyle) {
403 return !aStyle.mCounterIncrement.IsEmpty() ||
404 !aStyle.mCounterReset.IsEmpty() || !aStyle.mCounterSet.IsEmpty();
407 bool nsCounterManager::AddCounterChanges(nsIFrame* aFrame) {
408 // For elements with 'display:list-item' we add a default
409 // 'counter-increment:list-item' unless 'counter-increment' already has a
410 // value for 'list-item'.
412 // https://drafts.csswg.org/css-lists-3/#declaring-a-list-item
414 // We inherit `display` for some anonymous boxes, but we don't want them to
415 // increment the list-item counter.
416 const bool requiresListItemIncrement =
417 aFrame->StyleDisplay()->IsListItem() && !aFrame->Style()->IsAnonBox();
419 const nsStyleContent* styleContent = aFrame->StyleContent();
421 if (!requiresListItemIncrement && !HasCounters(*styleContent)) {
422 MOZ_ASSERT(!aFrame->HasAnyStateBits(NS_FRAME_HAS_CSS_COUNTER_STYLE));
423 return false;
426 aFrame->AddStateBits(NS_FRAME_HAS_CSS_COUNTER_STYLE);
428 bool dirty = false;
429 // Add in order, resets first, so all the comparisons will be optimized
430 // for addition at the end of the list.
432 int32_t i = 0;
433 for (const auto& pair : styleContent->mCounterReset.AsSpan()) {
434 dirty |= AddCounterChangeNode(*this, aFrame, i++, pair,
435 nsCounterChangeNode::RESET);
438 bool hasListItemIncrement = false;
440 int32_t i = 0;
441 for (const auto& pair : styleContent->mCounterIncrement.AsSpan()) {
442 hasListItemIncrement |= pair.name.AsAtom() == nsGkAtoms::list_item;
443 if (pair.value != 0) {
444 dirty |= AddCounterChangeNode(*this, aFrame, i++, pair,
445 nsCounterChangeNode::INCREMENT);
450 if (requiresListItemIncrement && !hasListItemIncrement) {
451 RefPtr<nsAtom> atom = nsGkAtoms::list_item;
452 // We use a magic value here to signal to SetScope() that it should
453 // set the value to -1 or 1 depending on if the scope is reversed()
454 // or not.
455 auto listItemIncrement = nsStyleContent::CounterPair{
456 {StyleAtom(atom.forget())}, std::numeric_limits<int32_t>::min()};
457 dirty |= AddCounterChangeNode(
458 *this, aFrame, styleContent->mCounterIncrement.Length(),
459 listItemIncrement, nsCounterChangeNode::INCREMENT);
463 int32_t i = 0;
464 for (const auto& pair : styleContent->mCounterSet.AsSpan()) {
465 dirty |= AddCounterChangeNode(*this, aFrame, i++, pair,
466 nsCounterChangeNode::SET);
469 return dirty;
472 nsCounterList* nsCounterManager::GetOrCreateCounterList(nsAtom* aCounterName) {
473 MOZ_ASSERT(aCounterName);
474 return mNames.GetOrInsertNew(aCounterName, aCounterName, mScope);
477 nsCounterList* nsCounterManager::GetCounterList(nsAtom* aCounterName) {
478 MOZ_ASSERT(aCounterName);
479 return mNames.Get(aCounterName);
482 void nsCounterManager::RecalcAll() {
483 for (const auto& list : mNames.Values()) {
484 if (list->IsDirty()) {
485 list->RecalcAll();
490 void nsCounterManager::SetAllDirty() {
491 for (const auto& list : mNames.Values()) {
492 list->SetDirty();
496 bool nsCounterManager::DestroyNodesFor(nsIFrame* aFrame) {
497 MOZ_ASSERT(aFrame->HasAnyStateBits(NS_FRAME_HAS_CSS_COUNTER_STYLE),
498 "why call me?");
499 bool destroyedAny = false;
500 for (const auto& list : mNames.Values()) {
501 if (list->DestroyNodesFor(aFrame)) {
502 destroyedAny = true;
503 list->SetDirty();
506 return destroyedAny;
509 #ifdef ACCESSIBILITY
510 bool nsCounterManager::GetFirstCounterValueForFrame(
511 nsIFrame* aFrame, CounterValue& aOrdinal) const {
512 if (const auto* list = mNames.Get(nsGkAtoms::list_item)) {
513 for (nsCounterNode* n = list->GetFirstNodeFor(aFrame);
514 n && n->mPseudoFrame == aFrame; n = list->Next(n)) {
515 if (n->mType == nsCounterNode::USE) {
516 aOrdinal = n->mValueAfter;
517 return true;
522 return false;
524 #endif
526 #if defined(DEBUG) || defined(MOZ_LAYOUT_DEBUGGER)
527 void nsCounterManager::Dump() const {
528 printf("\n\nCounter Manager Lists:\n");
529 for (const auto& entry : mNames) {
530 printf("Counter named \"%s\":\n", nsAtomCString(entry.GetKey()).get());
532 nsCounterList* list = entry.GetWeak();
533 int32_t i = 0;
534 for (nsCounterNode* node = list->First(); node; node = list->Next(node)) {
535 const char* types[] = {"RESET", "INCREMENT", "SET", "USE"};
536 printf(
537 " Node #%d @%p frame=%p index=%d type=%s valAfter=%d\n"
538 " scope-start=%p scope-prev=%p",
539 i++, (void*)node, (void*)node->mPseudoFrame, node->mContentIndex,
540 types[node->mType], node->mValueAfter, (void*)node->mScopeStart,
541 (void*)node->mScopePrev);
542 if (node->mType == nsCounterNode::USE) {
543 nsAutoString text;
544 node->UseNode()->GetText(text);
545 printf(" text=%s", NS_ConvertUTF16toUTF8(text).get());
547 printf("\n");
550 printf("\n\n");
552 #endif