[CSS Grid Layout] Performance optimization: avoid computing overflow alignment if...
[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
47     const LayoutUnit& baseSize() const
48     {
49         ASSERT(isGrowthLimitBiggerThanBaseSize());
50         return m_baseSize;
51     }
52
53     const LayoutUnit& growthLimit() const
54     {
55         ASSERT(isGrowthLimitBiggerThanBaseSize());
56         return m_growthLimit;
57     }
58
59     void setBaseSize(LayoutUnit baseSize)
60     {
61         m_baseSize = baseSize;
62         ensureGrowthLimitIsBiggerThanBaseSize();
63     }
64
65     void setGrowthLimit(LayoutUnit growthLimit)
66     {
67         m_growthLimit = growthLimit;
68         ensureGrowthLimitIsBiggerThanBaseSize();
69     }
70
71     bool growthLimitIsInfinite() const
72     {
73         return m_growthLimit == infinity;
74     }
75
76     bool infiniteGrowthPotential() const
77     {
78         return growthLimitIsInfinite() || m_infinitelyGrowable;
79     }
80
81     const LayoutUnit& growthLimitIfNotInfinite() const
82     {
83         ASSERT(isGrowthLimitBiggerThanBaseSize());
84         return (m_growthLimit == infinity) ? m_baseSize : m_growthLimit;
85     }
86
87     const LayoutUnit& plannedSize() const { return m_plannedSize; }
88
89     void setPlannedSize(LayoutUnit plannedSize)
90     {
91         m_plannedSize = plannedSize;
92     }
93
94     LayoutUnit& tempSize() { return m_tempSize; }
95
96     bool infinitelyGrowable() const { return m_infinitelyGrowable; }
97
98     void setInfinitelyGrowable(bool infinitelyGrowable)
99     {
100         m_infinitelyGrowable = infinitelyGrowable;
101     }
102
103 private:
104     bool isGrowthLimitBiggerThanBaseSize() const { return growthLimitIsInfinite() || m_growthLimit >= m_baseSize; }
105
106     void ensureGrowthLimitIsBiggerThanBaseSize()
107     {
108         if (m_growthLimit != infinity && m_growthLimit < m_baseSize)
109             m_growthLimit = m_baseSize;
110     }
111
112     LayoutUnit m_baseSize { 0 };
113     LayoutUnit m_growthLimit { 0 };
114     LayoutUnit m_plannedSize { 0 };
115     LayoutUnit m_tempSize { 0 };
116     bool m_infinitelyGrowable { false };
117 };
118
119 struct GridTrackForNormalization {
120     GridTrackForNormalization(const GridTrack& track, double flex)
121         : m_track(&track)
122         , m_flex(flex)
123         , m_normalizedFlexValue(track.baseSize() / flex)
124     {
125     }
126
127     const GridTrack* m_track;
128     double m_flex;
129     LayoutUnit m_normalizedFlexValue;
130 };
131
132 class RenderGrid::GridIterator {
133     WTF_MAKE_NONCOPYABLE(GridIterator);
134 public:
135     // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
136     // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
137     GridIterator(const Vector<Vector<Vector<RenderBox*, 1>>>& grid, GridTrackSizingDirection direction, unsigned fixedTrackIndex, unsigned varyingTrackIndex = 0)
138         : m_grid(grid)
139         , m_direction(direction)
140         , m_rowIndex((direction == ForColumns) ? varyingTrackIndex : fixedTrackIndex)
141         , m_columnIndex((direction == ForColumns) ? fixedTrackIndex : varyingTrackIndex)
142         , m_childIndex(0)
143     {
144         ASSERT(m_rowIndex < m_grid.size());
145         ASSERT(m_columnIndex < m_grid[0].size());
146     }
147
148     RenderBox* nextGridItem()
149     {
150         if (!m_grid.size())
151             return 0;
152
153         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
154         const unsigned endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
155         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
156             const auto& children = m_grid[m_rowIndex][m_columnIndex];
157             if (m_childIndex < children.size())
158                 return children[m_childIndex++];
159
160             m_childIndex = 0;
161         }
162         return 0;
163     }
164
165     bool isEmptyAreaEnough(unsigned rowSpan, unsigned columnSpan) const
166     {
167         // Ignore cells outside current grid as we will grow it later if needed.
168         unsigned maxRows = std::min<unsigned>(m_rowIndex + rowSpan, m_grid.size());
169         unsigned maxColumns = std::min<unsigned>(m_columnIndex + columnSpan, m_grid[0].size());
170
171         // This adds a O(N^2) behavior that shouldn't be a big deal as we expect spanning areas to be small.
172         for (unsigned row = m_rowIndex; row < maxRows; ++row) {
173             for (unsigned column = m_columnIndex; column < maxColumns; ++column) {
174                 auto& children = m_grid[row][column];
175                 if (!children.isEmpty())
176                     return false;
177             }
178         }
179
180         return true;
181     }
182
183     std::unique_ptr<GridCoordinate> nextEmptyGridArea(unsigned fixedTrackSpan, unsigned varyingTrackSpan)
184     {
185         ASSERT(fixedTrackSpan >= 1 && varyingTrackSpan >= 1);
186
187         if (m_grid.isEmpty())
188             return nullptr;
189
190         unsigned rowSpan = (m_direction == ForColumns) ? varyingTrackSpan : fixedTrackSpan;
191         unsigned columnSpan = (m_direction == ForColumns) ? fixedTrackSpan : varyingTrackSpan;
192
193         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
194         const unsigned endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
195         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
196             if (isEmptyAreaEnough(rowSpan, columnSpan)) {
197                 std::unique_ptr<GridCoordinate> result = std::make_unique<GridCoordinate>(GridSpan(m_rowIndex, m_rowIndex + rowSpan - 1), GridSpan(m_columnIndex, m_columnIndex + columnSpan - 1));
198                 // Advance the iterator to avoid an infinite loop where we would return the same grid area over and over.
199                 ++varyingTrackIndex;
200                 return result;
201             }
202         }
203         return nullptr;
204     }
205
206 private:
207     const Vector<Vector<Vector<RenderBox*, 1>>>& m_grid;
208     GridTrackSizingDirection m_direction;
209     unsigned m_rowIndex;
210     unsigned m_columnIndex;
211     unsigned m_childIndex;
212 };
213
214 class RenderGrid::GridSizingData {
215     WTF_MAKE_NONCOPYABLE(GridSizingData);
216 public:
217     GridSizingData(unsigned gridColumnCount, unsigned gridRowCount)
218         : columnTracks(gridColumnCount)
219         , rowTracks(gridRowCount)
220     {
221     }
222
223     Vector<GridTrack> columnTracks;
224     Vector<GridTrack> rowTracks;
225     Vector<unsigned> contentSizedTracksIndex;
226
227     // Performance optimization: hold onto these Vectors until the end of Layout to avoid repeated malloc / free.
228     Vector<GridTrack*> filteredTracks;
229     Vector<GridTrack*> growBeyondGrowthLimitsTracks;
230     Vector<GridItemWithSpan> itemsSortedByIncreasingSpan;
231 };
232
233 RenderGrid::RenderGrid(Element& element, Ref<RenderStyle>&& style)
234     : RenderBlock(element, WTF::move(style), 0)
235     , m_orderIterator(*this)
236 {
237     // All of our children must be block level.
238     setChildrenInline(false);
239 }
240
241 RenderGrid::~RenderGrid()
242 {
243 }
244
245 void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
246 {
247     ASSERT(needsLayout());
248
249     if (!relayoutChildren && simplifiedLayout())
250         return;
251
252     // FIXME: Much of this method is boiler plate that matches RenderBox::layoutBlock and Render*FlexibleBox::layoutBlock.
253     // It would be nice to refactor some of the duplicate code.
254     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
255     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
256
257     preparePaginationBeforeBlockLayout(relayoutChildren);
258
259     LayoutSize previousSize = size();
260
261     setLogicalHeight(0);
262     updateLogicalWidth();
263
264     layoutGridItems();
265
266     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
267     updateLogicalHeight();
268
269     if (size() != previousSize)
270         relayoutChildren = true;
271
272     layoutPositionedObjects(relayoutChildren || isRoot());
273
274     computeOverflow(oldClientAfterEdge);
275     statePusher.pop();
276
277     updateLayerTransform();
278
279     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
280     // we overflow or not.
281     updateScrollInfoAfterLayout();
282
283     repainter.repaintAfterLayout();
284
285     clearNeedsLayout();
286 }
287
288 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
289 {
290     bool wasPopulated = gridWasPopulated();
291     if (!wasPopulated)
292         const_cast<RenderGrid*>(this)->placeItemsOnGrid();
293
294     GridSizingData sizingData(gridColumnCount(), gridRowCount());
295     LayoutUnit availableLogicalSpace = 0;
296     const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
297
298     for (auto& column : sizingData.columnTracks) {
299         LayoutUnit minTrackBreadth = column.baseSize();
300         LayoutUnit maxTrackBreadth = column.growthLimit();
301
302         minLogicalWidth += minTrackBreadth;
303         maxLogicalWidth += maxTrackBreadth;
304     }
305
306     LayoutUnit scrollbarWidth = intrinsicScrollbarLogicalWidth();
307     minLogicalWidth += scrollbarWidth;
308     maxLogicalWidth += scrollbarWidth;
309
310     if (!wasPopulated)
311         const_cast<RenderGrid*>(this)->clearGrid();
312 }
313
314 void RenderGrid::computePreferredLogicalWidths()
315 {
316     ASSERT(preferredLogicalWidthsDirty());
317
318     m_minPreferredLogicalWidth = 0;
319     m_maxPreferredLogicalWidth = 0;
320
321     // FIXME: We don't take our own logical width into account. Once we do, we need to make sure
322     // we apply (and test the interaction with) min-width / max-width.
323
324     computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
325
326     LayoutUnit borderAndPaddingInInlineDirection = borderAndPaddingLogicalWidth();
327     m_minPreferredLogicalWidth += borderAndPaddingInInlineDirection;
328     m_maxPreferredLogicalWidth += borderAndPaddingInInlineDirection;
329
330     setPreferredLogicalWidthsDirty(false);
331 }
332
333 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
334 {
335     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
336     computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
337 }
338
339 bool RenderGrid::gridElementIsShrinkToFit()
340 {
341     return isFloatingOrOutOfFlowPositioned();
342 }
343
344 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
345 {
346     const LayoutUnit initialAvailableLogicalSpace = availableLogicalSpace;
347     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
348     Vector<unsigned> flexibleSizedTracksIndex;
349     sizingData.contentSizedTracksIndex.shrink(0);
350
351     // 1. Initialize per Grid track variables.
352     for (unsigned i = 0; i < tracks.size(); ++i) {
353         GridTrack& track = tracks[i];
354         const GridTrackSize& trackSize = gridTrackSize(direction, i);
355         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
356         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
357
358         track.setBaseSize(computeUsedBreadthOfMinLength(direction, minTrackBreadth));
359         track.setGrowthLimit(computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.baseSize()));
360         track.setInfinitelyGrowable(false);
361
362         if (trackSize.isContentSized())
363             sizingData.contentSizedTracksIndex.append(i);
364         if (trackSize.maxTrackBreadth().isFlex())
365             flexibleSizedTracksIndex.append(i);
366     }
367
368     // 2. Resolve content-based TrackSizingFunctions.
369     if (!sizingData.contentSizedTracksIndex.isEmpty())
370         resolveContentBasedTrackSizingFunctions(direction, sizingData);
371
372     for (auto& track : tracks) {
373         ASSERT(!track.growthLimitIsInfinite());
374         availableLogicalSpace -= track.baseSize();
375     }
376
377     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
378
379     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
380         return;
381
382     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until availableLogicalSpace is exhausted.
383     if (!hasUndefinedRemainingSpace) {
384         const unsigned tracksSize = tracks.size();
385         Vector<GridTrack*> tracksForDistribution(tracksSize);
386         for (unsigned i = 0; i < tracksSize; ++i) {
387             tracksForDistribution[i] = tracks.data() + i;
388             tracksForDistribution[i]->setPlannedSize(tracksForDistribution[i]->baseSize());
389         }
390
391         distributeSpaceToTracks<MaximizeTracks>(tracksForDistribution, nullptr, availableLogicalSpace);
392
393         for (auto* track : tracksForDistribution)
394             track->setBaseSize(track->plannedSize());
395     } else {
396         for (auto& track : tracks)
397             track.setBaseSize(track.growthLimit());
398     }
399
400     if (flexibleSizedTracksIndex.isEmpty())
401         return;
402
403     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
404     double normalizedFractionBreadth = 0;
405     if (!hasUndefinedRemainingSpace)
406         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, initialAvailableLogicalSpace);
407     else {
408         for (auto trackIndex : flexibleSizedTracksIndex) {
409             const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
410             normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].baseSize() / trackSize.maxTrackBreadth().flex());
411         }
412
413         for (unsigned i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
414             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
415             while (RenderBox* gridItem = iterator.nextGridItem()) {
416                 const GridCoordinate coordinate = cachedGridCoordinate(*gridItem);
417                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
418
419                 // Do not include already processed items.
420                 if (i > 0 && span.resolvedInitialPosition.toInt() <= flexibleSizedTracksIndex[i - 1])
421                     continue;
422
423                 double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(*gridItem, direction, sizingData.columnTracks));
424                 normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
425             }
426         }
427     }
428
429     for (auto trackIndex : flexibleSizedTracksIndex) {
430         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
431         GridTrack& track = tracks[trackIndex];
432         LayoutUnit baseSize = std::max<LayoutUnit>(track.baseSize(), normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
433         track.setBaseSize(baseSize);
434         availableLogicalSpace -= baseSize;
435     }
436 }
437
438 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
439 {
440     if (gridLength.isFlex())
441         return 0;
442
443     const Length& trackLength = gridLength.length();
444     ASSERT(!trackLength.isAuto());
445     if (trackLength.isSpecified())
446         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
447
448     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
449     return 0;
450 }
451
452 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
453 {
454     if (gridLength.isFlex())
455         return usedBreadth;
456
457     const Length& trackLength = gridLength.length();
458     ASSERT(!trackLength.isAuto());
459     if (trackLength.isSpecified()) {
460         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
461         ASSERT(computedBreadth != infinity);
462         return computedBreadth;
463     }
464
465     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
466     return infinity;
467 }
468
469 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
470 {
471     ASSERT(trackLength.isSpecified());
472     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : std::max(LayoutUnit(), computeContentLogicalHeight(style().logicalHeight())));
473 }
474
475 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit spaceToFill) const
476 {
477     LayoutUnit allocatedSpace;
478     Vector<GridTrackForNormalization> tracksForNormalization;
479     for (auto& position : tracksSpan) {
480         GridTrack& track = tracks[position.toInt()];
481         allocatedSpace += track.baseSize();
482
483         const GridTrackSize& trackSize = gridTrackSize(direction, position.toInt());
484         if (!trackSize.maxTrackBreadth().isFlex())
485             continue;
486
487         tracksForNormalization.append(GridTrackForNormalization(track, trackSize.maxTrackBreadth().flex()));
488     }
489
490     // The function is not called if we don't have <flex> grid tracks
491     ASSERT(!tracksForNormalization.isEmpty());
492
493     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
494               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
495                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
496               });
497
498     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
499     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
500     // fit into availableLogicalSpaceIgnoringFractionTracks.
501     double accumulatedFractions = 0;
502     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
503     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = spaceToFill - allocatedSpace;
504
505     for (auto& track : tracksForNormalization) {
506         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
507             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
508             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
509             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
510                 break;
511
512             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
513         }
514
515         accumulatedFractions += track.m_flex;
516         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
517         availableLogicalSpaceIgnoringFractionTracks += track.m_track->baseSize();
518     }
519
520     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
521 }
522
523 bool RenderGrid::hasDefiniteLogicalSize(GridTrackSizingDirection direction) const
524 {
525     return (direction == ForRows) ? hasDefiniteLogicalHeight() : hasDefiniteLogicalWidth();
526 }
527
528 GridTrackSize RenderGrid::gridTrackSize(GridTrackSizingDirection direction, unsigned i) const
529 {
530     bool isForColumns = (direction == ForColumns);
531     auto& trackStyles =  isForColumns ? style().gridColumns() : style().gridRows();
532     auto& trackSize = (i >= trackStyles.size()) ? (isForColumns ? style().gridAutoColumns() : style().gridAutoRows()) : trackStyles[i];
533
534     GridLength minTrackBreadth = trackSize.minTrackBreadth();
535     GridLength maxTrackBreadth = trackSize.maxTrackBreadth();
536
537     if (minTrackBreadth.isPercentage() || maxTrackBreadth.isPercentage()) {
538         if (!hasDefiniteLogicalSize(direction)) {
539             if (minTrackBreadth.isPercentage())
540                 minTrackBreadth = Length(MinContent);
541             if (maxTrackBreadth.isPercentage())
542                 maxTrackBreadth = Length(MaxContent);
543         }
544     }
545
546     return GridTrackSize(minTrackBreadth, maxTrackBreadth);
547 }
548
549 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox& child, Vector<GridTrack>& columnTracks)
550 {
551     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
552     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
553     if (child.hasRelativeLogicalHeight() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth) {
554         child.setNeedsLayout(MarkOnlyThis);
555         // We need to clear the stretched height to properly compute logical height during layout.
556         child.clearOverrideLogicalContentHeight();
557     }
558
559     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
560     // If |child| has a relative logical height, we shouldn't let it override its intrinsic height, which is
561     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
562     if (child.hasRelativeLogicalHeight())
563         child.setOverrideContainingBlockContentLogicalHeight(-1);
564     child.layoutIfNeeded();
565     return child.logicalHeight() + child.marginLogicalHeight();
566 }
567
568 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
569 {
570     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
571     // FIXME: Properly support orthogonal writing mode.
572     if (hasOrthogonalWritingMode)
573         return 0;
574
575     if (direction == ForColumns) {
576         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
577         // what we are interested in here. Thus we need to set the override logical width to -1 (no possible resolution).
578         if (child.hasRelativeLogicalWidth())
579             child.setOverrideContainingBlockContentLogicalWidth(-1);
580
581         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
582         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
583         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
584     }
585
586     return logicalContentHeightForChild(child, columnTracks);
587 }
588
589 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
590 {
591     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
592     // FIXME: Properly support orthogonal writing mode.
593     if (hasOrthogonalWritingMode)
594         return LayoutUnit();
595
596     if (direction == ForColumns) {
597         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
598         // what we are interested in here. Thus we need to set the override logical width to -1 (no possible resolution).
599         if (child.hasRelativeLogicalWidth())
600             child.setOverrideContainingBlockContentLogicalWidth(-1);
601
602         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
603         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
604         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
605     }
606
607     return logicalContentHeightForChild(child, columnTracks);
608 }
609
610 class GridItemWithSpan {
611 public:
612     GridItemWithSpan(RenderBox& gridItem, GridCoordinate coordinate, GridTrackSizingDirection direction)
613         : m_gridItem(gridItem)
614         , m_coordinate(coordinate)
615     {
616         const GridSpan& span = (direction == ForRows) ? coordinate.rows : coordinate.columns;
617         m_span = span.resolvedFinalPosition.toInt() - span.resolvedInitialPosition.toInt() + 1;
618     }
619
620     RenderBox& gridItem() const { return m_gridItem; }
621     GridCoordinate coordinate() const { return m_coordinate; }
622 #if !ASSERT_DISABLED
623     size_t span() const { return m_span; }
624 #endif
625
626     bool operator<(const GridItemWithSpan other) const
627     {
628         return m_span < other.m_span;
629     }
630
631 private:
632     std::reference_wrapper<RenderBox> m_gridItem;
633     GridCoordinate m_coordinate;
634     unsigned m_span;
635 };
636
637 bool RenderGrid::spanningItemCrossesFlexibleSizedTracks(const GridCoordinate& coordinate, GridTrackSizingDirection direction) const
638 {
639     const GridSpan itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
640     for (auto trackPosition : itemSpan) {
641         const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
642         if (trackSize.minTrackBreadth().isFlex() || trackSize.maxTrackBreadth().isFlex())
643             return true;
644     }
645
646     return false;
647 }
648
649 static inline unsigned integerSpanForDirection(const GridCoordinate& coordinate, GridTrackSizingDirection direction)
650 {
651     return (direction == ForRows) ? coordinate.rows.integerSpan() : coordinate.columns.integerSpan();
652 }
653
654 struct GridItemsSpanGroupRange {
655     Vector<GridItemWithSpan>::iterator rangeStart;
656     Vector<GridItemWithSpan>::iterator rangeEnd;
657 };
658
659 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
660 {
661     sizingData.itemsSortedByIncreasingSpan.shrink(0);
662     HashSet<RenderBox*> itemsSet;
663     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
664         GridIterator iterator(m_grid, direction, trackIndex);
665         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
666
667         while (RenderBox* gridItem = iterator.nextGridItem()) {
668             if (itemsSet.add(gridItem).isNewEntry) {
669                 const GridCoordinate& coordinate = cachedGridCoordinate(*gridItem);
670                 if (integerSpanForDirection(coordinate, direction) == 1)
671                     resolveContentBasedTrackSizingFunctionsForNonSpanningItems(direction, coordinate, *gridItem, track, sizingData.columnTracks);
672                 else if (!spanningItemCrossesFlexibleSizedTracks(coordinate, direction))
673                     sizingData.itemsSortedByIncreasingSpan.append(GridItemWithSpan(*gridItem, coordinate, direction));
674             }
675         }
676     }
677     std::sort(sizingData.itemsSortedByIncreasingSpan.begin(), sizingData.itemsSortedByIncreasingSpan.end());
678
679     auto it = sizingData.itemsSortedByIncreasingSpan.begin();
680     auto end = sizingData.itemsSortedByIncreasingSpan.end();
681     while (it != end) {
682         GridItemsSpanGroupRange spanGroupRange = { it, std::upper_bound(it, end, *it) };
683         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMinimums>(direction, sizingData, spanGroupRange);
684         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMinimums>(direction, sizingData, spanGroupRange);
685         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMaximums>(direction, sizingData, spanGroupRange);
686         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMaximums>(direction, sizingData, spanGroupRange);
687         it = spanGroupRange.rangeEnd;
688     }
689
690     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
691         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
692         if (track.growthLimitIsInfinite())
693             track.setGrowthLimit(track.baseSize());
694     }
695 }
696
697 void RenderGrid::resolveContentBasedTrackSizingFunctionsForNonSpanningItems(GridTrackSizingDirection direction, const GridCoordinate& coordinate, RenderBox& gridItem, GridTrack& track, Vector<GridTrack>& columnTracks)
698 {
699     const GridResolvedPosition trackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
700     GridTrackSize trackSize = gridTrackSize(direction, trackPosition.toInt());
701
702     if (trackSize.hasMinContentMinTrackBreadth())
703         track.setBaseSize(std::max(track.baseSize(), minContentForChild(gridItem, direction, columnTracks)));
704     else if (trackSize.hasMaxContentMinTrackBreadth())
705         track.setBaseSize(std::max(track.baseSize(), maxContentForChild(gridItem, direction, columnTracks)));
706
707     if (trackSize.hasMinContentMaxTrackBreadth())
708         track.setGrowthLimit(std::max(track.growthLimit(), minContentForChild(gridItem, direction, columnTracks)));
709     else if (trackSize.hasMaxContentMaxTrackBreadth())
710         track.setGrowthLimit(std::max(track.growthLimit(), maxContentForChild(gridItem, direction, columnTracks)));
711 }
712
713 const LayoutUnit& RenderGrid::trackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track, TrackSizeRestriction restriction)
714 {
715     switch (phase) {
716     case ResolveIntrinsicMinimums:
717     case ResolveMaxContentMinimums:
718     case MaximizeTracks:
719         return track.baseSize();
720     case ResolveIntrinsicMaximums:
721     case ResolveMaxContentMaximums:
722         return restriction == AllowInfinity ? track.growthLimit() : track.growthLimitIfNotInfinite();
723     }
724
725     ASSERT_NOT_REACHED();
726     return track.baseSize();
727 }
728
729 bool RenderGrid::shouldProcessTrackForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
730 {
731     switch (phase) {
732     case ResolveIntrinsicMinimums:
733         return trackSize.hasMinOrMaxContentMinTrackBreadth();
734     case ResolveMaxContentMinimums:
735         return trackSize.hasMaxContentMinTrackBreadth();
736     case ResolveIntrinsicMaximums:
737         return trackSize.hasMinOrMaxContentMaxTrackBreadth();
738     case ResolveMaxContentMaximums:
739         return trackSize.hasMaxContentMaxTrackBreadth();
740     case MaximizeTracks:
741         ASSERT_NOT_REACHED();
742         return false;
743     }
744
745     ASSERT_NOT_REACHED();
746     return false;
747 }
748
749 bool RenderGrid::trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
750 {
751     switch (phase) {
752     case ResolveIntrinsicMinimums:
753         return trackSize.hasMinContentMinTrackBreadthAndMinOrMaxContentMaxTrackBreadth();
754     case ResolveMaxContentMinimums:
755         return trackSize.hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth();
756     case ResolveIntrinsicMaximums:
757     case ResolveMaxContentMaximums:
758         return true;
759     case MaximizeTracks:
760         ASSERT_NOT_REACHED();
761         return false;
762     }
763
764     ASSERT_NOT_REACHED();
765     return false;
766 }
767
768 void RenderGrid::markAsInfinitelyGrowableForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
769 {
770     switch (phase) {
771     case ResolveIntrinsicMinimums:
772     case ResolveMaxContentMinimums:
773         return;
774     case ResolveIntrinsicMaximums:
775         if (trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity) == infinity  && track.plannedSize() != infinity)
776             track.setInfinitelyGrowable(true);
777         return;
778     case ResolveMaxContentMaximums:
779         if (track.infinitelyGrowable())
780             track.setInfinitelyGrowable(false);
781         return;
782     case MaximizeTracks:
783         ASSERT_NOT_REACHED();
784         return;
785     }
786
787     ASSERT_NOT_REACHED();
788 }
789
790 void RenderGrid::updateTrackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
791 {
792     switch (phase) {
793     case ResolveIntrinsicMinimums:
794     case ResolveMaxContentMinimums:
795         track.setBaseSize(track.plannedSize());
796         return;
797     case ResolveIntrinsicMaximums:
798     case ResolveMaxContentMaximums:
799         track.setGrowthLimit(track.plannedSize());
800         return;
801     case MaximizeTracks:
802         ASSERT_NOT_REACHED();
803         return;
804     }
805
806     ASSERT_NOT_REACHED();
807 }
808
809 LayoutUnit RenderGrid::currentItemSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, RenderBox& gridItem, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
810 {
811     switch (phase) {
812     case ResolveIntrinsicMinimums:
813     case ResolveIntrinsicMaximums:
814         return minContentForChild(gridItem, direction, columnTracks);
815     case ResolveMaxContentMinimums:
816     case ResolveMaxContentMaximums:
817         return maxContentForChild(gridItem, direction, columnTracks);
818     case MaximizeTracks:
819         ASSERT_NOT_REACHED();
820         return 0;
821     }
822
823     ASSERT_NOT_REACHED();
824     return 0;
825 }
826
827 template <RenderGrid::TrackSizeComputationPhase phase>
828 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, const GridItemsSpanGroupRange& gridItemsWithSpan)
829 {
830     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
831     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
832         GridTrack& track = tracks[trackIndex];
833         track.setPlannedSize(trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity));
834     }
835
836     for (auto it = gridItemsWithSpan.rangeStart; it != gridItemsWithSpan.rangeEnd; ++it) {
837         GridItemWithSpan& gridItemWithSpan = *it;
838         ASSERT(gridItemWithSpan.span() > 1);
839         const GridCoordinate& coordinate = gridItemWithSpan.coordinate();
840         const GridSpan& itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
841
842         sizingData.filteredTracks.shrink(0);
843         sizingData.growBeyondGrowthLimitsTracks.shrink(0);
844         LayoutUnit spanningTracksSize;
845         for (auto& trackPosition : itemSpan) {
846             const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
847             GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPosition.toInt()] : sizingData.rowTracks[trackPosition.toInt()];
848             spanningTracksSize += trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
849             if (!shouldProcessTrackForTrackSizeComputationPhase(phase, trackSize))
850                 continue;
851
852             sizingData.filteredTracks.append(&track);
853
854             if (trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(phase, trackSize))
855                 sizingData.growBeyondGrowthLimitsTracks.append(&track);
856         }
857
858         if (sizingData.filteredTracks.isEmpty())
859             continue;
860
861         LayoutUnit extraSpace = currentItemSizeForTrackSizeComputationPhase(phase, gridItemWithSpan.gridItem(), direction, sizingData.columnTracks) - spanningTracksSize;
862         extraSpace = std::max<LayoutUnit>(extraSpace, 0);
863         auto& tracksToGrowBeyondGrowthLimits = sizingData.growBeyondGrowthLimitsTracks.isEmpty() ? sizingData.filteredTracks : sizingData.growBeyondGrowthLimitsTracks;
864         distributeSpaceToTracks<phase>(sizingData.filteredTracks, &tracksToGrowBeyondGrowthLimits, extraSpace);
865     }
866
867     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
868         GridTrack& track = tracks[trackIndex];
869         markAsInfinitelyGrowableForTrackSizeComputationPhase(phase, track);
870         updateTrackSizeForTrackSizeComputationPhase(phase, track);
871     }
872 }
873
874 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
875 {
876     // This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
877     // (forall x: NOT x < x).
878     if (track1->infiniteGrowthPotential() && track2->infiniteGrowthPotential())
879         return false;
880
881     if (track1->infiniteGrowthPotential() || track2->infiniteGrowthPotential())
882         return track2->infiniteGrowthPotential();
883
884     return (track1->growthLimit() - track1->baseSize()) < (track2->growthLimit() - track2->baseSize());
885 }
886
887 template <RenderGrid::TrackSizeComputationPhase phase>
888 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, const Vector<GridTrack*>* growBeyondGrowthLimitsTracks, LayoutUnit& availableLogicalSpace)
889 {
890     ASSERT(availableLogicalSpace >= 0);
891
892     for (auto* track : tracks)
893         track->tempSize() = trackSizeForTrackSizeComputationPhase(phase, *track, ForbidInfinity);
894
895     if (availableLogicalSpace > 0) {
896         std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
897
898         unsigned tracksSize = tracks.size();
899         for (unsigned i = 0; i < tracksSize; ++i) {
900             GridTrack& track = *tracks[i];
901             const LayoutUnit& trackBreadth = trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
902             bool infiniteGrowthPotential = track.infiniteGrowthPotential();
903             LayoutUnit trackGrowthPotential = infiniteGrowthPotential ? track.growthLimit() : track.growthLimit() - trackBreadth;
904             // Let's avoid computing availableLogicalSpaceShare as much as possible as it's a hot spot in performance tests.
905             if (trackGrowthPotential > 0 || infiniteGrowthPotential) {
906                 LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
907                 LayoutUnit growthShare = infiniteGrowthPotential ? availableLogicalSpaceShare : std::min(availableLogicalSpaceShare, trackGrowthPotential);
908                 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.");
909                 track.tempSize() += growthShare;
910                 availableLogicalSpace -= growthShare;
911             }
912         }
913     }
914
915     if (availableLogicalSpace > 0 && growBeyondGrowthLimitsTracks) {
916         unsigned tracksGrowingBeyondGrowthLimitsSize = growBeyondGrowthLimitsTracks->size();
917         for (unsigned i = 0; i < tracksGrowingBeyondGrowthLimitsSize; ++i) {
918             GridTrack* track = growBeyondGrowthLimitsTracks->at(i);
919             LayoutUnit growthShare = availableLogicalSpace / (tracksGrowingBeyondGrowthLimitsSize - i);
920             track->tempSize() += growthShare;
921             availableLogicalSpace -= growthShare;
922         }
923     }
924
925     for (auto* track : tracks)
926         track->setPlannedSize(track->plannedSize() == infinity ? track->tempSize() : std::max(track->plannedSize(), track->tempSize()));
927 }
928
929 #ifndef NDEBUG
930 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
931 {
932     for (unsigned i = 0; i < tracks.size(); ++i) {
933         const GridTrackSize& trackSize = gridTrackSize(direction, i);
934         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
935         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].baseSize())
936             return false;
937     }
938     return true;
939 }
940 #endif
941
942 void RenderGrid::ensureGridSize(unsigned maximumRowIndex, unsigned maximumColumnIndex)
943 {
944     const unsigned oldRowCount = gridRowCount();
945     if (maximumRowIndex >= oldRowCount) {
946         m_grid.grow(maximumRowIndex + 1);
947         for (unsigned row = oldRowCount; row < gridRowCount(); ++row)
948             m_grid[row].grow(gridColumnCount());
949     }
950
951     if (maximumColumnIndex >= gridColumnCount()) {
952         for (unsigned row = 0; row < gridRowCount(); ++row)
953             m_grid[row].grow(maximumColumnIndex + 1);
954     }
955 }
956
957 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
958 {
959     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
960
961     for (auto& row : coordinate.rows) {
962         for (auto& column : coordinate.columns)
963             m_grid[row.toInt()][column.toInt()].append(&child);
964     }
965     m_gridItemCoordinate.set(&child, coordinate);
966 }
967
968 void RenderGrid::placeItemsOnGrid()
969 {
970     ASSERT(!gridWasPopulated());
971     ASSERT(m_gridItemCoordinate.isEmpty());
972
973     populateExplicitGridAndOrderIterator();
974
975     Vector<RenderBox*> autoMajorAxisAutoGridItems;
976     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
977     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
978         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
979         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
980
981         if (unresolvedRowPositions.requiresAutoPlacement() || unresolvedColumnPositions.requiresAutoPlacement()) {
982
983             bool majorAxisDirectionIsForColumns = autoPlacementMajorAxisDirection() == ForColumns;
984             if ((majorAxisDirectionIsForColumns && unresolvedColumnPositions.requiresAutoPlacement())
985                 || (!majorAxisDirectionIsForColumns && unresolvedRowPositions.requiresAutoPlacement()))
986                 autoMajorAxisAutoGridItems.append(child);
987             else
988                 specifiedMajorAxisAutoGridItems.append(child);
989             continue;
990         }
991         GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
992         GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
993         insertItemIntoGrid(*child, GridCoordinate(rowPositions, columnPositions));
994     }
995
996     ASSERT(gridRowCount() >= GridResolvedPosition::explicitGridRowCount(style()));
997     ASSERT(gridColumnCount() >= GridResolvedPosition::explicitGridColumnCount(style()));
998
999     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
1000     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
1001 }
1002
1003 void RenderGrid::populateExplicitGridAndOrderIterator()
1004 {
1005     OrderIteratorPopulator populator(m_orderIterator);
1006     unsigned maximumRowIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridRowCount(style()));
1007     unsigned maximumColumnIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridColumnCount(style()));
1008
1009     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1010         populator.collectChild(*child);
1011
1012         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
1013         if (!unresolvedRowPositions.requiresAutoPlacement()) {
1014             GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
1015             maximumRowIndex = std::max(maximumRowIndex, rowPositions.resolvedFinalPosition.next().toInt());
1016         } else {
1017             // Grow the grid for items with a definite row span, getting the largest such span.
1018             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
1019             maximumRowIndex = std::max(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
1020         }
1021
1022         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
1023         if (!unresolvedColumnPositions.requiresAutoPlacement()) {
1024             GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
1025             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions.resolvedFinalPosition.next().toInt());
1026         } else {
1027             // Grow the grid for items with a definite column span, getting the largest such span.
1028             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
1029             maximumColumnIndex = std::max(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
1030         }
1031     }
1032
1033     m_grid.grow(maximumRowIndex);
1034     for (auto& column : m_grid)
1035         column.grow(maximumColumnIndex);
1036 }
1037
1038 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
1039 {
1040     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
1041     const unsigned endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
1042     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
1043     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
1044 }
1045
1046 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1047 {
1048     bool isForColumns = autoPlacementMajorAxisDirection() == ForColumns;
1049     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1050
1051     // Mapping between the major axis tracks (rows or columns) and the last auto-placed item's position inserted on
1052     // that track. This is needed to implement "sparse" packing for items locked to a given track.
1053     // See http://dev.w3.org/csswg/css-grid/#auto-placement-algo
1054     HashMap<unsigned, unsigned, DefaultHash<unsigned>::Hash, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> minorAxisCursors;
1055
1056     for (auto& autoGridItem : autoGridItems) {
1057         auto unresolvedMajorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
1058         ASSERT(!unresolvedMajorAxisPositions.requiresAutoPlacement());
1059         GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMajorAxisPositions, style());
1060         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1061         unsigned majorAxisInitialPosition = majorAxisPositions.resolvedInitialPosition.toInt();
1062
1063         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions.resolvedInitialPosition.toInt(), isGridAutoFlowDense ? 0 : minorAxisCursors.get(majorAxisInitialPosition));
1064         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1065         if (!emptyGridArea)
1066             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), majorAxisPositions);
1067         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
1068
1069         if (!isGridAutoFlowDense)
1070             minorAxisCursors.set(majorAxisInitialPosition, isForColumns ? emptyGridArea->rows.resolvedInitialPosition.toInt() : emptyGridArea->columns.resolvedInitialPosition.toInt());
1071     }
1072 }
1073
1074 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1075 {
1076     AutoPlacementCursor autoPlacementCursor = {0, 0};
1077     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1078
1079     for (auto& autoGridItem : autoGridItems) {
1080         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
1081
1082         if (isGridAutoFlowDense) {
1083             autoPlacementCursor.first = 0;
1084             autoPlacementCursor.second = 0;
1085         }
1086     }
1087 }
1088
1089 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
1090 {
1091     ASSERT(GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()).requiresAutoPlacement());
1092     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
1093
1094     const unsigned endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
1095     unsigned majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
1096     unsigned minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
1097
1098     std::unique_ptr<GridCoordinate> emptyGridArea;
1099     auto unresolvedMinorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
1100     if (!unresolvedMinorAxisPositions.requiresAutoPlacement()) {
1101         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMinorAxisPositions, style());
1102
1103         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
1104         if (minorAxisPositions.resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
1105             majorAxisAutoPlacementCursor++;
1106
1107         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
1108             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions.resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
1109             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions.integerSpan(), majorAxisPositions.integerSpan());
1110         }
1111
1112         if (!emptyGridArea)
1113             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1114     } else {
1115         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1116
1117         for (unsigned majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
1118             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
1119             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1120
1121             if (emptyGridArea) {
1122                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
1123                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
1124                 const unsigned endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
1125                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
1126                     break;
1127
1128                 // Discard empty grid area as it does not fit in the minor axis direction.
1129                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
1130                 emptyGridArea = nullptr;
1131             }
1132
1133             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
1134             minorAxisAutoPlacementCursor = 0;
1135         }
1136
1137         if (!emptyGridArea)
1138             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1139     }
1140
1141     insertItemIntoGrid(gridItem, *emptyGridArea);
1142     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
1143     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
1144 }
1145
1146 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
1147 {
1148     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
1149 }
1150
1151 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
1152 {
1153     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
1154 }
1155
1156 void RenderGrid::clearGrid()
1157 {
1158     m_grid.clear();
1159     m_gridItemCoordinate.clear();
1160 }
1161
1162 void RenderGrid::layoutGridItems()
1163 {
1164     placeItemsOnGrid();
1165
1166     GridSizingData sizingData(gridColumnCount(), gridRowCount());
1167     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
1168     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
1169     computeUsedBreadthOfGridTracks(ForRows, sizingData);
1170     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
1171
1172     populateGridPositions(sizingData);
1173
1174     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1175         // Because the grid area cannot be styled, we don't need to adjust
1176         // the grid breadth to account for 'box-sizing'.
1177         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
1178         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
1179
1180         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(*child, ForColumns, sizingData.columnTracks);
1181         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(*child, ForRows, sizingData.rowTracks);
1182         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && child->hasRelativeLogicalHeight()))
1183             child->setNeedsLayout(MarkOnlyThis);
1184
1185         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
1186         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
1187
1188         LayoutRect oldChildRect = child->frameRect();
1189
1190         // Stretching logic might force a child layout, so we need to run it before the layoutIfNeeded
1191         // call to avoid unnecessary relayouts. This might imply that child margins, needed to correctly
1192         // determine the available space before stretching, are not set yet.
1193         applyStretchAlignmentToChildIfNeeded(*child, overrideContainingBlockContentLogicalHeight);
1194
1195         child->layoutIfNeeded();
1196
1197         child->setLogicalLocation(findChildLogicalPosition(*child));
1198
1199         // If the child moved, we have to repaint it as well as any floating/positioned
1200         // descendants. An exception is if we need a layout. In this case, we know we're going to
1201         // repaint ourselves (and the child) anyway.
1202         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
1203             child->repaintDuringLayoutIfMoved(oldChildRect);
1204     }
1205
1206     for (auto& row : sizingData.rowTracks)
1207         setLogicalHeight(logicalHeight() + row.baseSize());
1208
1209     // min / max logical height is handled in updateLogicalHeight().
1210     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
1211     if (hasLineIfEmpty()) {
1212         LayoutUnit minHeight = borderAndPaddingLogicalHeight()
1213             + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes)
1214             + scrollbarLogicalHeight();
1215         if (height() < minHeight)
1216             setLogicalHeight(minHeight);
1217     }
1218
1219     clearGrid();
1220 }
1221
1222 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
1223 {
1224     ASSERT(m_gridItemCoordinate.contains(&gridItem));
1225     return m_gridItemCoordinate.get(&gridItem);
1226 }
1227
1228 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1229 {
1230     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1231     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1232     LayoutUnit gridAreaBreadth = 0;
1233     for (auto& trackPosition : span)
1234         gridAreaBreadth += tracks[trackPosition.toInt()].baseSize();
1235     return gridAreaBreadth;
1236 }
1237
1238 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
1239 {
1240     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
1241     m_columnPositions[0] = borderAndPaddingStart();
1242     for (unsigned i = 0; i < m_columnPositions.size() - 1; ++i)
1243         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].baseSize();
1244
1245     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
1246     m_rowPositions[0] = borderAndPaddingBefore();
1247     for (unsigned i = 0; i < m_rowPositions.size() - 1; ++i)
1248         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].baseSize();
1249 }
1250
1251 static inline LayoutUnit computeOverflowAlignmentOffset(OverflowAlignment overflow, LayoutUnit trackBreadth, LayoutUnit childBreadth)
1252 {
1253     LayoutUnit offset = trackBreadth - childBreadth;
1254     switch (overflow) {
1255     case OverflowAlignmentSafe:
1256         // If overflow is 'safe', we have to make sure we don't overflow the 'start'
1257         // edge (potentially cause some data loss as the overflow is unreachable).
1258         return std::max<LayoutUnit>(0, offset);
1259     case OverflowAlignmentTrue:
1260     case OverflowAlignmentDefault:
1261         // If we overflow our alignment container and overflow is 'true' (default), we
1262         // ignore the overflow and just return the value regardless (which may cause data
1263         // loss as we overflow the 'start' edge).
1264         return offset;
1265     }
1266
1267     ASSERT_NOT_REACHED();
1268     return 0;
1269 }
1270
1271 bool RenderGrid::allowedToStretchLogicalHeightForChild(const RenderBox& child) const
1272 {
1273     return child.style().logicalHeight().isAuto() && !child.style().marginBeforeUsing(&style()).isAuto() && !child.style().marginAfterUsing(&style()).isAuto();
1274 }
1275
1276 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1277 bool RenderGrid::needToStretchChildLogicalHeight(const RenderBox& child) const
1278 {
1279     if (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch) != ItemPositionStretch)
1280         return false;
1281
1282     return isHorizontalWritingMode() && child.style().height().isAuto();
1283 }
1284
1285 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1286 LayoutUnit RenderGrid::marginLogicalHeightForChild(const RenderBox& child) const
1287 {
1288     return isHorizontalWritingMode() ? child.verticalMarginExtent() : child.horizontalMarginExtent();
1289 }
1290
1291 LayoutUnit RenderGrid::availableAlignmentSpaceForChildBeforeStretching(LayoutUnit gridAreaBreadthForChild, const RenderBox& child) const
1292 {
1293     return gridAreaBreadthForChild - marginLogicalHeightForChild(child);
1294 }
1295
1296 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1297 void RenderGrid::applyStretchAlignmentToChildIfNeeded(RenderBox& child, LayoutUnit gridAreaBreadthForChild)
1298 {
1299     if (!allowedToStretchLogicalHeightForChild(child) || RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch) != ItemPositionStretch) {
1300         child.clearOverrideLogicalContentHeight();
1301         return;
1302     }
1303
1304     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1305     // FIXME: If the child has orthogonal flow, then it already has an override height set, so use it.
1306     // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1307     if (!hasOrthogonalWritingMode) {
1308         LayoutUnit stretchedLogicalHeight = availableAlignmentSpaceForChildBeforeStretching(gridAreaBreadthForChild, child);
1309         LayoutUnit desiredLogicalHeight = child.constrainLogicalHeightByMinMax(stretchedLogicalHeight);
1310
1311         // FIXME: Can avoid laying out here in some cases. See https://webkit.org/b/87905.
1312         bool childNeedsRelayout = desiredLogicalHeight != child.logicalHeight();
1313         if (childNeedsRelayout || !child.hasOverrideLogicalContentHeight())
1314             child.setOverrideLogicalContentHeight(desiredLogicalHeight - child.borderAndPaddingLogicalHeight());
1315         if (childNeedsRelayout) {
1316             child.setLogicalHeight(0);
1317             child.setNeedsLayout();
1318         }
1319     }
1320 }
1321
1322 GridAxisPosition RenderGrid::columnAxisPositionForChild(const RenderBox& child) const
1323 {
1324     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1325     bool hasSameWritingMode = child.style().writingMode() == style().writingMode();
1326
1327     switch (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch)) {
1328     case ItemPositionSelfStart:
1329         // If orthogonal writing-modes, this computes to 'start'.
1330         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1331         // self-start is based on the child's block axis direction. That's why we need to check against the grid container's block flow.
1332         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisStart : GridAxisEnd;
1333     case ItemPositionSelfEnd:
1334         // If orthogonal writing-modes, this computes to 'end'.
1335         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1336         // self-end is based on the child's block axis direction. That's why we need to check against the grid container's block flow.
1337         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisEnd : GridAxisStart;
1338     case ItemPositionLeft:
1339         // The alignment axis (column axis) and the inline axis are parallell in
1340         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1341         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1342         return GridAxisStart;
1343     case ItemPositionRight:
1344         // The alignment axis (column axis) and the inline axis are parallell in
1345         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1346         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1347         return hasOrthogonalWritingMode ? GridAxisEnd : GridAxisStart;
1348     case ItemPositionCenter:
1349         return GridAxisCenter;
1350     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1351     case ItemPositionStart:
1352         return GridAxisStart;
1353     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1354     case ItemPositionEnd:
1355         return GridAxisEnd;
1356     case ItemPositionStretch:
1357         return GridAxisStart;
1358     case ItemPositionBaseline:
1359     case ItemPositionLastBaseline:
1360         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1361         return GridAxisStart;
1362     case ItemPositionAuto:
1363         break;
1364     }
1365
1366     ASSERT_NOT_REACHED();
1367     return GridAxisStart;
1368 }
1369
1370 GridAxisPosition RenderGrid::rowAxisPositionForChild(const RenderBox& child) const
1371 {
1372     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1373     bool hasSameDirection = child.style().direction() == style().direction();
1374     bool isLTR = style().isLeftToRightDirection();
1375
1376     switch (RenderStyle::resolveJustification(style(), child.style(), ItemPositionStretch)) {
1377     case ItemPositionSelfStart:
1378         // For orthogonal writing-modes, this computes to 'start'
1379         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1380         // self-start is based on the child's direction. That's why we need to check against the grid container's direction.
1381         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisStart : GridAxisEnd;
1382     case ItemPositionSelfEnd:
1383         // For orthogonal writing-modes, this computes to 'start'
1384         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1385         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisEnd : GridAxisStart;
1386     case ItemPositionLeft:
1387         return isLTR ? GridAxisStart : GridAxisEnd;
1388     case ItemPositionRight:
1389         return isLTR ? GridAxisEnd : GridAxisStart;
1390     case ItemPositionCenter:
1391         return GridAxisCenter;
1392     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1393     case ItemPositionStart:
1394         return GridAxisStart;
1395     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1396     case ItemPositionEnd:
1397         return GridAxisEnd;
1398     case ItemPositionStretch:
1399         return GridAxisStart;
1400     case ItemPositionBaseline:
1401     case ItemPositionLastBaseline:
1402         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1403         return GridAxisStart;
1404     case ItemPositionAuto:
1405         break;
1406     }
1407
1408     ASSERT_NOT_REACHED();
1409     return GridAxisStart;
1410 }
1411
1412 LayoutUnit RenderGrid::rowPositionForChild(const RenderBox& child) const
1413 {
1414     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1415     LayoutUnit startOfRow = m_rowPositions[coordinate.rows.resolvedInitialPosition.toInt()];
1416     LayoutUnit startPosition = startOfRow + marginBeforeForChild(child);
1417
1418     GridAxisPosition axisPosition = columnAxisPositionForChild(child);
1419     switch (axisPosition) {
1420     case GridAxisStart:
1421         return startPosition;
1422     case GridAxisEnd:
1423     case GridAxisCenter: {
1424         LayoutUnit endOfRow = m_rowPositions[coordinate.rows.resolvedFinalPosition.next().toInt()];
1425         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveAlignmentOverflow(style(), child.style()), endOfRow - startOfRow, child.logicalHeight() + child.marginLogicalHeight());
1426         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1427     }
1428     }
1429
1430     ASSERT_NOT_REACHED();
1431     return 0;
1432 }
1433
1434
1435 LayoutUnit RenderGrid::columnPositionForChild(const RenderBox& child) const
1436 {
1437     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1438     LayoutUnit startOfColumn = m_columnPositions[coordinate.columns.resolvedInitialPosition.toInt()];
1439     LayoutUnit startPosition = startOfColumn + marginStartForChild(child);
1440
1441     GridAxisPosition axisPosition = rowAxisPositionForChild(child);
1442     switch (axisPosition) {
1443     case GridAxisStart:
1444         return startPosition;
1445     case GridAxisEnd:
1446     case GridAxisCenter: {
1447         LayoutUnit endOfColumn = m_columnPositions[coordinate.columns.resolvedFinalPosition.next().toInt()];
1448         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveJustificationOverflow(style(), child.style()), endOfColumn - startOfColumn, child.logicalWidth() + child.marginLogicalWidth());
1449         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1450     }
1451     }
1452
1453     ASSERT_NOT_REACHED();
1454     return 0;
1455 }
1456
1457 LayoutPoint RenderGrid::findChildLogicalPosition(const RenderBox& child) const
1458 {
1459     LayoutUnit columnPosition = columnPositionForChild(child);
1460     // We stored m_columnPositions's data ignoring the direction, hence we might need now
1461     // to translate positions from RTL to LTR, as it's more convenient for painting.
1462     if (!style().isLeftToRightDirection())
1463         columnPosition = (m_columnPositions[m_columnPositions.size() - 1] + borderAndPaddingLogicalLeft()) - columnPosition  - child.logicalWidth();
1464
1465     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
1466     return LayoutPoint(columnPosition, rowPositionForChild(child));
1467 }
1468
1469 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1470 {
1471     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1472         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect, PaintAsInlineBlock);
1473 }
1474
1475 const char* RenderGrid::renderName() const
1476 {
1477     if (isFloating())
1478         return "RenderGrid (floating)";
1479     if (isOutOfFlowPositioned())
1480         return "RenderGrid (positioned)";
1481     if (isAnonymous())
1482         return "RenderGrid (generated)";
1483     if (isRelPositioned())
1484         return "RenderGrid (relative positioned)";
1485     return "RenderGrid";
1486 }
1487
1488 } // namespace WebCore
1489
1490 #endif /* ENABLE(CSS_GRID_LAYOUT) */