[CSS Grid Layout] Remove stack from grid-auto-flow syntax
[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, unsigned fixedTrackIndex, unsigned 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         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
109         const unsigned 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(unsigned rowSpan, unsigned columnSpan) const
121     {
122         // Ignore cells outside current grid as we will grow it later if needed.
123         unsigned maxRows = std::min<unsigned>(m_rowIndex + rowSpan, m_grid.size());
124         unsigned maxColumns = std::min<unsigned>(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 (unsigned row = m_rowIndex; row < maxRows; ++row) {
128             for (unsigned 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(unsigned fixedTrackSpan, unsigned varyingTrackSpan)
139     {
140         ASSERT(fixedTrackSpan >= 1 && varyingTrackSpan >= 1);
141
142         if (m_grid.isEmpty())
143             return nullptr;
144
145         unsigned rowSpan = (m_direction == ForColumns) ? varyingTrackSpan : fixedTrackSpan;
146         unsigned columnSpan = (m_direction == ForColumns) ? fixedTrackSpan : varyingTrackSpan;
147
148         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
149         const unsigned 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     unsigned m_rowIndex;
165     unsigned m_columnIndex;
166     unsigned m_childIndex;
167 };
168
169 class RenderGrid::GridSizingData {
170     WTF_MAKE_NONCOPYABLE(GridSizingData);
171 public:
172     GridSizingData(unsigned gridColumnCount, unsigned gridRowCount)
173         : columnTracks(gridColumnCount)
174         , rowTracks(gridRowCount)
175     {
176     }
177
178     Vector<GridTrack> columnTracks;
179     Vector<GridTrack> rowTracks;
180     Vector<unsigned> 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     Vector<unsigned> growAboveMaxBreadthTrackIndexes;
186 };
187
188 RenderGrid::RenderGrid(Element& element, Ref<RenderStyle>&& style)
189     : RenderBlock(element, WTF::move(style), 0)
190     , m_orderIterator(*this)
191 {
192     // All of our children must be block level.
193     setChildrenInline(false);
194 }
195
196 RenderGrid::~RenderGrid()
197 {
198 }
199
200 void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
201 {
202     ASSERT(needsLayout());
203
204     if (!relayoutChildren && simplifiedLayout())
205         return;
206
207     // FIXME: Much of this method is boiler plate that matches RenderBox::layoutBlock and Render*FlexibleBox::layoutBlock.
208     // It would be nice to refactor some of the duplicate code.
209     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
210     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
211
212     preparePaginationBeforeBlockLayout(relayoutChildren);
213
214     LayoutSize previousSize = size();
215
216     setLogicalHeight(0);
217     updateLogicalWidth();
218
219     layoutGridItems();
220
221     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
222     updateLogicalHeight();
223
224     if (size() != previousSize)
225         relayoutChildren = true;
226
227     layoutPositionedObjects(relayoutChildren || isRoot());
228
229     computeOverflow(oldClientAfterEdge);
230     statePusher.pop();
231
232     updateLayerTransform();
233
234     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
235     // we overflow or not.
236     updateScrollInfoAfterLayout();
237
238     repainter.repaintAfterLayout();
239
240     clearNeedsLayout();
241 }
242
243 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
244 {
245     bool wasPopulated = gridWasPopulated();
246     if (!wasPopulated)
247         const_cast<RenderGrid*>(this)->placeItemsOnGrid();
248
249     GridSizingData sizingData(gridColumnCount(), gridRowCount());
250     LayoutUnit availableLogicalSpace = 0;
251     const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
252
253     for (auto& column : sizingData.columnTracks) {
254         LayoutUnit minTrackBreadth = column.m_usedBreadth;
255         LayoutUnit maxTrackBreadth = column.m_maxBreadth;
256         maxTrackBreadth = std::max(maxTrackBreadth, minTrackBreadth);
257
258         minLogicalWidth += minTrackBreadth;
259         maxLogicalWidth += maxTrackBreadth;
260
261         // FIXME: This should add in the scrollbarWidth (e.g. see RenderFlexibleBox).
262     }
263
264     if (!wasPopulated)
265         const_cast<RenderGrid*>(this)->clearGrid();
266 }
267
268 void RenderGrid::computePreferredLogicalWidths()
269 {
270     ASSERT(preferredLogicalWidthsDirty());
271
272     m_minPreferredLogicalWidth = 0;
273     m_maxPreferredLogicalWidth = 0;
274
275     // FIXME: We don't take our own logical width into account. Once we do, we need to make sure
276     // we apply (and test the interaction with) min-width / max-width.
277
278     computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
279
280     LayoutUnit borderAndPaddingInInlineDirection = borderAndPaddingLogicalWidth();
281     m_minPreferredLogicalWidth += borderAndPaddingInInlineDirection;
282     m_maxPreferredLogicalWidth += borderAndPaddingInInlineDirection;
283
284     setPreferredLogicalWidthsDirty(false);
285 }
286
287 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
288 {
289     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
290     computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
291 }
292
293 bool RenderGrid::gridElementIsShrinkToFit()
294 {
295     return isFloatingOrOutOfFlowPositioned();
296 }
297
298 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
299 {
300     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
301     Vector<unsigned> flexibleSizedTracksIndex;
302     sizingData.contentSizedTracksIndex.shrink(0);
303
304     // 1. Initialize per Grid track variables.
305     for (unsigned i = 0; i < tracks.size(); ++i) {
306         GridTrack& track = tracks[i];
307         const GridTrackSize& trackSize = gridTrackSize(direction, i);
308         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
309         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
310
311         track.m_usedBreadth = computeUsedBreadthOfMinLength(direction, minTrackBreadth);
312         track.m_maxBreadth = computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.m_usedBreadth);
313
314         if (track.m_maxBreadth != infinity)
315             track.m_maxBreadth = std::max(track.m_maxBreadth, track.m_usedBreadth);
316
317         if (trackSize.isContentSized())
318             sizingData.contentSizedTracksIndex.append(i);
319         if (trackSize.maxTrackBreadth().isFlex())
320             flexibleSizedTracksIndex.append(i);
321     }
322
323     // 2. Resolve content-based TrackSizingFunctions.
324     if (!sizingData.contentSizedTracksIndex.isEmpty())
325         resolveContentBasedTrackSizingFunctions(direction, sizingData);
326
327     for (auto& track : tracks) {
328         ASSERT(track.m_maxBreadth != infinity);
329         availableLogicalSpace -= track.m_usedBreadth;
330     }
331
332     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
333
334     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
335         return;
336
337     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until
338     // availableLogicalSpace (RemainingSpace in the specs) is exhausted.
339     if (!hasUndefinedRemainingSpace) {
340         const unsigned tracksSize = tracks.size();
341         Vector<GridTrack*> tracksForDistribution(tracksSize);
342         for (unsigned i = 0; i < tracksSize; ++i)
343             tracksForDistribution[i] = tracks.data() + i;
344
345         distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
346     } else {
347         for (auto& track : tracks)
348             track.m_usedBreadth = track.m_maxBreadth;
349     }
350
351     if (flexibleSizedTracksIndex.isEmpty())
352         return;
353
354     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
355     double normalizedFractionBreadth = 0;
356     if (!hasUndefinedRemainingSpace)
357         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, availableLogicalSpace);
358     else {
359         for (auto trackIndex : flexibleSizedTracksIndex) {
360             const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
361             normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].m_usedBreadth / trackSize.maxTrackBreadth().flex());
362         }
363
364         for (unsigned i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
365             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
366             while (RenderBox* gridItem = iterator.nextGridItem()) {
367                 const GridCoordinate coordinate = cachedGridCoordinate(*gridItem);
368                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
369
370                 // Do not include already processed items.
371                 if (i > 0 && span.resolvedInitialPosition.toInt() <= flexibleSizedTracksIndex[i - 1])
372                     continue;
373
374                 double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(*gridItem, direction, sizingData.columnTracks));
375                 normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
376             }
377         }
378     }
379
380     for (auto trackIndex : flexibleSizedTracksIndex) {
381         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
382         GridTrack& track = tracks[trackIndex];
383         track.m_usedBreadth = std::max<LayoutUnit>(track.m_usedBreadth, normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
384     }
385 }
386
387 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
388 {
389     if (gridLength.isFlex())
390         return 0;
391
392     const Length& trackLength = gridLength.length();
393     ASSERT(!trackLength.isAuto());
394     if (trackLength.isSpecified())
395         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
396
397     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
398     return 0;
399 }
400
401 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
402 {
403     if (gridLength.isFlex())
404         return usedBreadth;
405
406     const Length& trackLength = gridLength.length();
407     ASSERT(!trackLength.isAuto());
408     if (trackLength.isSpecified()) {
409         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
410         ASSERT(computedBreadth != infinity);
411         return computedBreadth;
412     }
413
414     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
415     return infinity;
416 }
417
418 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
419 {
420     ASSERT(trackLength.isSpecified());
421     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style().logicalHeight()));
422 }
423
424 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
425 {
426     // |availableLogicalSpace| already accounts for the used breadths so no need to remove it here.
427
428     Vector<GridTrackForNormalization> tracksForNormalization;
429     for (auto& position : tracksSpan) {
430         const GridTrackSize& trackSize = gridTrackSize(direction, position.toInt());
431         if (!trackSize.maxTrackBreadth().isFlex())
432             continue;
433
434         tracksForNormalization.append(GridTrackForNormalization(tracks[position.toInt()], trackSize.maxTrackBreadth().flex()));
435     }
436
437     // The function is not called if we don't have <flex> grid tracks
438     ASSERT(!tracksForNormalization.isEmpty());
439
440     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
441               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
442                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
443               });
444
445     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
446     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
447     // fit into availableLogicalSpaceIgnoringFractionTracks.
448     double accumulatedFractions = 0;
449     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
450     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = availableLogicalSpace;
451
452     for (auto& track : tracksForNormalization) {
453         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
454             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
455             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
456             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
457                 break;
458
459             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
460         }
461
462         accumulatedFractions += track.m_flex;
463         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
464         availableLogicalSpaceIgnoringFractionTracks += track.m_track->m_usedBreadth;
465     }
466
467     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
468 }
469
470 GridTrackSize RenderGrid::gridTrackSize(GridTrackSizingDirection direction, unsigned i) const
471 {
472     bool isForColumns = (direction == ForColumns);
473     auto& trackStyles =  isForColumns ? style().gridColumns() : style().gridRows();
474     auto& trackSize = (i >= trackStyles.size()) ? (isForColumns ? style().gridAutoColumns() : style().gridAutoRows()) : trackStyles[i];
475
476     // If the logical width/height of the grid container is indefinite, percentage values are treated as <auto> (or in
477     // the case of minmax() as min-content for the first position and max-content for the second).
478     Length logicalSize = isForColumns ? style().logicalWidth() : style().logicalHeight();
479     if (logicalSize.isIntrinsicOrAuto()) {
480         const GridLength& oldMinTrackBreadth = trackSize.minTrackBreadth();
481         const GridLength& oldMaxTrackBreadth = trackSize.maxTrackBreadth();
482         return GridTrackSize(oldMinTrackBreadth.isPercentage() ? Length(MinContent) : oldMinTrackBreadth, oldMaxTrackBreadth.isPercentage() ? Length(MaxContent) : oldMaxTrackBreadth);
483     }
484
485     return trackSize;
486 }
487
488 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox& child, Vector<GridTrack>& columnTracks)
489 {
490     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
491     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
492     if (child.style().logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
493         child.setNeedsLayout(MarkOnlyThis);
494
495     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
496     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
497     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
498     child.setOverrideContainingBlockContentLogicalHeight(-1);
499     child.layoutIfNeeded();
500     return child.logicalHeight() + child.marginLogicalHeight();
501 }
502
503 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
504 {
505     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
506     // FIXME: Properly support orthogonal writing mode.
507     if (hasOrthogonalWritingMode)
508         return 0;
509
510     if (direction == ForColumns) {
511         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
512         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
513         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
514     }
515
516     return logicalContentHeightForChild(child, columnTracks);
517 }
518
519 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
520 {
521     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
522     // FIXME: Properly support orthogonal writing mode.
523     if (hasOrthogonalWritingMode)
524         return LayoutUnit();
525
526     if (direction == ForColumns) {
527         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
528         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
529         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
530     }
531
532     return logicalContentHeightForChild(child, columnTracks);
533 }
534
535 class GridItemWithSpan {
536 public:
537     GridItemWithSpan(RenderBox& gridItem, GridCoordinate coordinate, GridTrackSizingDirection direction)
538         : m_gridItem(gridItem)
539         , m_coordinate(coordinate)
540     {
541         const GridSpan& span = (direction == ForRows) ? coordinate.rows : coordinate.columns;
542         m_span = span.resolvedFinalPosition.toInt() - span.resolvedInitialPosition.toInt() + 1;
543     }
544
545     RenderBox& gridItem() const { return m_gridItem; }
546     GridCoordinate coordinate() const { return m_coordinate; }
547
548     bool operator<(const GridItemWithSpan other) const
549     {
550         return m_span < other.m_span;
551     }
552
553 private:
554     std::reference_wrapper<RenderBox> m_gridItem;
555     GridCoordinate m_coordinate;
556     unsigned m_span;
557 };
558
559 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
560 {
561     // FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track.
562
563     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
564         GridIterator iterator(m_grid, direction, trackIndex);
565         HashSet<RenderBox*> itemsSet;
566         Vector<GridItemWithSpan> itemsSortedByIncreasingSpan;
567
568         while (RenderBox* gridItem = iterator.nextGridItem()) {
569             if (itemsSet.add(gridItem).isNewEntry)
570                 itemsSortedByIncreasingSpan.append(GridItemWithSpan(*gridItem, cachedGridCoordinate(*gridItem), direction));
571         }
572         std::stable_sort(itemsSortedByIncreasingSpan.begin(), itemsSortedByIncreasingSpan.end());
573
574         for (auto& itemWithSpan : itemsSortedByIncreasingSpan) {
575             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, &GridTrackSize::hasMinContentMinTrackBreadthAndMinOrMaxContentMaxTrackBreadth);
576             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, &GridTrackSize::hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth);
577             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
578             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, itemWithSpan, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
579         }
580
581         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
582         if (track.m_maxBreadth == infinity)
583             track.m_maxBreadth = track.m_usedBreadth;
584     }
585 }
586
587 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, GridItemWithSpan& gridItemWithSpan, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, FilterFunction growAboveMaxBreadthFilterFunction)
588 {
589     const GridCoordinate& coordinate = gridItemWithSpan.coordinate();
590     const GridResolvedPosition initialTrackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
591     const GridResolvedPosition finalTrackPosition = (direction == ForColumns) ? coordinate.columns.resolvedFinalPosition : coordinate.rows.resolvedFinalPosition;
592
593     sizingData.filteredTracks.shrink(0);
594     sizingData.growAboveMaxBreadthTrackIndexes.shrink(0);
595     for (GridResolvedPosition trackIndex = initialTrackPosition; trackIndex <= finalTrackPosition; ++trackIndex) {
596         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex.toInt());
597         if (!(trackSize.*filterFunction)())
598             continue;
599
600         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex.toInt()] : sizingData.rowTracks[trackIndex.toInt()];
601         sizingData.filteredTracks.append(&track);
602
603         if (growAboveMaxBreadthFilterFunction && (trackSize.*growAboveMaxBreadthFilterFunction)())
604             sizingData.growAboveMaxBreadthTrackIndexes.append(sizingData.filteredTracks.size() - 1);
605     }
606
607     if (sizingData.filteredTracks.isEmpty())
608         return;
609
610     LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItemWithSpan.gridItem(), direction, sizingData.columnTracks);
611     for (GridResolvedPosition trackPositionForSpace = initialTrackPosition; trackPositionForSpace <= finalTrackPosition; ++trackPositionForSpace) {
612         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPositionForSpace.toInt()] : sizingData.rowTracks[trackPositionForSpace.toInt()];
613         additionalBreadthSpace -= (track.*trackGetter)();
614     }
615
616     // Specs mandate to floor additionalBreadthSpace (extra-space in specs) to 0. Instead we directly avoid the function
617     // call in those cases as it will be a noop in terms of track sizing.
618     if (additionalBreadthSpace > 0)
619         distributeSpaceToTracks(sizingData.filteredTracks, &sizingData.growAboveMaxBreadthTrackIndexes, trackGetter, trackGrowthFunction, sizingData, additionalBreadthSpace);
620 }
621
622 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
623 {
624     // This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
625     // (forall x: NOT x < x).
626     if (track1->m_maxBreadth == infinity && track2->m_maxBreadth == infinity)
627         return false;
628
629     if (track1->m_maxBreadth == infinity || track2->m_maxBreadth == infinity)
630         return track2->m_maxBreadth == infinity;
631
632     return (track1->m_maxBreadth - track1->m_usedBreadth) < (track2->m_maxBreadth - track2->m_usedBreadth);
633 }
634
635 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<unsigned>* growAboveMaxBreadthTrackIndexes, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
636 {
637     ASSERT(availableLogicalSpace > 0);
638     std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
639
640     unsigned tracksSize = tracks.size();
641     sizingData.distributeTrackVector.resize(tracksSize);
642
643     for (unsigned i = 0; i < tracksSize; ++i) {
644         GridTrack& track = *tracks[i];
645         LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
646         bool infiniteGrowthPotential = track.m_maxBreadth == infinity;
647         LayoutUnit trackGrowthPotential = infiniteGrowthPotential ? track.m_maxBreadth : track.m_maxBreadth - trackBreadth;
648         sizingData.distributeTrackVector[i] = trackBreadth;
649         // Let's avoid computing availableLogicalSpaceShare as much as possible as it's a hot spot in performance tests.
650         if (trackGrowthPotential > 0 || infiniteGrowthPotential) {
651             LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
652             LayoutUnit growthShare = infiniteGrowthPotential ? availableLogicalSpaceShare : std::min(availableLogicalSpaceShare, trackGrowthPotential);
653             ASSERT_WITH_MESSAGE(growthShare >= 0, "We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function. We can still have 0 as growthShare if the amount of tracks greatly exceeds the availableLogicalSpace.");
654             sizingData.distributeTrackVector[i] += growthShare;
655             availableLogicalSpace -= growthShare;
656         }
657     }
658
659     if (availableLogicalSpace > 0 && growAboveMaxBreadthTrackIndexes) {
660         unsigned indexesSize = growAboveMaxBreadthTrackIndexes->size();
661         unsigned tracksGrowingAboveMaxBreadthSize = indexesSize ? indexesSize : tracksSize;
662         // If we have a non-null empty vector of track indexes to grow above max breadth means that we should grow all
663         // affected tracks.
664         for (unsigned i = 0; i < tracksGrowingAboveMaxBreadthSize; ++i) {
665             LayoutUnit growthShare = availableLogicalSpace / (tracksGrowingAboveMaxBreadthSize - i);
666             unsigned distributeTrackIndex = indexesSize ? growAboveMaxBreadthTrackIndexes->at(i) : i;
667             sizingData.distributeTrackVector[distributeTrackIndex] += growthShare;
668             availableLogicalSpace -= growthShare;
669         }
670     }
671
672     for (unsigned i = 0; i < tracksSize; ++i) {
673         LayoutUnit growth = sizingData.distributeTrackVector[i] - (tracks[i]->*trackGetter)();
674         if (growth >= 0)
675             (tracks[i]->*trackGrowthFunction)(growth);
676     }
677 }
678
679 #ifndef NDEBUG
680 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
681 {
682     for (unsigned i = 0; i < tracks.size(); ++i) {
683         const GridTrackSize& trackSize = gridTrackSize(direction, i);
684         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
685         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].m_usedBreadth)
686             return false;
687     }
688     return true;
689 }
690 #endif
691
692 void RenderGrid::ensureGridSize(unsigned maximumRowIndex, unsigned maximumColumnIndex)
693 {
694     const unsigned oldRowCount = gridRowCount();
695     if (maximumRowIndex >= oldRowCount) {
696         m_grid.grow(maximumRowIndex + 1);
697         for (unsigned row = oldRowCount; row < gridRowCount(); ++row)
698             m_grid[row].grow(gridColumnCount());
699     }
700
701     if (maximumColumnIndex >= gridColumnCount()) {
702         for (unsigned row = 0; row < gridRowCount(); ++row)
703             m_grid[row].grow(maximumColumnIndex + 1);
704     }
705 }
706
707 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
708 {
709     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
710
711     for (auto& row : coordinate.rows) {
712         for (auto& column : coordinate.columns)
713             m_grid[row.toInt()][column.toInt()].append(&child);
714     }
715     m_gridItemCoordinate.set(&child, coordinate);
716 }
717
718 void RenderGrid::placeItemsOnGrid()
719 {
720     ASSERT(!gridWasPopulated());
721     ASSERT(m_gridItemCoordinate.isEmpty());
722
723     populateExplicitGridAndOrderIterator();
724
725     Vector<RenderBox*> autoMajorAxisAutoGridItems;
726     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
727     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
728         // FIXME: We never re-resolve positions if the grid is grown during auto-placement which may lead auto / <integer>
729         // positions to not match the author's intent. The specification is unclear on what should be done in this case.
730         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
731         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
732         if (!rowPositions || !columnPositions) {
733             GridSpan* majorAxisPositions = (autoPlacementMajorAxisDirection() == ForColumns) ? columnPositions.get() : rowPositions.get();
734             if (!majorAxisPositions)
735                 autoMajorAxisAutoGridItems.append(child);
736             else
737                 specifiedMajorAxisAutoGridItems.append(child);
738             continue;
739         }
740         insertItemIntoGrid(*child, GridCoordinate(*rowPositions, *columnPositions));
741     }
742
743     ASSERT(gridRowCount() >= GridResolvedPosition::explicitGridRowCount(style()));
744     ASSERT(gridColumnCount() >= GridResolvedPosition::explicitGridColumnCount(style()));
745
746     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
747     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
748 }
749
750 void RenderGrid::populateExplicitGridAndOrderIterator()
751 {
752     OrderIteratorPopulator populator(m_orderIterator);
753     unsigned maximumRowIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridRowCount(style()));
754     unsigned maximumColumnIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridColumnCount(style()));
755
756     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
757         populator.collectChild(*child);
758
759         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
760         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
761         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
762
763         // |positions| is 0 if we need to run the auto-placement algorithm.
764         if (rowPositions)
765             maximumRowIndex = std::max(maximumRowIndex, rowPositions->resolvedFinalPosition.next().toInt());
766         else {
767             // Grow the grid for items with a definite row span, getting the largest such span.
768             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
769             maximumRowIndex = std::max(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
770         }
771
772         if (columnPositions)
773             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->resolvedFinalPosition.next().toInt());
774         else {
775             // Grow the grid for items with a definite column span, getting the largest such span.
776             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
777             maximumColumnIndex = std::max(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
778         }
779     }
780
781     m_grid.grow(maximumRowIndex);
782     for (auto& column : m_grid)
783         column.grow(maximumColumnIndex);
784 }
785
786 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
787 {
788     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
789     const unsigned endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
790     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
791     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
792 }
793
794 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
795 {
796     for (auto& autoGridItem : autoGridItems) {
797         std::unique_ptr<GridSpan> majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
798         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
799
800         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->resolvedInitialPosition.toInt());
801         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions->integerSpan(), minorAxisPositions.integerSpan());
802         if (!emptyGridArea)
803             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), *majorAxisPositions);
804         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
805     }
806 }
807
808 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
809 {
810     AutoPlacementCursor autoPlacementCursor = {0, 0};
811     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
812
813     for (auto& autoGridItem : autoGridItems) {
814         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
815
816         if (isGridAutoFlowDense) {
817             autoPlacementCursor.first = 0;
818             autoPlacementCursor.second = 0;
819         }
820     }
821 }
822
823 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
824 {
825     std::unique_ptr<GridSpan> minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
826     ASSERT(!GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()));
827     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
828
829     const unsigned endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
830     unsigned majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
831     unsigned minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
832
833     std::unique_ptr<GridCoordinate> emptyGridArea;
834     if (minorAxisPositions) {
835         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
836         if (minorAxisPositions->resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
837             majorAxisAutoPlacementCursor++;
838
839         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
840             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions->resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
841             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions->integerSpan(), majorAxisPositions.integerSpan());
842         }
843
844         if (!emptyGridArea)
845             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), *minorAxisPositions);
846     } else {
847         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
848
849         for (unsigned majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
850             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
851             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
852
853             if (emptyGridArea) {
854                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
855                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
856                 const unsigned endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
857                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
858                     break;
859
860                 // Discard empty grid area as it does not fit in the minor axis direction.
861                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
862                 emptyGridArea = nullptr;
863             }
864
865             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
866             minorAxisAutoPlacementCursor = 0;
867         }
868
869         if (!emptyGridArea)
870             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
871     }
872
873     insertItemIntoGrid(gridItem, *emptyGridArea);
874     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
875     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
876 }
877
878 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
879 {
880     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
881 }
882
883 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
884 {
885     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
886 }
887
888 void RenderGrid::clearGrid()
889 {
890     m_grid.clear();
891     m_gridItemCoordinate.clear();
892 }
893
894 void RenderGrid::layoutGridItems()
895 {
896     placeItemsOnGrid();
897
898     GridSizingData sizingData(gridColumnCount(), gridRowCount());
899     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
900     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
901     computeUsedBreadthOfGridTracks(ForRows, sizingData);
902     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
903
904     populateGridPositions(sizingData);
905
906     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
907         // Because the grid area cannot be styled, we don't need to adjust
908         // the grid breadth to account for 'box-sizing'.
909         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
910         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
911
912         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(*child, ForColumns, sizingData.columnTracks);
913         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(*child, ForRows, sizingData.rowTracks);
914         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && child->hasRelativeLogicalHeight()))
915             child->setNeedsLayout(MarkOnlyThis);
916
917         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
918         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
919
920         LayoutRect oldChildRect = child->frameRect();
921
922         // FIXME: Grid items should stretch to fill their cells. Once we
923         // implement grid-{column,row}-align, we can also shrink to fit. For
924         // now, just size as if we were a regular child.
925         child->layoutIfNeeded();
926
927         child->setLogicalLocation(findChildLogicalPosition(*child, sizingData));
928
929         // If the child moved, we have to repaint it as well as any floating/positioned
930         // descendants. An exception is if we need a layout. In this case, we know we're going to
931         // repaint ourselves (and the child) anyway.
932         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
933             child->repaintDuringLayoutIfMoved(oldChildRect);
934     }
935
936     for (auto& row : sizingData.rowTracks)
937         setLogicalHeight(logicalHeight() + row.m_usedBreadth);
938
939     // min / max logical height is handled in updateLogicalHeight().
940     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
941     clearGrid();
942 }
943
944 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
945 {
946     ASSERT(m_gridItemCoordinate.contains(&gridItem));
947     return m_gridItemCoordinate.get(&gridItem);
948 }
949
950 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
951 {
952     const GridCoordinate& coordinate = cachedGridCoordinate(child);
953     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
954     LayoutUnit gridAreaBreadth = 0;
955     for (auto& trackPosition : span)
956         gridAreaBreadth += tracks[trackPosition.toInt()].m_usedBreadth;
957     return gridAreaBreadth;
958 }
959
960 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
961 {
962     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
963     m_columnPositions[0] = borderAndPaddingStart();
964     for (unsigned i = 0; i < m_columnPositions.size() - 1; ++i)
965         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
966
967     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
968     m_rowPositions[0] = borderAndPaddingBefore();
969     for (unsigned i = 0; i < m_rowPositions.size() - 1; ++i)
970         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
971 }
972
973 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox& child, const GridSizingData& sizingData)
974 {
975     const GridCoordinate& coordinate = cachedGridCoordinate(child);
976     ASSERT_UNUSED(sizingData, coordinate.columns.resolvedInitialPosition.toInt() < sizingData.columnTracks.size());
977     ASSERT_UNUSED(sizingData, coordinate.rows.resolvedInitialPosition.toInt() < sizingData.rowTracks.size());
978
979     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
980     return LayoutPoint(m_columnPositions[coordinate.columns.resolvedInitialPosition.toInt()] + marginStartForChild(child), m_rowPositions[coordinate.rows.resolvedInitialPosition.toInt()] + marginBeforeForChild(child));
981 }
982
983 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
984 {
985     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
986         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect);
987 }
988
989 const char* RenderGrid::renderName() const
990 {
991     if (isFloating())
992         return "RenderGrid (floating)";
993     if (isOutOfFlowPositioned())
994         return "RenderGrid (positioned)";
995     if (isAnonymous())
996         return "RenderGrid (generated)";
997     if (isRelPositioned())
998         return "RenderGrid (relative positioned)";
999     return "RenderGrid";
1000 }
1001
1002 } // namespace WebCore
1003
1004 #endif /* ENABLE(CSS_GRID_LAYOUT) */