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