[CSS Grid Layout] Use modern for-loops in RenderGrid
[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 (auto& column : sizingData.columnTracks) {
251         LayoutUnit minTrackBreadth = column.m_usedBreadth;
252         LayoutUnit maxTrackBreadth = column.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         if (track.m_maxBreadth != infinity)
311             track.m_maxBreadth = std::max(track.m_maxBreadth, track.m_usedBreadth);
312
313         if (trackSize.isContentSized())
314             sizingData.contentSizedTracksIndex.append(i);
315         if (trackSize.maxTrackBreadth().isFlex())
316             flexibleSizedTracksIndex.append(i);
317     }
318
319     // 2. Resolve content-based TrackSizingFunctions.
320     if (!sizingData.contentSizedTracksIndex.isEmpty())
321         resolveContentBasedTrackSizingFunctions(direction, sizingData);
322
323     for (auto& track : tracks) {
324         ASSERT(track.m_maxBreadth != infinity);
325         availableLogicalSpace -= track.m_usedBreadth;
326     }
327
328     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
329
330     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
331         return;
332
333     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until
334     // availableLogicalSpace (RemainingSpace in the specs) is exhausted.
335     if (!hasUndefinedRemainingSpace) {
336         const size_t tracksSize = tracks.size();
337         Vector<GridTrack*> tracksForDistribution(tracksSize);
338         for (size_t i = 0; i < tracksSize; ++i)
339             tracksForDistribution[i] = tracks.data() + i;
340
341         distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
342     } else {
343         for (auto& track : tracks)
344             track.m_usedBreadth = track.m_maxBreadth;
345     }
346
347     if (flexibleSizedTracksIndex.isEmpty())
348         return;
349
350     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
351     double normalizedFractionBreadth = 0;
352     if (!hasUndefinedRemainingSpace)
353         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, availableLogicalSpace);
354     else {
355         for (auto trackIndex : flexibleSizedTracksIndex) {
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 (auto trackIndex : flexibleSizedTracksIndex) {
377         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
378         GridTrack& track = tracks[trackIndex];
379         track.m_usedBreadth = std::max<LayoutUnit>(track.m_usedBreadth, normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
380     }
381 }
382
383 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
384 {
385     if (gridLength.isFlex())
386         return 0;
387
388     const Length& trackLength = gridLength.length();
389     ASSERT(!trackLength.isAuto());
390     if (trackLength.isSpecified())
391         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
392
393     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
394     return 0;
395 }
396
397 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
398 {
399     if (gridLength.isFlex())
400         return usedBreadth;
401
402     const Length& trackLength = gridLength.length();
403     ASSERT(!trackLength.isAuto());
404     if (trackLength.isSpecified()) {
405         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
406         ASSERT(computedBreadth != infinity);
407         return computedBreadth;
408     }
409
410     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
411     return infinity;
412 }
413
414 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
415 {
416     ASSERT(trackLength.isSpecified());
417     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style().logicalHeight()));
418 }
419
420 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
421 {
422     // |availableLogicalSpace| already accounts for the used breadths so no need to remove it here.
423
424     Vector<GridTrackForNormalization> tracksForNormalization;
425     for (auto position : tracksSpan) {
426         const GridTrackSize& trackSize = gridTrackSize(direction, position.toInt());
427         if (!trackSize.maxTrackBreadth().isFlex())
428             continue;
429
430         tracksForNormalization.append(GridTrackForNormalization(tracks[position.toInt()], trackSize.maxTrackBreadth().flex()));
431     }
432
433     // The function is not called if we don't have <flex> grid tracks
434     ASSERT(!tracksForNormalization.isEmpty());
435
436     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
437               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
438                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
439               });
440
441     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
442     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
443     // fit into availableLogicalSpaceIgnoringFractionTracks.
444     double accumulatedFractions = 0;
445     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
446     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = availableLogicalSpace;
447
448     for (auto& track : tracksForNormalization) {
449         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
450             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
451             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
452             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
453                 break;
454
455             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
456         }
457
458         accumulatedFractions += track.m_flex;
459         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
460         availableLogicalSpaceIgnoringFractionTracks += track.m_track->m_usedBreadth;
461     }
462
463     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
464 }
465
466 GridTrackSize RenderGrid::gridTrackSize(GridTrackSizingDirection direction, size_t i) const
467 {
468     bool isForColumns = (direction == ForColumns);
469     auto& trackStyles =  isForColumns ? style().gridColumns() : style().gridRows();
470     auto& trackSize = (i >= trackStyles.size()) ? (isForColumns ? style().gridAutoColumns() : style().gridAutoRows()) : trackStyles[i];
471
472     // If the logical width/height of the grid container is indefinite, percentage values are treated as <auto> (or in
473     // the case of minmax() as min-content for the first position and max-content for the second).
474     Length logicalSize = isForColumns ? style().logicalWidth() : style().logicalHeight();
475     if (logicalSize.isIntrinsicOrAuto()) {
476         const GridLength& oldMinTrackBreadth = trackSize.minTrackBreadth();
477         const GridLength& oldMaxTrackBreadth = trackSize.maxTrackBreadth();
478         return GridTrackSize(oldMinTrackBreadth.isPercentage() ? Length(MinContent) : oldMinTrackBreadth, oldMaxTrackBreadth.isPercentage() ? Length(MaxContent) : oldMaxTrackBreadth);
479     }
480
481     return trackSize;
482 }
483
484 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox& child, Vector<GridTrack>& columnTracks)
485 {
486     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
487     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
488     if (child.style().logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
489         child.setNeedsLayout(MarkOnlyThis);
490
491     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
492     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
493     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
494     child.setOverrideContainingBlockContentLogicalHeight(-1);
495     child.layoutIfNeeded();
496     return child.logicalHeight() + child.marginLogicalHeight();
497 }
498
499 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
500 {
501     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
502     // FIXME: Properly support orthogonal writing mode.
503     if (hasOrthogonalWritingMode)
504         return 0;
505
506     if (direction == ForColumns) {
507         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
508         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
509         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
510     }
511
512     return logicalContentHeightForChild(child, columnTracks);
513 }
514
515 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
516 {
517     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
518     // FIXME: Properly support orthogonal writing mode.
519     if (hasOrthogonalWritingMode)
520         return LayoutUnit();
521
522     if (direction == ForColumns) {
523         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
524         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
525         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
526     }
527
528     return logicalContentHeightForChild(child, columnTracks);
529 }
530
531 class GridItemWithSpan {
532 public:
533     GridItemWithSpan(RenderBox& gridItem, GridCoordinate coordinate, GridTrackSizingDirection direction)
534         : m_gridItem(gridItem)
535         , m_coordinate(coordinate)
536     {
537         const GridSpan& span = (direction == ForRows) ? coordinate.rows : coordinate.columns;
538         m_span = span.resolvedFinalPosition.toInt() - span.resolvedInitialPosition.toInt() + 1;
539     }
540
541     RenderBox& gridItem() const { return m_gridItem; }
542     GridCoordinate coordinate() const { return m_coordinate; }
543
544     bool operator<(const GridItemWithSpan other) const
545     {
546         return m_span < other.m_span;
547     }
548
549 private:
550     std::reference_wrapper<RenderBox> m_gridItem;
551     GridCoordinate m_coordinate;
552     size_t m_span;
553 };
554
555 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
556 {
557     // FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track.
558
559     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
560         GridIterator iterator(m_grid, direction, trackIndex);
561         HashSet<RenderBox*> itemsSet;
562         Vector<GridItemWithSpan> itemsSortedByIncreasingSpan;
563
564         while (RenderBox* gridItem = iterator.nextGridItem()) {
565             if (itemsSet.add(gridItem).isNewEntry)
566                 itemsSortedByIncreasingSpan.append(GridItemWithSpan(*gridItem, cachedGridCoordinate(*gridItem), direction));
567         }
568         std::stable_sort(itemsSortedByIncreasingSpan.begin(), itemsSortedByIncreasingSpan.end());
569
570         for (auto& itemWithSpan : itemsSortedByIncreasingSpan) {
571             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
572             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
573             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
574             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
575         }
576
577         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
578         if (track.m_maxBreadth == infinity)
579             track.m_maxBreadth = track.m_usedBreadth;
580     }
581 }
582
583 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, GridItemWithSpan& gridItemWithSpan, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction)
584 {
585     const GridCoordinate& coordinate = gridItemWithSpan.coordinate();
586     const GridResolvedPosition initialTrackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
587     const GridResolvedPosition finalTrackPosition = (direction == ForColumns) ? coordinate.columns.resolvedFinalPosition : coordinate.rows.resolvedFinalPosition;
588
589     sizingData.filteredTracks.shrink(0);
590     for (GridResolvedPosition trackIndex = initialTrackPosition; trackIndex <= finalTrackPosition; ++trackIndex) {
591         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex.toInt());
592         if (!(trackSize.*filterFunction)())
593             continue;
594
595         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex.toInt()] : sizingData.rowTracks[trackIndex.toInt()];
596         sizingData.filteredTracks.append(&track);
597     }
598
599     if (sizingData.filteredTracks.isEmpty())
600         return;
601
602     LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItemWithSpan.gridItem(), direction, sizingData.columnTracks);
603     for (GridResolvedPosition trackPositionForSpace = initialTrackPosition; trackPositionForSpace <= finalTrackPosition; ++trackPositionForSpace) {
604         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPositionForSpace.toInt()] : sizingData.rowTracks[trackPositionForSpace.toInt()];
605         additionalBreadthSpace -= (track.*trackGetter)();
606     }
607
608     // FIXME: We should pass different values for |tracksForGrowthAboveMaxBreadth|.
609     // Specs mandate to floor additionalBreadthSpace (extra-space in specs) to 0. Instead we directly avoid the function
610     // call in those cases as it will be a noop in terms of track sizing.
611     if (additionalBreadthSpace > 0)
612         distributeSpaceToTracks(sizingData.filteredTracks, &sizingData.filteredTracks, trackGetter, trackGrowthFunction, sizingData, additionalBreadthSpace);
613 }
614
615 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
616 {
617     // This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
618     // (forall x: NOT x < x).
619     if (track1->m_maxBreadth == infinity && track2->m_maxBreadth == infinity)
620         return false;
621
622     if (track1->m_maxBreadth == infinity || track2->m_maxBreadth == infinity)
623         return track2->m_maxBreadth == infinity;
624
625     return (track1->m_maxBreadth - track1->m_usedBreadth) < (track2->m_maxBreadth - track2->m_usedBreadth);
626 }
627
628 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
629 {
630     ASSERT(availableLogicalSpace > 0);
631     std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
632
633     size_t tracksSize = tracks.size();
634     sizingData.distributeTrackVector.resize(tracksSize);
635
636     for (size_t i = 0; i < tracksSize; ++i) {
637         GridTrack& track = *tracks[i];
638         LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
639         bool infiniteGrowthPotential = track.m_maxBreadth == infinity;
640         LayoutUnit trackGrowthPotential = infiniteGrowthPotential ? track.m_maxBreadth : track.m_maxBreadth - trackBreadth;
641         sizingData.distributeTrackVector[i] = trackBreadth;
642         // Let's avoid computing availableLogicalSpaceShare as much as possible as it's a hot spot in performance tests.
643         if (trackGrowthPotential > 0 || infiniteGrowthPotential) {
644             LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
645             LayoutUnit growthShare = infiniteGrowthPotential ? availableLogicalSpaceShare : std::min(availableLogicalSpaceShare, trackGrowthPotential);
646             ASSERT(growthShare > 0);
647             // We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function.
648             sizingData.distributeTrackVector[i] += growthShare;
649             availableLogicalSpace -= growthShare;
650         }
651     }
652
653     if (availableLogicalSpace > 0 && tracksForGrowthAboveMaxBreadth) {
654         tracksSize = tracksForGrowthAboveMaxBreadth->size();
655         for (size_t i = 0; i < tracksSize; ++i) {
656             LayoutUnit growthShare = availableLogicalSpace / (tracksSize - i);
657             sizingData.distributeTrackVector[i] += growthShare;
658             availableLogicalSpace -= growthShare;
659         }
660     }
661
662     for (size_t i = 0; i < tracksSize; ++i) {
663         LayoutUnit growth = sizingData.distributeTrackVector[i] - (tracks[i]->*trackGetter)();
664         if (growth >= 0)
665             (tracks[i]->*trackGrowthFunction)(growth);
666     }
667 }
668
669 #ifndef NDEBUG
670 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
671 {
672     for (size_t i = 0; i < tracks.size(); ++i) {
673         const GridTrackSize& trackSize = gridTrackSize(direction, i);
674         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
675         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].m_usedBreadth)
676             return false;
677     }
678     return true;
679 }
680 #endif
681
682 void RenderGrid::ensureGridSize(size_t maximumRowIndex, size_t maximumColumnIndex)
683 {
684     const size_t oldRowCount = gridRowCount();
685     if (maximumRowIndex >= oldRowCount) {
686         m_grid.grow(maximumRowIndex + 1);
687         for (size_t row = oldRowCount; row < gridRowCount(); ++row)
688             m_grid[row].grow(gridColumnCount());
689     }
690
691     if (maximumColumnIndex >= gridColumnCount()) {
692         for (size_t row = 0; row < gridRowCount(); ++row)
693             m_grid[row].grow(maximumColumnIndex + 1);
694     }
695 }
696
697 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
698 {
699     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
700
701     for (auto row : coordinate.rows) {
702         for (auto column : coordinate.columns)
703             m_grid[row.toInt()][column.toInt()].append(&child);
704     }
705     m_gridItemCoordinate.set(&child, coordinate);
706 }
707
708 void RenderGrid::placeItemsOnGrid()
709 {
710     ASSERT(!gridWasPopulated());
711     ASSERT(m_gridItemCoordinate.isEmpty());
712
713     populateExplicitGridAndOrderIterator();
714
715     Vector<RenderBox*> autoMajorAxisAutoGridItems;
716     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
717     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
718         // FIXME: We never re-resolve positions if the grid is grown during auto-placement which may lead auto / <integer>
719         // positions to not match the author's intent. The specification is unclear on what should be done in this case.
720         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
721         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
722         if (!rowPositions || !columnPositions) {
723             GridSpan* majorAxisPositions = (autoPlacementMajorAxisDirection() == ForColumns) ? columnPositions.get() : rowPositions.get();
724             if (!majorAxisPositions)
725                 autoMajorAxisAutoGridItems.append(child);
726             else
727                 specifiedMajorAxisAutoGridItems.append(child);
728             continue;
729         }
730         insertItemIntoGrid(*child, GridCoordinate(*rowPositions, *columnPositions));
731     }
732
733     ASSERT(gridRowCount() >= style().gridRows().size());
734     ASSERT(gridColumnCount() >= style().gridColumns().size());
735
736     // FIXME: Implement properly "stack" value in auto-placement algorithm.
737     if (style().isGridAutoFlowAlgorithmStack()) {
738         // If we did collect some grid items, they won't be placed thus never laid out.
739         ASSERT(!autoMajorAxisAutoGridItems.size());
740         ASSERT(!specifiedMajorAxisAutoGridItems.size());
741         return;
742     }
743
744     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
745     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
746 }
747
748 void RenderGrid::populateExplicitGridAndOrderIterator()
749 {
750     OrderIteratorPopulator populator(m_orderIterator);
751     size_t maximumRowIndex = std::max<size_t>(1, style().gridRows().size());
752     size_t maximumColumnIndex = std::max<size_t>(1, style().gridColumns().size());
753
754     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
755         populator.collectChild(*child);
756
757         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
758         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
759         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
760
761         // |positions| is 0 if we need to run the auto-placement algorithm.
762         if (rowPositions)
763             maximumRowIndex = std::max(maximumRowIndex, rowPositions->resolvedFinalPosition.next().toInt());
764         else {
765             // Grow the grid for items with a definite row span, getting the largest such span.
766             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
767             maximumRowIndex = std::max<size_t>(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
768         }
769
770         if (columnPositions)
771             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->resolvedFinalPosition.next().toInt());
772         else {
773             // Grow the grid for items with a definite column span, getting the largest such span.
774             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
775             maximumColumnIndex = std::max<size_t>(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
776         }
777     }
778
779     m_grid.grow(maximumRowIndex);
780     for (auto& column : m_grid)
781         column.grow(maximumColumnIndex);
782 }
783
784 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
785 {
786     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
787     const size_t endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
788     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
789     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
790 }
791
792 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
793 {
794     for (auto& autoGridItem : autoGridItems) {
795         std::unique_ptr<GridSpan> majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
796         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
797
798         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->resolvedInitialPosition.toInt());
799         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions->integerSpan(), minorAxisPositions.integerSpan());
800         if (!emptyGridArea)
801             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), *majorAxisPositions);
802         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
803     }
804 }
805
806 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
807 {
808     AutoPlacementCursor autoPlacementCursor = {0, 0};
809     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
810
811     for (auto& autoGridItem : autoGridItems) {
812         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
813
814         if (isGridAutoFlowDense) {
815             autoPlacementCursor.first = 0;
816             autoPlacementCursor.second = 0;
817         }
818     }
819 }
820
821 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
822 {
823     std::unique_ptr<GridSpan> minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
824     ASSERT(!GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()));
825     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
826
827     const size_t endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
828     size_t majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
829     size_t minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
830
831     std::unique_ptr<GridCoordinate> emptyGridArea;
832     if (minorAxisPositions) {
833         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
834         if (minorAxisPositions->resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
835             majorAxisAutoPlacementCursor++;
836
837         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
838             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions->resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
839             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions->integerSpan(), majorAxisPositions.integerSpan());
840         }
841
842         if (!emptyGridArea)
843             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), *minorAxisPositions);
844     } else {
845         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
846
847         for (size_t majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
848             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
849             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
850
851             if (emptyGridArea) {
852                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
853                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
854                 const size_t endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
855                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
856                     break;
857
858                 // Discard empty grid area as it does not fit in the minor axis direction.
859                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
860                 emptyGridArea = nullptr;
861             }
862
863             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
864             minorAxisAutoPlacementCursor = 0;
865         }
866
867         if (!emptyGridArea)
868             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
869     }
870
871     insertItemIntoGrid(gridItem, *emptyGridArea);
872     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
873     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
874 }
875
876 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
877 {
878     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
879 }
880
881 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
882 {
883     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
884 }
885
886 void RenderGrid::clearGrid()
887 {
888     m_grid.clear();
889     m_gridItemCoordinate.clear();
890 }
891
892 void RenderGrid::layoutGridItems()
893 {
894     placeItemsOnGrid();
895
896     GridSizingData sizingData(gridColumnCount(), gridRowCount());
897     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
898     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
899     computeUsedBreadthOfGridTracks(ForRows, sizingData);
900     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
901
902     populateGridPositions(sizingData);
903
904     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
905         // Because the grid area cannot be styled, we don't need to adjust
906         // the grid breadth to account for 'box-sizing'.
907         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
908         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
909
910         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(*child, ForColumns, sizingData.columnTracks);
911         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(*child, ForRows, sizingData.rowTracks);
912         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && child->hasRelativeLogicalHeight()))
913             child->setNeedsLayout(MarkOnlyThis);
914
915         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
916         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
917
918         LayoutRect oldChildRect = child->frameRect();
919
920         // FIXME: Grid items should stretch to fill their cells. Once we
921         // implement grid-{column,row}-align, we can also shrink to fit. For
922         // now, just size as if we were a regular child.
923         child->layoutIfNeeded();
924
925         child->setLogicalLocation(findChildLogicalPosition(*child, sizingData));
926
927         // If the child moved, we have to repaint it as well as any floating/positioned
928         // descendants. An exception is if we need a layout. In this case, we know we're going to
929         // repaint ourselves (and the child) anyway.
930         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
931             child->repaintDuringLayoutIfMoved(oldChildRect);
932     }
933
934     for (auto& row : sizingData.rowTracks)
935         setLogicalHeight(logicalHeight() + row.m_usedBreadth);
936
937     // min / max logical height is handled in updateLogicalHeight().
938     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
939     clearGrid();
940 }
941
942 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
943 {
944     ASSERT(m_gridItemCoordinate.contains(&gridItem));
945     return m_gridItemCoordinate.get(&gridItem);
946 }
947
948 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
949 {
950     const GridCoordinate& coordinate = cachedGridCoordinate(child);
951     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
952     LayoutUnit gridAreaBreadth = 0;
953     for (auto trackPosition : span)
954         gridAreaBreadth += tracks[trackPosition.toInt()].m_usedBreadth;
955     return gridAreaBreadth;
956 }
957
958 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
959 {
960     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
961     m_columnPositions[0] = borderAndPaddingStart();
962     for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
963         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
964
965     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
966     m_rowPositions[0] = borderAndPaddingBefore();
967     for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
968         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
969 }
970
971 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox& child, const GridSizingData& sizingData)
972 {
973     const GridCoordinate& coordinate = cachedGridCoordinate(child);
974     ASSERT_UNUSED(sizingData, coordinate.columns.resolvedInitialPosition.toInt() < sizingData.columnTracks.size());
975     ASSERT_UNUSED(sizingData, coordinate.rows.resolvedInitialPosition.toInt() < sizingData.rowTracks.size());
976
977     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
978     return LayoutPoint(m_columnPositions[coordinate.columns.resolvedInitialPosition.toInt()] + marginStartForChild(child), m_rowPositions[coordinate.rows.resolvedInitialPosition.toInt()] + marginBeforeForChild(child));
979 }
980
981 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
982 {
983     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
984         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect);
985 }
986
987 const char* RenderGrid::renderName() const
988 {
989     if (isFloating())
990         return "RenderGrid (floating)";
991     if (isOutOfFlowPositioned())
992         return "RenderGrid (positioned)";
993     if (isAnonymous())
994         return "RenderGrid (generated)";
995     if (isRelPositioned())
996         return "RenderGrid (relative positioned)";
997     return "RenderGrid";
998 }
999
1000 } // namespace WebCore
1001
1002 #endif /* ENABLE(CSS_GRID_LAYOUT) */