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