1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 #include "nsTableRowFrame.h"
7 
8 #include "mozilla/Maybe.h"
9 #include "mozilla/PresShell.h"
10 #include "nsTableRowGroupFrame.h"
11 #include "nsPresContext.h"
12 #include "mozilla/ComputedStyle.h"
13 #include "nsStyleConsts.h"
14 #include "nsGkAtoms.h"
15 #include "nsIContent.h"
16 #include "nsIFrame.h"
17 #include "nsIFrameInlines.h"
18 #include "nsTableFrame.h"
19 #include "nsTableCellFrame.h"
20 #include "nsCSSRendering.h"
21 #include "nsHTMLParts.h"
22 #include "nsTableColGroupFrame.h"
23 #include "nsTableColFrame.h"
24 #include "nsCOMPtr.h"
25 #include "nsDisplayList.h"
26 #include "nsIFrameInlines.h"
27 #include <algorithm>
28 
29 using namespace mozilla;
30 
31 namespace mozilla {
32 
33 struct TableCellReflowInput : public ReflowInput {
TableCellReflowInputmozilla::TableCellReflowInput34   TableCellReflowInput(nsPresContext* aPresContext,
35                        const ReflowInput& aParentReflowInput, nsIFrame* aFrame,
36                        const LogicalSize& aAvailableSpace, uint32_t aFlags = 0)
37       : ReflowInput(aPresContext, aParentReflowInput, aFrame, aAvailableSpace,
38                     Nothing(), aFlags) {}
39 
40   void FixUp(const LogicalSize& aAvailSpace);
41 };
42 
43 }  // namespace mozilla
44 
FixUp(const LogicalSize & aAvailSpace)45 void TableCellReflowInput::FixUp(const LogicalSize& aAvailSpace) {
46   // fix the mComputed values during a pass 2 reflow since the cell can be a
47   // percentage base
48   NS_WARNING_ASSERTION(
49       NS_UNCONSTRAINEDSIZE != aAvailSpace.ISize(mWritingMode),
50       "have unconstrained inline-size; this should only result from very large "
51       "sizes, not attempts at intrinsic inline size calculation");
52   if (NS_UNCONSTRAINEDSIZE != ComputedISize()) {
53     nscoord computedISize =
54         aAvailSpace.ISize(mWritingMode) -
55         ComputedLogicalBorderPadding().IStartEnd(mWritingMode);
56     computedISize = std::max(0, computedISize);
57     SetComputedISize(computedISize);
58   }
59   if (NS_UNCONSTRAINEDSIZE != ComputedBSize() &&
60       NS_UNCONSTRAINEDSIZE != aAvailSpace.BSize(mWritingMode)) {
61     nscoord computedBSize =
62         aAvailSpace.BSize(mWritingMode) -
63         ComputedLogicalBorderPadding().BStartEnd(mWritingMode);
64     computedBSize = std::max(0, computedBSize);
65     SetComputedBSize(computedBSize);
66   }
67 }
68 
InitChildReflowInput(nsPresContext & aPresContext,const LogicalSize & aAvailSize,bool aBorderCollapse,TableCellReflowInput & aReflowInput)69 void nsTableRowFrame::InitChildReflowInput(nsPresContext& aPresContext,
70                                            const LogicalSize& aAvailSize,
71                                            bool aBorderCollapse,
72                                            TableCellReflowInput& aReflowInput) {
73   nsMargin collapseBorder;
74   nsMargin* pCollapseBorder = nullptr;
75   if (aBorderCollapse) {
76     // we only reflow cells, so don't need to check frame type
77     nsBCTableCellFrame* bcCellFrame = (nsBCTableCellFrame*)aReflowInput.mFrame;
78     if (bcCellFrame) {
79       WritingMode wm = GetWritingMode();
80       collapseBorder = bcCellFrame->GetBorderWidth(wm).GetPhysicalMargin(wm);
81       pCollapseBorder = &collapseBorder;
82     }
83   }
84   aReflowInput.Init(&aPresContext, Nothing(), pCollapseBorder);
85   aReflowInput.FixUp(aAvailSize);
86 }
87 
SetFixedBSize(nscoord aValue)88 void nsTableRowFrame::SetFixedBSize(nscoord aValue) {
89   nscoord bsize = std::max(0, aValue);
90   if (HasFixedBSize()) {
91     if (bsize > mStyleFixedBSize) {
92       mStyleFixedBSize = bsize;
93     }
94   } else {
95     mStyleFixedBSize = bsize;
96     if (bsize > 0) {
97       SetHasFixedBSize(true);
98     }
99   }
100 }
101 
SetPctBSize(float aPctValue,bool aForce)102 void nsTableRowFrame::SetPctBSize(float aPctValue, bool aForce) {
103   nscoord bsize = std::max(0, NSToCoordRound(aPctValue * 100.0f));
104   if (HasPctBSize()) {
105     if ((bsize > mStylePctBSize) || aForce) {
106       mStylePctBSize = bsize;
107     }
108   } else {
109     mStylePctBSize = bsize;
110     if (bsize > 0) {
111       SetHasPctBSize(true);
112     }
113   }
114 }
115 
116 /* ----------- nsTableRowFrame ---------- */
117 
118 NS_QUERYFRAME_HEAD(nsTableRowFrame)
NS_QUERYFRAME_ENTRY(nsTableRowFrame)119   NS_QUERYFRAME_ENTRY(nsTableRowFrame)
120 NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)
121 
122 nsTableRowFrame::nsTableRowFrame(ComputedStyle* aStyle,
123                                  nsPresContext* aPresContext, ClassID aID)
124     : nsContainerFrame(aStyle, aPresContext, aID),
125       mContentBSize(0),
126       mStylePctBSize(0),
127       mStyleFixedBSize(0),
128       mMaxCellAscent(0),
129       mMaxCellDescent(0),
130       mBStartBorderWidth(0),
131       mBEndBorderWidth(0),
132       mIEndContBorderWidth(0),
133       mBStartContBorderWidth(0),
134       mIStartContBorderWidth(0) {
135   mBits.mRowIndex = 0;
136   mBits.mHasFixedBSize = 0;
137   mBits.mHasPctBSize = 0;
138   mBits.mFirstInserted = 0;
139   ResetBSize(0);
140 }
141 
142 nsTableRowFrame::~nsTableRowFrame() = default;
143 
Init(nsIContent * aContent,nsContainerFrame * aParent,nsIFrame * aPrevInFlow)144 void nsTableRowFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
145                            nsIFrame* aPrevInFlow) {
146   // Let the base class do its initialization
147   nsContainerFrame::Init(aContent, aParent, aPrevInFlow);
148 
149   NS_ASSERTION(mozilla::StyleDisplay::TableRow == StyleDisplay()->mDisplay,
150                "wrong display on table row frame");
151 
152   if (aPrevInFlow) {
153     // Set the row index
154     nsTableRowFrame* rowFrame = (nsTableRowFrame*)aPrevInFlow;
155 
156     SetRowIndex(rowFrame->GetRowIndex());
157   } else {
158     mWritingMode = GetTableFrame()->GetWritingMode();
159   }
160 }
161 
DestroyFrom(nsIFrame * aDestructRoot,PostDestroyData & aPostDestroyData)162 void nsTableRowFrame::DestroyFrom(nsIFrame* aDestructRoot,
163                                   PostDestroyData& aPostDestroyData) {
164   if (HasAnyStateBits(NS_FRAME_CAN_HAVE_ABSPOS_CHILDREN)) {
165     nsTableFrame::UnregisterPositionedTablePart(this, aDestructRoot);
166   }
167 
168   nsContainerFrame::DestroyFrom(aDestructRoot, aPostDestroyData);
169 }
170 
171 /* virtual */
DidSetComputedStyle(ComputedStyle * aOldComputedStyle)172 void nsTableRowFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
173   nsContainerFrame::DidSetComputedStyle(aOldComputedStyle);
174 
175   if (!aOldComputedStyle)  // avoid this on init
176     return;
177 
178   nsTableFrame* tableFrame = GetTableFrame();
179   if (tableFrame->IsBorderCollapse() &&
180       tableFrame->BCRecalcNeeded(aOldComputedStyle, Style())) {
181     TableArea damageArea(0, GetRowIndex(), tableFrame->GetColCount(), 1);
182     tableFrame->AddBCDamageArea(damageArea);
183   }
184 }
185 
AppendFrames(ChildListID aListID,nsFrameList & aFrameList)186 void nsTableRowFrame::AppendFrames(ChildListID aListID,
187                                    nsFrameList& aFrameList) {
188   NS_ASSERTION(aListID == kPrincipalList, "unexpected child list");
189 
190   DrainSelfOverflowList();  // ensure the last frame is in mFrames
191   const nsFrameList::Slice& newCells =
192       mFrames.AppendFrames(nullptr, aFrameList);
193 
194   // Add the new cell frames to the table
195   nsTableFrame* tableFrame = GetTableFrame();
196   for (nsFrameList::Enumerator e(newCells); !e.AtEnd(); e.Next()) {
197     nsIFrame* childFrame = e.get();
198     NS_ASSERTION(childFrame->IsTableCellFrame(),
199                  "Not a table cell frame/pseudo frame construction failure");
200     tableFrame->AppendCell(static_cast<nsTableCellFrame&>(*childFrame),
201                            GetRowIndex());
202   }
203 
204   PresShell()->FrameNeedsReflow(this, IntrinsicDirty::TreeChange,
205                                 NS_FRAME_HAS_DIRTY_CHILDREN);
206   tableFrame->SetGeometryDirty();
207 }
208 
InsertFrames(ChildListID aListID,nsIFrame * aPrevFrame,const nsLineList::iterator * aPrevFrameLine,nsFrameList & aFrameList)209 void nsTableRowFrame::InsertFrames(ChildListID aListID, nsIFrame* aPrevFrame,
210                                    const nsLineList::iterator* aPrevFrameLine,
211                                    nsFrameList& aFrameList) {
212   NS_ASSERTION(aListID == kPrincipalList, "unexpected child list");
213   NS_ASSERTION(!aPrevFrame || aPrevFrame->GetParent() == this,
214                "inserting after sibling frame with different parent");
215   if (mFrames.IsEmpty() || (aPrevFrame && !aPrevFrame->GetNextSibling())) {
216     // This is actually an append (though our caller didn't figure that out),
217     // and our append codepath is both simpler/faster _and_ less buggy.
218     // https://bugzilla.mozilla.org/show_bug.cgi?id=1388898 tracks the bugginess
219     AppendFrames(aListID, aFrameList);
220     return;
221   }
222 
223   DrainSelfOverflowList();  // ensure aPrevFrame is in mFrames
224   // Insert Frames in the frame list
225   const nsFrameList::Slice& newCells =
226       mFrames.InsertFrames(nullptr, aPrevFrame, aFrameList);
227 
228   nsTableCellFrame* prevCellFrame =
229       static_cast<nsTableCellFrame*>(nsTableFrame::GetFrameAtOrBefore(
230           this, aPrevFrame, LayoutFrameType::TableCell));
231   nsTArray<nsTableCellFrame*> cellChildren;
232   for (nsFrameList::Enumerator e(newCells); !e.AtEnd(); e.Next()) {
233     nsIFrame* childFrame = e.get();
234     NS_ASSERTION(childFrame->IsTableCellFrame(),
235                  "Not a table cell frame/pseudo frame construction failure");
236     cellChildren.AppendElement(static_cast<nsTableCellFrame*>(childFrame));
237   }
238   // insert the cells into the cell map
239   int32_t colIndex = -1;
240   if (prevCellFrame) {
241     colIndex = prevCellFrame->ColIndex();
242   }
243   nsTableFrame* tableFrame = GetTableFrame();
244   tableFrame->InsertCells(cellChildren, GetRowIndex(), colIndex);
245 
246   PresShell()->FrameNeedsReflow(this, IntrinsicDirty::TreeChange,
247                                 NS_FRAME_HAS_DIRTY_CHILDREN);
248   tableFrame->SetGeometryDirty();
249 }
250 
RemoveFrame(ChildListID aListID,nsIFrame * aOldFrame)251 void nsTableRowFrame::RemoveFrame(ChildListID aListID, nsIFrame* aOldFrame) {
252   NS_ASSERTION(aListID == kPrincipalList, "unexpected child list");
253 
254   MOZ_ASSERT((nsTableCellFrame*)do_QueryFrame(aOldFrame));
255   nsTableCellFrame* cellFrame = static_cast<nsTableCellFrame*>(aOldFrame);
256   // remove the cell from the cell map
257   nsTableFrame* tableFrame = GetTableFrame();
258   tableFrame->RemoveCell(cellFrame, GetRowIndex());
259 
260   // Remove the frame and destroy it
261   mFrames.DestroyFrame(aOldFrame);
262 
263   PresShell()->FrameNeedsReflow(this, IntrinsicDirty::TreeChange,
264                                 NS_FRAME_HAS_DIRTY_CHILDREN);
265 
266   tableFrame->SetGeometryDirty();
267 }
268 
269 /* virtual */
GetUsedMargin() const270 nsMargin nsTableRowFrame::GetUsedMargin() const { return nsMargin(0, 0, 0, 0); }
271 
272 /* virtual */
GetUsedBorder() const273 nsMargin nsTableRowFrame::GetUsedBorder() const { return nsMargin(0, 0, 0, 0); }
274 
275 /* virtual */
GetUsedPadding() const276 nsMargin nsTableRowFrame::GetUsedPadding() const {
277   return nsMargin(0, 0, 0, 0);
278 }
279 
GetBSizeOfRowsSpannedBelowFirst(nsTableCellFrame & aTableCellFrame,nsTableFrame & aTableFrame,const WritingMode aWM)280 static nscoord GetBSizeOfRowsSpannedBelowFirst(
281     nsTableCellFrame& aTableCellFrame, nsTableFrame& aTableFrame,
282     const WritingMode aWM) {
283   nscoord bsize = 0;
284   int32_t rowSpan = aTableFrame.GetEffectiveRowSpan(aTableCellFrame);
285   // add in bsize of rows spanned beyond the 1st one
286   nsIFrame* nextRow = aTableCellFrame.GetParent()->GetNextSibling();
287   for (int32_t rowX = 1; ((rowX < rowSpan) && nextRow);) {
288     if (nextRow->IsTableRowFrame()) {
289       bsize += nextRow->BSize(aWM);
290       rowX++;
291     }
292     bsize += aTableFrame.GetRowSpacing(rowX);
293     nextRow = nextRow->GetNextSibling();
294   }
295   return bsize;
296 }
297 
298 /**
299  * Post-reflow hook. This is where the table row does its post-processing
300  */
DidResize()301 void nsTableRowFrame::DidResize() {
302   // Resize and re-align the cell frames based on our row bsize
303   nsTableFrame* tableFrame = GetTableFrame();
304 
305   WritingMode wm = GetWritingMode();
306   ReflowOutput desiredSize(wm);
307   desiredSize.SetSize(wm, GetLogicalSize(wm));
308   desiredSize.SetOverflowAreasToDesiredBounds();
309 
310   nsSize containerSize = mRect.Size();
311 
312   for (nsIFrame* childFrame : mFrames) {
313     nsTableCellFrame* cellFrame = do_QueryFrame(childFrame);
314     if (cellFrame) {
315       nscoord cellBSize = BSize(wm) + GetBSizeOfRowsSpannedBelowFirst(
316                                           *cellFrame, *tableFrame, wm);
317 
318       // If the bsize for the cell has changed, we need to reset it;
319       // and in vertical-rl mode, we need to update the cell's block position
320       // to account for the containerSize, which may not have been known
321       // earlier, so we always apply it here.
322       LogicalSize cellSize = cellFrame->GetLogicalSize(wm);
323       if (cellSize.BSize(wm) != cellBSize || wm.IsVerticalRL()) {
324         nsRect cellOldRect = cellFrame->GetRect();
325         nsRect cellVisualOverflow = cellFrame->GetVisualOverflowRect();
326 
327         if (wm.IsVerticalRL()) {
328           // Get the old position of the cell, as we want to preserve its
329           // inline coordinate.
330           LogicalPoint oldPos =
331               cellFrame->GetLogicalPosition(wm, containerSize);
332 
333           // The cell should normally be aligned with the row's block-start,
334           // so set the B component of the position to zero:
335           LogicalPoint newPos(wm, oldPos.I(wm), 0);
336 
337           // ...unless relative positioning is in effect, in which case the
338           // cell may have been moved away from the row's block-start
339           if (cellFrame->IsRelativelyPositioned()) {
340             // Find out where the cell would have been without relative
341             // positioning.
342             LogicalPoint oldNormalPos =
343                 cellFrame->GetLogicalNormalPosition(wm, containerSize);
344             // The difference (if any) between oldPos and oldNormalPos reflects
345             // relative positioning that was applied to the cell, and which we
346             // need to incorporate when resetting the position.
347             newPos.B(wm) = oldPos.B(wm) - oldNormalPos.B(wm);
348           }
349 
350           if (oldPos != newPos) {
351             cellFrame->SetPosition(wm, newPos, containerSize);
352             nsTableFrame::RePositionViews(cellFrame);
353           }
354         }
355 
356         cellSize.BSize(wm) = cellBSize;
357         cellFrame->SetSize(wm, cellSize);
358 
359         nsTableFrame* tableFrame = GetTableFrame();
360         if (tableFrame->IsBorderCollapse()) {
361           nsTableFrame::InvalidateTableFrame(cellFrame, cellOldRect,
362                                              cellVisualOverflow, false);
363         }
364       }
365 
366       // realign cell content based on the new bsize.  We might be able to
367       // skip this if the bsize didn't change... maybe.  Hard to tell.
368       cellFrame->BlockDirAlignChild(wm, mMaxCellAscent);
369 
370       // Always store the overflow, even if the height didn't change, since
371       // we'll lose part of our overflow area otherwise.
372       ConsiderChildOverflow(desiredSize.mOverflowAreas, cellFrame);
373 
374       // Note that if the cell's *content* needs to change in response
375       // to this height, it will get a special bsize reflow.
376     }
377   }
378   FinishAndStoreOverflow(&desiredSize);
379   if (HasView()) {
380     nsContainerFrame::SyncFrameViewAfterReflow(PresContext(), this, GetView(),
381                                                desiredSize.VisualOverflow(),
382                                                ReflowChildFlags::Default);
383   }
384   // Let our base class do the usual work
385 }
386 
387 // returns max-ascent amongst all cells that have 'vertical-align: baseline'
388 // *including* cells with rowspans
GetMaxCellAscent() const389 nscoord nsTableRowFrame::GetMaxCellAscent() const { return mMaxCellAscent; }
390 
GetRowBaseline(WritingMode aWM)391 nscoord nsTableRowFrame::GetRowBaseline(WritingMode aWM) {
392   if (mMaxCellAscent) {
393     return mMaxCellAscent;
394   }
395 
396   // If we get here, we don't have a baseline on any of the cells in this row.
397 
398   nscoord ascent = 0;
399   for (nsIFrame* childFrame : mFrames) {
400     MOZ_ASSERT(childFrame->IsTableCellFrame());
401     nscoord s = childFrame->SynthesizeBaselineBOffsetFromContentBox(
402         aWM, BaselineSharingGroup::First);
403     ascent = std::max(ascent, s);
404   }
405   return ascent;
406 }
407 
GetInitialBSize(nscoord aPctBasis) const408 nscoord nsTableRowFrame::GetInitialBSize(nscoord aPctBasis) const {
409   nscoord bsize = 0;
410   if ((aPctBasis > 0) && HasPctBSize()) {
411     bsize = NSToCoordRound(GetPctBSize() * (float)aPctBasis);
412   }
413   if (HasFixedBSize()) {
414     bsize = std::max(bsize, GetFixedBSize());
415   }
416   return std::max(bsize, GetContentBSize());
417 }
418 
ResetBSize(nscoord aFixedBSize)419 void nsTableRowFrame::ResetBSize(nscoord aFixedBSize) {
420   SetHasFixedBSize(false);
421   SetHasPctBSize(false);
422   SetFixedBSize(0);
423   SetPctBSize(0);
424   SetContentBSize(0);
425 
426   if (aFixedBSize > 0) {
427     SetFixedBSize(aFixedBSize);
428   }
429 
430   mMaxCellAscent = 0;
431   mMaxCellDescent = 0;
432 }
433 
UpdateBSize(nscoord aBSize,nscoord aAscent,nscoord aDescent,nsTableFrame * aTableFrame,nsTableCellFrame * aCellFrame)434 void nsTableRowFrame::UpdateBSize(nscoord aBSize, nscoord aAscent,
435                                   nscoord aDescent, nsTableFrame* aTableFrame,
436                                   nsTableCellFrame* aCellFrame) {
437   if (!aTableFrame || !aCellFrame) {
438     NS_ASSERTION(false, "invalid call");
439     return;
440   }
441 
442   if (aBSize != NS_UNCONSTRAINEDSIZE) {
443     if (!(aCellFrame->HasVerticalAlignBaseline())) {  // only the cell's height
444                                                       // matters
445       if (GetInitialBSize() < aBSize) {
446         int32_t rowSpan = aTableFrame->GetEffectiveRowSpan(*aCellFrame);
447         if (rowSpan == 1) {
448           SetContentBSize(aBSize);
449         }
450       }
451     } else {  // the alignment on the baseline can change the bsize
452       NS_ASSERTION((aAscent != NS_UNCONSTRAINEDSIZE) &&
453                        (aDescent != NS_UNCONSTRAINEDSIZE),
454                    "invalid call");
455       // see if this is a long ascender
456       if (mMaxCellAscent < aAscent) {
457         mMaxCellAscent = aAscent;
458       }
459       // see if this is a long descender and without rowspan
460       if (mMaxCellDescent < aDescent) {
461         int32_t rowSpan = aTableFrame->GetEffectiveRowSpan(*aCellFrame);
462         if (rowSpan == 1) {
463           mMaxCellDescent = aDescent;
464         }
465       }
466       // keep the tallest bsize in sync
467       if (GetInitialBSize() < mMaxCellAscent + mMaxCellDescent) {
468         SetContentBSize(mMaxCellAscent + mMaxCellDescent);
469       }
470     }
471   }
472 }
473 
CalcBSize(const ReflowInput & aReflowInput)474 nscoord nsTableRowFrame::CalcBSize(const ReflowInput& aReflowInput) {
475   nsTableFrame* tableFrame = GetTableFrame();
476   nscoord computedBSize = (NS_UNCONSTRAINEDSIZE == aReflowInput.ComputedBSize())
477                               ? 0
478                               : aReflowInput.ComputedBSize();
479   ResetBSize(computedBSize);
480 
481   WritingMode wm = aReflowInput.GetWritingMode();
482   const nsStylePosition* position = StylePosition();
483   const auto& bsizeStyleCoord = position->BSize(wm);
484   if (bsizeStyleCoord.ConvertsToLength()) {
485     SetFixedBSize(bsizeStyleCoord.ToLength());
486   } else if (bsizeStyleCoord.ConvertsToPercentage()) {
487     SetPctBSize(bsizeStyleCoord.ToPercentage());
488   }
489 
490   for (nsIFrame* kidFrame : mFrames) {
491     nsTableCellFrame* cellFrame = do_QueryFrame(kidFrame);
492     if (cellFrame) {
493       MOZ_ASSERT(cellFrame->GetWritingMode() == wm);
494       LogicalSize desSize = cellFrame->GetDesiredSize();
495       if ((NS_UNCONSTRAINEDSIZE == aReflowInput.AvailableBSize()) &&
496           !GetPrevInFlow()) {
497         CalculateCellActualBSize(cellFrame, desSize.BSize(wm), wm);
498       }
499       // bsize may have changed, adjust descent to absorb any excess difference
500       nscoord ascent;
501       if (!kidFrame->PrincipalChildList()
502                .FirstChild()
503                ->PrincipalChildList()
504                .FirstChild())
505         ascent = desSize.BSize(wm);
506       else
507         ascent = cellFrame->GetCellBaseline();
508       nscoord descent = desSize.BSize(wm) - ascent;
509       UpdateBSize(desSize.BSize(wm), ascent, descent, tableFrame, cellFrame);
510     }
511   }
512   return GetInitialBSize();
513 }
514 
PaintCellBackgroundsForFrame(nsIFrame * aFrame,nsDisplayListBuilder * aBuilder,const nsDisplayListSet & aLists,const nsPoint & aOffset)515 void nsTableRowFrame::PaintCellBackgroundsForFrame(
516     nsIFrame* aFrame, nsDisplayListBuilder* aBuilder,
517     const nsDisplayListSet& aLists, const nsPoint& aOffset) {
518   // Compute background rect by iterating all cell frame.
519   const nsPoint toReferenceFrame = aBuilder->ToReferenceFrame(aFrame);
520   for (nsTableCellFrame* cell = GetFirstCell(); cell;
521        cell = cell->GetNextCell()) {
522     if (!cell->ShouldPaintBackground(aBuilder)) {
523       continue;
524     }
525 
526     auto cellRect =
527         cell->GetRectRelativeToSelf() + cell->GetNormalPosition() + aOffset;
528     if (!aBuilder->GetDirtyRect().Intersects(cellRect)) {
529       continue;
530     }
531     cellRect += toReferenceFrame;
532     nsDisplayBackgroundImage::AppendBackgroundItemsToTop(
533         aBuilder, aFrame, cellRect, aLists.BorderBackground(), true, nullptr,
534         aFrame->GetRectRelativeToSelf() + toReferenceFrame, cell);
535   }
536 }
537 
BuildDisplayList(nsDisplayListBuilder * aBuilder,const nsDisplayListSet & aLists)538 void nsTableRowFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
539                                        const nsDisplayListSet& aLists) {
540   DisplayOutsetBoxShadow(aBuilder, aLists.BorderBackground());
541 
542   PaintCellBackgroundsForFrame(this, aBuilder, aLists);
543 
544   DisplayInsetBoxShadow(aBuilder, aLists.BorderBackground());
545 
546   DisplayOutline(aBuilder, aLists);
547 
548   for (nsIFrame* kid : PrincipalChildList()) {
549     BuildDisplayListForChild(aBuilder, kid, aLists);
550   }
551 }
552 
GetLogicalSkipSides(const ReflowInput * aReflowInput) const553 nsIFrame::LogicalSides nsTableRowFrame::GetLogicalSkipSides(
554     const ReflowInput* aReflowInput) const {
555   LogicalSides skip(mWritingMode);
556   if (MOZ_UNLIKELY(StyleBorder()->mBoxDecorationBreak ==
557                    StyleBoxDecorationBreak::Clone)) {
558     return skip;
559   }
560 
561   if (nullptr != GetPrevInFlow()) {
562     skip |= eLogicalSideBitsBStart;
563   }
564   if (nullptr != GetNextInFlow()) {
565     skip |= eLogicalSideBitsBEnd;
566   }
567   return skip;
568 }
569 
570 // Calculate the cell's actual bsize given its pass2 bsize.
571 // Takes into account the specified bsize (in the style).
572 // Modifies the desired bsize that is passed in.
CalculateCellActualBSize(nsTableCellFrame * aCellFrame,nscoord & aDesiredBSize,WritingMode aWM)573 nsresult nsTableRowFrame::CalculateCellActualBSize(nsTableCellFrame* aCellFrame,
574                                                    nscoord& aDesiredBSize,
575                                                    WritingMode aWM) {
576   nscoord specifiedBSize = 0;
577 
578   // Get the bsize specified in the style information
579   const nsStylePosition* position = aCellFrame->StylePosition();
580 
581   int32_t rowSpan = GetTableFrame()->GetEffectiveRowSpan(*aCellFrame);
582 
583   const auto& bsizeStyleCoord = position->BSize(aWM);
584   if (bsizeStyleCoord.ConvertsToLength()) {
585     // In quirks mode, table cell isize should be content-box, but bsize
586     // should be border-box.
587     // Because of this historic anomaly, we do not use quirk.css
588     // (since we can't specify one value of box-sizing for isize and another
589     // for bsize)
590     specifiedBSize = bsizeStyleCoord.ToLength();
591     if (PresContext()->CompatibilityMode() != eCompatibility_NavQuirks &&
592         position->mBoxSizing == StyleBoxSizing::Content) {
593       specifiedBSize +=
594           aCellFrame->GetLogicalUsedBorderAndPadding(aWM).BStartEnd(aWM);
595     }
596 
597     if (1 == rowSpan) {
598       SetFixedBSize(specifiedBSize);
599     }
600   } else if (bsizeStyleCoord.ConvertsToPercentage()) {
601     if (1 == rowSpan) {
602       SetPctBSize(bsizeStyleCoord.ToPercentage());
603     }
604   }
605 
606   // If the specified bsize is greater than the desired bsize,
607   // then use the specified bsize
608   if (specifiedBSize > aDesiredBSize) {
609     aDesiredBSize = specifiedBSize;
610   }
611 
612   return NS_OK;
613 }
614 
615 // Calculates the available isize for the table cell based on the known
616 // column isizes taking into account column spans and column spacing
CalcAvailISize(nsTableFrame & aTableFrame,nsTableCellFrame & aCellFrame)617 static nscoord CalcAvailISize(nsTableFrame& aTableFrame,
618                               nsTableCellFrame& aCellFrame) {
619   nscoord cellAvailISize = 0;
620   uint32_t colIndex = aCellFrame.ColIndex();
621   int32_t colspan = aTableFrame.GetEffectiveColSpan(aCellFrame);
622   NS_ASSERTION(colspan > 0, "effective colspan should be positive");
623   nsTableFrame* fifTable =
624       static_cast<nsTableFrame*>(aTableFrame.FirstInFlow());
625 
626   for (int32_t spanX = 0; spanX < colspan; spanX++) {
627     cellAvailISize += fifTable->GetColumnISizeFromFirstInFlow(colIndex + spanX);
628     if (spanX > 0 && aTableFrame.ColumnHasCellSpacingBefore(colIndex + spanX)) {
629       cellAvailISize += aTableFrame.GetColSpacing(colIndex + spanX - 1);
630     }
631   }
632   return cellAvailISize;
633 }
634 
GetSpaceBetween(int32_t aPrevColIndex,int32_t aColIndex,int32_t aColSpan,nsTableFrame & aTableFrame,bool aCheckVisibility)635 static nscoord GetSpaceBetween(int32_t aPrevColIndex, int32_t aColIndex,
636                                int32_t aColSpan, nsTableFrame& aTableFrame,
637                                bool aCheckVisibility) {
638   nscoord space = 0;
639   int32_t colIdx;
640   nsTableFrame* fifTable =
641       static_cast<nsTableFrame*>(aTableFrame.FirstInFlow());
642   for (colIdx = aPrevColIndex + 1; aColIndex > colIdx; colIdx++) {
643     bool isCollapsed = false;
644     if (!aCheckVisibility) {
645       space += fifTable->GetColumnISizeFromFirstInFlow(colIdx);
646     } else {
647       nsTableColFrame* colFrame = aTableFrame.GetColFrame(colIdx);
648       const nsStyleVisibility* colVis = colFrame->StyleVisibility();
649       bool collapseCol = StyleVisibility::Collapse == colVis->mVisible;
650       nsIFrame* cgFrame = colFrame->GetParent();
651       const nsStyleVisibility* groupVis = cgFrame->StyleVisibility();
652       bool collapseGroup = StyleVisibility::Collapse == groupVis->mVisible;
653       isCollapsed = collapseCol || collapseGroup;
654       if (!isCollapsed)
655         space += fifTable->GetColumnISizeFromFirstInFlow(colIdx);
656     }
657     if (!isCollapsed && aTableFrame.ColumnHasCellSpacingBefore(colIdx)) {
658       space += aTableFrame.GetColSpacing(colIdx - 1);
659     }
660   }
661   return space;
662 }
663 
664 // subtract the bsizes of aRow's prev in flows from the unpaginated bsize
CalcBSizeFromUnpaginatedBSize(nsTableRowFrame & aRow,WritingMode aWM)665 static nscoord CalcBSizeFromUnpaginatedBSize(nsTableRowFrame& aRow,
666                                              WritingMode aWM) {
667   nscoord bsize = 0;
668   nsTableRowFrame* firstInFlow =
669       static_cast<nsTableRowFrame*>(aRow.FirstInFlow());
670   if (firstInFlow->HasUnpaginatedBSize()) {
671     bsize = firstInFlow->GetUnpaginatedBSize();
672     for (nsIFrame* prevInFlow = aRow.GetPrevInFlow(); prevInFlow;
673          prevInFlow = prevInFlow->GetPrevInFlow()) {
674       bsize -= prevInFlow->BSize(aWM);
675     }
676   }
677   return std::max(bsize, 0);
678 }
679 
ReflowChildren(nsPresContext * aPresContext,ReflowOutput & aDesiredSize,const ReflowInput & aReflowInput,nsTableFrame & aTableFrame,nsReflowStatus & aStatus)680 void nsTableRowFrame::ReflowChildren(nsPresContext* aPresContext,
681                                      ReflowOutput& aDesiredSize,
682                                      const ReflowInput& aReflowInput,
683                                      nsTableFrame& aTableFrame,
684                                      nsReflowStatus& aStatus) {
685   aStatus.Reset();
686 
687   // XXXldb Should we be checking constrained bsize instead?
688   const bool isPaginated = aPresContext->IsPaginated();
689   const bool borderCollapse = aTableFrame.IsBorderCollapse();
690 
691   int32_t cellColSpan =
692       1;  // must be defined here so it's set properly for non-cell kids
693 
694   // remember the col index of the previous cell to handle rowspans into this
695   // row
696   int32_t prevColIndex = -1;
697   nscoord iCoord = 0;  // running total of children inline-coord offset
698 
699   // This computes the max of all cell bsizes
700   nscoord cellMaxBSize = 0;
701 
702   // Reflow each of our existing cell frames
703   WritingMode wm = aReflowInput.GetWritingMode();
704   nsSize containerSize = aReflowInput.ComputedSizeAsContainerIfConstrained();
705 
706   for (nsIFrame* kidFrame : mFrames) {
707     nsTableCellFrame* cellFrame = do_QueryFrame(kidFrame);
708     if (!cellFrame) {
709       // XXXldb nsCSSFrameConstructor needs to enforce this!
710       MOZ_ASSERT_UNREACHABLE("yikes, a non-row child");
711 
712       // it's an unknown frame type, give it a generic reflow and ignore the
713       // results
714       TableCellReflowInput kidReflowInput(
715           aPresContext, aReflowInput, kidFrame,
716           LogicalSize(kidFrame->GetWritingMode(), 0, 0),
717           ReflowInput::CALLER_WILL_INIT);
718       InitChildReflowInput(*aPresContext, LogicalSize(wm), false,
719                            kidReflowInput);
720       ReflowOutput desiredSize(aReflowInput);
721       nsReflowStatus status;
722       ReflowChild(kidFrame, aPresContext, desiredSize, kidReflowInput, 0, 0,
723                   ReflowChildFlags::Default, status);
724       kidFrame->DidReflow(aPresContext, nullptr);
725 
726       continue;
727     }
728 
729     // See if we should only reflow the dirty child frames
730     bool doReflowChild = true;
731     if (!aReflowInput.ShouldReflowAllKids() && !aTableFrame.IsGeometryDirty() &&
732         !NS_SUBTREE_DIRTY(kidFrame)) {
733       if (!aReflowInput.mFlags.mSpecialBSizeReflow) doReflowChild = false;
734     } else if ((NS_UNCONSTRAINEDSIZE != aReflowInput.AvailableBSize())) {
735       // We don't reflow a rowspan >1 cell here with a constrained bsize.
736       // That happens in nsTableRowGroupFrame::SplitSpanningCells.
737       if (aTableFrame.GetEffectiveRowSpan(*cellFrame) > 1) {
738         doReflowChild = false;
739       }
740     }
741     if (aReflowInput.mFlags.mSpecialBSizeReflow) {
742       if (!isPaginated &&
743           !cellFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE)) {
744         continue;
745       }
746     }
747 
748     uint32_t cellColIndex = cellFrame->ColIndex();
749     cellColSpan = aTableFrame.GetEffectiveColSpan(*cellFrame);
750 
751     // If the adjacent cell is in a prior row (because of a rowspan) add in the
752     // space NOTE: prevColIndex can be -1 here.
753     if (prevColIndex != (static_cast<int32_t>(cellColIndex) - 1)) {
754       iCoord += GetSpaceBetween(prevColIndex, cellColIndex, cellColSpan,
755                                 aTableFrame, false);
756     }
757 
758     // remember the rightmost (ltr) or leftmost (rtl) column this cell spans
759     // into
760     prevColIndex = cellColIndex + (cellColSpan - 1);
761 
762     // Reflow the child frame
763     nsRect kidRect = kidFrame->GetRect();
764     LogicalPoint origKidNormalPosition =
765         kidFrame->GetLogicalNormalPosition(wm, containerSize);
766     // All cells' no-relative-positioning position should be snapped to the
767     // row's bstart edge.
768     // This doesn't hold in vertical-rl mode, where we don't yet know the
769     // correct containerSize for the row frame. In that case, we'll have to
770     // fix up child positions later, after determining our desiredSize.
771     NS_ASSERTION(origKidNormalPosition.B(wm) == 0 || wm.IsVerticalRL(),
772                  "unexpected kid position");
773 
774     nsRect kidVisualOverflow = kidFrame->GetVisualOverflowRect();
775     LogicalPoint kidPosition(wm, iCoord, 0);
776     bool firstReflow = kidFrame->HasAnyStateBits(NS_FRAME_FIRST_REFLOW);
777 
778     if (doReflowChild) {
779       // Calculate the available isize for the table cell using the known
780       // column isizes
781       nscoord availCellISize = CalcAvailISize(aTableFrame, *cellFrame);
782 
783       Maybe<TableCellReflowInput> kidReflowInput;
784       ReflowOutput desiredSize(aReflowInput);
785 
786       // If the avail isize is not the same as last time we reflowed the cell or
787       // the cell wants to be bigger than what was available last time or
788       // it is a style change reflow or we are printing, then we must reflow the
789       // cell. Otherwise we can skip the reflow.
790       // XXXldb Why is this condition distinct from doReflowChild above?
791       WritingMode wm = aReflowInput.GetWritingMode();
792       NS_ASSERTION(cellFrame->GetWritingMode() == wm,
793                    "expected consistent writing-mode within table");
794       LogicalSize cellDesiredSize = cellFrame->GetDesiredSize();
795       if ((availCellISize != cellFrame->GetPriorAvailISize()) ||
796           (cellDesiredSize.ISize(wm) > cellFrame->GetPriorAvailISize()) ||
797           HasAnyStateBits(NS_FRAME_IS_DIRTY) || isPaginated ||
798           NS_SUBTREE_DIRTY(cellFrame) ||
799           // See if it needs a special reflow, or if it had one that we need to
800           // undo.
801           cellFrame->HasAnyStateBits(NS_FRAME_CONTAINS_RELATIVE_BSIZE) ||
802           HasPctBSize()) {
803         // Reflow the cell to fit the available isize, bsize
804         // XXX The old IR_ChildIsDirty code used availCellISize here.
805         LogicalSize kidAvailSize(wm, availCellISize,
806                                  aReflowInput.AvailableBSize());
807 
808         // Reflow the child
809         kidReflowInput.emplace(aPresContext, aReflowInput, kidFrame,
810                                kidAvailSize, ReflowInput::CALLER_WILL_INIT);
811         InitChildReflowInput(*aPresContext, kidAvailSize, borderCollapse,
812                              *kidReflowInput);
813 
814         nsReflowStatus status;
815         ReflowChild(kidFrame, aPresContext, desiredSize, *kidReflowInput, wm,
816                     kidPosition, containerSize, ReflowChildFlags::Default,
817                     status);
818 
819         // allow the table to determine if/how the table needs to be rebalanced
820         // If any of the cells are not complete, then we're not complete
821         if (status.IsIncomplete()) {
822           aStatus.Reset();
823           aStatus.SetIncomplete();
824         }
825       } else {
826         if (iCoord != origKidNormalPosition.I(wm)) {
827           kidFrame->InvalidateFrameSubtree();
828         }
829 
830         desiredSize.SetSize(wm, cellDesiredSize);
831         desiredSize.mOverflowAreas = cellFrame->GetOverflowAreas();
832 
833         // if we are in a floated table, our position is not yet established, so
834         // we cannot reposition our views the containing block will do this for
835         // us after positioning the table
836         if (!aTableFrame.IsFloating()) {
837           // Because we may have moved the frame we need to make sure any views
838           // are positioned properly. We have to do this, because any one of our
839           // parent frames could have moved and we have no way of knowing...
840           nsTableFrame::RePositionViews(kidFrame);
841         }
842       }
843 
844       if (NS_UNCONSTRAINEDSIZE == aReflowInput.AvailableBSize()) {
845         if (!GetPrevInFlow()) {
846           // Calculate the cell's actual bsize given its pass2 bsize. This
847           // function takes into account the specified bsize (in the style)
848           CalculateCellActualBSize(cellFrame, desiredSize.BSize(wm), wm);
849         }
850         // bsize may have changed, adjust descent to absorb any excess
851         // difference
852         nscoord ascent;
853         if (!kidFrame->PrincipalChildList()
854                  .FirstChild()
855                  ->PrincipalChildList()
856                  .FirstChild()) {
857           ascent = desiredSize.BSize(wm);
858         } else {
859           ascent = ((nsTableCellFrame*)kidFrame)->GetCellBaseline();
860         }
861         nscoord descent = desiredSize.BSize(wm) - ascent;
862         UpdateBSize(desiredSize.BSize(wm), ascent, descent, &aTableFrame,
863                     cellFrame);
864       } else {
865         cellMaxBSize = std::max(cellMaxBSize, desiredSize.BSize(wm));
866         int32_t rowSpan =
867             aTableFrame.GetEffectiveRowSpan((nsTableCellFrame&)*kidFrame);
868         if (1 == rowSpan) {
869           SetContentBSize(cellMaxBSize);
870         }
871       }
872 
873       // Place the child
874       desiredSize.ISize(wm) = availCellISize;
875 
876       ReflowChildFlags flags = ReflowChildFlags::Default;
877 
878       if (kidReflowInput) {
879         // We reflowed. Apply relative positioning in the normal way.
880         flags = ReflowChildFlags::ApplyRelativePositioning;
881       } else if (kidFrame->IsRelativelyPositioned()) {
882         // We didn't reflow.  Do the positioning part of what
883         // MovePositionBy does internally.  (This codepath should really
884         // be merged into the else below if we can.)
885         nsMargin* computedOffsetProp =
886             kidFrame->GetProperty(nsIFrame::ComputedOffsetProperty());
887 
888         // On our fist reflow sticky children may not have the property yet (we
889         // need to reflow the children first to size the scroll frame).
890         LogicalMargin computedOffsets(
891             wm, computedOffsetProp ? *computedOffsetProp : nsMargin());
892         ReflowInput::ApplyRelativePositioning(kidFrame, wm, computedOffsets,
893                                               &kidPosition, containerSize);
894       }
895 
896       // In vertical-rl mode, we are likely to have containerSize.width = 0
897       // because ComputedWidth() was NS_UNCONSTRAINEDSIZE.
898       // For cases where that's wrong, we will fix up the position later.
899       FinishReflowChild(kidFrame, aPresContext, desiredSize,
900                         kidReflowInput.ptrOr(nullptr), wm, kidPosition,
901                         containerSize, flags);
902 
903       nsTableFrame* tableFrame = GetTableFrame();
904       if (tableFrame->IsBorderCollapse()) {
905         nsTableFrame::InvalidateTableFrame(kidFrame, kidRect, kidVisualOverflow,
906                                            firstReflow);
907       }
908 
909       iCoord += desiredSize.ISize(wm);
910     } else {
911       if (iCoord != origKidNormalPosition.I(wm)) {
912         // Invalidate the old position
913         kidFrame->InvalidateFrameSubtree();
914         // Move to the new position. As above, we need to account for relative
915         // positioning.
916         kidFrame->MovePositionBy(
917             wm, LogicalPoint(wm, iCoord - origKidNormalPosition.I(wm), 0));
918         nsTableFrame::RePositionViews(kidFrame);
919         // invalidate the new position
920         kidFrame->InvalidateFrameSubtree();
921       }
922       // we need to account for the cell's isize even if it isn't reflowed
923       iCoord += kidFrame->ISize(wm);
924 
925       if (kidFrame->GetNextInFlow()) {
926         aStatus.Reset();
927         aStatus.SetIncomplete();
928       }
929     }
930     ConsiderChildOverflow(aDesiredSize.mOverflowAreas, kidFrame);
931     iCoord += aTableFrame.GetColSpacing(cellColIndex);
932   }
933 
934   // Just set our isize to what was available.
935   // The table will calculate the isize and not use our value.
936   aDesiredSize.ISize(wm) = aReflowInput.AvailableISize();
937 
938   if (aReflowInput.mFlags.mSpecialBSizeReflow) {
939     aDesiredSize.BSize(wm) = BSize(wm);
940   } else if (NS_UNCONSTRAINEDSIZE == aReflowInput.AvailableBSize()) {
941     aDesiredSize.BSize(wm) = CalcBSize(aReflowInput);
942     if (GetPrevInFlow()) {
943       nscoord bsize = CalcBSizeFromUnpaginatedBSize(*this, wm);
944       aDesiredSize.BSize(wm) = std::max(aDesiredSize.BSize(wm), bsize);
945     } else {
946       if (isPaginated && HasStyleBSize()) {
947         // set the unpaginated bsize so next in flows can try to honor it
948         SetHasUnpaginatedBSize(true);
949         SetUnpaginatedBSize(aPresContext, aDesiredSize.BSize(wm));
950       }
951       if (isPaginated && HasUnpaginatedBSize()) {
952         aDesiredSize.BSize(wm) =
953             std::max(aDesiredSize.BSize(wm), GetUnpaginatedBSize());
954       }
955     }
956   } else {  // constrained bsize, paginated
957     // Compute the bsize we should have from style (subtracting the
958     // bsize from our prev-in-flows from the style bsize)
959     nscoord styleBSize = CalcBSizeFromUnpaginatedBSize(*this, wm);
960     if (styleBSize > aReflowInput.AvailableBSize()) {
961       styleBSize = aReflowInput.AvailableBSize();
962       aStatus.SetIncomplete();
963     }
964     aDesiredSize.BSize(wm) = std::max(cellMaxBSize, styleBSize);
965   }
966 
967   if (wm.IsVerticalRL()) {
968     // Any children whose width was not the same as our final
969     // aDesiredSize.BSize will have been misplaced earlier at the
970     // FinishReflowChild stage. So fix them up now.
971     for (nsIFrame* kidFrame : mFrames) {
972       nsTableCellFrame* cellFrame = do_QueryFrame(kidFrame);
973       if (!cellFrame) {
974         continue;
975       }
976       if (kidFrame->BSize(wm) != aDesiredSize.BSize(wm)) {
977         kidFrame->MovePositionBy(
978             wm,
979             LogicalPoint(wm, 0, kidFrame->BSize(wm) - aDesiredSize.BSize(wm)));
980         nsTableFrame::RePositionViews(kidFrame);
981         // Do we need to InvalidateFrameSubtree() here?
982       }
983     }
984   }
985 
986   aDesiredSize.UnionOverflowAreasWithDesiredBounds();
987   FinishAndStoreOverflow(&aDesiredSize);
988 }
989 
990 /** Layout the entire row.
991  * This method stacks cells in the inline dir according to HTML 4.0 rules.
992  */
Reflow(nsPresContext * aPresContext,ReflowOutput & aDesiredSize,const ReflowInput & aReflowInput,nsReflowStatus & aStatus)993 void nsTableRowFrame::Reflow(nsPresContext* aPresContext,
994                              ReflowOutput& aDesiredSize,
995                              const ReflowInput& aReflowInput,
996                              nsReflowStatus& aStatus) {
997   MarkInReflow();
998   DO_GLOBAL_REFLOW_COUNT("nsTableRowFrame");
999   DISPLAY_REFLOW(aPresContext, this, aReflowInput, aDesiredSize, aStatus);
1000   MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
1001 
1002   WritingMode wm = aReflowInput.GetWritingMode();
1003 
1004   nsTableFrame* tableFrame = GetTableFrame();
1005   const nsStyleVisibility* rowVis = StyleVisibility();
1006   bool collapseRow = StyleVisibility::Collapse == rowVis->mVisible;
1007   if (collapseRow) {
1008     tableFrame->SetNeedToCollapse(true);
1009   }
1010 
1011   // see if a special bsize reflow needs to occur due to having a pct bsize
1012   nsTableFrame::CheckRequestSpecialBSizeReflow(aReflowInput);
1013 
1014   // See if we have a cell with specified/pct bsize
1015   InitHasCellWithStyleBSize(tableFrame);
1016 
1017   ReflowChildren(aPresContext, aDesiredSize, aReflowInput, *tableFrame,
1018                  aStatus);
1019 
1020   if (aPresContext->IsPaginated() && !aStatus.IsFullyComplete() &&
1021       ShouldAvoidBreakInside(aReflowInput)) {
1022     aStatus.SetInlineLineBreakBeforeAndReset();
1023   }
1024 
1025   // Just set our isize to what was available.
1026   // The table will calculate the isize and not use our value.
1027   aDesiredSize.ISize(wm) = aReflowInput.AvailableISize();
1028 
1029   // If our parent is in initial reflow, it'll handle invalidating our
1030   // entire overflow rect.
1031   if (!GetParent()->HasAnyStateBits(NS_FRAME_FIRST_REFLOW) &&
1032       nsSize(aDesiredSize.Width(), aDesiredSize.Height()) != mRect.Size()) {
1033     InvalidateFrame();
1034   }
1035 
1036   // Any absolutely-positioned children will get reflowed in
1037   // nsFrame::FixupPositionedTableParts in another pass, so propagate our
1038   // dirtiness to them before our parent clears our dirty bits.
1039   PushDirtyBitToAbsoluteFrames();
1040 
1041   NS_FRAME_SET_TRUNCATION(aStatus, aReflowInput, aDesiredSize);
1042 }
1043 
1044 /**
1045  * This function is called by the row group frame's SplitRowGroup() code when
1046  * pushing a row frame that has cell frames that span into it. The cell frame
1047  * should be reflowed with the specified height
1048  */
ReflowCellFrame(nsPresContext * aPresContext,const ReflowInput & aReflowInput,bool aIsTopOfPage,nsTableCellFrame * aCellFrame,nscoord aAvailableBSize,nsReflowStatus & aStatus)1049 nscoord nsTableRowFrame::ReflowCellFrame(nsPresContext* aPresContext,
1050                                          const ReflowInput& aReflowInput,
1051                                          bool aIsTopOfPage,
1052                                          nsTableCellFrame* aCellFrame,
1053                                          nscoord aAvailableBSize,
1054                                          nsReflowStatus& aStatus) {
1055   WritingMode wm = aReflowInput.GetWritingMode();
1056 
1057   // Reflow the cell frame with the specified height. Use the existing width
1058   nsSize containerSize = aCellFrame->GetSize();
1059   LogicalRect cellRect = aCellFrame->GetLogicalRect(wm, containerSize);
1060   nsRect cellVisualOverflow = aCellFrame->GetVisualOverflowRect();
1061 
1062   LogicalSize cellSize = cellRect.Size(wm);
1063   LogicalSize availSize(wm, cellRect.ISize(wm), aAvailableBSize);
1064   bool borderCollapse = GetTableFrame()->IsBorderCollapse();
1065   NS_ASSERTION(aCellFrame->GetWritingMode() == wm,
1066                "expected consistent writing-mode within table");
1067   TableCellReflowInput cellReflowInput(aPresContext, aReflowInput, aCellFrame,
1068                                        availSize,
1069                                        ReflowInput::CALLER_WILL_INIT);
1070   InitChildReflowInput(*aPresContext, availSize, borderCollapse,
1071                        cellReflowInput);
1072   cellReflowInput.mFlags.mIsTopOfPage = aIsTopOfPage;
1073 
1074   ReflowOutput desiredSize(aReflowInput);
1075 
1076   ReflowChild(aCellFrame, aPresContext, desiredSize, cellReflowInput, 0, 0,
1077               ReflowChildFlags::NoMoveFrame, aStatus);
1078   bool fullyComplete = aStatus.IsComplete() && !aStatus.IsTruncated();
1079   if (fullyComplete) {
1080     desiredSize.BSize(wm) = aAvailableBSize;
1081   }
1082   aCellFrame->SetSize(
1083       wm, LogicalSize(wm, cellSize.ISize(wm), desiredSize.BSize(wm)));
1084 
1085   // Note: BlockDirAlignChild can affect the overflow rect.
1086   // XXX What happens if this cell has 'vertical-align: baseline' ?
1087   // XXX Why is it assumed that the cell's ascent hasn't changed ?
1088   if (fullyComplete) {
1089     aCellFrame->BlockDirAlignChild(wm, mMaxCellAscent);
1090   }
1091 
1092   nsTableFrame::InvalidateTableFrame(
1093       aCellFrame, cellRect.GetPhysicalRect(wm, containerSize),
1094       cellVisualOverflow, aCellFrame->HasAnyStateBits(NS_FRAME_FIRST_REFLOW));
1095 
1096   aCellFrame->DidReflow(aPresContext, nullptr);
1097 
1098   return desiredSize.BSize(wm);
1099 }
1100 
CollapseRowIfNecessary(nscoord aRowOffset,nscoord aISize,bool aCollapseGroup,bool & aDidCollapse)1101 nscoord nsTableRowFrame::CollapseRowIfNecessary(nscoord aRowOffset,
1102                                                 nscoord aISize,
1103                                                 bool aCollapseGroup,
1104                                                 bool& aDidCollapse) {
1105   const nsStyleVisibility* rowVis = StyleVisibility();
1106   bool collapseRow = StyleVisibility::Collapse == rowVis->mVisible;
1107   nsTableFrame* tableFrame =
1108       static_cast<nsTableFrame*>(GetTableFrame()->FirstInFlow());
1109   if (collapseRow) {
1110     tableFrame->SetNeedToCollapse(true);
1111   }
1112 
1113   if (aRowOffset != 0) {
1114     // We're moving, so invalidate our old position
1115     InvalidateFrameSubtree();
1116   }
1117 
1118   WritingMode wm = GetWritingMode();
1119 
1120   nsSize parentSize = GetParent()->GetSize();
1121   LogicalRect rowRect = GetLogicalRect(wm, parentSize);
1122   nsRect oldRect = mRect;
1123   nsRect oldVisualOverflow = GetVisualOverflowRect();
1124 
1125   rowRect.BStart(wm) -= aRowOffset;
1126   rowRect.ISize(wm) = aISize;
1127   nsOverflowAreas overflow;
1128   nscoord shift = 0;
1129   nsSize containerSize = mRect.Size();
1130 
1131   if (aCollapseGroup || collapseRow) {
1132     aDidCollapse = true;
1133     shift = rowRect.BSize(wm);
1134     nsTableCellFrame* cellFrame = GetFirstCell();
1135     if (cellFrame) {
1136       uint32_t rowIndex = cellFrame->RowIndex();
1137       shift += tableFrame->GetRowSpacing(rowIndex);
1138       while (cellFrame) {
1139         LogicalRect cRect = cellFrame->GetLogicalRect(wm, containerSize);
1140         // If aRowOffset != 0, there's no point in invalidating the cells, since
1141         // we've already invalidated our overflow area.  Note that we _do_ still
1142         // need to invalidate if our row is not moving, because the cell might
1143         // span out of this row, so invalidating our row rect won't do enough.
1144         if (aRowOffset == 0) {
1145           InvalidateFrame();
1146         }
1147         cRect.BSize(wm) = 0;
1148         cellFrame->SetRect(wm, cRect, containerSize);
1149         cellFrame = cellFrame->GetNextCell();
1150       }
1151     } else {
1152       shift += tableFrame->GetRowSpacing(GetRowIndex());
1153     }
1154     rowRect.BSize(wm) = 0;
1155   } else {  // row is not collapsed
1156     // remember the col index of the previous cell to handle rowspans into this
1157     // row
1158     int32_t prevColIndex = -1;
1159     nscoord iPos = 0;  // running total of children inline-axis offset
1160     nsTableFrame* fifTable =
1161         static_cast<nsTableFrame*>(tableFrame->FirstInFlow());
1162 
1163     for (nsIFrame* kidFrame : mFrames) {
1164       nsTableCellFrame* cellFrame = do_QueryFrame(kidFrame);
1165       if (cellFrame) {
1166         uint32_t cellColIndex = cellFrame->ColIndex();
1167         int32_t cellColSpan = tableFrame->GetEffectiveColSpan(*cellFrame);
1168 
1169         // If the adjacent cell is in a prior row (because of a rowspan) add in
1170         // the space
1171         // NOTE: prevColIndex can be -1 here.
1172         if (prevColIndex != (static_cast<int32_t>(cellColIndex) - 1)) {
1173           iPos += GetSpaceBetween(prevColIndex, cellColIndex, cellColSpan,
1174                                   *tableFrame, true);
1175         }
1176         LogicalRect cRect(wm, iPos, 0, 0, rowRect.BSize(wm));
1177 
1178         // remember the last (iend-wards-most) column this cell spans into
1179         prevColIndex = cellColIndex + cellColSpan - 1;
1180         int32_t actualColSpan = cellColSpan;
1181         bool isVisible = false;
1182         for (int32_t colIdx = cellColIndex; actualColSpan > 0;
1183              colIdx++, actualColSpan--) {
1184           nsTableColFrame* colFrame = tableFrame->GetColFrame(colIdx);
1185           const nsStyleVisibility* colVis = colFrame->StyleVisibility();
1186           bool collapseCol = StyleVisibility::Collapse == colVis->mVisible;
1187           nsIFrame* cgFrame = colFrame->GetParent();
1188           const nsStyleVisibility* groupVis = cgFrame->StyleVisibility();
1189           bool collapseGroup = StyleVisibility::Collapse == groupVis->mVisible;
1190           bool isCollapsed = collapseCol || collapseGroup;
1191           if (!isCollapsed) {
1192             cRect.ISize(wm) += fifTable->GetColumnISizeFromFirstInFlow(colIdx);
1193             isVisible = true;
1194             if ((actualColSpan > 1)) {
1195               nsTableColFrame* nextColFrame =
1196                   tableFrame->GetColFrame(colIdx + 1);
1197               const nsStyleVisibility* nextColVis =
1198                   nextColFrame->StyleVisibility();
1199               if (StyleVisibility::Collapse != nextColVis->mVisible &&
1200                   tableFrame->ColumnHasCellSpacingBefore(colIdx + 1)) {
1201                 cRect.ISize(wm) += tableFrame->GetColSpacing(cellColIndex);
1202               }
1203             }
1204           }
1205         }
1206         iPos += cRect.ISize(wm);
1207         if (isVisible) {
1208           iPos += tableFrame->GetColSpacing(cellColIndex);
1209         }
1210         int32_t actualRowSpan = tableFrame->GetEffectiveRowSpan(*cellFrame);
1211         nsTableRowFrame* rowFrame = GetNextRow();
1212         for (actualRowSpan--; actualRowSpan > 0 && rowFrame; actualRowSpan--) {
1213           const nsStyleVisibility* nextRowVis = rowFrame->StyleVisibility();
1214           bool collapseNextRow =
1215               StyleVisibility::Collapse == nextRowVis->mVisible;
1216           if (!collapseNextRow) {
1217             LogicalRect nextRect = rowFrame->GetLogicalRect(wm, containerSize);
1218             cRect.BSize(wm) +=
1219                 nextRect.BSize(wm) +
1220                 tableFrame->GetRowSpacing(rowFrame->GetRowIndex());
1221           }
1222           rowFrame = rowFrame->GetNextRow();
1223         }
1224 
1225         nsRect oldCellRect = cellFrame->GetRect();
1226         LogicalPoint oldCellNormalPos =
1227             cellFrame->GetLogicalNormalPosition(wm, containerSize);
1228 
1229         nsRect oldCellVisualOverflow = cellFrame->GetVisualOverflowRect();
1230 
1231         if (aRowOffset == 0 && cRect.Origin(wm) != oldCellNormalPos) {
1232           // We're moving the cell.  Invalidate the old overflow area
1233           cellFrame->InvalidateFrameSubtree();
1234         }
1235 
1236         cellFrame->MovePositionBy(wm, cRect.Origin(wm) - oldCellNormalPos);
1237         cellFrame->SetSize(wm, cRect.Size(wm));
1238 
1239         // XXXbz This looks completely bogus in the cases when we didn't
1240         // collapse the cell!
1241         LogicalRect cellBounds(wm, 0, 0, cRect.ISize(wm), cRect.BSize(wm));
1242         nsRect cellPhysicalBounds =
1243             cellBounds.GetPhysicalRect(wm, containerSize);
1244         nsOverflowAreas cellOverflow(cellPhysicalBounds, cellPhysicalBounds);
1245         cellFrame->FinishAndStoreOverflow(cellOverflow,
1246                                           cRect.Size(wm).GetPhysicalSize(wm));
1247         nsTableFrame::RePositionViews(cellFrame);
1248         ConsiderChildOverflow(overflow, cellFrame);
1249 
1250         if (aRowOffset == 0) {
1251           nsTableFrame::InvalidateTableFrame(cellFrame, oldCellRect,
1252                                              oldCellVisualOverflow, false);
1253         }
1254       }
1255     }
1256   }
1257 
1258   SetRect(wm, rowRect, containerSize);
1259   overflow.UnionAllWith(nsRect(0, 0, rowRect.Width(wm), rowRect.Height(wm)));
1260   FinishAndStoreOverflow(overflow, rowRect.Size(wm).GetPhysicalSize(wm));
1261 
1262   nsTableFrame::RePositionViews(this);
1263   nsTableFrame::InvalidateTableFrame(this, oldRect, oldVisualOverflow, false);
1264   return shift;
1265 }
1266 
1267 /*
1268  * The following method is called by the row group frame's SplitRowGroup()
1269  * when it creates a continuing cell frame and wants to insert it into the
1270  * row's child list.
1271  */
InsertCellFrame(nsTableCellFrame * aFrame,int32_t aColIndex)1272 void nsTableRowFrame::InsertCellFrame(nsTableCellFrame* aFrame,
1273                                       int32_t aColIndex) {
1274   // Find the cell frame where col index < aColIndex
1275   nsTableCellFrame* priorCell = nullptr;
1276   for (nsIFrame* child : mFrames) {
1277     nsTableCellFrame* cellFrame = do_QueryFrame(child);
1278     if (cellFrame) {
1279       uint32_t colIndex = cellFrame->ColIndex();
1280       // Can aColIndex be -1 here?  Let's assume it can for now.
1281       if (static_cast<int32_t>(colIndex) < aColIndex) {
1282         priorCell = cellFrame;
1283       } else
1284         break;
1285     }
1286   }
1287   mFrames.InsertFrame(this, priorCell, aFrame);
1288 }
1289 
GetNextRow() const1290 nsTableRowFrame* nsTableRowFrame::GetNextRow() const {
1291   nsIFrame* childFrame = GetNextSibling();
1292   while (childFrame) {
1293     nsTableRowFrame* rowFrame = do_QueryFrame(childFrame);
1294     if (rowFrame) {
1295       NS_ASSERTION(mozilla::StyleDisplay::TableRow ==
1296                        childFrame->StyleDisplay()->mDisplay,
1297                    "wrong display type on rowframe");
1298       return rowFrame;
1299     }
1300     childFrame = childFrame->GetNextSibling();
1301   }
1302   return nullptr;
1303 }
1304 
NS_DECLARE_FRAME_PROPERTY_SMALL_VALUE(RowUnpaginatedHeightProperty,nscoord)1305 NS_DECLARE_FRAME_PROPERTY_SMALL_VALUE(RowUnpaginatedHeightProperty, nscoord)
1306 
1307 void nsTableRowFrame::SetUnpaginatedBSize(nsPresContext* aPresContext,
1308                                           nscoord aValue) {
1309   NS_ASSERTION(!GetPrevInFlow(), "program error");
1310   // Set the property
1311   SetProperty(RowUnpaginatedHeightProperty(), aValue);
1312 }
1313 
GetUnpaginatedBSize()1314 nscoord nsTableRowFrame::GetUnpaginatedBSize() {
1315   return GetProperty(RowUnpaginatedHeightProperty());
1316 }
1317 
SetContinuousBCBorderWidth(LogicalSide aForSide,BCPixelSize aPixelValue)1318 void nsTableRowFrame::SetContinuousBCBorderWidth(LogicalSide aForSide,
1319                                                  BCPixelSize aPixelValue) {
1320   switch (aForSide) {
1321     case eLogicalSideIEnd:
1322       mIEndContBorderWidth = aPixelValue;
1323       return;
1324     case eLogicalSideBStart:
1325       mBStartContBorderWidth = aPixelValue;
1326       return;
1327     case eLogicalSideIStart:
1328       mIStartContBorderWidth = aPixelValue;
1329       return;
1330     default:
1331       NS_ERROR("invalid LogicalSide arg");
1332   }
1333 }
1334 #ifdef ACCESSIBILITY
AccessibleType()1335 a11y::AccType nsTableRowFrame::AccessibleType() {
1336   return a11y::eHTMLTableRowType;
1337 }
1338 #endif
1339 /**
1340  * Sets the NS_ROW_HAS_CELL_WITH_STYLE_BSIZE bit to indicate whether
1341  * this row has any cells that have non-auto-bsize.  (Row-spanning
1342  * cells are ignored.)
1343  */
InitHasCellWithStyleBSize(nsTableFrame * aTableFrame)1344 void nsTableRowFrame::InitHasCellWithStyleBSize(nsTableFrame* aTableFrame) {
1345   WritingMode wm = GetWritingMode();
1346 
1347   for (nsIFrame* kidFrame : mFrames) {
1348     nsTableCellFrame* cellFrame = do_QueryFrame(kidFrame);
1349     if (!cellFrame) {
1350       MOZ_ASSERT_UNREACHABLE("Table row has a non-cell child.");
1351       continue;
1352     }
1353     // Ignore row-spanning cells
1354     const auto& cellBSize = cellFrame->StylePosition()->BSize(wm);
1355     if (aTableFrame->GetEffectiveRowSpan(*cellFrame) == 1 &&
1356         !cellBSize.IsAuto() &&
1357         /* calc() with both percentages and lengths treated like 'auto' */
1358         (cellBSize.ConvertsToLength() || cellBSize.ConvertsToPercentage())) {
1359       AddStateBits(NS_ROW_HAS_CELL_WITH_STYLE_BSIZE);
1360       return;
1361     }
1362   }
1363   RemoveStateBits(NS_ROW_HAS_CELL_WITH_STYLE_BSIZE);
1364 }
1365 
InvalidateFrame(uint32_t aDisplayItemKey,bool aRebuildDisplayItems)1366 void nsTableRowFrame::InvalidateFrame(uint32_t aDisplayItemKey,
1367                                       bool aRebuildDisplayItems) {
1368   nsIFrame::InvalidateFrame(aDisplayItemKey, aRebuildDisplayItems);
1369   if (GetTableFrame()->IsBorderCollapse()) {
1370     GetParent()->InvalidateFrameWithRect(
1371         GetVisualOverflowRect() + GetPosition(), aDisplayItemKey, false);
1372   }
1373 }
1374 
InvalidateFrameWithRect(const nsRect & aRect,uint32_t aDisplayItemKey,bool aRebuildDisplayItems)1375 void nsTableRowFrame::InvalidateFrameWithRect(const nsRect& aRect,
1376                                               uint32_t aDisplayItemKey,
1377                                               bool aRebuildDisplayItems) {
1378   nsIFrame::InvalidateFrameWithRect(aRect, aDisplayItemKey,
1379                                     aRebuildDisplayItems);
1380   // If we have filters applied that would affects our bounds, then
1381   // we get an inactive layer created and this is computed
1382   // within FrameLayerBuilder
1383   GetParent()->InvalidateFrameWithRect(aRect + GetPosition(), aDisplayItemKey,
1384                                        false);
1385 }
1386 
1387 /* ----- global methods ----- */
1388 
NS_NewTableRowFrame(PresShell * aPresShell,ComputedStyle * aStyle)1389 nsTableRowFrame* NS_NewTableRowFrame(PresShell* aPresShell,
1390                                      ComputedStyle* aStyle) {
1391   return new (aPresShell) nsTableRowFrame(aStyle, aPresShell->GetPresContext());
1392 }
1393 
NS_IMPL_FRAMEARENA_HELPERS(nsTableRowFrame)1394 NS_IMPL_FRAMEARENA_HELPERS(nsTableRowFrame)
1395 
1396 #ifdef DEBUG_FRAME_DUMP
1397 nsresult nsTableRowFrame::GetFrameName(nsAString& aResult) const {
1398   return MakeFrameName(NS_LITERAL_STRING("TableRow"), aResult);
1399 }
1400 #endif
1401