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/. */
6 
7 /* representation of one line within a block frame, a CSS line box */
8 
9 #include "nsLineBox.h"
10 
11 #include "mozilla/ArenaObjectID.h"
12 #include "mozilla/Assertions.h"
13 #include "mozilla/Likely.h"
14 #include "mozilla/PresShell.h"
15 #include "mozilla/Sprintf.h"
16 #include "mozilla/WritingModes.h"
17 #include "mozilla/ToString.h"
18 #include "nsBidiPresUtils.h"
19 #include "nsIFrame.h"
20 #include "nsIFrameInlines.h"
21 #include "nsPresArena.h"
22 #include "nsPrintfCString.h"
23 #include "nsWindowSizes.h"
24 
25 #ifdef DEBUG
26 static int32_t ctorCount;
GetCtorCount()27 int32_t nsLineBox::GetCtorCount() { return ctorCount; }
28 #endif
29 
30 #ifndef _MSC_VER
31 // static nsLineBox constant; initialized in the header file.
32 const uint32_t nsLineBox::kMinChildCountForHashtable;
33 #endif
34 
35 using namespace mozilla;
36 
nsLineBox(nsIFrame * aFrame,int32_t aCount,bool aIsBlock)37 nsLineBox::nsLineBox(nsIFrame* aFrame, int32_t aCount, bool aIsBlock)
38     : mFirstChild(aFrame),
39       mWritingMode(),
40       mContainerSize(-1, -1),
41       mBounds(WritingMode()),  // mBounds will be initialized with the correct
42                                // writing mode when it is set
43       mFrames(),
44       mAscent(),
45       mAllFlags(0),
46       mData(nullptr) {
47   // Assert that the union elements chosen for initialisation are at
48   // least as large as all other elements in their respective unions, so
49   // as to ensure that no parts are missed.
50   static_assert(sizeof(mFrames) >= sizeof(mChildCount), "nsLineBox init #1");
51   static_assert(sizeof(mAllFlags) >= sizeof(mFlags), "nsLineBox init #2");
52   static_assert(sizeof(mData) >= sizeof(mBlockData), "nsLineBox init #3");
53   static_assert(sizeof(mData) >= sizeof(mInlineData), "nsLineBox init #4");
54 
55   MOZ_COUNT_CTOR(nsLineBox);
56 #ifdef DEBUG
57   ++ctorCount;
58   NS_ASSERTION(!aIsBlock || aCount == 1, "Blocks must have exactly one child");
59   nsIFrame* f = aFrame;
60   for (int32_t n = aCount; n > 0; f = f->GetNextSibling(), --n) {
61     NS_ASSERTION(aIsBlock == f->IsBlockOutside(), "wrong kind of child frame");
62   }
63 #endif
64   static_assert(static_cast<int>(StyleClear::Max) <= 15,
65                 "FlagBits needs more bits to store the full range of "
66                 "break type ('clear') values");
67   mChildCount = aCount;
68   MarkDirty();
69   mFlags.mBlock = aIsBlock;
70 }
71 
~nsLineBox()72 nsLineBox::~nsLineBox() {
73   MOZ_COUNT_DTOR(nsLineBox);
74   if (MOZ_UNLIKELY(mFlags.mHasHashedFrames)) {
75     delete mFrames;
76   }
77   Cleanup();
78 }
79 
NS_NewLineBox(PresShell * aPresShell,nsIFrame * aFrame,bool aIsBlock)80 nsLineBox* NS_NewLineBox(PresShell* aPresShell, nsIFrame* aFrame,
81                          bool aIsBlock) {
82   return new (aPresShell) nsLineBox(aFrame, 1, aIsBlock);
83 }
84 
NS_NewLineBox(PresShell * aPresShell,nsLineBox * aFromLine,nsIFrame * aFrame,int32_t aCount)85 nsLineBox* NS_NewLineBox(PresShell* aPresShell, nsLineBox* aFromLine,
86                          nsIFrame* aFrame, int32_t aCount) {
87   nsLineBox* newLine = new (aPresShell) nsLineBox(aFrame, aCount, false);
88   newLine->NoteFramesMovedFrom(aFromLine);
89   newLine->mContainerSize = aFromLine->mContainerSize;
90   return newLine;
91 }
92 
AddSizeOfExcludingThis(nsWindowSizes & aSizes) const93 void nsLineBox::AddSizeOfExcludingThis(nsWindowSizes& aSizes) const {
94   if (mFlags.mHasHashedFrames) {
95     aSizes.mLayoutFramePropertiesSize +=
96         mFrames->ShallowSizeOfIncludingThis(aSizes.mState.mMallocSizeOf);
97   }
98 }
99 
StealHashTableFrom(nsLineBox * aFromLine,uint32_t aFromLineNewCount)100 void nsLineBox::StealHashTableFrom(nsLineBox* aFromLine,
101                                    uint32_t aFromLineNewCount) {
102   MOZ_ASSERT(!mFlags.mHasHashedFrames);
103   MOZ_ASSERT(GetChildCount() >= int32_t(aFromLineNewCount));
104   mFrames = aFromLine->mFrames;
105   mFlags.mHasHashedFrames = 1;
106   aFromLine->mFlags.mHasHashedFrames = 0;
107   aFromLine->mChildCount = aFromLineNewCount;
108   // remove aFromLine's frames that aren't on this line
109   nsIFrame* f = aFromLine->mFirstChild;
110   for (uint32_t i = 0; i < aFromLineNewCount; f = f->GetNextSibling(), ++i) {
111     mFrames->Remove(f);
112   }
113 }
114 
NoteFramesMovedFrom(nsLineBox * aFromLine)115 void nsLineBox::NoteFramesMovedFrom(nsLineBox* aFromLine) {
116   uint32_t fromCount = aFromLine->GetChildCount();
117   uint32_t toCount = GetChildCount();
118   MOZ_ASSERT(toCount <= fromCount, "moved more frames than aFromLine has");
119   uint32_t fromNewCount = fromCount - toCount;
120   if (MOZ_LIKELY(!aFromLine->mFlags.mHasHashedFrames)) {
121     aFromLine->mChildCount = fromNewCount;
122     MOZ_ASSERT(toCount < kMinChildCountForHashtable);
123   } else if (fromNewCount < kMinChildCountForHashtable) {
124     // aFromLine has a hash table but will not have it after moving the frames
125     // so this line can steal the hash table if it needs it.
126     if (toCount >= kMinChildCountForHashtable) {
127       StealHashTableFrom(aFromLine, fromNewCount);
128     } else {
129       delete aFromLine->mFrames;
130       aFromLine->mFlags.mHasHashedFrames = 0;
131       aFromLine->mChildCount = fromNewCount;
132     }
133   } else {
134     // aFromLine still needs a hash table.
135     if (toCount < kMinChildCountForHashtable) {
136       // remove the moved frames from it
137       nsIFrame* f = mFirstChild;
138       for (uint32_t i = 0; i < toCount; f = f->GetNextSibling(), ++i) {
139         aFromLine->mFrames->Remove(f);
140       }
141     } else if (toCount <= fromNewCount) {
142       // This line needs a hash table, allocate a hash table for it since that
143       // means fewer hash ops.
144       nsIFrame* f = mFirstChild;
145       for (uint32_t i = 0; i < toCount; f = f->GetNextSibling(), ++i) {
146         aFromLine->mFrames->Remove(f);  // toCount RemoveEntry
147       }
148       SwitchToHashtable();  // toCount PutEntry
149     } else {
150       // This line needs a hash table, but it's fewer hash ops to steal
151       // aFromLine's hash table and allocate a new hash table for that line.
152       StealHashTableFrom(aFromLine, fromNewCount);  // fromNewCount RemoveEntry
153       aFromLine->SwitchToHashtable();               // fromNewCount PutEntry
154     }
155   }
156 }
157 
operator new(size_t sz,PresShell * aPresShell)158 void* nsLineBox::operator new(size_t sz, PresShell* aPresShell) {
159   return aPresShell->AllocateByObjectID(eArenaObjectID_nsLineBox, sz);
160 }
161 
Destroy(PresShell * aPresShell)162 void nsLineBox::Destroy(PresShell* aPresShell) {
163   this->nsLineBox::~nsLineBox();
164   aPresShell->FreeByObjectID(eArenaObjectID_nsLineBox, this);
165 }
166 
Cleanup()167 void nsLineBox::Cleanup() {
168   if (mData) {
169     if (IsBlock()) {
170       delete mBlockData;
171     } else {
172       delete mInlineData;
173     }
174     mData = nullptr;
175   }
176 }
177 
178 #ifdef DEBUG_FRAME_DUMP
ListFloats(FILE * out,const char * aPrefix,const nsFloatCacheList & aFloats)179 static void ListFloats(FILE* out, const char* aPrefix,
180                        const nsFloatCacheList& aFloats) {
181   nsFloatCache* fc = aFloats.Head();
182   while (fc) {
183     nsCString str(aPrefix);
184     nsIFrame* frame = fc->mFloat;
185     str += nsPrintfCString("floatframe@%p ", static_cast<void*>(frame));
186     if (frame) {
187       nsAutoString frameName;
188       frame->GetFrameName(frameName);
189       str += NS_ConvertUTF16toUTF8(frameName).get();
190     } else {
191       str += "\n###!!! NULL out-of-flow frame";
192     }
193     fprintf_stderr(out, "%s\n", str.get());
194     fc = fc->Next();
195   }
196 }
197 
BreakTypeToString(StyleClear aBreakType)198 /* static */ const char* nsLineBox::BreakTypeToString(StyleClear aBreakType) {
199   switch (aBreakType) {
200     case StyleClear::None:
201       return "nobr";
202     case StyleClear::Left:
203       return "leftbr";
204     case StyleClear::Right:
205       return "rightbr";
206     case StyleClear::Both:
207       return "leftbr+rightbr";
208     case StyleClear::Line:
209       return "linebr";
210     case StyleClear::Max:
211       return "leftbr+rightbr+linebr";
212   }
213   return "unknown";
214 }
215 
StateToString(char * aBuf,int32_t aBufSize) const216 char* nsLineBox::StateToString(char* aBuf, int32_t aBufSize) const {
217   snprintf(aBuf, aBufSize, "%s,%s,%s,%s,%s,before:%s,after:%s[0x%x]",
218            IsBlock() ? "block" : "inline", IsDirty() ? "dirty" : "clean",
219            IsPreviousMarginDirty() ? "prevmargindirty" : "prevmarginclean",
220            IsImpactedByFloat() ? "impacted" : "not-impacted",
221            IsLineWrapped() ? "wrapped" : "not-wrapped",
222            BreakTypeToString(GetBreakTypeBefore()),
223            BreakTypeToString(GetBreakTypeAfter()), mAllFlags);
224   return aBuf;
225 }
226 
List(FILE * out,int32_t aIndent,nsIFrame::ListFlags aFlags) const227 void nsLineBox::List(FILE* out, int32_t aIndent,
228                      nsIFrame::ListFlags aFlags) const {
229   nsCString str;
230   while (aIndent-- > 0) {
231     str += "  ";
232   }
233   List(out, str.get(), aFlags);
234 }
235 
List(FILE * out,const char * aPrefix,nsIFrame::ListFlags aFlags) const236 void nsLineBox::List(FILE* out, const char* aPrefix,
237                      nsIFrame::ListFlags aFlags) const {
238   nsCString str(aPrefix);
239   char cbuf[100];
240   str += nsPrintfCString("line@%p count=%d state=%s ",
241                          static_cast<const void*>(this), GetChildCount(),
242                          StateToString(cbuf, sizeof(cbuf)));
243   if (IsBlock() && !GetCarriedOutBEndMargin().IsZero()) {
244     const nscoord bm = GetCarriedOutBEndMargin().get();
245     str += nsPrintfCString("bm=%s ",
246                            nsIFrame::ConvertToString(bm, aFlags).c_str());
247   }
248   nsRect bounds = GetPhysicalBounds();
249   str +=
250       nsPrintfCString("%s ", nsIFrame::ConvertToString(bounds, aFlags).c_str());
251   if (mWritingMode.IsVertical() || mWritingMode.IsBidiRTL()) {
252     str += nsPrintfCString(
253         "wm=%s cs=(%s) logical-rect=%s ", ToString(mWritingMode).c_str(),
254         nsIFrame::ConvertToString(mContainerSize, aFlags).c_str(),
255         nsIFrame::ConvertToString(mBounds, mWritingMode, aFlags).c_str());
256   }
257   if (mData) {
258     const nsRect vo = mData->mOverflowAreas.InkOverflow();
259     const nsRect so = mData->mOverflowAreas.ScrollableOverflow();
260     if (!vo.IsEqualEdges(bounds) || !so.IsEqualEdges(bounds)) {
261       str += nsPrintfCString("ink-overflow=%s scr-overflow=%s ",
262                              nsIFrame::ConvertToString(vo, aFlags).c_str(),
263                              nsIFrame::ConvertToString(so, aFlags).c_str());
264     }
265   }
266   fprintf_stderr(out, "%s<\n", str.get());
267 
268   nsIFrame* frame = mFirstChild;
269   int32_t n = GetChildCount();
270   nsCString pfx(aPrefix);
271   pfx += "  ";
272   while (--n >= 0) {
273     frame->List(out, pfx.get(), aFlags);
274     frame = frame->GetNextSibling();
275   }
276 
277   if (HasFloats()) {
278     fprintf_stderr(out, "%s> floats <\n", aPrefix);
279     ListFloats(out, pfx.get(), mInlineData->mFloats);
280   }
281   fprintf_stderr(out, "%s>\n", aPrefix);
282 }
283 
LastChild() const284 nsIFrame* nsLineBox::LastChild() const {
285   nsIFrame* frame = mFirstChild;
286   int32_t n = GetChildCount() - 1;
287   while (--n >= 0) {
288     frame = frame->GetNextSibling();
289   }
290   return frame;
291 }
292 #endif
293 
IndexOf(nsIFrame * aFrame) const294 int32_t nsLineBox::IndexOf(nsIFrame* aFrame) const {
295   int32_t i, n = GetChildCount();
296   nsIFrame* frame = mFirstChild;
297   for (i = 0; i < n; i++) {
298     if (frame == aFrame) {
299       return i;
300     }
301     frame = frame->GetNextSibling();
302   }
303   return -1;
304 }
305 
RIndexOf(nsIFrame * aFrame,nsIFrame * aLastFrameInLine) const306 int32_t nsLineBox::RIndexOf(nsIFrame* aFrame,
307                             nsIFrame* aLastFrameInLine) const {
308   nsIFrame* frame = aLastFrameInLine;
309   for (int32_t i = GetChildCount() - 1; i >= 0; --i) {
310     MOZ_ASSERT(i != 0 || frame == mFirstChild,
311                "caller provided incorrect last frame");
312     if (frame == aFrame) {
313       return i;
314     }
315     frame = frame->GetPrevSibling();
316   }
317   return -1;
318 }
319 
IsEmpty() const320 bool nsLineBox::IsEmpty() const {
321   if (IsBlock()) return mFirstChild->IsEmpty();
322 
323   int32_t n;
324   nsIFrame* kid;
325   for (n = GetChildCount(), kid = mFirstChild; n > 0;
326        --n, kid = kid->GetNextSibling()) {
327     if (!kid->IsEmpty()) return false;
328   }
329   if (HasMarker()) {
330     return false;
331   }
332   return true;
333 }
334 
CachedIsEmpty()335 bool nsLineBox::CachedIsEmpty() {
336   if (mFlags.mDirty) {
337     return IsEmpty();
338   }
339 
340   if (mFlags.mEmptyCacheValid) {
341     return mFlags.mEmptyCacheState;
342   }
343 
344   bool result;
345   if (IsBlock()) {
346     result = mFirstChild->CachedIsEmpty();
347   } else {
348     int32_t n;
349     nsIFrame* kid;
350     result = true;
351     for (n = GetChildCount(), kid = mFirstChild; n > 0;
352          --n, kid = kid->GetNextSibling()) {
353       if (!kid->CachedIsEmpty()) {
354         result = false;
355         break;
356       }
357     }
358     if (HasMarker()) {
359       result = false;
360     }
361   }
362 
363   mFlags.mEmptyCacheValid = true;
364   mFlags.mEmptyCacheState = result;
365   return result;
366 }
367 
DeleteLineList(nsPresContext * aPresContext,nsLineList & aLines,nsIFrame * aDestructRoot,nsFrameList * aFrames,PostDestroyData & aPostDestroyData)368 void nsLineBox::DeleteLineList(nsPresContext* aPresContext, nsLineList& aLines,
369                                nsIFrame* aDestructRoot, nsFrameList* aFrames,
370                                PostDestroyData& aPostDestroyData) {
371   PresShell* presShell = aPresContext->PresShell();
372 
373   // Keep our line list and frame list up to date as we
374   // remove frames, in case something wants to traverse the
375   // frame tree while we're destroying.
376   while (!aLines.empty()) {
377     nsLineBox* line = aLines.front();
378     if (MOZ_UNLIKELY(line->mFlags.mHasHashedFrames)) {
379       line->SwitchToCounter();  // Avoid expensive has table removals.
380     }
381     while (line->GetChildCount() > 0) {
382       nsIFrame* child = aFrames->RemoveFirstChild();
383       MOZ_DIAGNOSTIC_ASSERT(child->PresContext() == aPresContext);
384       MOZ_DIAGNOSTIC_ASSERT(child == line->mFirstChild, "Lines out of sync");
385       line->mFirstChild = aFrames->FirstChild();
386       line->NoteFrameRemoved(child);
387       child->DestroyFrom(aDestructRoot, aPostDestroyData);
388     }
389     MOZ_DIAGNOSTIC_ASSERT(line == aLines.front(),
390                           "destroying child frames messed up our lines!");
391     aLines.pop_front();
392     line->Destroy(presShell);
393   }
394 }
395 
RFindLineContaining(nsIFrame * aFrame,const nsLineList::iterator & aBegin,nsLineList::iterator & aEnd,nsIFrame * aLastFrameBeforeEnd,int32_t * aFrameIndexInLine)396 bool nsLineBox::RFindLineContaining(nsIFrame* aFrame,
397                                     const nsLineList::iterator& aBegin,
398                                     nsLineList::iterator& aEnd,
399                                     nsIFrame* aLastFrameBeforeEnd,
400                                     int32_t* aFrameIndexInLine) {
401   MOZ_ASSERT(aFrame, "null ptr");
402 
403   nsIFrame* curFrame = aLastFrameBeforeEnd;
404   while (aBegin != aEnd) {
405     --aEnd;
406     NS_ASSERTION(aEnd->LastChild() == curFrame, "Unexpected curFrame");
407     if (MOZ_UNLIKELY(aEnd->mFlags.mHasHashedFrames) &&
408         !aEnd->Contains(aFrame)) {
409       if (aEnd->mFirstChild) {
410         curFrame = aEnd->mFirstChild->GetPrevSibling();
411       }
412       continue;
413     }
414     // i is the index of curFrame in aEnd
415     int32_t i = aEnd->GetChildCount() - 1;
416     while (i >= 0) {
417       if (curFrame == aFrame) {
418         *aFrameIndexInLine = i;
419         return true;
420       }
421       --i;
422       curFrame = curFrame->GetPrevSibling();
423     }
424     MOZ_ASSERT(!aEnd->mFlags.mHasHashedFrames, "Contains lied to us!");
425   }
426   *aFrameIndexInLine = -1;
427   return false;
428 }
429 
GetCarriedOutBEndMargin() const430 nsCollapsingMargin nsLineBox::GetCarriedOutBEndMargin() const {
431   NS_ASSERTION(IsBlock(), "GetCarriedOutBEndMargin called on non-block line.");
432   return (IsBlock() && mBlockData) ? mBlockData->mCarriedOutBEndMargin
433                                    : nsCollapsingMargin();
434 }
435 
SetCarriedOutBEndMargin(nsCollapsingMargin aValue)436 bool nsLineBox::SetCarriedOutBEndMargin(nsCollapsingMargin aValue) {
437   bool changed = false;
438   if (IsBlock()) {
439     if (!aValue.IsZero()) {
440       if (!mBlockData) {
441         mBlockData = new ExtraBlockData(GetPhysicalBounds());
442       }
443       changed = aValue != mBlockData->mCarriedOutBEndMargin;
444       mBlockData->mCarriedOutBEndMargin = aValue;
445     } else if (mBlockData) {
446       changed = aValue != mBlockData->mCarriedOutBEndMargin;
447       mBlockData->mCarriedOutBEndMargin = aValue;
448       MaybeFreeData();
449     }
450   }
451   return changed;
452 }
453 
MaybeFreeData()454 void nsLineBox::MaybeFreeData() {
455   nsRect bounds = GetPhysicalBounds();
456   if (mData && mData->mOverflowAreas == OverflowAreas(bounds, bounds)) {
457     if (IsInline()) {
458       if (mInlineData->mFloats.IsEmpty()) {
459         delete mInlineData;
460         mInlineData = nullptr;
461       }
462     } else if (mBlockData->mCarriedOutBEndMargin.IsZero()) {
463       delete mBlockData;
464       mBlockData = nullptr;
465     }
466   }
467 }
468 
469 // XXX get rid of this???
GetFirstFloat()470 nsFloatCache* nsLineBox::GetFirstFloat() {
471   MOZ_ASSERT(IsInline(), "block line can't have floats");
472   return mInlineData ? mInlineData->mFloats.Head() : nullptr;
473 }
474 
475 // XXX this might be too eager to free memory
FreeFloats(nsFloatCacheFreeList & aFreeList)476 void nsLineBox::FreeFloats(nsFloatCacheFreeList& aFreeList) {
477   MOZ_ASSERT(IsInline(), "block line can't have floats");
478   if (IsInline() && mInlineData) {
479     if (mInlineData->mFloats.NotEmpty()) {
480       aFreeList.Append(mInlineData->mFloats);
481     }
482     MaybeFreeData();
483   }
484 }
485 
AppendFloats(nsFloatCacheFreeList & aFreeList)486 void nsLineBox::AppendFloats(nsFloatCacheFreeList& aFreeList) {
487   MOZ_ASSERT(IsInline(), "block line can't have floats");
488   if (IsInline()) {
489     if (aFreeList.NotEmpty()) {
490       if (!mInlineData) {
491         mInlineData = new ExtraInlineData(GetPhysicalBounds());
492       }
493       mInlineData->mFloats.Append(aFreeList);
494     }
495   }
496 }
497 
RemoveFloat(nsIFrame * aFrame)498 bool nsLineBox::RemoveFloat(nsIFrame* aFrame) {
499   MOZ_ASSERT(IsInline(), "block line can't have floats");
500   if (IsInline() && mInlineData) {
501     nsFloatCache* fc = mInlineData->mFloats.Find(aFrame);
502     if (fc) {
503       // Note: the placeholder is part of the line's child list
504       // and will be removed later.
505       mInlineData->mFloats.Remove(fc);
506       delete fc;
507       MaybeFreeData();
508       return true;
509     }
510   }
511   return false;
512 }
513 
SetFloatEdges(nscoord aStart,nscoord aEnd)514 void nsLineBox::SetFloatEdges(nscoord aStart, nscoord aEnd) {
515   MOZ_ASSERT(IsInline(), "block line can't have float edges");
516   if (!mInlineData) {
517     mInlineData = new ExtraInlineData(GetPhysicalBounds());
518   }
519   mInlineData->mFloatEdgeIStart = aStart;
520   mInlineData->mFloatEdgeIEnd = aEnd;
521 }
522 
ClearFloatEdges()523 void nsLineBox::ClearFloatEdges() {
524   MOZ_ASSERT(IsInline(), "block line can't have float edges");
525   if (mInlineData) {
526     mInlineData->mFloatEdgeIStart = nscoord_MIN;
527     mInlineData->mFloatEdgeIEnd = nscoord_MIN;
528   }
529 }
530 
SetOverflowAreas(const OverflowAreas & aOverflowAreas)531 void nsLineBox::SetOverflowAreas(const OverflowAreas& aOverflowAreas) {
532 #ifdef DEBUG
533   for (const auto otype : mozilla::AllOverflowTypes()) {
534     NS_ASSERTION(aOverflowAreas.Overflow(otype).width >= 0,
535                  "Illegal width for an overflow area!");
536     NS_ASSERTION(aOverflowAreas.Overflow(otype).height >= 0,
537                  "Illegal height for an overflow area!");
538   }
539 #endif
540 
541   nsRect bounds = GetPhysicalBounds();
542   if (!aOverflowAreas.InkOverflow().IsEqualInterior(bounds) ||
543       !aOverflowAreas.ScrollableOverflow().IsEqualEdges(bounds)) {
544     if (!mData) {
545       if (IsInline()) {
546         mInlineData = new ExtraInlineData(bounds);
547       } else {
548         mBlockData = new ExtraBlockData(bounds);
549       }
550     }
551     mData->mOverflowAreas = aOverflowAreas;
552   } else if (mData) {
553     // Store away new value so that MaybeFreeData compares against
554     // the right value.
555     mData->mOverflowAreas = aOverflowAreas;
556     MaybeFreeData();
557   }
558 }
559 
560 //----------------------------------------------------------------------
561 
GetLine(int32_t aLineNumber)562 Result<nsILineIterator::LineInfo, nsresult> nsLineIterator::GetLine(
563     int32_t aLineNumber) {
564   const nsLineBox* line = GetLineAt(aLineNumber);
565   if (!line) {
566     return Err(NS_ERROR_FAILURE);
567   }
568   LineInfo structure;
569   structure.mFirstFrameOnLine = line->mFirstChild;
570   structure.mNumFramesOnLine = line->GetChildCount();
571   structure.mLineBounds = line->GetPhysicalBounds();
572   structure.mIsWrapped = line->IsLineWrapped();
573   return structure;
574 }
575 
FindLineContaining(nsIFrame * aFrame,int32_t aStartLine)576 int32_t nsLineIterator::FindLineContaining(nsIFrame* aFrame,
577                                            int32_t aStartLine) {
578   const nsLineBox* line = GetLineAt(aStartLine);
579   MOZ_ASSERT(line, "aStartLine out of range");
580   while (line) {
581     if (line->Contains(aFrame)) {
582       return mIndex;
583     }
584     line = GetNextLine();
585   }
586   return -1;
587 }
588 
589 NS_IMETHODIMP
CheckLineOrder(int32_t aLine,bool * aIsReordered,nsIFrame ** aFirstVisual,nsIFrame ** aLastVisual)590 nsLineIterator::CheckLineOrder(int32_t aLine, bool* aIsReordered,
591                                nsIFrame** aFirstVisual,
592                                nsIFrame** aLastVisual) {
593   const nsLineBox* line = GetLineAt(aLine);
594   MOZ_ASSERT(line, "aLine out of range!");
595 
596   if (!line || !line->mFirstChild) {  // empty line
597     *aIsReordered = false;
598     *aFirstVisual = nullptr;
599     *aLastVisual = nullptr;
600     return NS_OK;
601   }
602 
603   nsIFrame* leftmostFrame;
604   nsIFrame* rightmostFrame;
605   *aIsReordered =
606       nsBidiPresUtils::CheckLineOrder(line->mFirstChild, line->GetChildCount(),
607                                       &leftmostFrame, &rightmostFrame);
608 
609   // map leftmost/rightmost to first/last according to paragraph direction
610   *aFirstVisual = mRightToLeft ? rightmostFrame : leftmostFrame;
611   *aLastVisual = mRightToLeft ? leftmostFrame : rightmostFrame;
612 
613   return NS_OK;
614 }
615 
616 NS_IMETHODIMP
FindFrameAt(int32_t aLineNumber,nsPoint aPos,nsIFrame ** aFrameFound,bool * aPosIsBeforeFirstFrame,bool * aPosIsAfterLastFrame)617 nsLineIterator::FindFrameAt(int32_t aLineNumber, nsPoint aPos,
618                             nsIFrame** aFrameFound,
619                             bool* aPosIsBeforeFirstFrame,
620                             bool* aPosIsAfterLastFrame) {
621   MOZ_ASSERT(aFrameFound && aPosIsBeforeFirstFrame && aPosIsAfterLastFrame,
622              "null OUT ptr");
623 
624   if (!aFrameFound || !aPosIsBeforeFirstFrame || !aPosIsAfterLastFrame) {
625     return NS_ERROR_NULL_POINTER;
626   }
627 
628   const nsLineBox* line = GetLineAt(aLineNumber);
629   if (!line) {
630     *aFrameFound = nullptr;
631     *aPosIsBeforeFirstFrame = true;
632     *aPosIsAfterLastFrame = false;
633     return NS_OK;
634   }
635 
636   if (line->ISize() == 0 && line->BSize() == 0) return NS_ERROR_FAILURE;
637 
638   nsIFrame* frame = line->mFirstChild;
639   nsIFrame* closestFromStart = nullptr;
640   nsIFrame* closestFromEnd = nullptr;
641 
642   WritingMode wm = line->mWritingMode;
643   nsSize containerSize = line->mContainerSize;
644 
645   LogicalPoint pos(wm, aPos, containerSize);
646 
647   int32_t n = line->GetChildCount();
648   while (n--) {
649     LogicalRect rect = frame->GetLogicalRect(wm, containerSize);
650     if (rect.ISize(wm) > 0) {
651       // If pos.I() is inside this frame - this is it
652       if (rect.IStart(wm) <= pos.I(wm) && rect.IEnd(wm) > pos.I(wm)) {
653         closestFromStart = closestFromEnd = frame;
654         break;
655       }
656       if (rect.IStart(wm) < pos.I(wm)) {
657         if (!closestFromStart ||
658             rect.IEnd(wm) >
659                 closestFromStart->GetLogicalRect(wm, containerSize).IEnd(wm))
660           closestFromStart = frame;
661       } else {
662         if (!closestFromEnd ||
663             rect.IStart(wm) <
664                 closestFromEnd->GetLogicalRect(wm, containerSize).IStart(wm))
665           closestFromEnd = frame;
666       }
667     }
668     frame = frame->GetNextSibling();
669   }
670   if (!closestFromStart && !closestFromEnd) {
671     // All frames were zero-width. Just take the first one.
672     closestFromStart = closestFromEnd = line->mFirstChild;
673   }
674   *aPosIsBeforeFirstFrame = mRightToLeft ? !closestFromEnd : !closestFromStart;
675   *aPosIsAfterLastFrame = mRightToLeft ? !closestFromStart : !closestFromEnd;
676   if (closestFromStart == closestFromEnd) {
677     *aFrameFound = closestFromStart;
678   } else if (!closestFromStart) {
679     *aFrameFound = closestFromEnd;
680   } else if (!closestFromEnd) {
681     *aFrameFound = closestFromStart;
682   } else {  // we're between two frames
683     nscoord delta =
684         closestFromEnd->GetLogicalRect(wm, containerSize).IStart(wm) -
685         closestFromStart->GetLogicalRect(wm, containerSize).IEnd(wm);
686     if (pos.I(wm) <
687         closestFromStart->GetLogicalRect(wm, containerSize).IEnd(wm) +
688             delta / 2) {
689       *aFrameFound = closestFromStart;
690     } else {
691       *aFrameFound = closestFromEnd;
692     }
693   }
694   return NS_OK;
695 }
696 
697 //----------------------------------------------------------------------
698 
699 #ifdef NS_BUILD_REFCNT_LOGGING
nsFloatCacheList()700 nsFloatCacheList::nsFloatCacheList() : mHead(nullptr) {
701   MOZ_COUNT_CTOR(nsFloatCacheList);
702 }
703 #endif
704 
~nsFloatCacheList()705 nsFloatCacheList::~nsFloatCacheList() {
706   DeleteAll();
707   MOZ_COUNT_DTOR(nsFloatCacheList);
708 }
709 
DeleteAll()710 void nsFloatCacheList::DeleteAll() {
711   nsFloatCache* c = mHead;
712   while (c) {
713     nsFloatCache* next = c->Next();
714     delete c;
715     c = next;
716   }
717   mHead = nullptr;
718 }
719 
Tail() const720 nsFloatCache* nsFloatCacheList::Tail() const {
721   nsFloatCache* fc = mHead;
722   while (fc) {
723     if (!fc->mNext) {
724       break;
725     }
726     fc = fc->mNext;
727   }
728   return fc;
729 }
730 
Append(nsFloatCacheFreeList & aList)731 void nsFloatCacheList::Append(nsFloatCacheFreeList& aList) {
732   MOZ_ASSERT(aList.NotEmpty(), "Appending empty list will fail");
733 
734   nsFloatCache* tail = Tail();
735   if (tail) {
736     NS_ASSERTION(!tail->mNext, "Bogus!");
737     tail->mNext = aList.mHead;
738   } else {
739     NS_ASSERTION(!mHead, "Bogus!");
740     mHead = aList.mHead;
741   }
742   aList.mHead = nullptr;
743   aList.mTail = nullptr;
744 }
745 
Find(nsIFrame * aOutOfFlowFrame)746 nsFloatCache* nsFloatCacheList::Find(nsIFrame* aOutOfFlowFrame) {
747   nsFloatCache* fc = mHead;
748   while (fc) {
749     if (fc->mFloat == aOutOfFlowFrame) {
750       break;
751     }
752     fc = fc->Next();
753   }
754   return fc;
755 }
756 
RemoveAndReturnPrev(nsFloatCache * aElement)757 nsFloatCache* nsFloatCacheList::RemoveAndReturnPrev(nsFloatCache* aElement) {
758   nsFloatCache* fc = mHead;
759   nsFloatCache* prev = nullptr;
760   while (fc) {
761     if (fc == aElement) {
762       if (prev) {
763         prev->mNext = fc->mNext;
764       } else {
765         mHead = fc->mNext;
766       }
767       return prev;
768     }
769     prev = fc;
770     fc = fc->mNext;
771   }
772   return nullptr;
773 }
774 
775 //----------------------------------------------------------------------
776 
777 #ifdef NS_BUILD_REFCNT_LOGGING
nsFloatCacheFreeList()778 nsFloatCacheFreeList::nsFloatCacheFreeList() : mTail(nullptr) {
779   MOZ_COUNT_CTOR(nsFloatCacheFreeList);
780 }
781 
~nsFloatCacheFreeList()782 nsFloatCacheFreeList::~nsFloatCacheFreeList() {
783   MOZ_COUNT_DTOR(nsFloatCacheFreeList);
784 }
785 #endif
786 
Append(nsFloatCacheList & aList)787 void nsFloatCacheFreeList::Append(nsFloatCacheList& aList) {
788   MOZ_ASSERT(aList.NotEmpty(), "Appending empty list will fail");
789 
790   if (mTail) {
791     NS_ASSERTION(!mTail->mNext, "Bogus");
792     mTail->mNext = aList.mHead;
793   } else {
794     NS_ASSERTION(!mHead, "Bogus");
795     mHead = aList.mHead;
796   }
797   mTail = aList.Tail();
798   aList.mHead = nullptr;
799 }
800 
Remove(nsFloatCache * aElement)801 void nsFloatCacheFreeList::Remove(nsFloatCache* aElement) {
802   nsFloatCache* prev = nsFloatCacheList::RemoveAndReturnPrev(aElement);
803   if (mTail == aElement) {
804     mTail = prev;
805   }
806 }
807 
DeleteAll()808 void nsFloatCacheFreeList::DeleteAll() {
809   nsFloatCacheList::DeleteAll();
810   mTail = nullptr;
811 }
812 
Alloc(nsIFrame * aFloat)813 nsFloatCache* nsFloatCacheFreeList::Alloc(nsIFrame* aFloat) {
814   MOZ_ASSERT(aFloat->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW),
815              "This is a float cache, why isn't the frame out-of-flow?");
816 
817   nsFloatCache* fc = mHead;
818   if (mHead) {
819     if (mHead == mTail) {
820       mHead = mTail = nullptr;
821     } else {
822       mHead = fc->mNext;
823     }
824     fc->mNext = nullptr;
825   } else {
826     fc = new nsFloatCache();
827   }
828   fc->mFloat = aFloat;
829   return fc;
830 }
831 
Append(nsFloatCache * aFloat)832 void nsFloatCacheFreeList::Append(nsFloatCache* aFloat) {
833   NS_ASSERTION(!aFloat->mNext, "Bogus!");
834   aFloat->mNext = nullptr;
835   if (mTail) {
836     NS_ASSERTION(!mTail->mNext, "Bogus!");
837     mTail->mNext = aFloat;
838     mTail = aFloat;
839   } else {
840     NS_ASSERTION(!mHead, "Bogus!");
841     mHead = mTail = aFloat;
842   }
843 }
844 
845 //----------------------------------------------------------------------
846 
nsFloatCache()847 nsFloatCache::nsFloatCache() : mFloat(nullptr), mNext(nullptr) {
848   MOZ_COUNT_CTOR(nsFloatCache);
849 }
850 
851 #ifdef NS_BUILD_REFCNT_LOGGING
~nsFloatCache()852 nsFloatCache::~nsFloatCache() { MOZ_COUNT_DTOR(nsFloatCache); }
853 #endif
854