[CSS Grid Layout] RenderGrid methods should take RenderBox references
[WebKit-https.git] / Source / WebCore / rendering / RenderGrid.cpp
1 /*
2  * Copyright (C) 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2013, 2014 Igalia S.L.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "RenderGrid.h"
29
30 #if ENABLE(CSS_GRID_LAYOUT)
31
32 #include "GridCoordinate.h"
33 #include "GridResolvedPosition.h"
34 #include "LayoutRepainter.h"
35 #include "RenderLayer.h"
36 #include "RenderView.h"
37 #include <wtf/NeverDestroyed.h>
38
39 namespace WebCore {
40
41 static const int infinity = -1;
42
43 class GridTrack {
44 public:
45     GridTrack()
46         : m_usedBreadth(0)
47         , m_maxBreadth(0)
48     {
49     }
50
51     void growUsedBreadth(LayoutUnit growth)
52     {
53         ASSERT(growth >= 0);
54         m_usedBreadth += growth;
55     }
56     LayoutUnit usedBreadth() const { return m_usedBreadth; }
57
58     void growMaxBreadth(LayoutUnit growth)
59     {
60         if (m_maxBreadth == infinity)
61             m_maxBreadth = m_usedBreadth + growth;
62         else
63             m_maxBreadth += growth;
64     }
65     LayoutUnit maxBreadthIfNotInfinite() const
66     {
67         return (m_maxBreadth == infinity) ? m_usedBreadth : m_maxBreadth;
68     }
69
70     LayoutUnit m_usedBreadth;
71     LayoutUnit m_maxBreadth;
72 };
73
74 struct GridTrackForNormalization {
75     GridTrackForNormalization(const GridTrack& track, double flex)
76         : m_track(&track)
77         , m_flex(flex)
78         , m_normalizedFlexValue(track.m_usedBreadth / flex)
79     {
80     }
81
82     const GridTrack* m_track;
83     double m_flex;
84     LayoutUnit m_normalizedFlexValue;
85 };
86
87 class RenderGrid::GridIterator {
88     WTF_MAKE_NONCOPYABLE(GridIterator);
89 public:
90     // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
91     // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
92     GridIterator(const Vector<Vector<Vector<RenderBox*, 1>>>& grid, GridTrackSizingDirection direction, size_t fixedTrackIndex, size_t varyingTrackIndex = 0)
93         : m_grid(grid)
94         , m_direction(direction)
95         , m_rowIndex((direction == ForColumns) ? varyingTrackIndex : fixedTrackIndex)
96         , m_columnIndex((direction == ForColumns) ? fixedTrackIndex : varyingTrackIndex)
97         , m_childIndex(0)
98     {
99         ASSERT(m_rowIndex < m_grid.size());
100         ASSERT(m_columnIndex < m_grid[0].size());
101     }
102
103     RenderBox* nextGridItem()
104     {
105         if (!m_grid.size())
106             return 0;
107
108         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
109         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
110         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
111             const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
112             if (m_childIndex < children.size())
113                 return children[m_childIndex++];
114
115             m_childIndex = 0;
116         }
117         return 0;
118     }
119
120     bool isEmptyAreaEnough(size_t rowSpan, size_t columnSpan) const
121     {
122         // Ignore cells outside current grid as we will grow it later if needed.
123         size_t maxRows = std::min(m_rowIndex + rowSpan, m_grid.size());
124         size_t maxColumns = std::min(m_columnIndex + columnSpan, m_grid[0].size());
125
126         // This adds a O(N^2) behavior that shouldn't be a big deal as we expect spanning areas to be small.
127         for (size_t row = m_rowIndex; row < maxRows; ++row) {
128             for (size_t column = m_columnIndex; column < maxColumns; ++column) {
129                 const Vector<RenderBox*>& children = m_grid[row][column];
130                 if (!children.isEmpty())
131                     return false;
132             }
133         }
134
135         return true;
136     }
137
138     std::unique_ptr<GridCoordinate> nextEmptyGridArea(size_t fixedTrackSpan, size_t varyingTrackSpan)
139     {
140         ASSERT(fixedTrackSpan >= 1 && varyingTrackSpan >= 1);
141
142         if (m_grid.isEmpty())
143             return nullptr;
144
145         size_t rowSpan = (m_direction == ForColumns) ? varyingTrackSpan : fixedTrackSpan;
146         size_t columnSpan = (m_direction == ForColumns) ? fixedTrackSpan : varyingTrackSpan;
147
148         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
149         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
150         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
151             if (isEmptyAreaEnough(rowSpan, columnSpan)) {
152                 std::unique_ptr<GridCoordinate> result = std::make_unique<GridCoordinate>(GridSpan(m_rowIndex, m_rowIndex + rowSpan - 1), GridSpan(m_columnIndex, m_columnIndex + columnSpan - 1));
153                 // Advance the iterator to avoid an infinite loop where we would return the same grid area over and over.
154                 ++varyingTrackIndex;
155                 return result;
156             }
157         }
158         return nullptr;
159     }
160
161 private:
162     const Vector<Vector<Vector<RenderBox*, 1>>>& m_grid;
163     GridTrackSizingDirection m_direction;
164     size_t m_rowIndex;
165     size_t m_columnIndex;
166     size_t m_childIndex;
167 };
168
169 class RenderGrid::GridSizingData {
170     WTF_MAKE_NONCOPYABLE(GridSizingData);
171 public:
172     GridSizingData(size_t gridColumnCount, size_t gridRowCount)
173         : columnTracks(gridColumnCount)
174         , rowTracks(gridRowCount)
175     {
176     }
177
178     Vector<GridTrack> columnTracks;
179     Vector<GridTrack> rowTracks;
180     Vector<size_t> contentSizedTracksIndex;
181
182     // Performance optimization: hold onto these Vectors until the end of Layout to avoid repeated malloc / free.
183     Vector<LayoutUnit> distributeTrackVector;
184     Vector<GridTrack*> filteredTracks;
185 };
186
187 RenderGrid::RenderGrid(Element& element, PassRef<RenderStyle> style)
188     : RenderBlock(element, WTF::move(style), 0)
189     , m_orderIterator(*this)
190 {
191     // All of our children must be block level.
192     setChildrenInline(false);
193 }
194
195 RenderGrid::~RenderGrid()
196 {
197 }
198
199 void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
200 {
201     ASSERT(needsLayout());
202
203     if (!relayoutChildren && simplifiedLayout())
204         return;
205
206     // FIXME: Much of this method is boiler plate that matches RenderBox::layoutBlock and Render*FlexibleBox::layoutBlock.
207     // It would be nice to refactor some of the duplicate code.
208     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
209     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
210
211     preparePaginationBeforeBlockLayout(relayoutChildren);
212
213     LayoutSize previousSize = size();
214
215     setLogicalHeight(0);
216     updateLogicalWidth();
217
218     layoutGridItems();
219
220     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
221     updateLogicalHeight();
222
223     if (size() != previousSize)
224         relayoutChildren = true;
225
226     layoutPositionedObjects(relayoutChildren || isRoot());
227
228     computeOverflow(oldClientAfterEdge);
229     statePusher.pop();
230
231     updateLayerTransform();
232
233     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
234     // we overflow or not.
235     updateScrollInfoAfterLayout();
236
237     repainter.repaintAfterLayout();
238
239     clearNeedsLayout();
240 }
241
242 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
243 {
244     const_cast<RenderGrid*>(this)->placeItemsOnGrid();
245
246     GridSizingData sizingData(gridColumnCount(), gridRowCount());
247     LayoutUnit availableLogicalSpace = 0;
248     const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
249
250     for (size_t i = 0; i < sizingData.columnTracks.size(); ++i) {
251         LayoutUnit minTrackBreadth = sizingData.columnTracks[i].m_usedBreadth;
252         LayoutUnit maxTrackBreadth = sizingData.columnTracks[i].m_maxBreadth;
253         maxTrackBreadth = std::max(maxTrackBreadth, minTrackBreadth);
254
255         minLogicalWidth += minTrackBreadth;
256         maxLogicalWidth += maxTrackBreadth;
257
258         // FIXME: This should add in the scrollbarWidth (e.g. see RenderFlexibleBox).
259     }
260
261     const_cast<RenderGrid*>(this)->clearGrid();
262 }
263
264 void RenderGrid::computePreferredLogicalWidths()
265 {
266     ASSERT(preferredLogicalWidthsDirty());
267
268     m_minPreferredLogicalWidth = 0;
269     m_maxPreferredLogicalWidth = 0;
270
271     // FIXME: We don't take our own logical width into account. Once we do, we need to make sure
272     // we apply (and test the interaction with) min-width / max-width.
273
274     computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
275
276     LayoutUnit borderAndPaddingInInlineDirection = borderAndPaddingLogicalWidth();
277     m_minPreferredLogicalWidth += borderAndPaddingInInlineDirection;
278     m_maxPreferredLogicalWidth += borderAndPaddingInInlineDirection;
279
280     setPreferredLogicalWidthsDirty(false);
281 }
282
283 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
284 {
285     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
286     computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
287 }
288
289 bool RenderGrid::gridElementIsShrinkToFit()
290 {
291     return isFloatingOrOutOfFlowPositioned();
292 }
293
294 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
295 {
296     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
297     Vector<size_t> flexibleSizedTracksIndex;
298     sizingData.contentSizedTracksIndex.shrink(0);
299
300     // 1. Initialize per Grid track variables.
301     for (size_t i = 0; i < tracks.size(); ++i) {
302         GridTrack& track = tracks[i];
303         const GridTrackSize& trackSize = gridTrackSize(direction, i);
304         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
305         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
306
307         track.m_usedBreadth = computeUsedBreadthOfMinLength(direction, minTrackBreadth);
308         track.m_maxBreadth = computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.m_usedBreadth);
309
310         track.m_maxBreadth = std::max(track.m_maxBreadth, track.m_usedBreadth);
311
312         if (trackSize.isContentSized())
313             sizingData.contentSizedTracksIndex.append(i);
314         if (trackSize.maxTrackBreadth().isFlex())
315             flexibleSizedTracksIndex.append(i);
316     }
317
318     // 2. Resolve content-based TrackSizingFunctions.
319     if (!sizingData.contentSizedTracksIndex.isEmpty())
320         resolveContentBasedTrackSizingFunctions(direction, sizingData);
321
322     for (size_t i = 0; i < tracks.size(); ++i) {
323         ASSERT(tracks[i].m_maxBreadth != infinity);
324         availableLogicalSpace -= tracks[i].m_usedBreadth;
325     }
326
327     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
328
329     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
330         return;
331
332     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until
333     // availableLogicalSpace (RemainingSpace in the specs) is exhausted.
334     const size_t tracksSize = tracks.size();
335     if (!hasUndefinedRemainingSpace) {
336         Vector<GridTrack*> tracksForDistribution(tracksSize);
337         for (size_t i = 0; i < tracksSize; ++i)
338             tracksForDistribution[i] = tracks.data() + i;
339
340         distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
341     } else {
342         for (size_t i = 0; i < tracksSize; ++i)
343             tracks[i].m_usedBreadth = tracks[i].m_maxBreadth;
344     }
345
346     if (flexibleSizedTracksIndex.isEmpty())
347         return;
348
349     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
350     double normalizedFractionBreadth = 0;
351     if (!hasUndefinedRemainingSpace)
352         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, availableLogicalSpace);
353     else {
354         for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
355             const size_t trackIndex = flexibleSizedTracksIndex[i];
356             const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
357             normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].m_usedBreadth / trackSize.maxTrackBreadth().flex());
358         }
359
360         for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
361             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
362             while (RenderBox* gridItem = iterator.nextGridItem()) {
363                 const GridCoordinate coordinate = cachedGridCoordinate(*gridItem);
364                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
365
366                 // Do not include already processed items.
367                 if (i > 0 && span.resolvedInitialPosition.toInt() <= flexibleSizedTracksIndex[i - 1])
368                     continue;
369
370                 double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(*gridItem, direction, sizingData.columnTracks));
371                 normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
372             }
373         }
374     }
375
376     for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
377         const size_t trackIndex = flexibleSizedTracksIndex[i];
378         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
379
380         tracks[trackIndex].m_usedBreadth = std::max<LayoutUnit>(tracks[trackIndex].m_usedBreadth, normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
381     }
382 }
383
384 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
385 {
386     if (gridLength.isFlex())
387         return 0;
388
389     const Length& trackLength = gridLength.length();
390     ASSERT(!trackLength.isAuto());
391     if (trackLength.isSpecified())
392         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
393
394     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
395     return 0;
396 }
397
398 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
399 {
400     if (gridLength.isFlex())
401         return usedBreadth;
402
403     const Length& trackLength = gridLength.length();
404     ASSERT(!trackLength.isAuto());
405     if (trackLength.isSpecified()) {
406         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
407         ASSERT(computedBreadth != infinity);
408         return computedBreadth;
409     }
410
411     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
412     return infinity;
413 }
414
415 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
416 {
417     ASSERT(trackLength.isSpecified());
418     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style().logicalHeight()));
419 }
420
421 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
422 {
423     // |availableLogicalSpace| already accounts for the used breadths so no need to remove it here.
424
425     Vector<GridTrackForNormalization> tracksForNormalization;
426     for (auto position : tracksSpan) {
427         const GridTrackSize& trackSize = gridTrackSize(direction, position.toInt());
428         if (!trackSize.maxTrackBreadth().isFlex())
429             continue;
430
431         tracksForNormalization.append(GridTrackForNormalization(tracks[position.toInt()], trackSize.maxTrackBreadth().flex()));
432     }
433
434     // The function is not called if we don't have <flex> grid tracks
435     ASSERT(!tracksForNormalization.isEmpty());
436
437     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
438               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
439                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
440               });
441
442     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
443     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
444     // fit into availableLogicalSpaceIgnoringFractionTracks.
445     double accumulatedFractions = 0;
446     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
447     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = availableLogicalSpace;
448
449     for (size_t i = 0; i < tracksForNormalization.size(); ++i) {
450         const GridTrackForNormalization& track = tracksForNormalization[i];
451         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
452             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
453             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
454             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
455                 break;
456
457             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
458         }
459
460         accumulatedFractions += track.m_flex;
461         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
462         availableLogicalSpaceIgnoringFractionTracks += track.m_track->m_usedBreadth;
463     }
464
465     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
466 }
467
468 const GridTrackSize& RenderGrid::gridTrackSize(GridTrackSizingDirection direction, size_t i) const
469 {
470     const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style().gridColumns() : style().gridRows();
471     if (i >= trackStyles.size())
472         return (direction == ForColumns) ? style().gridAutoColumns() : style().gridAutoRows();
473
474     const GridTrackSize& trackSize = trackStyles[i];
475     // If the logical width/height of the grid container is indefinite, percentage values are treated as <auto>.
476     if (trackSize.isPercentage()) {
477         Length logicalSize = direction == ForColumns ? style().logicalWidth() : style().logicalHeight();
478         if (logicalSize.isIntrinsicOrAuto()) {
479             static NeverDestroyed<GridTrackSize> autoTrackSize(Auto);
480             return autoTrackSize.get();
481         }
482     }
483
484     return trackSize;
485 }
486
487 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox& child, Vector<GridTrack>& columnTracks)
488 {
489     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
490     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
491     if (child.style().logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
492         child.setNeedsLayout(MarkOnlyThis);
493
494     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
495     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
496     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
497     child.setOverrideContainingBlockContentLogicalHeight(-1);
498     child.layoutIfNeeded();
499     return child.logicalHeight() + child.marginLogicalHeight();
500 }
501
502 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
503 {
504     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
505     // FIXME: Properly support orthogonal writing mode.
506     if (hasOrthogonalWritingMode)
507         return 0;
508
509     if (direction == ForColumns) {
510         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
511         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
512         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
513     }
514
515     return logicalContentHeightForChild(child, columnTracks);
516 }
517
518 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
519 {
520     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
521     // FIXME: Properly support orthogonal writing mode.
522     if (hasOrthogonalWritingMode)
523         return LayoutUnit();
524
525     if (direction == ForColumns) {
526         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
527         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
528         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
529     }
530
531     return logicalContentHeightForChild(child, columnTracks);
532 }
533
534 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
535 {
536     // FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track.
537
538     for (size_t i = 0; i < sizingData.contentSizedTracksIndex.size(); ++i) {
539         GridIterator iterator(m_grid, direction, sizingData.contentSizedTracksIndex[i]);
540         while (RenderBox* gridItem = iterator.nextGridItem()) {
541             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, *gridItem, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
542             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, *gridItem, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
543             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, *gridItem, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
544             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, *gridItem, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
545         }
546
547         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[i] : sizingData.rowTracks[i];
548         if (track.m_maxBreadth == infinity)
549             track.m_maxBreadth = track.m_usedBreadth;
550     }
551 }
552
553 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, RenderBox& gridItem, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction)
554 {
555     const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
556     const GridResolvedPosition initialTrackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
557     const GridResolvedPosition finalTrackPosition = (direction == ForColumns) ? coordinate.columns.resolvedFinalPosition : coordinate.rows.resolvedFinalPosition;
558
559     sizingData.filteredTracks.shrink(0);
560     for (GridResolvedPosition trackIndex = initialTrackPosition; trackIndex <= finalTrackPosition; ++trackIndex) {
561         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex.toInt());
562         if (!(trackSize.*filterFunction)())
563             continue;
564
565         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex.toInt()] : sizingData.rowTracks[trackIndex.toInt()];
566         sizingData.filteredTracks.append(&track);
567     }
568
569     if (sizingData.filteredTracks.isEmpty())
570         return;
571
572     LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItem, direction, sizingData.columnTracks);
573     for (GridResolvedPosition trackPositionForSpace = initialTrackPosition; trackPositionForSpace <= finalTrackPosition; ++trackPositionForSpace) {
574         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPositionForSpace.toInt()] : sizingData.rowTracks[trackPositionForSpace.toInt()];
575         additionalBreadthSpace -= (track.*trackGetter)();
576     }
577
578     // FIXME: We should pass different values for |tracksForGrowthAboveMaxBreadth|.
579     distributeSpaceToTracks(sizingData.filteredTracks, &sizingData.filteredTracks, trackGetter, trackGrowthFunction, sizingData, additionalBreadthSpace);
580 }
581
582 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
583 {
584     return (track1->m_maxBreadth - track1->m_usedBreadth) < (track2->m_maxBreadth - track2->m_usedBreadth);
585 }
586
587 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
588 {
589     std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
590
591     size_t tracksSize = tracks.size();
592     sizingData.distributeTrackVector.resize(tracksSize);
593
594     for (size_t i = 0; i < tracksSize; ++i) {
595         GridTrack& track = *tracks[i];
596         LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
597         LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
598         LayoutUnit growthShare = std::max(LayoutUnit(), std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth));
599         // We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function.
600         sizingData.distributeTrackVector[i] = trackBreadth + growthShare;
601         availableLogicalSpace -= growthShare;
602     }
603
604     if (availableLogicalSpace > 0 && tracksForGrowthAboveMaxBreadth) {
605         tracksSize = tracksForGrowthAboveMaxBreadth->size();
606         for (size_t i = 0; i < tracksSize; ++i) {
607             LayoutUnit growthShare = availableLogicalSpace / (tracksSize - i);
608             sizingData.distributeTrackVector[i] += growthShare;
609             availableLogicalSpace -= growthShare;
610         }
611     }
612
613     for (size_t i = 0; i < tracksSize; ++i) {
614         LayoutUnit growth = sizingData.distributeTrackVector[i] - (tracks[i]->*trackGetter)();
615         if (growth >= 0)
616             (tracks[i]->*trackGrowthFunction)(growth);
617     }
618 }
619
620 #ifndef NDEBUG
621 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
622 {
623     for (size_t i = 0; i < tracks.size(); ++i) {
624         const GridTrackSize& trackSize = gridTrackSize(direction, i);
625         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
626         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].m_usedBreadth)
627             return false;
628     }
629     return true;
630 }
631 #endif
632
633 void RenderGrid::ensureGridSize(size_t maximumRowIndex, size_t maximumColumnIndex)
634 {
635     const size_t oldRowCount = gridRowCount();
636     if (maximumRowIndex >= oldRowCount) {
637         m_grid.grow(maximumRowIndex + 1);
638         for (size_t row = oldRowCount; row < gridRowCount(); ++row)
639             m_grid[row].grow(gridColumnCount());
640     }
641
642     if (maximumColumnIndex >= gridColumnCount()) {
643         for (size_t row = 0; row < gridRowCount(); ++row)
644             m_grid[row].grow(maximumColumnIndex + 1);
645     }
646 }
647
648 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
649 {
650     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
651
652     for (auto row : coordinate.rows) {
653         for (auto column : coordinate.columns)
654             m_grid[row.toInt()][column.toInt()].append(&child);
655     }
656     m_gridItemCoordinate.set(&child, coordinate);
657 }
658
659 void RenderGrid::placeItemsOnGrid()
660 {
661     ASSERT(!gridWasPopulated());
662     ASSERT(m_gridItemCoordinate.isEmpty());
663
664     populateExplicitGridAndOrderIterator();
665
666     Vector<RenderBox*> autoMajorAxisAutoGridItems;
667     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
668     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
669         // FIXME: We never re-resolve positions if the grid is grown during auto-placement which may lead auto / <integer>
670         // positions to not match the author's intent. The specification is unclear on what should be done in this case.
671         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
672         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
673         if (!rowPositions || !columnPositions) {
674             GridSpan* majorAxisPositions = (autoPlacementMajorAxisDirection() == ForColumns) ? columnPositions.get() : rowPositions.get();
675             if (!majorAxisPositions)
676                 autoMajorAxisAutoGridItems.append(child);
677             else
678                 specifiedMajorAxisAutoGridItems.append(child);
679             continue;
680         }
681         insertItemIntoGrid(*child, GridCoordinate(*rowPositions, *columnPositions));
682     }
683
684     ASSERT(gridRowCount() >= style().gridRows().size());
685     ASSERT(gridColumnCount() >= style().gridColumns().size());
686
687     // FIXME: Implement properly "stack" value in auto-placement algorithm.
688     if (style().isGridAutoFlowAlgorithmStack()) {
689         // If we did collect some grid items, they won't be placed thus never laid out.
690         ASSERT(!autoMajorAxisAutoGridItems.size());
691         ASSERT(!specifiedMajorAxisAutoGridItems.size());
692         return;
693     }
694
695     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
696     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
697 }
698
699 void RenderGrid::populateExplicitGridAndOrderIterator()
700 {
701     OrderIteratorPopulator populator(m_orderIterator);
702     size_t maximumRowIndex = std::max<size_t>(1, style().gridRows().size());
703     size_t maximumColumnIndex = std::max<size_t>(1, style().gridColumns().size());
704
705     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
706         populator.collectChild(*child);
707
708         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
709         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
710         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
711
712         // |positions| is 0 if we need to run the auto-placement algorithm.
713         if (rowPositions)
714             maximumRowIndex = std::max(maximumRowIndex, rowPositions->resolvedFinalPosition.next().toInt());
715         else {
716             // Grow the grid for items with a definite row span, getting the largest such span.
717             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
718             maximumRowIndex = std::max<size_t>(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
719         }
720
721         if (columnPositions)
722             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->resolvedFinalPosition.next().toInt());
723         else {
724             // Grow the grid for items with a definite column span, getting the largest such span.
725             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
726             maximumColumnIndex = std::max<size_t>(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
727         }
728     }
729
730     m_grid.grow(maximumRowIndex);
731     for (size_t i = 0; i < m_grid.size(); ++i)
732         m_grid[i].grow(maximumColumnIndex);
733 }
734
735 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
736 {
737     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
738     const size_t endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
739     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
740     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
741 }
742
743 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
744 {
745     for (auto& autoGridItem : autoGridItems) {
746         std::unique_ptr<GridSpan> majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
747         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
748
749         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->resolvedInitialPosition.toInt());
750         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions->integerSpan(), minorAxisPositions.integerSpan());
751         if (!emptyGridArea)
752             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), *majorAxisPositions);
753         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
754     }
755 }
756
757 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
758 {
759     AutoPlacementCursor autoPlacementCursor = {0, 0};
760     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
761
762     for (auto& autoGridItem : autoGridItems) {
763         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
764
765         if (isGridAutoFlowDense) {
766             autoPlacementCursor.first = 0;
767             autoPlacementCursor.second = 0;
768         }
769     }
770 }
771
772 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
773 {
774     std::unique_ptr<GridSpan> minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
775     ASSERT(!GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()));
776     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
777
778     const size_t endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
779     size_t majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
780     size_t minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
781
782     std::unique_ptr<GridCoordinate> emptyGridArea;
783     if (minorAxisPositions) {
784         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
785         if (minorAxisPositions->resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
786             majorAxisAutoPlacementCursor++;
787
788         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
789             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions->resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
790             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions->integerSpan(), majorAxisPositions.integerSpan());
791         }
792
793         if (!emptyGridArea)
794             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), *minorAxisPositions);
795     } else {
796         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
797
798         for (size_t majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
799             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
800             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
801
802             if (emptyGridArea) {
803                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
804                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
805                 const size_t endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
806                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
807                     break;
808
809                 // Discard empty grid area as it does not fit in the minor axis direction.
810                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
811                 emptyGridArea = nullptr;
812             }
813
814             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
815             minorAxisAutoPlacementCursor = 0;
816         }
817
818         if (!emptyGridArea)
819             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
820     }
821
822     insertItemIntoGrid(gridItem, *emptyGridArea);
823     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
824     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
825 }
826
827 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
828 {
829     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
830 }
831
832 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
833 {
834     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
835 }
836
837 void RenderGrid::clearGrid()
838 {
839     m_grid.clear();
840     m_gridItemCoordinate.clear();
841 }
842
843 void RenderGrid::layoutGridItems()
844 {
845     placeItemsOnGrid();
846
847     GridSizingData sizingData(gridColumnCount(), gridRowCount());
848     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
849     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
850     computeUsedBreadthOfGridTracks(ForRows, sizingData);
851     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
852
853     populateGridPositions(sizingData);
854
855     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
856         // Because the grid area cannot be styled, we don't need to adjust
857         // the grid breadth to account for 'box-sizing'.
858         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
859         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
860
861         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(*child, ForColumns, sizingData.columnTracks);
862         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(*child, ForRows, sizingData.rowTracks);
863         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && child->hasRelativeLogicalHeight()))
864             child->setNeedsLayout(MarkOnlyThis);
865
866         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
867         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
868
869         LayoutRect oldChildRect = child->frameRect();
870
871         // FIXME: Grid items should stretch to fill their cells. Once we
872         // implement grid-{column,row}-align, we can also shrink to fit. For
873         // now, just size as if we were a regular child.
874         child->layoutIfNeeded();
875
876         child->setLogicalLocation(findChildLogicalPosition(*child, sizingData));
877
878         // If the child moved, we have to repaint it as well as any floating/positioned
879         // descendants. An exception is if we need a layout. In this case, we know we're going to
880         // repaint ourselves (and the child) anyway.
881         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
882             child->repaintDuringLayoutIfMoved(oldChildRect);
883     }
884
885     for (size_t i = 0; i < sizingData.rowTracks.size(); ++i)
886         setLogicalHeight(logicalHeight() + sizingData.rowTracks[i].m_usedBreadth);
887
888     // min / max logical height is handled in updateLogicalHeight().
889     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
890     clearGrid();
891 }
892
893 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
894 {
895     ASSERT(m_gridItemCoordinate.contains(&gridItem));
896     return m_gridItemCoordinate.get(&gridItem);
897 }
898
899 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
900 {
901     const GridCoordinate& coordinate = cachedGridCoordinate(child);
902     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
903     LayoutUnit gridAreaBreadth = 0;
904     for (auto trackPosition : span)
905         gridAreaBreadth += tracks[trackPosition.toInt()].m_usedBreadth;
906     return gridAreaBreadth;
907 }
908
909 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
910 {
911     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
912     m_columnPositions[0] = borderAndPaddingStart();
913     for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
914         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
915
916     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
917     m_rowPositions[0] = borderAndPaddingBefore();
918     for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
919         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
920 }
921
922 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox& child, const GridSizingData& sizingData)
923 {
924     const GridCoordinate& coordinate = cachedGridCoordinate(child);
925     ASSERT_UNUSED(sizingData, coordinate.columns.resolvedInitialPosition.toInt() < sizingData.columnTracks.size());
926     ASSERT_UNUSED(sizingData, coordinate.rows.resolvedInitialPosition.toInt() < sizingData.rowTracks.size());
927
928     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
929     return LayoutPoint(m_columnPositions[coordinate.columns.resolvedInitialPosition.toInt()] + marginStartForChild(child), m_rowPositions[coordinate.rows.resolvedInitialPosition.toInt()] + marginBeforeForChild(child));
930 }
931
932 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
933 {
934     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
935         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect);
936 }
937
938 const char* RenderGrid::renderName() const
939 {
940     if (isFloating())
941         return "RenderGrid (floating)";
942     if (isOutOfFlowPositioned())
943         return "RenderGrid (positioned)";
944     if (isAnonymous())
945         return "RenderGrid (generated)";
946     if (isRelPositioned())
947         return "RenderGrid (relative positioned)";
948     return "RenderGrid";
949 }
950
951 } // namespace WebCore
952
953 #endif /* ENABLE(CSS_GRID_LAYOUT) */