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