6b7c6061a8ce833fcbf5f50741f33dcde1cb7804
[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         // We need to clear the stretched height to properly compute logical height during layout.
596         child.clearOverrideLogicalContentHeight();
597     }
598
599     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
600     // If |child| has a relative logical height, we shouldn't let it override its intrinsic height, which is
601     // what we are interested in here. Thus we need to set the override logical height to Nullopt (no possible resolution).
602     if (child.hasRelativeLogicalHeight())
603         child.setOverrideContainingBlockContentLogicalHeight(Nullopt);
604     child.layoutIfNeeded();
605     return child.logicalHeight() + child.marginLogicalHeight();
606 }
607
608 LayoutUnit RenderGrid::minSizeForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
609 {
610     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
611     // FIXME: Properly support orthogonal writing mode.
612     if (hasOrthogonalWritingMode)
613         return { };
614
615     const Length& childMinSize = direction == ForColumns ? child.style().logicalMinWidth() : child.style().logicalMinHeight();
616     if (childMinSize.isAuto()) {
617         // FIXME: Implement intrinsic aspect ratio support (transferred size in specs).
618         return minContentForChild(child, direction, columnTracks);
619     }
620
621     if (direction == ForColumns)
622         return child.computeLogicalWidthInRegionUsing(MinSize, childMinSize, contentLogicalWidth(), this, nullptr);
623
624     return child.computeContentAndScrollbarLogicalHeightUsing(MinSize, childMinSize, child.logicalHeight()).valueOr(0);
625 }
626
627 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
628 {
629     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
630     // FIXME: Properly support orthogonal writing mode.
631     if (hasOrthogonalWritingMode)
632         return 0;
633
634     if (direction == ForColumns) {
635         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
636         // what we are interested in here. Thus we need to set the override logical width to Nullopt (no possible resolution).
637         if (child.hasRelativeLogicalWidth())
638             child.setOverrideContainingBlockContentLogicalWidth(Nullopt);
639
640         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
641         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
642         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
643     }
644
645     return logicalContentHeightForChild(child, columnTracks);
646 }
647
648 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
649 {
650     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
651     // FIXME: Properly support orthogonal writing mode.
652     if (hasOrthogonalWritingMode)
653         return LayoutUnit();
654
655     if (direction == ForColumns) {
656         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
657         // what we are interested in here. Thus we need to set the override logical width to Nullopt (no possible resolution).
658         if (child.hasRelativeLogicalWidth())
659             child.setOverrideContainingBlockContentLogicalWidth(Nullopt);
660
661         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
662         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
663         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
664     }
665
666     return logicalContentHeightForChild(child, columnTracks);
667 }
668
669 class GridItemWithSpan {
670 public:
671     GridItemWithSpan(RenderBox& gridItem, GridCoordinate coordinate, GridTrackSizingDirection direction)
672         : m_gridItem(gridItem)
673         , m_coordinate(coordinate)
674     {
675         const GridSpan& span = (direction == ForRows) ? coordinate.rows : coordinate.columns;
676         m_span = span.resolvedFinalPosition.toInt() - span.resolvedInitialPosition.toInt() + 1;
677     }
678
679     RenderBox& gridItem() const { return m_gridItem; }
680     GridCoordinate coordinate() const { return m_coordinate; }
681 #if !ASSERT_DISABLED
682     size_t span() const { return m_span; }
683 #endif
684
685     bool operator<(const GridItemWithSpan other) const
686     {
687         return m_span < other.m_span;
688     }
689
690 private:
691     std::reference_wrapper<RenderBox> m_gridItem;
692     GridCoordinate m_coordinate;
693     unsigned m_span;
694 };
695
696 bool RenderGrid::spanningItemCrossesFlexibleSizedTracks(const GridCoordinate& coordinate, GridTrackSizingDirection direction) const
697 {
698     const GridSpan itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
699     for (auto trackPosition : itemSpan) {
700         const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
701         if (trackSize.minTrackBreadth().isFlex() || trackSize.maxTrackBreadth().isFlex())
702             return true;
703     }
704
705     return false;
706 }
707
708 static inline unsigned integerSpanForDirection(const GridCoordinate& coordinate, GridTrackSizingDirection direction)
709 {
710     return (direction == ForRows) ? coordinate.rows.integerSpan() : coordinate.columns.integerSpan();
711 }
712
713 struct GridItemsSpanGroupRange {
714     Vector<GridItemWithSpan>::iterator rangeStart;
715     Vector<GridItemWithSpan>::iterator rangeEnd;
716 };
717
718 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
719 {
720     sizingData.itemsSortedByIncreasingSpan.shrink(0);
721     HashSet<RenderBox*> itemsSet;
722     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
723         GridIterator iterator(m_grid, direction, trackIndex);
724         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
725
726         while (RenderBox* gridItem = iterator.nextGridItem()) {
727             if (itemsSet.add(gridItem).isNewEntry) {
728                 const GridCoordinate& coordinate = cachedGridCoordinate(*gridItem);
729                 if (integerSpanForDirection(coordinate, direction) == 1)
730                     resolveContentBasedTrackSizingFunctionsForNonSpanningItems(direction, coordinate, *gridItem, track, sizingData.columnTracks);
731                 else if (!spanningItemCrossesFlexibleSizedTracks(coordinate, direction))
732                     sizingData.itemsSortedByIncreasingSpan.append(GridItemWithSpan(*gridItem, coordinate, direction));
733             }
734         }
735     }
736     std::sort(sizingData.itemsSortedByIncreasingSpan.begin(), sizingData.itemsSortedByIncreasingSpan.end());
737
738     auto it = sizingData.itemsSortedByIncreasingSpan.begin();
739     auto end = sizingData.itemsSortedByIncreasingSpan.end();
740     while (it != end) {
741         GridItemsSpanGroupRange spanGroupRange = { it, std::upper_bound(it, end, *it) };
742         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMinimums>(direction, sizingData, spanGroupRange);
743         resolveContentBasedTrackSizingFunctionsForItems<ResolveContentBasedMinimums>(direction, sizingData, spanGroupRange);
744         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMinimums>(direction, sizingData, spanGroupRange);
745         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMaximums>(direction, sizingData, spanGroupRange);
746         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMaximums>(direction, sizingData, spanGroupRange);
747         it = spanGroupRange.rangeEnd;
748     }
749
750     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
751         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
752         if (track.growthLimitIsInfinite())
753             track.setGrowthLimit(track.baseSize());
754     }
755 }
756
757 void RenderGrid::resolveContentBasedTrackSizingFunctionsForNonSpanningItems(GridTrackSizingDirection direction, const GridCoordinate& coordinate, RenderBox& gridItem, GridTrack& track, Vector<GridTrack>& columnTracks)
758 {
759     const GridResolvedPosition trackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
760     GridTrackSize trackSize = gridTrackSize(direction, trackPosition.toInt());
761
762     if (trackSize.hasMinContentMinTrackBreadth())
763         track.setBaseSize(std::max(track.baseSize(), minContentForChild(gridItem, direction, columnTracks)));
764     else if (trackSize.hasMaxContentMinTrackBreadth())
765         track.setBaseSize(std::max(track.baseSize(), maxContentForChild(gridItem, direction, columnTracks)));
766     else if (trackSize.hasAutoMinTrackBreadth())
767         track.setBaseSize(std::max(track.baseSize(), minSizeForChild(gridItem, direction, columnTracks)));
768
769     if (trackSize.hasMinContentMaxTrackBreadth())
770         track.setGrowthLimit(std::max(track.growthLimit(), minContentForChild(gridItem, direction, columnTracks)));
771     else if (trackSize.hasMaxContentOrAutoMaxTrackBreadth())
772         track.setGrowthLimit(std::max(track.growthLimit(), maxContentForChild(gridItem, direction, columnTracks)));
773 }
774
775 const LayoutUnit& RenderGrid::trackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track, TrackSizeRestriction restriction)
776 {
777     switch (phase) {
778     case ResolveIntrinsicMinimums:
779     case ResolveContentBasedMinimums:
780     case ResolveMaxContentMinimums:
781     case MaximizeTracks:
782         return track.baseSize();
783     case ResolveIntrinsicMaximums:
784     case ResolveMaxContentMaximums:
785         return restriction == AllowInfinity ? track.growthLimit() : track.growthLimitIfNotInfinite();
786     }
787
788     ASSERT_NOT_REACHED();
789     return track.baseSize();
790 }
791
792 bool RenderGrid::shouldProcessTrackForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
793 {
794     switch (phase) {
795     case ResolveIntrinsicMinimums:
796         return trackSize.hasIntrinsicMinTrackBreadth();
797     case ResolveContentBasedMinimums:
798         return trackSize.hasMinOrMaxContentMinTrackBreadth();
799     case ResolveMaxContentMinimums:
800         return trackSize.hasMaxContentMinTrackBreadth();
801     case ResolveIntrinsicMaximums:
802         return trackSize.hasMinOrMaxContentMaxTrackBreadth();
803     case ResolveMaxContentMaximums:
804         return trackSize.hasMaxContentOrAutoMaxTrackBreadth();
805     case MaximizeTracks:
806         ASSERT_NOT_REACHED();
807         return false;
808     }
809
810     ASSERT_NOT_REACHED();
811     return false;
812 }
813
814 bool RenderGrid::trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
815 {
816     switch (phase) {
817     case ResolveIntrinsicMinimums:
818     case ResolveContentBasedMinimums:
819         return trackSize.hasAutoOrMinContentMinTrackBreadthAndIntrinsicMaxTrackBreadth();
820     case ResolveMaxContentMinimums:
821         return trackSize.hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth();
822     case ResolveIntrinsicMaximums:
823     case ResolveMaxContentMaximums:
824         return true;
825     case MaximizeTracks:
826         ASSERT_NOT_REACHED();
827         return false;
828     }
829
830     ASSERT_NOT_REACHED();
831     return false;
832 }
833
834 void RenderGrid::markAsInfinitelyGrowableForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
835 {
836     switch (phase) {
837     case ResolveIntrinsicMinimums:
838     case ResolveContentBasedMinimums:
839     case ResolveMaxContentMinimums:
840         return;
841     case ResolveIntrinsicMaximums:
842         if (trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity) == infinity  && track.plannedSize() != infinity)
843             track.setInfinitelyGrowable(true);
844         return;
845     case ResolveMaxContentMaximums:
846         if (track.infinitelyGrowable())
847             track.setInfinitelyGrowable(false);
848         return;
849     case MaximizeTracks:
850         ASSERT_NOT_REACHED();
851         return;
852     }
853
854     ASSERT_NOT_REACHED();
855 }
856
857 void RenderGrid::updateTrackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
858 {
859     switch (phase) {
860     case ResolveIntrinsicMinimums:
861     case ResolveContentBasedMinimums:
862     case ResolveMaxContentMinimums:
863         track.setBaseSize(track.plannedSize());
864         return;
865     case ResolveIntrinsicMaximums:
866     case ResolveMaxContentMaximums:
867         track.setGrowthLimit(track.plannedSize());
868         return;
869     case MaximizeTracks:
870         ASSERT_NOT_REACHED();
871         return;
872     }
873
874     ASSERT_NOT_REACHED();
875 }
876
877 LayoutUnit RenderGrid::currentItemSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, RenderBox& gridItem, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
878 {
879     switch (phase) {
880     case ResolveIntrinsicMinimums:
881         return minSizeForChild(gridItem, direction, columnTracks);
882     case ResolveContentBasedMinimums:
883     case ResolveIntrinsicMaximums:
884         return minContentForChild(gridItem, direction, columnTracks);
885     case ResolveMaxContentMinimums:
886     case ResolveMaxContentMaximums:
887         return maxContentForChild(gridItem, direction, columnTracks);
888     case MaximizeTracks:
889         ASSERT_NOT_REACHED();
890         return 0;
891     }
892
893     ASSERT_NOT_REACHED();
894     return 0;
895 }
896
897 template <RenderGrid::TrackSizeComputationPhase phase>
898 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, const GridItemsSpanGroupRange& gridItemsWithSpan)
899 {
900     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
901     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
902         GridTrack& track = tracks[trackIndex];
903         track.setPlannedSize(trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity));
904     }
905
906     for (auto it = gridItemsWithSpan.rangeStart; it != gridItemsWithSpan.rangeEnd; ++it) {
907         GridItemWithSpan& gridItemWithSpan = *it;
908         ASSERT(gridItemWithSpan.span() > 1);
909         const GridCoordinate& coordinate = gridItemWithSpan.coordinate();
910         const GridSpan& itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
911
912         sizingData.filteredTracks.shrink(0);
913         sizingData.growBeyondGrowthLimitsTracks.shrink(0);
914         LayoutUnit spanningTracksSize;
915         for (auto& trackPosition : itemSpan) {
916             const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
917             GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPosition.toInt()] : sizingData.rowTracks[trackPosition.toInt()];
918             spanningTracksSize += trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
919             if (!shouldProcessTrackForTrackSizeComputationPhase(phase, trackSize))
920                 continue;
921
922             sizingData.filteredTracks.append(&track);
923
924             if (trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(phase, trackSize))
925                 sizingData.growBeyondGrowthLimitsTracks.append(&track);
926         }
927
928         if (sizingData.filteredTracks.isEmpty())
929             continue;
930
931         spanningTracksSize += guttersSize(direction, itemSpan.integerSpan());
932
933         LayoutUnit extraSpace = currentItemSizeForTrackSizeComputationPhase(phase, gridItemWithSpan.gridItem(), direction, sizingData.columnTracks) - spanningTracksSize;
934         extraSpace = std::max<LayoutUnit>(extraSpace, 0);
935         auto& tracksToGrowBeyondGrowthLimits = sizingData.growBeyondGrowthLimitsTracks.isEmpty() ? sizingData.filteredTracks : sizingData.growBeyondGrowthLimitsTracks;
936         distributeSpaceToTracks<phase>(sizingData.filteredTracks, &tracksToGrowBeyondGrowthLimits, extraSpace);
937     }
938
939     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
940         GridTrack& track = tracks[trackIndex];
941         markAsInfinitelyGrowableForTrackSizeComputationPhase(phase, track);
942         updateTrackSizeForTrackSizeComputationPhase(phase, track);
943     }
944 }
945
946 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
947 {
948     // This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
949     // (forall x: NOT x < x).
950     if (track1->infiniteGrowthPotential() && track2->infiniteGrowthPotential())
951         return false;
952
953     if (track1->infiniteGrowthPotential() || track2->infiniteGrowthPotential())
954         return track2->infiniteGrowthPotential();
955
956     return (track1->growthLimit() - track1->baseSize()) < (track2->growthLimit() - track2->baseSize());
957 }
958
959 template <RenderGrid::TrackSizeComputationPhase phase>
960 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, const Vector<GridTrack*>* growBeyondGrowthLimitsTracks, LayoutUnit& availableLogicalSpace)
961 {
962     ASSERT(availableLogicalSpace >= 0);
963
964     for (auto* track : tracks)
965         track->tempSize() = trackSizeForTrackSizeComputationPhase(phase, *track, ForbidInfinity);
966
967     if (availableLogicalSpace > 0) {
968         std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
969
970         unsigned tracksSize = tracks.size();
971         for (unsigned i = 0; i < tracksSize; ++i) {
972             GridTrack& track = *tracks[i];
973             const LayoutUnit& trackBreadth = trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
974             bool infiniteGrowthPotential = track.infiniteGrowthPotential();
975             LayoutUnit trackGrowthPotential = infiniteGrowthPotential ? track.growthLimit() : track.growthLimit() - trackBreadth;
976             // Let's avoid computing availableLogicalSpaceShare as much as possible as it's a hot spot in performance tests.
977             if (trackGrowthPotential > 0 || infiniteGrowthPotential) {
978                 LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
979                 LayoutUnit growthShare = infiniteGrowthPotential ? availableLogicalSpaceShare : std::min(availableLogicalSpaceShare, trackGrowthPotential);
980                 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.");
981                 track.tempSize() += growthShare;
982                 availableLogicalSpace -= growthShare;
983             }
984         }
985     }
986
987     if (availableLogicalSpace > 0 && growBeyondGrowthLimitsTracks) {
988         unsigned tracksGrowingBeyondGrowthLimitsSize = growBeyondGrowthLimitsTracks->size();
989         for (unsigned i = 0; i < tracksGrowingBeyondGrowthLimitsSize; ++i) {
990             GridTrack* track = growBeyondGrowthLimitsTracks->at(i);
991             LayoutUnit growthShare = availableLogicalSpace / (tracksGrowingBeyondGrowthLimitsSize - i);
992             track->tempSize() += growthShare;
993             availableLogicalSpace -= growthShare;
994         }
995     }
996
997     for (auto* track : tracks)
998         track->setPlannedSize(track->plannedSize() == infinity ? track->tempSize() : std::max(track->plannedSize(), track->tempSize()));
999 }
1000
1001 #ifndef NDEBUG
1002 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
1003 {
1004     for (unsigned i = 0; i < tracks.size(); ++i) {
1005         const GridTrackSize& trackSize = gridTrackSize(direction, i);
1006         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
1007         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].baseSize())
1008             return false;
1009     }
1010     return true;
1011 }
1012 #endif
1013
1014 void RenderGrid::ensureGridSize(unsigned maximumRowIndex, unsigned maximumColumnIndex)
1015 {
1016     const unsigned oldRowCount = gridRowCount();
1017     if (maximumRowIndex >= oldRowCount) {
1018         m_grid.grow(maximumRowIndex + 1);
1019         for (unsigned row = oldRowCount; row < gridRowCount(); ++row)
1020             m_grid[row].grow(gridColumnCount());
1021     }
1022
1023     if (maximumColumnIndex >= gridColumnCount()) {
1024         for (unsigned row = 0; row < gridRowCount(); ++row)
1025             m_grid[row].grow(maximumColumnIndex + 1);
1026     }
1027 }
1028
1029 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
1030 {
1031     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
1032
1033     for (auto& row : coordinate.rows) {
1034         for (auto& column : coordinate.columns)
1035             m_grid[row.toInt()][column.toInt()].append(&child);
1036     }
1037     m_gridItemCoordinate.set(&child, coordinate);
1038 }
1039
1040 void RenderGrid::placeItemsOnGrid()
1041 {
1042     ASSERT(!gridWasPopulated());
1043     ASSERT(m_gridItemCoordinate.isEmpty());
1044
1045     populateExplicitGridAndOrderIterator();
1046
1047     Vector<RenderBox*> autoMajorAxisAutoGridItems;
1048     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
1049     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
1050         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
1051         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
1052
1053         if (unresolvedRowPositions.requiresAutoPlacement() || unresolvedColumnPositions.requiresAutoPlacement()) {
1054
1055             bool majorAxisDirectionIsForColumns = autoPlacementMajorAxisDirection() == ForColumns;
1056             if ((majorAxisDirectionIsForColumns && unresolvedColumnPositions.requiresAutoPlacement())
1057                 || (!majorAxisDirectionIsForColumns && unresolvedRowPositions.requiresAutoPlacement()))
1058                 autoMajorAxisAutoGridItems.append(child);
1059             else
1060                 specifiedMajorAxisAutoGridItems.append(child);
1061             continue;
1062         }
1063         GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
1064         GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
1065         insertItemIntoGrid(*child, GridCoordinate(rowPositions, columnPositions));
1066     }
1067
1068     ASSERT(gridRowCount() >= GridResolvedPosition::explicitGridRowCount(style()));
1069     ASSERT(gridColumnCount() >= GridResolvedPosition::explicitGridColumnCount(style()));
1070
1071     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
1072     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
1073 }
1074
1075 void RenderGrid::populateExplicitGridAndOrderIterator()
1076 {
1077     OrderIteratorPopulator populator(m_orderIterator);
1078     unsigned maximumRowIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridRowCount(style()));
1079     unsigned maximumColumnIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridColumnCount(style()));
1080
1081     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1082         populator.collectChild(*child);
1083
1084         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
1085         if (!unresolvedRowPositions.requiresAutoPlacement()) {
1086             GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
1087             maximumRowIndex = std::max(maximumRowIndex, rowPositions.resolvedFinalPosition.next().toInt());
1088         } else {
1089             // Grow the grid for items with a definite row span, getting the largest such span.
1090             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
1091             maximumRowIndex = std::max(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
1092         }
1093
1094         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
1095         if (!unresolvedColumnPositions.requiresAutoPlacement()) {
1096             GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
1097             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions.resolvedFinalPosition.next().toInt());
1098         } else {
1099             // Grow the grid for items with a definite column span, getting the largest such span.
1100             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
1101             maximumColumnIndex = std::max(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
1102         }
1103     }
1104
1105     m_grid.grow(maximumRowIndex);
1106     for (auto& column : m_grid)
1107         column.grow(maximumColumnIndex);
1108 }
1109
1110 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
1111 {
1112     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
1113     const unsigned endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
1114     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
1115     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
1116 }
1117
1118 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1119 {
1120     bool isForColumns = autoPlacementMajorAxisDirection() == ForColumns;
1121     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1122
1123     // Mapping between the major axis tracks (rows or columns) and the last auto-placed item's position inserted on
1124     // that track. This is needed to implement "sparse" packing for items locked to a given track.
1125     // See http://dev.w3.org/csswg/css-grid/#auto-placement-algo
1126     HashMap<unsigned, unsigned, DefaultHash<unsigned>::Hash, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> minorAxisCursors;
1127
1128     for (auto& autoGridItem : autoGridItems) {
1129         auto unresolvedMajorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
1130         ASSERT(!unresolvedMajorAxisPositions.requiresAutoPlacement());
1131         GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMajorAxisPositions, style());
1132         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1133         unsigned majorAxisInitialPosition = majorAxisPositions.resolvedInitialPosition.toInt();
1134
1135         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions.resolvedInitialPosition.toInt(), isGridAutoFlowDense ? 0 : minorAxisCursors.get(majorAxisInitialPosition));
1136         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1137         if (!emptyGridArea)
1138             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), majorAxisPositions);
1139         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
1140
1141         if (!isGridAutoFlowDense)
1142             minorAxisCursors.set(majorAxisInitialPosition, isForColumns ? emptyGridArea->rows.resolvedInitialPosition.toInt() : emptyGridArea->columns.resolvedInitialPosition.toInt());
1143     }
1144 }
1145
1146 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1147 {
1148     AutoPlacementCursor autoPlacementCursor = {0, 0};
1149     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1150
1151     for (auto& autoGridItem : autoGridItems) {
1152         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
1153
1154         if (isGridAutoFlowDense) {
1155             autoPlacementCursor.first = 0;
1156             autoPlacementCursor.second = 0;
1157         }
1158     }
1159 }
1160
1161 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
1162 {
1163     ASSERT(GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()).requiresAutoPlacement());
1164     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
1165
1166     const unsigned endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
1167     unsigned majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
1168     unsigned minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
1169
1170     std::unique_ptr<GridCoordinate> emptyGridArea;
1171     auto unresolvedMinorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
1172     if (!unresolvedMinorAxisPositions.requiresAutoPlacement()) {
1173         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMinorAxisPositions, style());
1174
1175         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
1176         if (minorAxisPositions.resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
1177             majorAxisAutoPlacementCursor++;
1178
1179         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
1180             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions.resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
1181             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions.integerSpan(), majorAxisPositions.integerSpan());
1182         }
1183
1184         if (!emptyGridArea)
1185             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1186     } else {
1187         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1188
1189         for (unsigned majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
1190             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
1191             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1192
1193             if (emptyGridArea) {
1194                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
1195                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
1196                 const unsigned endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
1197                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
1198                     break;
1199
1200                 // Discard empty grid area as it does not fit in the minor axis direction.
1201                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
1202                 emptyGridArea = nullptr;
1203             }
1204
1205             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
1206             minorAxisAutoPlacementCursor = 0;
1207         }
1208
1209         if (!emptyGridArea)
1210             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1211     }
1212
1213     insertItemIntoGrid(gridItem, *emptyGridArea);
1214     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
1215     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
1216 }
1217
1218 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
1219 {
1220     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
1221 }
1222
1223 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
1224 {
1225     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
1226 }
1227
1228 void RenderGrid::clearGrid()
1229 {
1230     m_grid.clear();
1231     m_gridItemCoordinate.clear();
1232 }
1233
1234 void RenderGrid::applyStretchAlignmentToTracksIfNeeded(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit availableSpace)
1235 {
1236     if (availableSpace <= 0
1237         || (direction == ForColumns && style().resolvedJustifyContentDistribution() != ContentDistributionStretch)
1238         || (direction == ForRows && style().resolvedAlignContentDistribution() != ContentDistributionStretch))
1239         return;
1240
1241     // Spec defines auto-sized tracks as the ones with an 'auto' max-sizing function.
1242     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
1243     Vector<unsigned> autoSizedTracksIndex;
1244     for (unsigned i = 0; i < tracks.size(); ++i) {
1245         const GridTrackSize& trackSize = gridTrackSize(direction, i);
1246         if (trackSize.hasAutoMaxTrackBreadth())
1247             autoSizedTracksIndex.append(i);
1248     }
1249
1250     unsigned numberOfAutoSizedTracks = autoSizedTracksIndex.size();
1251     if (numberOfAutoSizedTracks < 1)
1252         return;
1253
1254     LayoutUnit sizeToIncrease = availableSpace / numberOfAutoSizedTracks;
1255     for (const auto& trackIndex : autoSizedTracksIndex) {
1256         auto& track = tracks[trackIndex];
1257         track.setBaseSize(track.baseSize() + sizeToIncrease);
1258     }
1259 }
1260
1261 void RenderGrid::layoutGridItems()
1262 {
1263     placeItemsOnGrid();
1264
1265     LayoutUnit availableSpaceForColumns = availableLogicalWidth();
1266     LayoutUnit availableSpaceForRows = availableLogicalHeight(IncludeMarginBorderPadding);
1267
1268     // Remove space consumed by gutters from the available logical space.
1269     availableSpaceForColumns -= guttersSize(ForColumns, gridColumnCount());
1270     availableSpaceForRows -= guttersSize(ForRows, gridRowCount());
1271
1272     GridSizingData sizingData(gridColumnCount(), gridRowCount());
1273     computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableSpaceForColumns);
1274     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
1275     computeUsedBreadthOfGridTracks(ForRows, sizingData, availableSpaceForRows);
1276     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
1277
1278     applyStretchAlignmentToTracksIfNeeded(ForColumns, sizingData, availableSpaceForColumns);
1279     applyStretchAlignmentToTracksIfNeeded(ForRows, sizingData, availableSpaceForRows);
1280
1281     populateGridPositions(sizingData, availableSpaceForColumns, availableSpaceForRows);
1282
1283     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1284         // Because the grid area cannot be styled, we don't need to adjust
1285         // the grid breadth to account for 'box-sizing'.
1286         Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
1287         Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
1288
1289         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChildIncludingAlignmentOffsets(*child, ForColumns, sizingData);
1290         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChildIncludingAlignmentOffsets(*child, ForRows, sizingData);
1291         if (!oldOverrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalWidth.value() != overrideContainingBlockContentLogicalWidth
1292             || ((!oldOverrideContainingBlockContentLogicalHeight || oldOverrideContainingBlockContentLogicalHeight.value() != overrideContainingBlockContentLogicalHeight)
1293                 && child->hasRelativeLogicalHeight()))
1294             child->setNeedsLayout(MarkOnlyThis);
1295
1296         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
1297         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
1298
1299         LayoutRect oldChildRect = child->frameRect();
1300
1301         // Stretching logic might force a child layout, so we need to run it before the layoutIfNeeded
1302         // call to avoid unnecessary relayouts. This might imply that child margins, needed to correctly
1303         // determine the available space before stretching, are not set yet.
1304         applyStretchAlignmentToChildIfNeeded(*child);
1305
1306         child->layoutIfNeeded();
1307
1308         // We need pending layouts to be done in order to compute auto-margins properly.
1309         updateAutoMarginsInColumnAxisIfNeeded(*child);
1310         updateAutoMarginsInRowAxisIfNeeded(*child);
1311
1312         child->setLogicalLocation(findChildLogicalPosition(*child));
1313
1314         // If the child moved, we have to repaint it as well as any floating/positioned
1315         // descendants. An exception is if we need a layout. In this case, we know we're going to
1316         // repaint ourselves (and the child) anyway.
1317         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
1318             child->repaintDuringLayoutIfMoved(oldChildRect);
1319     }
1320
1321     LayoutUnit height = borderAndPaddingLogicalHeight() + scrollbarLogicalHeight();
1322     for (auto& row : sizingData.rowTracks)
1323         height += row.baseSize();
1324
1325     height += guttersSize(ForRows, sizingData.rowTracks.size());
1326     // min / max logical height is handled in updateLogicalHeight().
1327     if (hasLineIfEmpty()) {
1328         LayoutUnit minHeight = borderAndPaddingLogicalHeight()
1329             + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes)
1330             + scrollbarLogicalHeight();
1331         height = std::max(height, minHeight);
1332     }
1333     setLogicalHeight(height);
1334
1335     clearGrid();
1336 }
1337
1338 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
1339 {
1340     ASSERT(m_gridItemCoordinate.contains(&gridItem));
1341     return m_gridItemCoordinate.get(&gridItem);
1342 }
1343
1344 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1345 {
1346     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1347     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1348     LayoutUnit gridAreaBreadth = 0;
1349     for (auto& trackPosition : span)
1350         gridAreaBreadth += tracks[trackPosition.toInt()].baseSize();
1351
1352     gridAreaBreadth += guttersSize(direction, span.integerSpan());
1353
1354     return gridAreaBreadth;
1355 }
1356
1357 LayoutUnit RenderGrid::gridAreaBreadthForChildIncludingAlignmentOffsets(const RenderBox& child, GridTrackSizingDirection direction, const GridSizingData& sizingData) const
1358 {
1359     // We need the cached value when available because Content Distribution alignment properties
1360     // may have some influence in the final grid area breadth.
1361     const auto& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
1362     const auto& coordinate = cachedGridCoordinate(child);
1363     const auto& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1364     const auto& linePositions = (direction == ForColumns) ? m_columnPositions : m_rowPositions;
1365
1366     LayoutUnit initialTrackPosition = linePositions[span.resolvedInitialPosition.toInt()];
1367     LayoutUnit finalTrackPosition = linePositions[span.resolvedFinalPosition.toInt()];
1368
1369     // Track Positions vector stores the 'start' grid line of each track, so we have to add last track's baseSize.
1370     return finalTrackPosition - initialTrackPosition + tracks[span.resolvedFinalPosition.toInt()].baseSize();
1371 }
1372
1373 void RenderGrid::populateGridPositions(GridSizingData& sizingData, LayoutUnit availableSpaceForColumns, LayoutUnit availableSpaceForRows)
1374 {
1375     // Since we add alignment offsets and track gutters, grid lines are not always adjacent. Hence we will have to
1376     // assume from now on that we just store positions of the initial grid lines of each track,
1377     // except the last one, which is the only one considered as a final grid line of a track.
1378     // FIXME: This will affect the computed style value of grid tracks size, since we are
1379     // using these positions to compute them.
1380
1381     unsigned numberOfTracks = sizingData.columnTracks.size();
1382     unsigned numberOfLines = numberOfTracks + 1;
1383     unsigned lastLine = numberOfLines - 1;
1384     unsigned nextToLastLine = numberOfLines - 2;
1385     ContentAlignmentData offset = computeContentPositionAndDistributionOffset(ForColumns, availableSpaceForColumns, numberOfTracks);
1386     LayoutUnit trackGap = guttersSize(ForColumns, 2);
1387     m_columnPositions.resize(numberOfLines);
1388     m_columnPositions[0] = borderAndPaddingStart() + offset.positionOffset;
1389     for (unsigned i = 0; i < lastLine; ++i)
1390         m_columnPositions[i + 1] = m_columnPositions[i] + offset.distributionOffset + sizingData.columnTracks[i].baseSize() + trackGap;
1391     m_columnPositions[lastLine] = m_columnPositions[nextToLastLine] + sizingData.columnTracks[nextToLastLine].baseSize();
1392
1393     numberOfTracks = sizingData.rowTracks.size();
1394     numberOfLines = numberOfTracks + 1;
1395     lastLine = numberOfLines - 1;
1396     nextToLastLine = numberOfLines - 2;
1397     offset = computeContentPositionAndDistributionOffset(ForRows, availableSpaceForRows, numberOfTracks);
1398     trackGap = guttersSize(ForRows, 2);
1399     m_rowPositions.resize(numberOfLines);
1400     m_rowPositions[0] = borderAndPaddingBefore() + offset.positionOffset;
1401     for (unsigned i = 0; i < lastLine; ++i)
1402         m_rowPositions[i + 1] = m_rowPositions[i] + offset.distributionOffset + sizingData.rowTracks[i].baseSize() + trackGap;
1403     m_rowPositions[lastLine] = m_rowPositions[nextToLastLine] + sizingData.rowTracks[nextToLastLine].baseSize();
1404 }
1405
1406 static inline LayoutUnit computeOverflowAlignmentOffset(OverflowAlignment overflow, LayoutUnit trackBreadth, LayoutUnit childBreadth)
1407 {
1408     LayoutUnit offset = trackBreadth - childBreadth;
1409     switch (overflow) {
1410     case OverflowAlignmentSafe:
1411         // If overflow is 'safe', we have to make sure we don't overflow the 'start'
1412         // edge (potentially cause some data loss as the overflow is unreachable).
1413         return std::max<LayoutUnit>(0, offset);
1414     case OverflowAlignmentTrue:
1415     case OverflowAlignmentDefault:
1416         // If we overflow our alignment container and overflow is 'true' (default), we
1417         // ignore the overflow and just return the value regardless (which may cause data
1418         // loss as we overflow the 'start' edge).
1419         return offset;
1420     }
1421
1422     ASSERT_NOT_REACHED();
1423     return 0;
1424 }
1425
1426 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1427 bool RenderGrid::needToStretchChildLogicalHeight(const RenderBox& child) const
1428 {
1429     if (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch) != ItemPositionStretch)
1430         return false;
1431
1432     return isHorizontalWritingMode() && child.style().height().isAuto();
1433 }
1434
1435 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1436 LayoutUnit RenderGrid::marginLogicalHeightForChild(const RenderBox& child) const
1437 {
1438     return isHorizontalWritingMode() ? child.verticalMarginExtent() : child.horizontalMarginExtent();
1439 }
1440
1441 LayoutUnit RenderGrid::computeMarginLogicalHeightForChild(const RenderBox& child) const
1442 {
1443     if (!child.style().hasMargin())
1444         return 0;
1445
1446     LayoutUnit marginBefore;
1447     LayoutUnit marginAfter;
1448     child.computeBlockDirectionMargins(this, marginBefore, marginAfter);
1449
1450     return marginBefore + marginAfter;
1451 }
1452
1453 LayoutUnit RenderGrid::availableAlignmentSpaceForChildBeforeStretching(LayoutUnit gridAreaBreadthForChild, const RenderBox& child) const
1454 {
1455     // Because we want to avoid multiple layouts, stretching logic might be performed before
1456     // children are laid out, so we can't use the child cached values. Hence, we need to
1457     // compute margins in order to determine the available height before stretching.
1458     return gridAreaBreadthForChild - (child.needsLayout() ? computeMarginLogicalHeightForChild(child) : marginLogicalHeightForChild(child));
1459 }
1460
1461 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1462 void RenderGrid::applyStretchAlignmentToChildIfNeeded(RenderBox& child)
1463 {
1464     ASSERT(child.overrideContainingBlockContentLogicalWidth() && child.overrideContainingBlockContentLogicalHeight());
1465
1466     // We clear both width and height override values because we will decide now whether they
1467     // are allowed or not, evaluating the conditions which might have changed since the old
1468     // values were set.
1469     child.clearOverrideSize();
1470
1471     auto& gridStyle = style();
1472     auto& childStyle = child.style();
1473     bool isHorizontalMode = isHorizontalWritingMode();
1474     bool hasAutoSizeInRowAxis = isHorizontalMode ? childStyle.width().isAuto() : childStyle.height().isAuto();
1475     bool allowedToStretchChildAlongRowAxis = hasAutoSizeInRowAxis && !childStyle.marginStartUsing(&gridStyle).isAuto() && !childStyle.marginEndUsing(&gridStyle).isAuto();
1476     if (!allowedToStretchChildAlongRowAxis || RenderStyle::resolveJustification(gridStyle, childStyle, ItemPositionStretch) != ItemPositionStretch) {
1477         bool hasAutoMinSizeInRowAxis = isHorizontalMode ? childStyle.minWidth().isAuto() : childStyle.minHeight().isAuto();
1478         bool canShrinkToFitInRowAxisForChild = !hasAutoMinSizeInRowAxis || child.minPreferredLogicalWidth() <= child.overrideContainingBlockContentLogicalWidth().value();
1479         // TODO(lajava): how to handle orthogonality in this case ?.
1480         // TODO(lajava): grid track sizing and positioning do not support orthogonal modes yet.
1481         if (hasAutoSizeInRowAxis && canShrinkToFitInRowAxisForChild) {
1482             LayoutUnit childWidthToFitContent = std::max(std::min(child.maxPreferredLogicalWidth(), child.overrideContainingBlockContentLogicalWidth().value() - child.marginLogicalWidth()), child.minPreferredLogicalWidth());
1483             LayoutUnit desiredLogicalWidth = child.constrainLogicalHeightByMinMax(childWidthToFitContent, Nullopt);
1484             child.setOverrideLogicalContentWidth(desiredLogicalWidth - child.borderAndPaddingLogicalWidth());
1485             if (desiredLogicalWidth != child.logicalWidth())
1486                 child.setNeedsLayout();
1487         }
1488     }
1489
1490     bool hasAutoSizeInColumnAxis = isHorizontalMode ? childStyle.height().isAuto() : childStyle.width().isAuto();
1491     bool allowedToStretchChildAlongColumnAxis = hasAutoSizeInColumnAxis && !childStyle.marginBeforeUsing(&gridStyle).isAuto() && !childStyle.marginAfterUsing(&gridStyle).isAuto();
1492     if (allowedToStretchChildAlongColumnAxis && RenderStyle::resolveAlignment(gridStyle, childStyle, ItemPositionStretch) == ItemPositionStretch) {
1493         // TODO (lajava): If the child has orthogonal flow, then it already has an override height set, so use it.
1494         // TODO (lajava): grid track sizing and positioning do not support orthogonal modes yet.
1495         if (child.isHorizontalWritingMode() == isHorizontalMode) {
1496             LayoutUnit stretchedLogicalHeight = availableAlignmentSpaceForChildBeforeStretching(child.overrideContainingBlockContentLogicalHeight().value(), child);
1497             LayoutUnit desiredLogicalHeight = child.constrainLogicalHeightByMinMax(stretchedLogicalHeight, Nullopt);
1498             child.setOverrideLogicalContentHeight(desiredLogicalHeight - child.borderAndPaddingLogicalHeight());
1499             if (desiredLogicalHeight != child.logicalHeight()) {
1500                 // TODO (lajava): Can avoid laying out here in some cases. See https://webkit.org/b/87905.
1501                 child.setLogicalHeight(0);
1502                 child.setNeedsLayout();
1503             }
1504         }
1505     }
1506 }
1507
1508 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1509 bool RenderGrid::hasAutoMarginsInColumnAxis(const RenderBox& child) const
1510 {
1511     if (isHorizontalWritingMode())
1512         return child.style().marginTop().isAuto() || child.style().marginBottom().isAuto();
1513     return child.style().marginLeft().isAuto() || child.style().marginRight().isAuto();
1514 }
1515
1516 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1517 bool RenderGrid::hasAutoMarginsInRowAxis(const RenderBox& child) const
1518 {
1519     if (isHorizontalWritingMode())
1520         return child.style().marginLeft().isAuto() || child.style().marginRight().isAuto();
1521     return child.style().marginTop().isAuto() || child.style().marginBottom().isAuto();
1522 }
1523
1524 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1525 void RenderGrid::updateAutoMarginsInRowAxisIfNeeded(RenderBox& child)
1526 {
1527     ASSERT(!child.isOutOfFlowPositioned());
1528
1529     LayoutUnit availableAlignmentSpace = child.overrideContainingBlockContentLogicalWidth().value() - child.logicalWidth();
1530     if (availableAlignmentSpace <= 0)
1531         return;
1532
1533     const RenderStyle& parentStyle = style();
1534     Length marginStart = child.style().marginStartUsing(&parentStyle);
1535     Length marginEnd = child.style().marginEndUsing(&parentStyle);
1536     if (marginStart.isAuto() && marginEnd.isAuto()) {
1537         child.setMarginStart(availableAlignmentSpace / 2, &parentStyle);
1538         child.setMarginEnd(availableAlignmentSpace / 2, &parentStyle);
1539     } else if (marginStart.isAuto()) {
1540         child.setMarginStart(availableAlignmentSpace, &parentStyle);
1541     } else if (marginEnd.isAuto()) {
1542         child.setMarginEnd(availableAlignmentSpace, &parentStyle);
1543     }
1544 }
1545
1546 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1547 void RenderGrid::updateAutoMarginsInColumnAxisIfNeeded(RenderBox& child)
1548 {
1549     ASSERT(!child.isOutOfFlowPositioned());
1550
1551     LayoutUnit availableAlignmentSpace = child.overrideContainingBlockContentLogicalHeight().value() - child.logicalHeight();
1552     if (availableAlignmentSpace <= 0)
1553         return;
1554
1555     const RenderStyle& parentStyle = style();
1556     Length marginBefore = child.style().marginBeforeUsing(&parentStyle);
1557     Length marginAfter = child.style().marginAfterUsing(&parentStyle);
1558     if (marginBefore.isAuto() && marginAfter.isAuto()) {
1559         child.setMarginBefore(availableAlignmentSpace / 2, &parentStyle);
1560         child.setMarginAfter(availableAlignmentSpace / 2, &parentStyle);
1561     } else if (marginBefore.isAuto()) {
1562         child.setMarginBefore(availableAlignmentSpace, &parentStyle);
1563     } else if (marginAfter.isAuto()) {
1564         child.setMarginAfter(availableAlignmentSpace, &parentStyle);
1565     }
1566 }
1567
1568 GridAxisPosition RenderGrid::columnAxisPositionForChild(const RenderBox& child) const
1569 {
1570     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1571     bool hasSameWritingMode = child.style().writingMode() == style().writingMode();
1572
1573     switch (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch)) {
1574     case ItemPositionSelfStart:
1575         // If orthogonal writing-modes, this computes to 'start'.
1576         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1577         // 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.
1578         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisStart : GridAxisEnd;
1579     case ItemPositionSelfEnd:
1580         // If orthogonal writing-modes, this computes to 'end'.
1581         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1582         // 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.
1583         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisEnd : GridAxisStart;
1584     case ItemPositionLeft:
1585         // The alignment axis (column axis) and the inline axis are parallell in
1586         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1587         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1588         return GridAxisStart;
1589     case ItemPositionRight:
1590         // The alignment axis (column axis) and the inline axis are parallell in
1591         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1592         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1593         return hasOrthogonalWritingMode ? GridAxisEnd : GridAxisStart;
1594     case ItemPositionCenter:
1595         return GridAxisCenter;
1596     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1597     case ItemPositionStart:
1598         return GridAxisStart;
1599     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1600     case ItemPositionEnd:
1601         return GridAxisEnd;
1602     case ItemPositionStretch:
1603         return GridAxisStart;
1604     case ItemPositionBaseline:
1605     case ItemPositionLastBaseline:
1606         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1607         return GridAxisStart;
1608     case ItemPositionAuto:
1609         break;
1610     }
1611
1612     ASSERT_NOT_REACHED();
1613     return GridAxisStart;
1614 }
1615
1616 GridAxisPosition RenderGrid::rowAxisPositionForChild(const RenderBox& child) const
1617 {
1618     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1619     bool hasSameDirection = child.style().direction() == style().direction();
1620     bool isLTR = style().isLeftToRightDirection();
1621
1622     switch (RenderStyle::resolveJustification(style(), child.style(), ItemPositionStretch)) {
1623     case ItemPositionSelfStart:
1624         // For orthogonal writing-modes, this computes to 'start'
1625         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1626         // self-start is based on the child's direction. That's why we need to check against the grid container's direction.
1627         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisStart : GridAxisEnd;
1628     case ItemPositionSelfEnd:
1629         // For orthogonal writing-modes, this computes to 'start'
1630         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1631         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisEnd : GridAxisStart;
1632     case ItemPositionLeft:
1633         return isLTR ? GridAxisStart : GridAxisEnd;
1634     case ItemPositionRight:
1635         return isLTR ? GridAxisEnd : GridAxisStart;
1636     case ItemPositionCenter:
1637         return GridAxisCenter;
1638     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1639     case ItemPositionStart:
1640         return GridAxisStart;
1641     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1642     case ItemPositionEnd:
1643         return GridAxisEnd;
1644     case ItemPositionStretch:
1645         return GridAxisStart;
1646     case ItemPositionBaseline:
1647     case ItemPositionLastBaseline:
1648         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1649         return GridAxisStart;
1650     case ItemPositionAuto:
1651         break;
1652     }
1653
1654     ASSERT_NOT_REACHED();
1655     return GridAxisStart;
1656 }
1657
1658 static inline LayoutUnit offsetBetweenTracks(ContentDistributionType distribution, const Vector<LayoutUnit>& trackPositions, const LayoutUnit& childBreadth)
1659 {
1660     return (distribution == ContentDistributionStretch || ContentDistributionStretch == ContentDistributionDefault) ? LayoutUnit() : trackPositions[1] - trackPositions[0] - childBreadth;
1661 }
1662
1663 LayoutUnit RenderGrid::columnAxisOffsetForChild(const RenderBox& child) const
1664 {
1665     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1666     unsigned childStartLine = coordinate.rows.resolvedInitialPosition.toInt();
1667     LayoutUnit startOfRow = m_rowPositions[childStartLine];
1668     LayoutUnit startPosition = startOfRow + marginBeforeForChild(child);
1669     if (hasAutoMarginsInColumnAxis(child))
1670         return startPosition;
1671     GridAxisPosition axisPosition = columnAxisPositionForChild(child);
1672     switch (axisPosition) {
1673     case GridAxisStart:
1674         return startPosition;
1675     case GridAxisEnd:
1676     case GridAxisCenter: {
1677         unsigned childEndLine = coordinate.rows.resolvedFinalPosition.next().toInt();
1678         LayoutUnit endOfRow = m_rowPositions[childEndLine];
1679         // m_rowPositions include gutters so we need to substract them to get the actual end position for a given
1680         // row (this does not have to be done for the last track as there are no more m_rowPositions after it)
1681         if (childEndLine < m_rowPositions.size() - 1)
1682             endOfRow -= guttersSize(ForRows, 2);
1683         LayoutUnit childBreadth = child.logicalHeight() + child.marginLogicalHeight();
1684         // In order to properly adjust the Self Alignment values we need to consider the offset between tracks.
1685         if (childEndLine - childStartLine > 1 && childEndLine < m_rowPositions.size() - 1)
1686             endOfRow -= offsetBetweenTracks(style().resolvedAlignContentDistribution(), m_rowPositions, childBreadth);
1687         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveAlignmentOverflow(style(), child.style()), endOfRow - startOfRow, childBreadth);
1688         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1689     }
1690     }
1691
1692     ASSERT_NOT_REACHED();
1693     return 0;
1694 }
1695
1696
1697 LayoutUnit RenderGrid::rowAxisOffsetForChild(const RenderBox& child) const
1698 {
1699     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1700     unsigned childStartLine = coordinate.columns.resolvedInitialPosition.toInt();
1701     LayoutUnit startOfColumn = m_columnPositions[childStartLine];
1702     LayoutUnit startPosition = startOfColumn + marginStartForChild(child);
1703     if (hasAutoMarginsInRowAxis(child))
1704         return startPosition;
1705     GridAxisPosition axisPosition = rowAxisPositionForChild(child);
1706     switch (axisPosition) {
1707     case GridAxisStart:
1708         return startPosition;
1709     case GridAxisEnd:
1710     case GridAxisCenter: {
1711         unsigned childEndLine = coordinate.columns.resolvedFinalPosition.next().toInt();
1712         LayoutUnit endOfColumn = m_columnPositions[childEndLine];
1713         // m_columnPositions include gutters so we need to substract them to get the actual end position for a given
1714         // column (this does not have to be done for the last track as there are no more m_columnPositions after it)
1715         if (childEndLine < m_columnPositions.size() - 1)
1716             endOfColumn -= guttersSize(ForColumns, 2);
1717         LayoutUnit childBreadth = child.logicalWidth() + child.marginLogicalWidth();
1718         // In order to properly adjust the Self Alignment values we need to consider the offset between tracks.
1719         if (childEndLine - childStartLine > 1 && childEndLine < m_columnPositions.size() - 1)
1720             endOfColumn -= offsetBetweenTracks(style().resolvedJustifyContentDistribution(), m_columnPositions, childBreadth);
1721         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveJustificationOverflow(style(), child.style()), endOfColumn - startOfColumn, childBreadth);
1722         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1723     }
1724     }
1725
1726     ASSERT_NOT_REACHED();
1727     return 0;
1728 }
1729
1730 ContentPosition static resolveContentDistributionFallback(ContentDistributionType distribution)
1731 {
1732     switch (distribution) {
1733     case ContentDistributionSpaceBetween:
1734         return ContentPositionStart;
1735     case ContentDistributionSpaceAround:
1736         return ContentPositionCenter;
1737     case ContentDistributionSpaceEvenly:
1738         return ContentPositionCenter;
1739     case ContentDistributionStretch:
1740         return ContentPositionStart;
1741     case ContentDistributionDefault:
1742         return ContentPositionAuto;
1743     }
1744
1745     ASSERT_NOT_REACHED();
1746     return ContentPositionAuto;
1747 }
1748
1749 static inline LayoutUnit offsetToStartEdge(bool isLeftToRight, LayoutUnit availableSpace)
1750 {
1751     return isLeftToRight ? LayoutUnit() : availableSpace;
1752 }
1753
1754 static inline LayoutUnit offsetToEndEdge(bool isLeftToRight, LayoutUnit availableSpace)
1755 {
1756     return !isLeftToRight ? LayoutUnit() : availableSpace;
1757 }
1758
1759 static ContentAlignmentData contentDistributionOffset(LayoutUnit availableFreeSpace, ContentPosition& fallbackPosition, ContentDistributionType distribution, unsigned numberOfGridTracks)
1760 {
1761     if (distribution != ContentDistributionDefault && fallbackPosition == ContentPositionAuto)
1762         fallbackPosition = resolveContentDistributionFallback(distribution);
1763
1764     if (availableFreeSpace <= 0)
1765         return ContentAlignmentData::defaultOffsets();
1766
1767     LayoutUnit distributionOffset;
1768     switch (distribution) {
1769     case ContentDistributionSpaceBetween:
1770         if (numberOfGridTracks < 2)
1771             return ContentAlignmentData::defaultOffsets();
1772         return {0, availableFreeSpace / (numberOfGridTracks - 1)};
1773     case ContentDistributionSpaceAround:
1774         if (numberOfGridTracks < 1)
1775             return ContentAlignmentData::defaultOffsets();
1776         distributionOffset = availableFreeSpace / numberOfGridTracks;
1777         return {distributionOffset / 2, distributionOffset};
1778     case ContentDistributionSpaceEvenly:
1779         distributionOffset = availableFreeSpace / (numberOfGridTracks + 1);
1780         return {distributionOffset, distributionOffset};
1781     case ContentDistributionStretch:
1782         return {0, 0};
1783     case ContentDistributionDefault:
1784         return ContentAlignmentData::defaultOffsets();
1785     }
1786
1787     ASSERT_NOT_REACHED();
1788     return ContentAlignmentData::defaultOffsets();
1789 }
1790
1791 ContentAlignmentData RenderGrid::computeContentPositionAndDistributionOffset(GridTrackSizingDirection direction, LayoutUnit availableFreeSpace, unsigned numberOfGridTracks) const
1792 {
1793     bool isRowAxis = direction == ForColumns;
1794     ContentPosition position = isRowAxis ? style().resolvedJustifyContentPosition() : style().resolvedAlignContentPosition();
1795     ContentDistributionType distribution = isRowAxis ? style().resolvedJustifyContentDistribution() : style().resolvedAlignContentDistribution();
1796     // If <content-distribution> value can't be applied, 'position' will become the associated
1797     // <content-position> fallback value.
1798     ContentAlignmentData contentAlignment = contentDistributionOffset(availableFreeSpace, position, distribution, numberOfGridTracks);
1799     if (contentAlignment.isValid())
1800         return contentAlignment;
1801
1802     OverflowAlignment overflow = isRowAxis ? style().justifyContentOverflowAlignment() : style().alignContentOverflowAlignment();
1803     if (availableFreeSpace <= 0 && overflow == OverflowAlignmentSafe)
1804         return {0, 0};
1805
1806     switch (position) {
1807     case ContentPositionLeft:
1808         // The align-content's axis is always orthogonal to the inline-axis.
1809         return {0, 0};
1810     case ContentPositionRight:
1811         if (isRowAxis)
1812             return {availableFreeSpace, 0};
1813         // The align-content's axis is always orthogonal to the inline-axis.
1814         return {0, 0};
1815     case ContentPositionCenter:
1816         return {availableFreeSpace / 2, 0};
1817     case ContentPositionFlexEnd: // Only used in flex layout, for other layout, it's equivalent to 'end'.
1818     case ContentPositionEnd:
1819         if (isRowAxis)
1820             return {offsetToEndEdge(style().isLeftToRightDirection(), availableFreeSpace), 0};
1821         return {availableFreeSpace, 0};
1822     case ContentPositionFlexStart: // Only used in flex layout, for other layout, it's equivalent to 'start'.
1823     case ContentPositionStart:
1824         if (isRowAxis)
1825             return {offsetToStartEdge(style().isLeftToRightDirection(), availableFreeSpace), 0};
1826         return {0, 0};
1827     case ContentPositionBaseline:
1828     case ContentPositionLastBaseline:
1829         // FIXME: Implement the previous values. For now, we always 'start' align.
1830         // http://webkit.org/b/145566
1831         if (isRowAxis)
1832             return {offsetToStartEdge(style().isLeftToRightDirection(), availableFreeSpace), 0};
1833         return {0, 0};
1834     case ContentPositionAuto:
1835         break;
1836     }
1837
1838     ASSERT_NOT_REACHED();
1839     return {0, 0};
1840 }
1841
1842 LayoutPoint RenderGrid::findChildLogicalPosition(const RenderBox& child) const
1843 {
1844     LayoutUnit rowAxisOffset = rowAxisOffsetForChild(child);
1845     // We stored m_columnPositions's data ignoring the direction, hence we might need now
1846     // to translate positions from RTL to LTR, as it's more convenient for painting.
1847     if (!style().isLeftToRightDirection()) {
1848         LayoutUnit alignmentOffset =  m_columnPositions[0] - borderAndPaddingStart();
1849         LayoutUnit rightGridEdgePosition = m_columnPositions[m_columnPositions.size() - 1] + alignmentOffset + borderAndPaddingLogicalLeft();
1850         rowAxisOffset = rightGridEdgePosition - (rowAxisOffset + child.logicalWidth());
1851     }
1852
1853     return LayoutPoint(rowAxisOffset, columnAxisOffsetForChild(child));
1854 }
1855
1856 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1857 {
1858     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1859         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect, PaintAsInlineBlock);
1860 }
1861
1862 const char* RenderGrid::renderName() const
1863 {
1864     if (isFloating())
1865         return "RenderGrid (floating)";
1866     if (isOutOfFlowPositioned())
1867         return "RenderGrid (positioned)";
1868     if (isAnonymous())
1869         return "RenderGrid (generated)";
1870     if (isRelPositioned())
1871         return "RenderGrid (relative positioned)";
1872     return "RenderGrid";
1873 }
1874
1875 } // namespace WebCore
1876
1877 #endif /* ENABLE(CSS_GRID_LAYOUT) */