[CSS Grid Layout] Modify grid item height doesn't work
[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 ContentAlignmentData {
120     WTF_MAKE_FAST_ALLOCATED;
121 public:
122     bool isValid() { return positionOffset >= 0 && distributionOffset >= 0; }
123     static ContentAlignmentData defaultOffsets() { return {-1, -1}; }
124
125     LayoutUnit positionOffset;
126     LayoutUnit distributionOffset;
127 };
128
129 class RenderGrid::GridIterator {
130     WTF_MAKE_NONCOPYABLE(GridIterator);
131 public:
132     // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
133     // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
134     GridIterator(const Vector<Vector<Vector<RenderBox*, 1>>>& grid, GridTrackSizingDirection direction, unsigned fixedTrackIndex, unsigned varyingTrackIndex = 0)
135         : m_grid(grid)
136         , m_direction(direction)
137         , m_rowIndex((direction == ForColumns) ? varyingTrackIndex : fixedTrackIndex)
138         , m_columnIndex((direction == ForColumns) ? fixedTrackIndex : varyingTrackIndex)
139         , m_childIndex(0)
140     {
141         ASSERT(m_rowIndex < m_grid.size());
142         ASSERT(m_columnIndex < m_grid[0].size());
143     }
144
145     RenderBox* nextGridItem()
146     {
147         if (!m_grid.size())
148             return 0;
149
150         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
151         const unsigned endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
152         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
153             const auto& children = m_grid[m_rowIndex][m_columnIndex];
154             if (m_childIndex < children.size())
155                 return children[m_childIndex++];
156
157             m_childIndex = 0;
158         }
159         return 0;
160     }
161
162     bool isEmptyAreaEnough(unsigned rowSpan, unsigned columnSpan) const
163     {
164         // Ignore cells outside current grid as we will grow it later if needed.
165         unsigned maxRows = std::min<unsigned>(m_rowIndex + rowSpan, m_grid.size());
166         unsigned maxColumns = std::min<unsigned>(m_columnIndex + columnSpan, m_grid[0].size());
167
168         // This adds a O(N^2) behavior that shouldn't be a big deal as we expect spanning areas to be small.
169         for (unsigned row = m_rowIndex; row < maxRows; ++row) {
170             for (unsigned column = m_columnIndex; column < maxColumns; ++column) {
171                 auto& children = m_grid[row][column];
172                 if (!children.isEmpty())
173                     return false;
174             }
175         }
176
177         return true;
178     }
179
180     std::unique_ptr<GridCoordinate> nextEmptyGridArea(unsigned fixedTrackSpan, unsigned varyingTrackSpan)
181     {
182         ASSERT(fixedTrackSpan >= 1 && varyingTrackSpan >= 1);
183
184         if (m_grid.isEmpty())
185             return nullptr;
186
187         unsigned rowSpan = (m_direction == ForColumns) ? varyingTrackSpan : fixedTrackSpan;
188         unsigned columnSpan = (m_direction == ForColumns) ? fixedTrackSpan : varyingTrackSpan;
189
190         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
191         const unsigned endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
192         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
193             if (isEmptyAreaEnough(rowSpan, columnSpan)) {
194                 std::unique_ptr<GridCoordinate> result = std::make_unique<GridCoordinate>(GridSpan(m_rowIndex, m_rowIndex + rowSpan - 1), GridSpan(m_columnIndex, m_columnIndex + columnSpan - 1));
195                 // Advance the iterator to avoid an infinite loop where we would return the same grid area over and over.
196                 ++varyingTrackIndex;
197                 return result;
198             }
199         }
200         return nullptr;
201     }
202
203 private:
204     const Vector<Vector<Vector<RenderBox*, 1>>>& m_grid;
205     GridTrackSizingDirection m_direction;
206     unsigned m_rowIndex;
207     unsigned m_columnIndex;
208     unsigned m_childIndex;
209 };
210
211 class RenderGrid::GridSizingData {
212     WTF_MAKE_NONCOPYABLE(GridSizingData);
213 public:
214     GridSizingData(unsigned gridColumnCount, unsigned gridRowCount)
215         : columnTracks(gridColumnCount)
216         , rowTracks(gridRowCount)
217     {
218     }
219
220     Vector<GridTrack> columnTracks;
221     Vector<GridTrack> rowTracks;
222     Vector<unsigned> contentSizedTracksIndex;
223
224     // Performance optimization: hold onto these Vectors until the end of Layout to avoid repeated malloc / free.
225     Vector<GridTrack*> filteredTracks;
226     Vector<GridTrack*> growBeyondGrowthLimitsTracks;
227     Vector<GridItemWithSpan> itemsSortedByIncreasingSpan;
228 };
229
230 RenderGrid::RenderGrid(Element& element, Ref<RenderStyle>&& style)
231     : RenderBlock(element, WTF::move(style), 0)
232     , m_orderIterator(*this)
233 {
234     // All of our children must be block level.
235     setChildrenInline(false);
236 }
237
238 RenderGrid::~RenderGrid()
239 {
240 }
241
242 static inline bool defaultAlignmentIsStretch(ItemPosition position)
243 {
244     return position == ItemPositionStretch || position == ItemPositionAuto;
245 }
246
247 static inline bool defaultAlignmentChangedToStretchInRowAxis(const RenderStyle& oldStyle, const RenderStyle& newStyle)
248 {
249     return !defaultAlignmentIsStretch(oldStyle.justifyItemsPosition()) && defaultAlignmentIsStretch(newStyle.justifyItemsPosition());
250 }
251
252 static inline bool defaultAlignmentChangedFromStretchInColumnAxis(const RenderStyle& oldStyle, const RenderStyle& newStyle)
253 {
254     return defaultAlignmentIsStretch(oldStyle.alignItemsPosition()) && !defaultAlignmentIsStretch(newStyle.alignItemsPosition());
255 }
256
257 static inline bool selfAlignmentChangedToStretchInRowAxis(const RenderStyle& oldStyle, const RenderStyle& newStyle, const RenderStyle& childStyle)
258 {
259     return RenderStyle::resolveJustification(oldStyle, childStyle, ItemPositionStretch) != ItemPositionStretch
260         && RenderStyle::resolveJustification(newStyle, childStyle, ItemPositionStretch) == ItemPositionStretch;
261 }
262
263 static inline bool selfAlignmentChangedFromStretchInColumnAxis(const RenderStyle& oldStyle, const RenderStyle& newStyle, const RenderStyle& childStyle)
264 {
265     return RenderStyle::resolveAlignment(oldStyle, childStyle, ItemPositionStretch) == ItemPositionStretch
266         && RenderStyle::resolveAlignment(newStyle, childStyle, ItemPositionStretch) != ItemPositionStretch;
267 }
268
269 void RenderGrid::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
270 {
271     RenderBlock::styleDidChange(diff, oldStyle);
272     if (!oldStyle || diff != StyleDifferenceLayout)
273         return;
274
275     const RenderStyle& newStyle = style();
276     if (defaultAlignmentChangedToStretchInRowAxis(*oldStyle, newStyle) || defaultAlignmentChangedFromStretchInColumnAxis(*oldStyle, newStyle)) {
277         // Grid items that were not previously stretched in row-axis need to be relayed out so we can compute new available space.
278         // Grid items that were previously stretching in column-axis need to be relayed out so we can compute new available space.
279         // This is only necessary for stretching since other alignment values don't change the size of the box.
280         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
281             if (child->isOutOfFlowPositioned())
282                 continue;
283             if (selfAlignmentChangedToStretchInRowAxis(*oldStyle, newStyle, child->style()) || selfAlignmentChangedFromStretchInColumnAxis(*oldStyle, newStyle, child->style()))
284                 child->setChildNeedsLayout(MarkOnlyThis);
285         }
286     }
287 }
288
289 void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
290 {
291     ASSERT(needsLayout());
292
293     if (!relayoutChildren && simplifiedLayout())
294         return;
295
296     // FIXME: Much of this method is boiler plate that matches RenderBox::layoutBlock and Render*FlexibleBox::layoutBlock.
297     // It would be nice to refactor some of the duplicate code.
298     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
299     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
300
301     preparePaginationBeforeBlockLayout(relayoutChildren);
302
303     LayoutSize previousSize = size();
304
305     setLogicalHeight(0);
306     updateLogicalWidth();
307
308     layoutGridItems();
309
310     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
311     updateLogicalHeight();
312
313     if (size() != previousSize)
314         relayoutChildren = true;
315
316     layoutPositionedObjects(relayoutChildren || isRoot());
317
318     computeOverflow(oldClientAfterEdge);
319     statePusher.pop();
320
321     updateLayerTransform();
322
323     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
324     // we overflow or not.
325     updateScrollInfoAfterLayout();
326
327     repainter.repaintAfterLayout();
328
329     clearNeedsLayout();
330 }
331
332 LayoutUnit RenderGrid::guttersSize(GridTrackSizingDirection direction, size_t span) const
333 {
334     ASSERT(span >= 1);
335
336     if (span == 1)
337         return { };
338
339     const Length& trackGap = direction == ForColumns ? style().gridColumnGap() : style().gridRowGap();
340     return valueForLength(trackGap, 0) * (span - 1);
341 }
342
343 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
344 {
345     bool wasPopulated = gridWasPopulated();
346     if (!wasPopulated)
347         const_cast<RenderGrid*>(this)->placeItemsOnGrid();
348
349     GridSizingData sizingData(gridColumnCount(), gridRowCount());
350     LayoutUnit availableLogicalSpace = 0;
351     const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
352
353     for (auto& column : sizingData.columnTracks) {
354         LayoutUnit minTrackBreadth = column.baseSize();
355         LayoutUnit maxTrackBreadth = column.growthLimit();
356
357         minLogicalWidth += minTrackBreadth;
358         maxLogicalWidth += maxTrackBreadth;
359     }
360
361     LayoutUnit totalGuttersSize = guttersSize(ForColumns, sizingData.columnTracks.size());
362     minLogicalWidth += totalGuttersSize;
363     maxLogicalWidth += totalGuttersSize;
364
365     LayoutUnit scrollbarWidth = intrinsicScrollbarLogicalWidth();
366     minLogicalWidth += scrollbarWidth;
367     maxLogicalWidth += scrollbarWidth;
368
369     if (!wasPopulated)
370         const_cast<RenderGrid*>(this)->clearGrid();
371 }
372
373 bool RenderGrid::gridElementIsShrinkToFit()
374 {
375     return isFloatingOrOutOfFlowPositioned();
376 }
377
378 static inline double normalizedFlexFraction(const GridTrack& track, double flexFactor)
379 {
380     return track.baseSize() / std::max<double>(1, flexFactor);
381 }
382
383 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
384 {
385     const LayoutUnit initialAvailableLogicalSpace = availableLogicalSpace;
386     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
387     Vector<unsigned> flexibleSizedTracksIndex;
388     sizingData.contentSizedTracksIndex.shrink(0);
389
390     // 1. Initialize per Grid track variables.
391     for (unsigned i = 0; i < tracks.size(); ++i) {
392         GridTrack& track = tracks[i];
393         const GridTrackSize& trackSize = gridTrackSize(direction, i);
394         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
395         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
396
397         track.setBaseSize(computeUsedBreadthOfMinLength(direction, minTrackBreadth));
398         track.setGrowthLimit(computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.baseSize()));
399         track.setInfinitelyGrowable(false);
400
401         if (trackSize.isContentSized())
402             sizingData.contentSizedTracksIndex.append(i);
403         if (trackSize.maxTrackBreadth().isFlex())
404             flexibleSizedTracksIndex.append(i);
405     }
406
407     // 2. Resolve content-based TrackSizingFunctions.
408     if (!sizingData.contentSizedTracksIndex.isEmpty())
409         resolveContentBasedTrackSizingFunctions(direction, sizingData);
410
411     for (auto& track : tracks) {
412         ASSERT(!track.growthLimitIsInfinite());
413         availableLogicalSpace -= track.baseSize();
414     }
415
416     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
417
418     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
419         return;
420
421     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until availableLogicalSpace is exhausted.
422     if (!hasUndefinedRemainingSpace) {
423         const unsigned tracksSize = tracks.size();
424         Vector<GridTrack*> tracksForDistribution(tracksSize);
425         for (unsigned i = 0; i < tracksSize; ++i) {
426             tracksForDistribution[i] = tracks.data() + i;
427             tracksForDistribution[i]->setPlannedSize(tracksForDistribution[i]->baseSize());
428         }
429
430         distributeSpaceToTracks<MaximizeTracks>(tracksForDistribution, nullptr, availableLogicalSpace);
431
432         for (auto* track : tracksForDistribution)
433             track->setBaseSize(track->plannedSize());
434     } else {
435         for (auto& track : tracks)
436             track.setBaseSize(track.growthLimit());
437     }
438
439     if (flexibleSizedTracksIndex.isEmpty())
440         return;
441
442     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
443     double flexFraction = 0;
444     if (!hasUndefinedRemainingSpace)
445         flexFraction = findFlexFactorUnitSize(tracks, GridSpan(0, tracks.size() - 1), direction, initialAvailableLogicalSpace);
446     else {
447         for (const auto& trackIndex : flexibleSizedTracksIndex)
448             flexFraction = std::max(flexFraction, normalizedFlexFraction(tracks[trackIndex], gridTrackSize(direction, trackIndex).maxTrackBreadth().flex()));
449
450         for (unsigned i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
451             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
452             while (RenderBox* gridItem = iterator.nextGridItem()) {
453                 const GridCoordinate coordinate = cachedGridCoordinate(*gridItem);
454                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
455
456                 // Do not include already processed items.
457                 if (i > 0 && span.resolvedInitialPosition.toInt() <= flexibleSizedTracksIndex[i - 1])
458                     continue;
459
460                 flexFraction = std::max(flexFraction, findFlexFactorUnitSize(tracks, span, direction, maxContentForChild(*gridItem, direction, sizingData.columnTracks)));
461             }
462         }
463     }
464
465     for (auto trackIndex : flexibleSizedTracksIndex) {
466         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
467         GridTrack& track = tracks[trackIndex];
468         LayoutUnit baseSize = std::max<LayoutUnit>(track.baseSize(), flexFraction * trackSize.maxTrackBreadth().flex());
469         track.setBaseSize(baseSize);
470         availableLogicalSpace -= baseSize;
471     }
472 }
473
474 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
475 {
476     if (gridLength.isFlex())
477         return 0;
478
479     const Length& trackLength = gridLength.length();
480     if (trackLength.isSpecified())
481         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
482
483     ASSERT(trackLength.isMinContent() || trackLength.isAuto() || trackLength.isMaxContent());
484     return 0;
485 }
486
487 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
488 {
489     if (gridLength.isFlex())
490         return usedBreadth;
491
492     const Length& trackLength = gridLength.length();
493     if (trackLength.isSpecified()) {
494         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
495         ASSERT(computedBreadth != infinity);
496         return computedBreadth;
497     }
498
499     ASSERT(trackLength.isMinContent() || trackLength.isAuto() || trackLength.isMaxContent());
500     return infinity;
501 }
502
503 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
504 {
505     ASSERT(trackLength.isSpecified());
506     if (direction == ForColumns)
507         return valueForLength(trackLength, contentLogicalWidth());
508     return valueForLength(trackLength, computeContentLogicalHeight(MainOrPreferredSize, style().logicalHeight(), Nullopt).valueOr(0));
509 }
510
511 double RenderGrid::computeFlexFactorUnitSize(const Vector<GridTrack>& tracks, GridTrackSizingDirection direction, double flexFactorSum, LayoutUnit leftOverSpace, const Vector<unsigned, 8>& flexibleTracksIndexes, std::unique_ptr<TrackIndexSet> tracksToTreatAsInflexible) const
512 {
513     // We want to avoid the effect of flex factors sum below 1 making the factor unit size to grow exponentially.
514     double hypotheticalFactorUnitSize = leftOverSpace / std::max<double>(1, flexFactorSum);
515
516     // product of the hypothetical "flex factor unit" and any flexible track's "flex factor" must be grater than such track's "base size".
517     bool validFlexFactorUnit = true;
518     for (auto index : flexibleTracksIndexes) {
519         if (tracksToTreatAsInflexible && tracksToTreatAsInflexible->contains(index))
520             continue;
521         LayoutUnit baseSize = tracks[index].baseSize();
522         double flexFactor = gridTrackSize(direction, index).maxTrackBreadth().flex();
523         // treating all such tracks as inflexible.
524         if (baseSize > hypotheticalFactorUnitSize * flexFactor) {
525             leftOverSpace -= baseSize;
526             flexFactorSum -= flexFactor;
527             if (!tracksToTreatAsInflexible)
528                 tracksToTreatAsInflexible = std::unique_ptr<TrackIndexSet>(new TrackIndexSet());
529             tracksToTreatAsInflexible->add(index);
530             validFlexFactorUnit = false;
531         }
532     }
533     if (!validFlexFactorUnit)
534         return computeFlexFactorUnitSize(tracks, direction, flexFactorSum, leftOverSpace, flexibleTracksIndexes, WTF::move(tracksToTreatAsInflexible));
535     return hypotheticalFactorUnitSize;
536 }
537
538 double RenderGrid::findFlexFactorUnitSize(const Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit leftOverSpace) const
539 {
540     if (leftOverSpace <= 0)
541         return 0;
542
543     double flexFactorSum = 0;
544     Vector<unsigned, 8> flexibleTracksIndexes;
545     for (const auto& resolvedPosition : tracksSpan) {
546         unsigned trackIndex = resolvedPosition.toInt();
547         GridTrackSize trackSize = gridTrackSize(direction, trackIndex);
548         if (!trackSize.maxTrackBreadth().isFlex())
549             leftOverSpace -= tracks[trackIndex].baseSize();
550         else {
551             double flexFactor = trackSize.maxTrackBreadth().flex();
552             flexibleTracksIndexes.append(trackIndex);
553             flexFactorSum += flexFactor;
554         }
555     }
556
557     // The function is not called if we don't have <flex> grid tracks
558     ASSERT(!flexibleTracksIndexes.isEmpty());
559
560     return computeFlexFactorUnitSize(tracks, direction, flexFactorSum, leftOverSpace, flexibleTracksIndexes);
561 }
562
563 bool RenderGrid::hasDefiniteLogicalSize(GridTrackSizingDirection direction) const
564 {
565     return (direction == ForRows) ? hasDefiniteLogicalHeight() : hasDefiniteLogicalWidth();
566 }
567
568 GridTrackSize RenderGrid::gridTrackSize(GridTrackSizingDirection direction, unsigned i) const
569 {
570     bool isForColumns = (direction == ForColumns);
571     auto& trackStyles =  isForColumns ? style().gridColumns() : style().gridRows();
572     auto& trackSize = (i >= trackStyles.size()) ? (isForColumns ? style().gridAutoColumns() : style().gridAutoRows()) : trackStyles[i];
573
574     GridLength minTrackBreadth = trackSize.minTrackBreadth();
575     GridLength maxTrackBreadth = trackSize.maxTrackBreadth();
576
577     if (minTrackBreadth.isPercentage() || maxTrackBreadth.isPercentage()) {
578         if (!hasDefiniteLogicalSize(direction)) {
579             if (minTrackBreadth.isPercentage())
580                 minTrackBreadth = Length(MinContent);
581             if (maxTrackBreadth.isPercentage())
582                 maxTrackBreadth = Length(MaxContent);
583         }
584     }
585
586     return GridTrackSize(minTrackBreadth, maxTrackBreadth);
587 }
588
589 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox& child, Vector<GridTrack>& columnTracks)
590 {
591     Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
592     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
593     if (child.hasRelativeLogicalHeight() || !oldOverrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalWidth.value() != overrideContainingBlockContentLogicalWidth)
594         child.setNeedsLayout(MarkOnlyThis);
595
596     // We need to clear the stretched height to properly compute logical height during layout.
597     if (child.needsLayout())
598         child.clearOverrideLogicalContentHeight();
599
600     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
601     // If |child| has a relative logical height, we shouldn't let it override its intrinsic height, which is
602     // what we are interested in here. Thus we need to set the override logical height to Nullopt (no possible resolution).
603     if (child.hasRelativeLogicalHeight())
604         child.setOverrideContainingBlockContentLogicalHeight(Nullopt);
605     child.layoutIfNeeded();
606     return child.logicalHeight() + child.marginLogicalHeight();
607 }
608
609 LayoutUnit RenderGrid::minSizeForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
610 {
611     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
612     // FIXME: Properly support orthogonal writing mode.
613     if (hasOrthogonalWritingMode)
614         return { };
615
616     const Length& childMinSize = direction == ForColumns ? child.style().logicalMinWidth() : child.style().logicalMinHeight();
617     if (childMinSize.isAuto()) {
618         // FIXME: Implement intrinsic aspect ratio support (transferred size in specs).
619         return minContentForChild(child, direction, columnTracks);
620     }
621
622     if (direction == ForColumns)
623         return child.computeLogicalWidthInRegionUsing(MinSize, childMinSize, contentLogicalWidth(), this, nullptr);
624
625     return child.computeContentAndScrollbarLogicalHeightUsing(MinSize, childMinSize, child.logicalHeight()).valueOr(0);
626 }
627
628 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
629 {
630     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
631     // FIXME: Properly support orthogonal writing mode.
632     if (hasOrthogonalWritingMode)
633         return 0;
634
635     if (direction == ForColumns) {
636         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
637         // what we are interested in here. Thus we need to set the override logical width to Nullopt (no possible resolution).
638         if (child.hasRelativeLogicalWidth())
639             child.setOverrideContainingBlockContentLogicalWidth(Nullopt);
640
641         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
642         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
643         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
644     }
645
646     return logicalContentHeightForChild(child, columnTracks);
647 }
648
649 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
650 {
651     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
652     // FIXME: Properly support orthogonal writing mode.
653     if (hasOrthogonalWritingMode)
654         return LayoutUnit();
655
656     if (direction == ForColumns) {
657         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
658         // what we are interested in here. Thus we need to set the override logical width to Nullopt (no possible resolution).
659         if (child.hasRelativeLogicalWidth())
660             child.setOverrideContainingBlockContentLogicalWidth(Nullopt);
661
662         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
663         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
664         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
665     }
666
667     return logicalContentHeightForChild(child, columnTracks);
668 }
669
670 class GridItemWithSpan {
671 public:
672     GridItemWithSpan(RenderBox& gridItem, GridCoordinate coordinate, GridTrackSizingDirection direction)
673         : m_gridItem(gridItem)
674         , m_coordinate(coordinate)
675     {
676         const GridSpan& span = (direction == ForRows) ? coordinate.rows : coordinate.columns;
677         m_span = span.resolvedFinalPosition.toInt() - span.resolvedInitialPosition.toInt() + 1;
678     }
679
680     RenderBox& gridItem() const { return m_gridItem; }
681     GridCoordinate coordinate() const { return m_coordinate; }
682 #if !ASSERT_DISABLED
683     size_t span() const { return m_span; }
684 #endif
685
686     bool operator<(const GridItemWithSpan other) const
687     {
688         return m_span < other.m_span;
689     }
690
691 private:
692     std::reference_wrapper<RenderBox> m_gridItem;
693     GridCoordinate m_coordinate;
694     unsigned m_span;
695 };
696
697 bool RenderGrid::spanningItemCrossesFlexibleSizedTracks(const GridCoordinate& coordinate, GridTrackSizingDirection direction) const
698 {
699     const GridSpan itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
700     for (auto trackPosition : itemSpan) {
701         const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
702         if (trackSize.minTrackBreadth().isFlex() || trackSize.maxTrackBreadth().isFlex())
703             return true;
704     }
705
706     return false;
707 }
708
709 static inline unsigned integerSpanForDirection(const GridCoordinate& coordinate, GridTrackSizingDirection direction)
710 {
711     return (direction == ForRows) ? coordinate.rows.integerSpan() : coordinate.columns.integerSpan();
712 }
713
714 struct GridItemsSpanGroupRange {
715     Vector<GridItemWithSpan>::iterator rangeStart;
716     Vector<GridItemWithSpan>::iterator rangeEnd;
717 };
718
719 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
720 {
721     sizingData.itemsSortedByIncreasingSpan.shrink(0);
722     HashSet<RenderBox*> itemsSet;
723     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
724         GridIterator iterator(m_grid, direction, trackIndex);
725         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
726
727         while (RenderBox* gridItem = iterator.nextGridItem()) {
728             if (itemsSet.add(gridItem).isNewEntry) {
729                 const GridCoordinate& coordinate = cachedGridCoordinate(*gridItem);
730                 if (integerSpanForDirection(coordinate, direction) == 1)
731                     resolveContentBasedTrackSizingFunctionsForNonSpanningItems(direction, coordinate, *gridItem, track, sizingData.columnTracks);
732                 else if (!spanningItemCrossesFlexibleSizedTracks(coordinate, direction))
733                     sizingData.itemsSortedByIncreasingSpan.append(GridItemWithSpan(*gridItem, coordinate, direction));
734             }
735         }
736     }
737     std::sort(sizingData.itemsSortedByIncreasingSpan.begin(), sizingData.itemsSortedByIncreasingSpan.end());
738
739     auto it = sizingData.itemsSortedByIncreasingSpan.begin();
740     auto end = sizingData.itemsSortedByIncreasingSpan.end();
741     while (it != end) {
742         GridItemsSpanGroupRange spanGroupRange = { it, std::upper_bound(it, end, *it) };
743         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMinimums>(direction, sizingData, spanGroupRange);
744         resolveContentBasedTrackSizingFunctionsForItems<ResolveContentBasedMinimums>(direction, sizingData, spanGroupRange);
745         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMinimums>(direction, sizingData, spanGroupRange);
746         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMaximums>(direction, sizingData, spanGroupRange);
747         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMaximums>(direction, sizingData, spanGroupRange);
748         it = spanGroupRange.rangeEnd;
749     }
750
751     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
752         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
753         if (track.growthLimitIsInfinite())
754             track.setGrowthLimit(track.baseSize());
755     }
756 }
757
758 void RenderGrid::resolveContentBasedTrackSizingFunctionsForNonSpanningItems(GridTrackSizingDirection direction, const GridCoordinate& coordinate, RenderBox& gridItem, GridTrack& track, Vector<GridTrack>& columnTracks)
759 {
760     const GridResolvedPosition trackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
761     GridTrackSize trackSize = gridTrackSize(direction, trackPosition.toInt());
762
763     if (trackSize.hasMinContentMinTrackBreadth())
764         track.setBaseSize(std::max(track.baseSize(), minContentForChild(gridItem, direction, columnTracks)));
765     else if (trackSize.hasMaxContentMinTrackBreadth())
766         track.setBaseSize(std::max(track.baseSize(), maxContentForChild(gridItem, direction, columnTracks)));
767     else if (trackSize.hasAutoMinTrackBreadth())
768         track.setBaseSize(std::max(track.baseSize(), minSizeForChild(gridItem, direction, columnTracks)));
769
770     if (trackSize.hasMinContentMaxTrackBreadth())
771         track.setGrowthLimit(std::max(track.growthLimit(), minContentForChild(gridItem, direction, columnTracks)));
772     else if (trackSize.hasMaxContentOrAutoMaxTrackBreadth())
773         track.setGrowthLimit(std::max(track.growthLimit(), maxContentForChild(gridItem, direction, columnTracks)));
774 }
775
776 const LayoutUnit& RenderGrid::trackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track, TrackSizeRestriction restriction)
777 {
778     switch (phase) {
779     case ResolveIntrinsicMinimums:
780     case ResolveContentBasedMinimums:
781     case ResolveMaxContentMinimums:
782     case MaximizeTracks:
783         return track.baseSize();
784     case ResolveIntrinsicMaximums:
785     case ResolveMaxContentMaximums:
786         return restriction == AllowInfinity ? track.growthLimit() : track.growthLimitIfNotInfinite();
787     }
788
789     ASSERT_NOT_REACHED();
790     return track.baseSize();
791 }
792
793 bool RenderGrid::shouldProcessTrackForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
794 {
795     switch (phase) {
796     case ResolveIntrinsicMinimums:
797         return trackSize.hasIntrinsicMinTrackBreadth();
798     case ResolveContentBasedMinimums:
799         return trackSize.hasMinOrMaxContentMinTrackBreadth();
800     case ResolveMaxContentMinimums:
801         return trackSize.hasMaxContentMinTrackBreadth();
802     case ResolveIntrinsicMaximums:
803         return trackSize.hasMinOrMaxContentMaxTrackBreadth();
804     case ResolveMaxContentMaximums:
805         return trackSize.hasMaxContentOrAutoMaxTrackBreadth();
806     case MaximizeTracks:
807         ASSERT_NOT_REACHED();
808         return false;
809     }
810
811     ASSERT_NOT_REACHED();
812     return false;
813 }
814
815 bool RenderGrid::trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
816 {
817     switch (phase) {
818     case ResolveIntrinsicMinimums:
819     case ResolveContentBasedMinimums:
820         return trackSize.hasAutoOrMinContentMinTrackBreadthAndIntrinsicMaxTrackBreadth();
821     case ResolveMaxContentMinimums:
822         return trackSize.hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth();
823     case ResolveIntrinsicMaximums:
824     case ResolveMaxContentMaximums:
825         return true;
826     case MaximizeTracks:
827         ASSERT_NOT_REACHED();
828         return false;
829     }
830
831     ASSERT_NOT_REACHED();
832     return false;
833 }
834
835 void RenderGrid::markAsInfinitelyGrowableForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
836 {
837     switch (phase) {
838     case ResolveIntrinsicMinimums:
839     case ResolveContentBasedMinimums:
840     case ResolveMaxContentMinimums:
841         return;
842     case ResolveIntrinsicMaximums:
843         if (trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity) == infinity  && track.plannedSize() != infinity)
844             track.setInfinitelyGrowable(true);
845         return;
846     case ResolveMaxContentMaximums:
847         if (track.infinitelyGrowable())
848             track.setInfinitelyGrowable(false);
849         return;
850     case MaximizeTracks:
851         ASSERT_NOT_REACHED();
852         return;
853     }
854
855     ASSERT_NOT_REACHED();
856 }
857
858 void RenderGrid::updateTrackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
859 {
860     switch (phase) {
861     case ResolveIntrinsicMinimums:
862     case ResolveContentBasedMinimums:
863     case ResolveMaxContentMinimums:
864         track.setBaseSize(track.plannedSize());
865         return;
866     case ResolveIntrinsicMaximums:
867     case ResolveMaxContentMaximums:
868         track.setGrowthLimit(track.plannedSize());
869         return;
870     case MaximizeTracks:
871         ASSERT_NOT_REACHED();
872         return;
873     }
874
875     ASSERT_NOT_REACHED();
876 }
877
878 LayoutUnit RenderGrid::currentItemSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, RenderBox& gridItem, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
879 {
880     switch (phase) {
881     case ResolveIntrinsicMinimums:
882         return minSizeForChild(gridItem, direction, columnTracks);
883     case ResolveContentBasedMinimums:
884     case ResolveIntrinsicMaximums:
885         return minContentForChild(gridItem, direction, columnTracks);
886     case ResolveMaxContentMinimums:
887     case ResolveMaxContentMaximums:
888         return maxContentForChild(gridItem, direction, columnTracks);
889     case MaximizeTracks:
890         ASSERT_NOT_REACHED();
891         return 0;
892     }
893
894     ASSERT_NOT_REACHED();
895     return 0;
896 }
897
898 template <RenderGrid::TrackSizeComputationPhase phase>
899 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, const GridItemsSpanGroupRange& gridItemsWithSpan)
900 {
901     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
902     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
903         GridTrack& track = tracks[trackIndex];
904         track.setPlannedSize(trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity));
905     }
906
907     for (auto it = gridItemsWithSpan.rangeStart; it != gridItemsWithSpan.rangeEnd; ++it) {
908         GridItemWithSpan& gridItemWithSpan = *it;
909         ASSERT(gridItemWithSpan.span() > 1);
910         const GridCoordinate& coordinate = gridItemWithSpan.coordinate();
911         const GridSpan& itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
912
913         sizingData.filteredTracks.shrink(0);
914         sizingData.growBeyondGrowthLimitsTracks.shrink(0);
915         LayoutUnit spanningTracksSize;
916         for (auto& trackPosition : itemSpan) {
917             const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
918             GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPosition.toInt()] : sizingData.rowTracks[trackPosition.toInt()];
919             spanningTracksSize += trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
920             if (!shouldProcessTrackForTrackSizeComputationPhase(phase, trackSize))
921                 continue;
922
923             sizingData.filteredTracks.append(&track);
924
925             if (trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(phase, trackSize))
926                 sizingData.growBeyondGrowthLimitsTracks.append(&track);
927         }
928
929         if (sizingData.filteredTracks.isEmpty())
930             continue;
931
932         spanningTracksSize += guttersSize(direction, itemSpan.integerSpan());
933
934         LayoutUnit extraSpace = currentItemSizeForTrackSizeComputationPhase(phase, gridItemWithSpan.gridItem(), direction, sizingData.columnTracks) - spanningTracksSize;
935         extraSpace = std::max<LayoutUnit>(extraSpace, 0);
936         auto& tracksToGrowBeyondGrowthLimits = sizingData.growBeyondGrowthLimitsTracks.isEmpty() ? sizingData.filteredTracks : sizingData.growBeyondGrowthLimitsTracks;
937         distributeSpaceToTracks<phase>(sizingData.filteredTracks, &tracksToGrowBeyondGrowthLimits, extraSpace);
938     }
939
940     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
941         GridTrack& track = tracks[trackIndex];
942         markAsInfinitelyGrowableForTrackSizeComputationPhase(phase, track);
943         updateTrackSizeForTrackSizeComputationPhase(phase, track);
944     }
945 }
946
947 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
948 {
949     // This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
950     // (forall x: NOT x < x).
951     if (track1->infiniteGrowthPotential() && track2->infiniteGrowthPotential())
952         return false;
953
954     if (track1->infiniteGrowthPotential() || track2->infiniteGrowthPotential())
955         return track2->infiniteGrowthPotential();
956
957     return (track1->growthLimit() - track1->baseSize()) < (track2->growthLimit() - track2->baseSize());
958 }
959
960 template <RenderGrid::TrackSizeComputationPhase phase>
961 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, const Vector<GridTrack*>* growBeyondGrowthLimitsTracks, LayoutUnit& availableLogicalSpace)
962 {
963     ASSERT(availableLogicalSpace >= 0);
964
965     for (auto* track : tracks)
966         track->tempSize() = trackSizeForTrackSizeComputationPhase(phase, *track, ForbidInfinity);
967
968     if (availableLogicalSpace > 0) {
969         std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
970
971         unsigned tracksSize = tracks.size();
972         for (unsigned i = 0; i < tracksSize; ++i) {
973             GridTrack& track = *tracks[i];
974             const LayoutUnit& trackBreadth = trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
975             bool infiniteGrowthPotential = track.infiniteGrowthPotential();
976             LayoutUnit trackGrowthPotential = infiniteGrowthPotential ? track.growthLimit() : track.growthLimit() - trackBreadth;
977             // Let's avoid computing availableLogicalSpaceShare as much as possible as it's a hot spot in performance tests.
978             if (trackGrowthPotential > 0 || infiniteGrowthPotential) {
979                 LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
980                 LayoutUnit growthShare = infiniteGrowthPotential ? availableLogicalSpaceShare : std::min(availableLogicalSpaceShare, trackGrowthPotential);
981                 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.");
982                 track.tempSize() += growthShare;
983                 availableLogicalSpace -= growthShare;
984             }
985         }
986     }
987
988     if (availableLogicalSpace > 0 && growBeyondGrowthLimitsTracks) {
989         unsigned tracksGrowingBeyondGrowthLimitsSize = growBeyondGrowthLimitsTracks->size();
990         for (unsigned i = 0; i < tracksGrowingBeyondGrowthLimitsSize; ++i) {
991             GridTrack* track = growBeyondGrowthLimitsTracks->at(i);
992             LayoutUnit growthShare = availableLogicalSpace / (tracksGrowingBeyondGrowthLimitsSize - i);
993             track->tempSize() += growthShare;
994             availableLogicalSpace -= growthShare;
995         }
996     }
997
998     for (auto* track : tracks)
999         track->setPlannedSize(track->plannedSize() == infinity ? track->tempSize() : std::max(track->plannedSize(), track->tempSize()));
1000 }
1001
1002 #ifndef NDEBUG
1003 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
1004 {
1005     for (unsigned i = 0; i < tracks.size(); ++i) {
1006         const GridTrackSize& trackSize = gridTrackSize(direction, i);
1007         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
1008         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].baseSize())
1009             return false;
1010     }
1011     return true;
1012 }
1013 #endif
1014
1015 void RenderGrid::ensureGridSize(unsigned maximumRowIndex, unsigned maximumColumnIndex)
1016 {
1017     const unsigned oldRowCount = gridRowCount();
1018     if (maximumRowIndex >= oldRowCount) {
1019         m_grid.grow(maximumRowIndex + 1);
1020         for (unsigned row = oldRowCount; row < gridRowCount(); ++row)
1021             m_grid[row].grow(gridColumnCount());
1022     }
1023
1024     if (maximumColumnIndex >= gridColumnCount()) {
1025         for (unsigned row = 0; row < gridRowCount(); ++row)
1026             m_grid[row].grow(maximumColumnIndex + 1);
1027     }
1028 }
1029
1030 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
1031 {
1032     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
1033
1034     for (auto& row : coordinate.rows) {
1035         for (auto& column : coordinate.columns)
1036             m_grid[row.toInt()][column.toInt()].append(&child);
1037     }
1038     m_gridItemCoordinate.set(&child, coordinate);
1039 }
1040
1041 void RenderGrid::placeItemsOnGrid()
1042 {
1043     ASSERT(!gridWasPopulated());
1044     ASSERT(m_gridItemCoordinate.isEmpty());
1045
1046     populateExplicitGridAndOrderIterator();
1047
1048     Vector<RenderBox*> autoMajorAxisAutoGridItems;
1049     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
1050     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
1051         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
1052         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
1053
1054         if (unresolvedRowPositions.requiresAutoPlacement() || unresolvedColumnPositions.requiresAutoPlacement()) {
1055
1056             bool majorAxisDirectionIsForColumns = autoPlacementMajorAxisDirection() == ForColumns;
1057             if ((majorAxisDirectionIsForColumns && unresolvedColumnPositions.requiresAutoPlacement())
1058                 || (!majorAxisDirectionIsForColumns && unresolvedRowPositions.requiresAutoPlacement()))
1059                 autoMajorAxisAutoGridItems.append(child);
1060             else
1061                 specifiedMajorAxisAutoGridItems.append(child);
1062             continue;
1063         }
1064         GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
1065         GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
1066         insertItemIntoGrid(*child, GridCoordinate(rowPositions, columnPositions));
1067     }
1068
1069     ASSERT(gridRowCount() >= GridResolvedPosition::explicitGridRowCount(style()));
1070     ASSERT(gridColumnCount() >= GridResolvedPosition::explicitGridColumnCount(style()));
1071
1072     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
1073     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
1074 }
1075
1076 void RenderGrid::populateExplicitGridAndOrderIterator()
1077 {
1078     OrderIteratorPopulator populator(m_orderIterator);
1079     unsigned maximumRowIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridRowCount(style()));
1080     unsigned maximumColumnIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridColumnCount(style()));
1081
1082     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1083         populator.collectChild(*child);
1084
1085         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
1086         if (!unresolvedRowPositions.requiresAutoPlacement()) {
1087             GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
1088             maximumRowIndex = std::max(maximumRowIndex, rowPositions.resolvedFinalPosition.next().toInt());
1089         } else {
1090             // Grow the grid for items with a definite row span, getting the largest such span.
1091             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
1092             maximumRowIndex = std::max(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
1093         }
1094
1095         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
1096         if (!unresolvedColumnPositions.requiresAutoPlacement()) {
1097             GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
1098             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions.resolvedFinalPosition.next().toInt());
1099         } else {
1100             // Grow the grid for items with a definite column span, getting the largest such span.
1101             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
1102             maximumColumnIndex = std::max(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
1103         }
1104     }
1105
1106     m_grid.grow(maximumRowIndex);
1107     for (auto& column : m_grid)
1108         column.grow(maximumColumnIndex);
1109 }
1110
1111 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
1112 {
1113     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
1114     const unsigned endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
1115     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
1116     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
1117 }
1118
1119 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1120 {
1121     bool isForColumns = autoPlacementMajorAxisDirection() == ForColumns;
1122     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1123
1124     // Mapping between the major axis tracks (rows or columns) and the last auto-placed item's position inserted on
1125     // that track. This is needed to implement "sparse" packing for items locked to a given track.
1126     // See http://dev.w3.org/csswg/css-grid/#auto-placement-algo
1127     HashMap<unsigned, unsigned, DefaultHash<unsigned>::Hash, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> minorAxisCursors;
1128
1129     for (auto& autoGridItem : autoGridItems) {
1130         auto unresolvedMajorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
1131         ASSERT(!unresolvedMajorAxisPositions.requiresAutoPlacement());
1132         GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMajorAxisPositions, style());
1133         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1134         unsigned majorAxisInitialPosition = majorAxisPositions.resolvedInitialPosition.toInt();
1135
1136         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions.resolvedInitialPosition.toInt(), isGridAutoFlowDense ? 0 : minorAxisCursors.get(majorAxisInitialPosition));
1137         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1138         if (!emptyGridArea)
1139             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), majorAxisPositions);
1140         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
1141
1142         if (!isGridAutoFlowDense)
1143             minorAxisCursors.set(majorAxisInitialPosition, isForColumns ? emptyGridArea->rows.resolvedInitialPosition.toInt() : emptyGridArea->columns.resolvedInitialPosition.toInt());
1144     }
1145 }
1146
1147 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1148 {
1149     AutoPlacementCursor autoPlacementCursor = {0, 0};
1150     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1151
1152     for (auto& autoGridItem : autoGridItems) {
1153         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
1154
1155         if (isGridAutoFlowDense) {
1156             autoPlacementCursor.first = 0;
1157             autoPlacementCursor.second = 0;
1158         }
1159     }
1160 }
1161
1162 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
1163 {
1164     ASSERT(GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()).requiresAutoPlacement());
1165     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
1166
1167     const unsigned endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
1168     unsigned majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
1169     unsigned minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
1170
1171     std::unique_ptr<GridCoordinate> emptyGridArea;
1172     auto unresolvedMinorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
1173     if (!unresolvedMinorAxisPositions.requiresAutoPlacement()) {
1174         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMinorAxisPositions, style());
1175
1176         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
1177         if (minorAxisPositions.resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
1178             majorAxisAutoPlacementCursor++;
1179
1180         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
1181             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions.resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
1182             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions.integerSpan(), majorAxisPositions.integerSpan());
1183         }
1184
1185         if (!emptyGridArea)
1186             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1187     } else {
1188         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1189
1190         for (unsigned majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
1191             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
1192             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1193
1194             if (emptyGridArea) {
1195                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
1196                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
1197                 const unsigned endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
1198                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
1199                     break;
1200
1201                 // Discard empty grid area as it does not fit in the minor axis direction.
1202                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
1203                 emptyGridArea = nullptr;
1204             }
1205
1206             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
1207             minorAxisAutoPlacementCursor = 0;
1208         }
1209
1210         if (!emptyGridArea)
1211             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1212     }
1213
1214     insertItemIntoGrid(gridItem, *emptyGridArea);
1215     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
1216     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
1217 }
1218
1219 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
1220 {
1221     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
1222 }
1223
1224 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
1225 {
1226     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
1227 }
1228
1229 void RenderGrid::clearGrid()
1230 {
1231     m_grid.clear();
1232     m_gridItemCoordinate.clear();
1233 }
1234
1235 void RenderGrid::applyStretchAlignmentToTracksIfNeeded(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit availableSpace)
1236 {
1237     if (availableSpace <= 0
1238         || (direction == ForColumns && style().resolvedJustifyContentDistribution() != ContentDistributionStretch)
1239         || (direction == ForRows && style().resolvedAlignContentDistribution() != ContentDistributionStretch))
1240         return;
1241
1242     // Spec defines auto-sized tracks as the ones with an 'auto' max-sizing function.
1243     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
1244     Vector<unsigned> autoSizedTracksIndex;
1245     for (unsigned i = 0; i < tracks.size(); ++i) {
1246         const GridTrackSize& trackSize = gridTrackSize(direction, i);
1247         if (trackSize.hasAutoMaxTrackBreadth())
1248             autoSizedTracksIndex.append(i);
1249     }
1250
1251     unsigned numberOfAutoSizedTracks = autoSizedTracksIndex.size();
1252     if (numberOfAutoSizedTracks < 1)
1253         return;
1254
1255     LayoutUnit sizeToIncrease = availableSpace / numberOfAutoSizedTracks;
1256     for (const auto& trackIndex : autoSizedTracksIndex) {
1257         auto& track = tracks[trackIndex];
1258         track.setBaseSize(track.baseSize() + sizeToIncrease);
1259     }
1260 }
1261
1262 void RenderGrid::layoutGridItems()
1263 {
1264     placeItemsOnGrid();
1265
1266     LayoutUnit availableSpaceForColumns = availableLogicalWidth();
1267     LayoutUnit availableSpaceForRows = availableLogicalHeight(IncludeMarginBorderPadding);
1268
1269     // Remove space consumed by gutters from the available logical space.
1270     availableSpaceForColumns -= guttersSize(ForColumns, gridColumnCount());
1271     availableSpaceForRows -= guttersSize(ForRows, gridRowCount());
1272
1273     GridSizingData sizingData(gridColumnCount(), gridRowCount());
1274     computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableSpaceForColumns);
1275     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
1276     computeUsedBreadthOfGridTracks(ForRows, sizingData, availableSpaceForRows);
1277     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
1278
1279     applyStretchAlignmentToTracksIfNeeded(ForColumns, sizingData, availableSpaceForColumns);
1280     applyStretchAlignmentToTracksIfNeeded(ForRows, sizingData, availableSpaceForRows);
1281
1282     populateGridPositions(sizingData, availableSpaceForColumns, availableSpaceForRows);
1283
1284     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1285         // Because the grid area cannot be styled, we don't need to adjust
1286         // the grid breadth to account for 'box-sizing'.
1287         Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
1288         Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
1289
1290         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChildIncludingAlignmentOffsets(*child, ForColumns, sizingData);
1291         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChildIncludingAlignmentOffsets(*child, ForRows, sizingData);
1292         if (!oldOverrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalWidth.value() != overrideContainingBlockContentLogicalWidth
1293             || ((!oldOverrideContainingBlockContentLogicalHeight || oldOverrideContainingBlockContentLogicalHeight.value() != overrideContainingBlockContentLogicalHeight)
1294                 && child->hasRelativeLogicalHeight()))
1295             child->setNeedsLayout(MarkOnlyThis);
1296
1297         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
1298         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
1299
1300         LayoutRect oldChildRect = child->frameRect();
1301
1302         // Stretching logic might force a child layout, so we need to run it before the layoutIfNeeded
1303         // call to avoid unnecessary relayouts. This might imply that child margins, needed to correctly
1304         // determine the available space before stretching, are not set yet.
1305         applyStretchAlignmentToChildIfNeeded(*child);
1306
1307         child->layoutIfNeeded();
1308
1309         // We need pending layouts to be done in order to compute auto-margins properly.
1310         updateAutoMarginsInColumnAxisIfNeeded(*child);
1311         updateAutoMarginsInRowAxisIfNeeded(*child);
1312
1313         child->setLogicalLocation(findChildLogicalPosition(*child));
1314
1315         // If the child moved, we have to repaint it as well as any floating/positioned
1316         // descendants. An exception is if we need a layout. In this case, we know we're going to
1317         // repaint ourselves (and the child) anyway.
1318         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
1319             child->repaintDuringLayoutIfMoved(oldChildRect);
1320     }
1321
1322     LayoutUnit height = borderAndPaddingLogicalHeight() + scrollbarLogicalHeight();
1323     for (auto& row : sizingData.rowTracks)
1324         height += row.baseSize();
1325
1326     height += guttersSize(ForRows, sizingData.rowTracks.size());
1327     // min / max logical height is handled in updateLogicalHeight().
1328     if (hasLineIfEmpty()) {
1329         LayoutUnit minHeight = borderAndPaddingLogicalHeight()
1330             + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes)
1331             + scrollbarLogicalHeight();
1332         height = std::max(height, minHeight);
1333     }
1334     setLogicalHeight(height);
1335
1336     clearGrid();
1337 }
1338
1339 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
1340 {
1341     ASSERT(m_gridItemCoordinate.contains(&gridItem));
1342     return m_gridItemCoordinate.get(&gridItem);
1343 }
1344
1345 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1346 {
1347     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1348     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1349     LayoutUnit gridAreaBreadth = 0;
1350     for (auto& trackPosition : span)
1351         gridAreaBreadth += tracks[trackPosition.toInt()].baseSize();
1352
1353     gridAreaBreadth += guttersSize(direction, span.integerSpan());
1354
1355     return gridAreaBreadth;
1356 }
1357
1358 LayoutUnit RenderGrid::gridAreaBreadthForChildIncludingAlignmentOffsets(const RenderBox& child, GridTrackSizingDirection direction, const GridSizingData& sizingData) const
1359 {
1360     // We need the cached value when available because Content Distribution alignment properties
1361     // may have some influence in the final grid area breadth.
1362     const auto& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
1363     const auto& coordinate = cachedGridCoordinate(child);
1364     const auto& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1365     const auto& linePositions = (direction == ForColumns) ? m_columnPositions : m_rowPositions;
1366
1367     LayoutUnit initialTrackPosition = linePositions[span.resolvedInitialPosition.toInt()];
1368     LayoutUnit finalTrackPosition = linePositions[span.resolvedFinalPosition.toInt()];
1369
1370     // Track Positions vector stores the 'start' grid line of each track, so we have to add last track's baseSize.
1371     return finalTrackPosition - initialTrackPosition + tracks[span.resolvedFinalPosition.toInt()].baseSize();
1372 }
1373
1374 void RenderGrid::populateGridPositions(GridSizingData& sizingData, LayoutUnit availableSpaceForColumns, LayoutUnit availableSpaceForRows)
1375 {
1376     // Since we add alignment offsets and track gutters, grid lines are not always adjacent. Hence we will have to
1377     // assume from now on that we just store positions of the initial grid lines of each track,
1378     // except the last one, which is the only one considered as a final grid line of a track.
1379     // FIXME: This will affect the computed style value of grid tracks size, since we are
1380     // using these positions to compute them.
1381
1382     unsigned numberOfTracks = sizingData.columnTracks.size();
1383     unsigned numberOfLines = numberOfTracks + 1;
1384     unsigned lastLine = numberOfLines - 1;
1385     unsigned nextToLastLine = numberOfLines - 2;
1386     ContentAlignmentData offset = computeContentPositionAndDistributionOffset(ForColumns, availableSpaceForColumns, numberOfTracks);
1387     LayoutUnit trackGap = guttersSize(ForColumns, 2);
1388     m_columnPositions.resize(numberOfLines);
1389     m_columnPositions[0] = borderAndPaddingStart() + offset.positionOffset;
1390     for (unsigned i = 0; i < lastLine; ++i)
1391         m_columnPositions[i + 1] = m_columnPositions[i] + offset.distributionOffset + sizingData.columnTracks[i].baseSize() + trackGap;
1392     m_columnPositions[lastLine] = m_columnPositions[nextToLastLine] + sizingData.columnTracks[nextToLastLine].baseSize();
1393
1394     numberOfTracks = sizingData.rowTracks.size();
1395     numberOfLines = numberOfTracks + 1;
1396     lastLine = numberOfLines - 1;
1397     nextToLastLine = numberOfLines - 2;
1398     offset = computeContentPositionAndDistributionOffset(ForRows, availableSpaceForRows, numberOfTracks);
1399     trackGap = guttersSize(ForRows, 2);
1400     m_rowPositions.resize(numberOfLines);
1401     m_rowPositions[0] = borderAndPaddingBefore() + offset.positionOffset;
1402     for (unsigned i = 0; i < lastLine; ++i)
1403         m_rowPositions[i + 1] = m_rowPositions[i] + offset.distributionOffset + sizingData.rowTracks[i].baseSize() + trackGap;
1404     m_rowPositions[lastLine] = m_rowPositions[nextToLastLine] + sizingData.rowTracks[nextToLastLine].baseSize();
1405 }
1406
1407 static inline LayoutUnit computeOverflowAlignmentOffset(OverflowAlignment overflow, LayoutUnit trackBreadth, LayoutUnit childBreadth)
1408 {
1409     LayoutUnit offset = trackBreadth - childBreadth;
1410     switch (overflow) {
1411     case OverflowAlignmentSafe:
1412         // If overflow is 'safe', we have to make sure we don't overflow the 'start'
1413         // edge (potentially cause some data loss as the overflow is unreachable).
1414         return std::max<LayoutUnit>(0, offset);
1415     case OverflowAlignmentTrue:
1416     case OverflowAlignmentDefault:
1417         // If we overflow our alignment container and overflow is 'true' (default), we
1418         // ignore the overflow and just return the value regardless (which may cause data
1419         // loss as we overflow the 'start' edge).
1420         return offset;
1421     }
1422
1423     ASSERT_NOT_REACHED();
1424     return 0;
1425 }
1426
1427 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1428 bool RenderGrid::needToStretchChildLogicalHeight(const RenderBox& child) const
1429 {
1430     if (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch) != ItemPositionStretch)
1431         return false;
1432
1433     return isHorizontalWritingMode() && child.style().height().isAuto();
1434 }
1435
1436 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1437 LayoutUnit RenderGrid::marginLogicalHeightForChild(const RenderBox& child) const
1438 {
1439     return isHorizontalWritingMode() ? child.verticalMarginExtent() : child.horizontalMarginExtent();
1440 }
1441
1442 LayoutUnit RenderGrid::computeMarginLogicalHeightForChild(const RenderBox& child) const
1443 {
1444     if (!child.style().hasMargin())
1445         return 0;
1446
1447     LayoutUnit marginBefore;
1448     LayoutUnit marginAfter;
1449     child.computeBlockDirectionMargins(this, marginBefore, marginAfter);
1450
1451     return marginBefore + marginAfter;
1452 }
1453
1454 LayoutUnit RenderGrid::availableAlignmentSpaceForChildBeforeStretching(LayoutUnit gridAreaBreadthForChild, const RenderBox& child) const
1455 {
1456     // Because we want to avoid multiple layouts, stretching logic might be performed before
1457     // children are laid out, so we can't use the child cached values. Hence, we need to
1458     // compute margins in order to determine the available height before stretching.
1459     return gridAreaBreadthForChild - (child.needsLayout() ? computeMarginLogicalHeightForChild(child) : marginLogicalHeightForChild(child));
1460 }
1461
1462 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1463 void RenderGrid::applyStretchAlignmentToChildIfNeeded(RenderBox& child)
1464 {
1465     ASSERT(child.overrideContainingBlockContentLogicalWidth() && child.overrideContainingBlockContentLogicalHeight());
1466
1467     // We clear both width and height override values because we will decide now whether they
1468     // are allowed or not, evaluating the conditions which might have changed since the old
1469     // values were set.
1470     child.clearOverrideSize();
1471
1472     auto& gridStyle = style();
1473     auto& childStyle = child.style();
1474     bool isHorizontalMode = isHorizontalWritingMode();
1475     bool hasAutoSizeInRowAxis = isHorizontalMode ? childStyle.width().isAuto() : childStyle.height().isAuto();
1476     bool allowedToStretchChildAlongRowAxis = hasAutoSizeInRowAxis && !childStyle.marginStartUsing(&gridStyle).isAuto() && !childStyle.marginEndUsing(&gridStyle).isAuto();
1477     if (!allowedToStretchChildAlongRowAxis || RenderStyle::resolveJustification(gridStyle, childStyle, ItemPositionStretch) != ItemPositionStretch) {
1478         bool hasAutoMinSizeInRowAxis = isHorizontalMode ? childStyle.minWidth().isAuto() : childStyle.minHeight().isAuto();
1479         bool canShrinkToFitInRowAxisForChild = !hasAutoMinSizeInRowAxis || child.minPreferredLogicalWidth() <= child.overrideContainingBlockContentLogicalWidth().value();
1480         // TODO(lajava): how to handle orthogonality in this case ?.
1481         // TODO(lajava): grid track sizing and positioning do not support orthogonal modes yet.
1482         if (hasAutoSizeInRowAxis && canShrinkToFitInRowAxisForChild) {
1483             LayoutUnit childWidthToFitContent = std::max(std::min(child.maxPreferredLogicalWidth(), child.overrideContainingBlockContentLogicalWidth().value() - child.marginLogicalWidth()), child.minPreferredLogicalWidth());
1484             LayoutUnit desiredLogicalWidth = child.constrainLogicalHeightByMinMax(childWidthToFitContent, Nullopt);
1485             child.setOverrideLogicalContentWidth(desiredLogicalWidth - child.borderAndPaddingLogicalWidth());
1486             if (desiredLogicalWidth != child.logicalWidth())
1487                 child.setNeedsLayout();
1488         }
1489     }
1490
1491     bool hasAutoSizeInColumnAxis = isHorizontalMode ? childStyle.height().isAuto() : childStyle.width().isAuto();
1492     bool allowedToStretchChildAlongColumnAxis = hasAutoSizeInColumnAxis && !childStyle.marginBeforeUsing(&gridStyle).isAuto() && !childStyle.marginAfterUsing(&gridStyle).isAuto();
1493     if (allowedToStretchChildAlongColumnAxis && RenderStyle::resolveAlignment(gridStyle, childStyle, ItemPositionStretch) == ItemPositionStretch) {
1494         // TODO (lajava): If the child has orthogonal flow, then it already has an override height set, so use it.
1495         // TODO (lajava): grid track sizing and positioning do not support orthogonal modes yet.
1496         if (child.isHorizontalWritingMode() == isHorizontalMode) {
1497             LayoutUnit stretchedLogicalHeight = availableAlignmentSpaceForChildBeforeStretching(child.overrideContainingBlockContentLogicalHeight().value(), child);
1498             LayoutUnit desiredLogicalHeight = child.constrainLogicalHeightByMinMax(stretchedLogicalHeight, Nullopt);
1499             child.setOverrideLogicalContentHeight(desiredLogicalHeight - child.borderAndPaddingLogicalHeight());
1500             if (desiredLogicalHeight != child.logicalHeight()) {
1501                 // TODO (lajava): Can avoid laying out here in some cases. See https://webkit.org/b/87905.
1502                 child.setLogicalHeight(0);
1503                 child.setNeedsLayout();
1504             }
1505         }
1506     }
1507 }
1508
1509 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1510 bool RenderGrid::hasAutoMarginsInColumnAxis(const RenderBox& child) const
1511 {
1512     if (isHorizontalWritingMode())
1513         return child.style().marginTop().isAuto() || child.style().marginBottom().isAuto();
1514     return child.style().marginLeft().isAuto() || child.style().marginRight().isAuto();
1515 }
1516
1517 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1518 bool RenderGrid::hasAutoMarginsInRowAxis(const RenderBox& child) const
1519 {
1520     if (isHorizontalWritingMode())
1521         return child.style().marginLeft().isAuto() || child.style().marginRight().isAuto();
1522     return child.style().marginTop().isAuto() || child.style().marginBottom().isAuto();
1523 }
1524
1525 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1526 void RenderGrid::updateAutoMarginsInRowAxisIfNeeded(RenderBox& child)
1527 {
1528     ASSERT(!child.isOutOfFlowPositioned());
1529
1530     LayoutUnit availableAlignmentSpace = child.overrideContainingBlockContentLogicalWidth().value() - child.logicalWidth();
1531     if (availableAlignmentSpace <= 0)
1532         return;
1533
1534     const RenderStyle& parentStyle = style();
1535     Length marginStart = child.style().marginStartUsing(&parentStyle);
1536     Length marginEnd = child.style().marginEndUsing(&parentStyle);
1537     if (marginStart.isAuto() && marginEnd.isAuto()) {
1538         child.setMarginStart(availableAlignmentSpace / 2, &parentStyle);
1539         child.setMarginEnd(availableAlignmentSpace / 2, &parentStyle);
1540     } else if (marginStart.isAuto()) {
1541         child.setMarginStart(availableAlignmentSpace, &parentStyle);
1542     } else if (marginEnd.isAuto()) {
1543         child.setMarginEnd(availableAlignmentSpace, &parentStyle);
1544     }
1545 }
1546
1547 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1548 void RenderGrid::updateAutoMarginsInColumnAxisIfNeeded(RenderBox& child)
1549 {
1550     ASSERT(!child.isOutOfFlowPositioned());
1551
1552     LayoutUnit availableAlignmentSpace = child.overrideContainingBlockContentLogicalHeight().value() - child.logicalHeight();
1553     if (availableAlignmentSpace <= 0)
1554         return;
1555
1556     const RenderStyle& parentStyle = style();
1557     Length marginBefore = child.style().marginBeforeUsing(&parentStyle);
1558     Length marginAfter = child.style().marginAfterUsing(&parentStyle);
1559     if (marginBefore.isAuto() && marginAfter.isAuto()) {
1560         child.setMarginBefore(availableAlignmentSpace / 2, &parentStyle);
1561         child.setMarginAfter(availableAlignmentSpace / 2, &parentStyle);
1562     } else if (marginBefore.isAuto()) {
1563         child.setMarginBefore(availableAlignmentSpace, &parentStyle);
1564     } else if (marginAfter.isAuto()) {
1565         child.setMarginAfter(availableAlignmentSpace, &parentStyle);
1566     }
1567 }
1568
1569 GridAxisPosition RenderGrid::columnAxisPositionForChild(const RenderBox& child) const
1570 {
1571     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1572     bool hasSameWritingMode = child.style().writingMode() == style().writingMode();
1573
1574     switch (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch)) {
1575     case ItemPositionSelfStart:
1576         // If orthogonal writing-modes, this computes to 'start'.
1577         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1578         // 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.
1579         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisStart : GridAxisEnd;
1580     case ItemPositionSelfEnd:
1581         // If orthogonal writing-modes, this computes to 'end'.
1582         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1583         // 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.
1584         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisEnd : GridAxisStart;
1585     case ItemPositionLeft:
1586         // The alignment axis (column axis) and the inline axis are parallell in
1587         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1588         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1589         return GridAxisStart;
1590     case ItemPositionRight:
1591         // The alignment axis (column axis) and the inline axis are parallell in
1592         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1593         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1594         return hasOrthogonalWritingMode ? GridAxisEnd : GridAxisStart;
1595     case ItemPositionCenter:
1596         return GridAxisCenter;
1597     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1598     case ItemPositionStart:
1599         return GridAxisStart;
1600     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1601     case ItemPositionEnd:
1602         return GridAxisEnd;
1603     case ItemPositionStretch:
1604         return GridAxisStart;
1605     case ItemPositionBaseline:
1606     case ItemPositionLastBaseline:
1607         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1608         return GridAxisStart;
1609     case ItemPositionAuto:
1610         break;
1611     }
1612
1613     ASSERT_NOT_REACHED();
1614     return GridAxisStart;
1615 }
1616
1617 GridAxisPosition RenderGrid::rowAxisPositionForChild(const RenderBox& child) const
1618 {
1619     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1620     bool hasSameDirection = child.style().direction() == style().direction();
1621     bool isLTR = style().isLeftToRightDirection();
1622
1623     switch (RenderStyle::resolveJustification(style(), child.style(), ItemPositionStretch)) {
1624     case ItemPositionSelfStart:
1625         // For orthogonal writing-modes, this computes to 'start'
1626         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1627         // self-start is based on the child's direction. That's why we need to check against the grid container's direction.
1628         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisStart : GridAxisEnd;
1629     case ItemPositionSelfEnd:
1630         // For orthogonal writing-modes, this computes to 'start'
1631         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1632         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisEnd : GridAxisStart;
1633     case ItemPositionLeft:
1634         return isLTR ? GridAxisStart : GridAxisEnd;
1635     case ItemPositionRight:
1636         return isLTR ? GridAxisEnd : GridAxisStart;
1637     case ItemPositionCenter:
1638         return GridAxisCenter;
1639     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1640     case ItemPositionStart:
1641         return GridAxisStart;
1642     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1643     case ItemPositionEnd:
1644         return GridAxisEnd;
1645     case ItemPositionStretch:
1646         return GridAxisStart;
1647     case ItemPositionBaseline:
1648     case ItemPositionLastBaseline:
1649         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1650         return GridAxisStart;
1651     case ItemPositionAuto:
1652         break;
1653     }
1654
1655     ASSERT_NOT_REACHED();
1656     return GridAxisStart;
1657 }
1658
1659 static inline LayoutUnit offsetBetweenTracks(ContentDistributionType distribution, const Vector<LayoutUnit>& trackPositions, const LayoutUnit& childBreadth)
1660 {
1661     return (distribution == ContentDistributionStretch || ContentDistributionStretch == ContentDistributionDefault) ? LayoutUnit() : trackPositions[1] - trackPositions[0] - childBreadth;
1662 }
1663
1664 LayoutUnit RenderGrid::columnAxisOffsetForChild(const RenderBox& child) const
1665 {
1666     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1667     unsigned childStartLine = coordinate.rows.resolvedInitialPosition.toInt();
1668     LayoutUnit startOfRow = m_rowPositions[childStartLine];
1669     LayoutUnit startPosition = startOfRow + marginBeforeForChild(child);
1670     if (hasAutoMarginsInColumnAxis(child))
1671         return startPosition;
1672     GridAxisPosition axisPosition = columnAxisPositionForChild(child);
1673     switch (axisPosition) {
1674     case GridAxisStart:
1675         return startPosition;
1676     case GridAxisEnd:
1677     case GridAxisCenter: {
1678         unsigned childEndLine = coordinate.rows.resolvedFinalPosition.next().toInt();
1679         LayoutUnit endOfRow = m_rowPositions[childEndLine];
1680         // m_rowPositions include gutters so we need to substract them to get the actual end position for a given
1681         // row (this does not have to be done for the last track as there are no more m_rowPositions after it)
1682         if (childEndLine < m_rowPositions.size() - 1)
1683             endOfRow -= guttersSize(ForRows, 2);
1684         LayoutUnit childBreadth = child.logicalHeight() + child.marginLogicalHeight();
1685         // In order to properly adjust the Self Alignment values we need to consider the offset between tracks.
1686         if (childEndLine - childStartLine > 1 && childEndLine < m_rowPositions.size() - 1)
1687             endOfRow -= offsetBetweenTracks(style().resolvedAlignContentDistribution(), m_rowPositions, childBreadth);
1688         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveAlignmentOverflow(style(), child.style()), endOfRow - startOfRow, childBreadth);
1689         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1690     }
1691     }
1692
1693     ASSERT_NOT_REACHED();
1694     return 0;
1695 }
1696
1697
1698 LayoutUnit RenderGrid::rowAxisOffsetForChild(const RenderBox& child) const
1699 {
1700     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1701     unsigned childStartLine = coordinate.columns.resolvedInitialPosition.toInt();
1702     LayoutUnit startOfColumn = m_columnPositions[childStartLine];
1703     LayoutUnit startPosition = startOfColumn + marginStartForChild(child);
1704     if (hasAutoMarginsInRowAxis(child))
1705         return startPosition;
1706     GridAxisPosition axisPosition = rowAxisPositionForChild(child);
1707     switch (axisPosition) {
1708     case GridAxisStart:
1709         return startPosition;
1710     case GridAxisEnd:
1711     case GridAxisCenter: {
1712         unsigned childEndLine = coordinate.columns.resolvedFinalPosition.next().toInt();
1713         LayoutUnit endOfColumn = m_columnPositions[childEndLine];
1714         // m_columnPositions include gutters so we need to substract them to get the actual end position for a given
1715         // column (this does not have to be done for the last track as there are no more m_columnPositions after it)
1716         if (childEndLine < m_columnPositions.size() - 1)
1717             endOfColumn -= guttersSize(ForColumns, 2);
1718         LayoutUnit childBreadth = child.logicalWidth() + child.marginLogicalWidth();
1719         // In order to properly adjust the Self Alignment values we need to consider the offset between tracks.
1720         if (childEndLine - childStartLine > 1 && childEndLine < m_columnPositions.size() - 1)
1721             endOfColumn -= offsetBetweenTracks(style().resolvedJustifyContentDistribution(), m_columnPositions, childBreadth);
1722         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveJustificationOverflow(style(), child.style()), endOfColumn - startOfColumn, childBreadth);
1723         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1724     }
1725     }
1726
1727     ASSERT_NOT_REACHED();
1728     return 0;
1729 }
1730
1731 ContentPosition static resolveContentDistributionFallback(ContentDistributionType distribution)
1732 {
1733     switch (distribution) {
1734     case ContentDistributionSpaceBetween:
1735         return ContentPositionStart;
1736     case ContentDistributionSpaceAround:
1737         return ContentPositionCenter;
1738     case ContentDistributionSpaceEvenly:
1739         return ContentPositionCenter;
1740     case ContentDistributionStretch:
1741         return ContentPositionStart;
1742     case ContentDistributionDefault:
1743         return ContentPositionAuto;
1744     }
1745
1746     ASSERT_NOT_REACHED();
1747     return ContentPositionAuto;
1748 }
1749
1750 static inline LayoutUnit offsetToStartEdge(bool isLeftToRight, LayoutUnit availableSpace)
1751 {
1752     return isLeftToRight ? LayoutUnit() : availableSpace;
1753 }
1754
1755 static inline LayoutUnit offsetToEndEdge(bool isLeftToRight, LayoutUnit availableSpace)
1756 {
1757     return !isLeftToRight ? LayoutUnit() : availableSpace;
1758 }
1759
1760 static ContentAlignmentData contentDistributionOffset(LayoutUnit availableFreeSpace, ContentPosition& fallbackPosition, ContentDistributionType distribution, unsigned numberOfGridTracks)
1761 {
1762     if (distribution != ContentDistributionDefault && fallbackPosition == ContentPositionAuto)
1763         fallbackPosition = resolveContentDistributionFallback(distribution);
1764
1765     if (availableFreeSpace <= 0)
1766         return ContentAlignmentData::defaultOffsets();
1767
1768     LayoutUnit distributionOffset;
1769     switch (distribution) {
1770     case ContentDistributionSpaceBetween:
1771         if (numberOfGridTracks < 2)
1772             return ContentAlignmentData::defaultOffsets();
1773         return {0, availableFreeSpace / (numberOfGridTracks - 1)};
1774     case ContentDistributionSpaceAround:
1775         if (numberOfGridTracks < 1)
1776             return ContentAlignmentData::defaultOffsets();
1777         distributionOffset = availableFreeSpace / numberOfGridTracks;
1778         return {distributionOffset / 2, distributionOffset};
1779     case ContentDistributionSpaceEvenly:
1780         distributionOffset = availableFreeSpace / (numberOfGridTracks + 1);
1781         return {distributionOffset, distributionOffset};
1782     case ContentDistributionStretch:
1783         return {0, 0};
1784     case ContentDistributionDefault:
1785         return ContentAlignmentData::defaultOffsets();
1786     }
1787
1788     ASSERT_NOT_REACHED();
1789     return ContentAlignmentData::defaultOffsets();
1790 }
1791
1792 ContentAlignmentData RenderGrid::computeContentPositionAndDistributionOffset(GridTrackSizingDirection direction, LayoutUnit availableFreeSpace, unsigned numberOfGridTracks) const
1793 {
1794     bool isRowAxis = direction == ForColumns;
1795     ContentPosition position = isRowAxis ? style().resolvedJustifyContentPosition() : style().resolvedAlignContentPosition();
1796     ContentDistributionType distribution = isRowAxis ? style().resolvedJustifyContentDistribution() : style().resolvedAlignContentDistribution();
1797     // If <content-distribution> value can't be applied, 'position' will become the associated
1798     // <content-position> fallback value.
1799     ContentAlignmentData contentAlignment = contentDistributionOffset(availableFreeSpace, position, distribution, numberOfGridTracks);
1800     if (contentAlignment.isValid())
1801         return contentAlignment;
1802
1803     OverflowAlignment overflow = isRowAxis ? style().justifyContentOverflowAlignment() : style().alignContentOverflowAlignment();
1804     if (availableFreeSpace <= 0 && overflow == OverflowAlignmentSafe)
1805         return {0, 0};
1806
1807     switch (position) {
1808     case ContentPositionLeft:
1809         // The align-content's axis is always orthogonal to the inline-axis.
1810         return {0, 0};
1811     case ContentPositionRight:
1812         if (isRowAxis)
1813             return {availableFreeSpace, 0};
1814         // The align-content's axis is always orthogonal to the inline-axis.
1815         return {0, 0};
1816     case ContentPositionCenter:
1817         return {availableFreeSpace / 2, 0};
1818     case ContentPositionFlexEnd: // Only used in flex layout, for other layout, it's equivalent to 'end'.
1819     case ContentPositionEnd:
1820         if (isRowAxis)
1821             return {offsetToEndEdge(style().isLeftToRightDirection(), availableFreeSpace), 0};
1822         return {availableFreeSpace, 0};
1823     case ContentPositionFlexStart: // Only used in flex layout, for other layout, it's equivalent to 'start'.
1824     case ContentPositionStart:
1825         if (isRowAxis)
1826             return {offsetToStartEdge(style().isLeftToRightDirection(), availableFreeSpace), 0};
1827         return {0, 0};
1828     case ContentPositionBaseline:
1829     case ContentPositionLastBaseline:
1830         // FIXME: Implement the previous values. For now, we always 'start' align.
1831         // http://webkit.org/b/145566
1832         if (isRowAxis)
1833             return {offsetToStartEdge(style().isLeftToRightDirection(), availableFreeSpace), 0};
1834         return {0, 0};
1835     case ContentPositionAuto:
1836         break;
1837     }
1838
1839     ASSERT_NOT_REACHED();
1840     return {0, 0};
1841 }
1842
1843 LayoutPoint RenderGrid::findChildLogicalPosition(const RenderBox& child) const
1844 {
1845     LayoutUnit rowAxisOffset = rowAxisOffsetForChild(child);
1846     // We stored m_columnPositions's data ignoring the direction, hence we might need now
1847     // to translate positions from RTL to LTR, as it's more convenient for painting.
1848     if (!style().isLeftToRightDirection()) {
1849         LayoutUnit alignmentOffset =  m_columnPositions[0] - borderAndPaddingStart();
1850         LayoutUnit rightGridEdgePosition = m_columnPositions[m_columnPositions.size() - 1] + alignmentOffset + borderAndPaddingLogicalLeft();
1851         rowAxisOffset = rightGridEdgePosition - (rowAxisOffset + child.logicalWidth());
1852     }
1853
1854     return LayoutPoint(rowAxisOffset, columnAxisOffsetForChild(child));
1855 }
1856
1857 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1858 {
1859     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1860         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect, PaintAsInlineBlock);
1861 }
1862
1863 const char* RenderGrid::renderName() const
1864 {
1865     if (isFloating())
1866         return "RenderGrid (floating)";
1867     if (isOutOfFlowPositioned())
1868         return "RenderGrid (positioned)";
1869     if (isAnonymous())
1870         return "RenderGrid (generated)";
1871     if (isRelPositioned())
1872         return "RenderGrid (relative positioned)";
1873     return "RenderGrid";
1874 }
1875
1876 } // namespace WebCore
1877
1878 #endif /* ENABLE(CSS_GRID_LAYOUT) */