36049d46f7bac93c77b0c34edf00ac9dda5d3685
[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
306     LayoutUnit scrollbarWidth = intrinsicScrollbarLogicalWidth();
307     minLogicalWidth += scrollbarWidth;
308     maxLogicalWidth += scrollbarWidth;
309
310     if (!wasPopulated)
311         const_cast<RenderGrid*>(this)->clearGrid();
312 }
313
314 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
315 {
316     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
317     computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
318 }
319
320 bool RenderGrid::gridElementIsShrinkToFit()
321 {
322     return isFloatingOrOutOfFlowPositioned();
323 }
324
325 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
326 {
327     const LayoutUnit initialAvailableLogicalSpace = availableLogicalSpace;
328     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
329     Vector<unsigned> flexibleSizedTracksIndex;
330     sizingData.contentSizedTracksIndex.shrink(0);
331
332     // 1. Initialize per Grid track variables.
333     for (unsigned i = 0; i < tracks.size(); ++i) {
334         GridTrack& track = tracks[i];
335         const GridTrackSize& trackSize = gridTrackSize(direction, i);
336         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
337         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
338
339         track.setBaseSize(computeUsedBreadthOfMinLength(direction, minTrackBreadth));
340         track.setGrowthLimit(computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.baseSize()));
341         track.setInfinitelyGrowable(false);
342
343         if (trackSize.isContentSized())
344             sizingData.contentSizedTracksIndex.append(i);
345         if (trackSize.maxTrackBreadth().isFlex())
346             flexibleSizedTracksIndex.append(i);
347     }
348
349     // 2. Resolve content-based TrackSizingFunctions.
350     if (!sizingData.contentSizedTracksIndex.isEmpty())
351         resolveContentBasedTrackSizingFunctions(direction, sizingData);
352
353     for (auto& track : tracks) {
354         ASSERT(!track.growthLimitIsInfinite());
355         availableLogicalSpace -= track.baseSize();
356     }
357
358     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
359
360     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
361         return;
362
363     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until availableLogicalSpace is exhausted.
364     if (!hasUndefinedRemainingSpace) {
365         const unsigned tracksSize = tracks.size();
366         Vector<GridTrack*> tracksForDistribution(tracksSize);
367         for (unsigned i = 0; i < tracksSize; ++i) {
368             tracksForDistribution[i] = tracks.data() + i;
369             tracksForDistribution[i]->setPlannedSize(tracksForDistribution[i]->baseSize());
370         }
371
372         distributeSpaceToTracks<MaximizeTracks>(tracksForDistribution, nullptr, availableLogicalSpace);
373
374         for (auto* track : tracksForDistribution)
375             track->setBaseSize(track->plannedSize());
376     } else {
377         for (auto& track : tracks)
378             track.setBaseSize(track.growthLimit());
379     }
380
381     if (flexibleSizedTracksIndex.isEmpty())
382         return;
383
384     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
385     double normalizedFractionBreadth = 0;
386     if (!hasUndefinedRemainingSpace)
387         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, initialAvailableLogicalSpace);
388     else {
389         for (auto trackIndex : flexibleSizedTracksIndex) {
390             const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
391             normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].baseSize() / trackSize.maxTrackBreadth().flex());
392         }
393
394         for (unsigned i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
395             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
396             while (RenderBox* gridItem = iterator.nextGridItem()) {
397                 const GridCoordinate coordinate = cachedGridCoordinate(*gridItem);
398                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
399
400                 // Do not include already processed items.
401                 if (i > 0 && span.resolvedInitialPosition.toInt() <= flexibleSizedTracksIndex[i - 1])
402                     continue;
403
404                 double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(*gridItem, direction, sizingData.columnTracks));
405                 normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
406             }
407         }
408     }
409
410     for (auto trackIndex : flexibleSizedTracksIndex) {
411         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
412         GridTrack& track = tracks[trackIndex];
413         LayoutUnit baseSize = std::max<LayoutUnit>(track.baseSize(), normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
414         track.setBaseSize(baseSize);
415         availableLogicalSpace -= baseSize;
416     }
417 }
418
419 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
420 {
421     if (gridLength.isFlex())
422         return 0;
423
424     const Length& trackLength = gridLength.length();
425     ASSERT(!trackLength.isAuto());
426     if (trackLength.isSpecified())
427         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
428
429     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
430     return 0;
431 }
432
433 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
434 {
435     if (gridLength.isFlex())
436         return usedBreadth;
437
438     const Length& trackLength = gridLength.length();
439     ASSERT(!trackLength.isAuto());
440     if (trackLength.isSpecified()) {
441         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
442         ASSERT(computedBreadth != infinity);
443         return computedBreadth;
444     }
445
446     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
447     return infinity;
448 }
449
450 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
451 {
452     ASSERT(trackLength.isSpecified());
453     if (direction == ForColumns)
454         return valueForLength(trackLength, logicalWidth());
455     return valueForLength(trackLength, computeContentLogicalHeight(style().logicalHeight(), Nullopt).valueOr(0));
456 }
457
458 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit spaceToFill) const
459 {
460     LayoutUnit allocatedSpace;
461     Vector<GridTrackForNormalization> tracksForNormalization;
462     for (auto& position : tracksSpan) {
463         GridTrack& track = tracks[position.toInt()];
464         allocatedSpace += track.baseSize();
465
466         const GridTrackSize& trackSize = gridTrackSize(direction, position.toInt());
467         if (!trackSize.maxTrackBreadth().isFlex())
468             continue;
469
470         tracksForNormalization.append(GridTrackForNormalization(track, trackSize.maxTrackBreadth().flex()));
471     }
472
473     // The function is not called if we don't have <flex> grid tracks
474     ASSERT(!tracksForNormalization.isEmpty());
475
476     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
477               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
478                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
479               });
480
481     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
482     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
483     // fit into availableLogicalSpaceIgnoringFractionTracks.
484     double accumulatedFractions = 0;
485     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
486     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = spaceToFill - allocatedSpace;
487
488     for (auto& track : tracksForNormalization) {
489         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
490             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
491             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
492             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
493                 break;
494
495             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
496         }
497
498         accumulatedFractions += track.m_flex;
499         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
500         availableLogicalSpaceIgnoringFractionTracks += track.m_track->baseSize();
501     }
502
503     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
504 }
505
506 bool RenderGrid::hasDefiniteLogicalSize(GridTrackSizingDirection direction) const
507 {
508     return (direction == ForRows) ? hasDefiniteLogicalHeight() : hasDefiniteLogicalWidth();
509 }
510
511 GridTrackSize RenderGrid::gridTrackSize(GridTrackSizingDirection direction, unsigned i) const
512 {
513     bool isForColumns = (direction == ForColumns);
514     auto& trackStyles =  isForColumns ? style().gridColumns() : style().gridRows();
515     auto& trackSize = (i >= trackStyles.size()) ? (isForColumns ? style().gridAutoColumns() : style().gridAutoRows()) : trackStyles[i];
516
517     GridLength minTrackBreadth = trackSize.minTrackBreadth();
518     GridLength maxTrackBreadth = trackSize.maxTrackBreadth();
519
520     if (minTrackBreadth.isPercentage() || maxTrackBreadth.isPercentage()) {
521         if (!hasDefiniteLogicalSize(direction)) {
522             if (minTrackBreadth.isPercentage())
523                 minTrackBreadth = Length(MinContent);
524             if (maxTrackBreadth.isPercentage())
525                 maxTrackBreadth = Length(MaxContent);
526         }
527     }
528
529     return GridTrackSize(minTrackBreadth, maxTrackBreadth);
530 }
531
532 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox& child, Vector<GridTrack>& columnTracks)
533 {
534     Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
535     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
536     if (child.hasRelativeLogicalHeight() || !oldOverrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalWidth.value() != overrideContainingBlockContentLogicalWidth) {
537         child.setNeedsLayout(MarkOnlyThis);
538         // We need to clear the stretched height to properly compute logical height during layout.
539         child.clearOverrideLogicalContentHeight();
540     }
541
542     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
543     // If |child| has a relative logical height, we shouldn't let it override its intrinsic height, which is
544     // what we are interested in here. Thus we need to set the override logical height to Nullopt (no possible resolution).
545     if (child.hasRelativeLogicalHeight())
546         child.setOverrideContainingBlockContentLogicalHeight(Nullopt);
547     child.layoutIfNeeded();
548     return child.logicalHeight() + child.marginLogicalHeight();
549 }
550
551 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
552 {
553     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
554     // FIXME: Properly support orthogonal writing mode.
555     if (hasOrthogonalWritingMode)
556         return 0;
557
558     if (direction == ForColumns) {
559         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
560         // what we are interested in here. Thus we need to set the override logical width to Nullopt (no possible resolution).
561         if (child.hasRelativeLogicalWidth())
562             child.setOverrideContainingBlockContentLogicalWidth(Nullopt);
563
564         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
565         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
566         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
567     }
568
569     return logicalContentHeightForChild(child, columnTracks);
570 }
571
572 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
573 {
574     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
575     // FIXME: Properly support orthogonal writing mode.
576     if (hasOrthogonalWritingMode)
577         return LayoutUnit();
578
579     if (direction == ForColumns) {
580         // If |child| has a relative logical width, we shouldn't let it override its intrinsic width, which is
581         // what we are interested in here. Thus we need to set the override logical width to Nullopt (no possible resolution).
582         if (child.hasRelativeLogicalWidth())
583             child.setOverrideContainingBlockContentLogicalWidth(Nullopt);
584
585         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
586         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
587         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
588     }
589
590     return logicalContentHeightForChild(child, columnTracks);
591 }
592
593 class GridItemWithSpan {
594 public:
595     GridItemWithSpan(RenderBox& gridItem, GridCoordinate coordinate, GridTrackSizingDirection direction)
596         : m_gridItem(gridItem)
597         , m_coordinate(coordinate)
598     {
599         const GridSpan& span = (direction == ForRows) ? coordinate.rows : coordinate.columns;
600         m_span = span.resolvedFinalPosition.toInt() - span.resolvedInitialPosition.toInt() + 1;
601     }
602
603     RenderBox& gridItem() const { return m_gridItem; }
604     GridCoordinate coordinate() const { return m_coordinate; }
605 #if !ASSERT_DISABLED
606     size_t span() const { return m_span; }
607 #endif
608
609     bool operator<(const GridItemWithSpan other) const
610     {
611         return m_span < other.m_span;
612     }
613
614 private:
615     std::reference_wrapper<RenderBox> m_gridItem;
616     GridCoordinate m_coordinate;
617     unsigned m_span;
618 };
619
620 bool RenderGrid::spanningItemCrossesFlexibleSizedTracks(const GridCoordinate& coordinate, GridTrackSizingDirection direction) const
621 {
622     const GridSpan itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
623     for (auto trackPosition : itemSpan) {
624         const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
625         if (trackSize.minTrackBreadth().isFlex() || trackSize.maxTrackBreadth().isFlex())
626             return true;
627     }
628
629     return false;
630 }
631
632 static inline unsigned integerSpanForDirection(const GridCoordinate& coordinate, GridTrackSizingDirection direction)
633 {
634     return (direction == ForRows) ? coordinate.rows.integerSpan() : coordinate.columns.integerSpan();
635 }
636
637 struct GridItemsSpanGroupRange {
638     Vector<GridItemWithSpan>::iterator rangeStart;
639     Vector<GridItemWithSpan>::iterator rangeEnd;
640 };
641
642 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
643 {
644     sizingData.itemsSortedByIncreasingSpan.shrink(0);
645     HashSet<RenderBox*> itemsSet;
646     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
647         GridIterator iterator(m_grid, direction, trackIndex);
648         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
649
650         while (RenderBox* gridItem = iterator.nextGridItem()) {
651             if (itemsSet.add(gridItem).isNewEntry) {
652                 const GridCoordinate& coordinate = cachedGridCoordinate(*gridItem);
653                 if (integerSpanForDirection(coordinate, direction) == 1)
654                     resolveContentBasedTrackSizingFunctionsForNonSpanningItems(direction, coordinate, *gridItem, track, sizingData.columnTracks);
655                 else if (!spanningItemCrossesFlexibleSizedTracks(coordinate, direction))
656                     sizingData.itemsSortedByIncreasingSpan.append(GridItemWithSpan(*gridItem, coordinate, direction));
657             }
658         }
659     }
660     std::sort(sizingData.itemsSortedByIncreasingSpan.begin(), sizingData.itemsSortedByIncreasingSpan.end());
661
662     auto it = sizingData.itemsSortedByIncreasingSpan.begin();
663     auto end = sizingData.itemsSortedByIncreasingSpan.end();
664     while (it != end) {
665         GridItemsSpanGroupRange spanGroupRange = { it, std::upper_bound(it, end, *it) };
666         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMinimums>(direction, sizingData, spanGroupRange);
667         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMinimums>(direction, sizingData, spanGroupRange);
668         resolveContentBasedTrackSizingFunctionsForItems<ResolveIntrinsicMaximums>(direction, sizingData, spanGroupRange);
669         resolveContentBasedTrackSizingFunctionsForItems<ResolveMaxContentMaximums>(direction, sizingData, spanGroupRange);
670         it = spanGroupRange.rangeEnd;
671     }
672
673     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
674         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
675         if (track.growthLimitIsInfinite())
676             track.setGrowthLimit(track.baseSize());
677     }
678 }
679
680 void RenderGrid::resolveContentBasedTrackSizingFunctionsForNonSpanningItems(GridTrackSizingDirection direction, const GridCoordinate& coordinate, RenderBox& gridItem, GridTrack& track, Vector<GridTrack>& columnTracks)
681 {
682     const GridResolvedPosition trackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
683     GridTrackSize trackSize = gridTrackSize(direction, trackPosition.toInt());
684
685     if (trackSize.hasMinContentMinTrackBreadth())
686         track.setBaseSize(std::max(track.baseSize(), minContentForChild(gridItem, direction, columnTracks)));
687     else if (trackSize.hasMaxContentMinTrackBreadth())
688         track.setBaseSize(std::max(track.baseSize(), maxContentForChild(gridItem, direction, columnTracks)));
689
690     if (trackSize.hasMinContentMaxTrackBreadth())
691         track.setGrowthLimit(std::max(track.growthLimit(), minContentForChild(gridItem, direction, columnTracks)));
692     else if (trackSize.hasMaxContentMaxTrackBreadth())
693         track.setGrowthLimit(std::max(track.growthLimit(), maxContentForChild(gridItem, direction, columnTracks)));
694 }
695
696 const LayoutUnit& RenderGrid::trackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track, TrackSizeRestriction restriction)
697 {
698     switch (phase) {
699     case ResolveIntrinsicMinimums:
700     case ResolveMaxContentMinimums:
701     case MaximizeTracks:
702         return track.baseSize();
703     case ResolveIntrinsicMaximums:
704     case ResolveMaxContentMaximums:
705         return restriction == AllowInfinity ? track.growthLimit() : track.growthLimitIfNotInfinite();
706     }
707
708     ASSERT_NOT_REACHED();
709     return track.baseSize();
710 }
711
712 bool RenderGrid::shouldProcessTrackForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
713 {
714     switch (phase) {
715     case ResolveIntrinsicMinimums:
716         return trackSize.hasMinOrMaxContentMinTrackBreadth();
717     case ResolveMaxContentMinimums:
718         return trackSize.hasMaxContentMinTrackBreadth();
719     case ResolveIntrinsicMaximums:
720         return trackSize.hasMinOrMaxContentMaxTrackBreadth();
721     case ResolveMaxContentMaximums:
722         return trackSize.hasMaxContentMaxTrackBreadth();
723     case MaximizeTracks:
724         ASSERT_NOT_REACHED();
725         return false;
726     }
727
728     ASSERT_NOT_REACHED();
729     return false;
730 }
731
732 bool RenderGrid::trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(TrackSizeComputationPhase phase, const GridTrackSize& trackSize)
733 {
734     switch (phase) {
735     case ResolveIntrinsicMinimums:
736         return trackSize.hasMinContentMinTrackBreadthAndMinOrMaxContentMaxTrackBreadth();
737     case ResolveMaxContentMinimums:
738         return trackSize.hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth();
739     case ResolveIntrinsicMaximums:
740     case ResolveMaxContentMaximums:
741         return true;
742     case MaximizeTracks:
743         ASSERT_NOT_REACHED();
744         return false;
745     }
746
747     ASSERT_NOT_REACHED();
748     return false;
749 }
750
751 void RenderGrid::markAsInfinitelyGrowableForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
752 {
753     switch (phase) {
754     case ResolveIntrinsicMinimums:
755     case ResolveMaxContentMinimums:
756         return;
757     case ResolveIntrinsicMaximums:
758         if (trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity) == infinity  && track.plannedSize() != infinity)
759             track.setInfinitelyGrowable(true);
760         return;
761     case ResolveMaxContentMaximums:
762         if (track.infinitelyGrowable())
763             track.setInfinitelyGrowable(false);
764         return;
765     case MaximizeTracks:
766         ASSERT_NOT_REACHED();
767         return;
768     }
769
770     ASSERT_NOT_REACHED();
771 }
772
773 void RenderGrid::updateTrackSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, GridTrack& track)
774 {
775     switch (phase) {
776     case ResolveIntrinsicMinimums:
777     case ResolveMaxContentMinimums:
778         track.setBaseSize(track.plannedSize());
779         return;
780     case ResolveIntrinsicMaximums:
781     case ResolveMaxContentMaximums:
782         track.setGrowthLimit(track.plannedSize());
783         return;
784     case MaximizeTracks:
785         ASSERT_NOT_REACHED();
786         return;
787     }
788
789     ASSERT_NOT_REACHED();
790 }
791
792 LayoutUnit RenderGrid::currentItemSizeForTrackSizeComputationPhase(TrackSizeComputationPhase phase, RenderBox& gridItem, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
793 {
794     switch (phase) {
795     case ResolveIntrinsicMinimums:
796     case ResolveIntrinsicMaximums:
797         return minContentForChild(gridItem, direction, columnTracks);
798     case ResolveMaxContentMinimums:
799     case ResolveMaxContentMaximums:
800         return maxContentForChild(gridItem, direction, columnTracks);
801     case MaximizeTracks:
802         ASSERT_NOT_REACHED();
803         return 0;
804     }
805
806     ASSERT_NOT_REACHED();
807     return 0;
808 }
809
810 template <RenderGrid::TrackSizeComputationPhase phase>
811 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, const GridItemsSpanGroupRange& gridItemsWithSpan)
812 {
813     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
814     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
815         GridTrack& track = tracks[trackIndex];
816         track.setPlannedSize(trackSizeForTrackSizeComputationPhase(phase, track, AllowInfinity));
817     }
818
819     for (auto it = gridItemsWithSpan.rangeStart; it != gridItemsWithSpan.rangeEnd; ++it) {
820         GridItemWithSpan& gridItemWithSpan = *it;
821         ASSERT(gridItemWithSpan.span() > 1);
822         const GridCoordinate& coordinate = gridItemWithSpan.coordinate();
823         const GridSpan& itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
824
825         sizingData.filteredTracks.shrink(0);
826         sizingData.growBeyondGrowthLimitsTracks.shrink(0);
827         LayoutUnit spanningTracksSize;
828         for (auto& trackPosition : itemSpan) {
829             const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
830             GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPosition.toInt()] : sizingData.rowTracks[trackPosition.toInt()];
831             spanningTracksSize += trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
832             if (!shouldProcessTrackForTrackSizeComputationPhase(phase, trackSize))
833                 continue;
834
835             sizingData.filteredTracks.append(&track);
836
837             if (trackShouldGrowBeyondGrowthLimitsForTrackSizeComputationPhase(phase, trackSize))
838                 sizingData.growBeyondGrowthLimitsTracks.append(&track);
839         }
840
841         if (sizingData.filteredTracks.isEmpty())
842             continue;
843
844         LayoutUnit extraSpace = currentItemSizeForTrackSizeComputationPhase(phase, gridItemWithSpan.gridItem(), direction, sizingData.columnTracks) - spanningTracksSize;
845         extraSpace = std::max<LayoutUnit>(extraSpace, 0);
846         auto& tracksToGrowBeyondGrowthLimits = sizingData.growBeyondGrowthLimitsTracks.isEmpty() ? sizingData.filteredTracks : sizingData.growBeyondGrowthLimitsTracks;
847         distributeSpaceToTracks<phase>(sizingData.filteredTracks, &tracksToGrowBeyondGrowthLimits, extraSpace);
848     }
849
850     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
851         GridTrack& track = tracks[trackIndex];
852         markAsInfinitelyGrowableForTrackSizeComputationPhase(phase, track);
853         updateTrackSizeForTrackSizeComputationPhase(phase, track);
854     }
855 }
856
857 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
858 {
859     // This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
860     // (forall x: NOT x < x).
861     if (track1->infiniteGrowthPotential() && track2->infiniteGrowthPotential())
862         return false;
863
864     if (track1->infiniteGrowthPotential() || track2->infiniteGrowthPotential())
865         return track2->infiniteGrowthPotential();
866
867     return (track1->growthLimit() - track1->baseSize()) < (track2->growthLimit() - track2->baseSize());
868 }
869
870 template <RenderGrid::TrackSizeComputationPhase phase>
871 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, const Vector<GridTrack*>* growBeyondGrowthLimitsTracks, LayoutUnit& availableLogicalSpace)
872 {
873     ASSERT(availableLogicalSpace >= 0);
874
875     for (auto* track : tracks)
876         track->tempSize() = trackSizeForTrackSizeComputationPhase(phase, *track, ForbidInfinity);
877
878     if (availableLogicalSpace > 0) {
879         std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
880
881         unsigned tracksSize = tracks.size();
882         for (unsigned i = 0; i < tracksSize; ++i) {
883             GridTrack& track = *tracks[i];
884             const LayoutUnit& trackBreadth = trackSizeForTrackSizeComputationPhase(phase, track, ForbidInfinity);
885             bool infiniteGrowthPotential = track.infiniteGrowthPotential();
886             LayoutUnit trackGrowthPotential = infiniteGrowthPotential ? track.growthLimit() : track.growthLimit() - trackBreadth;
887             // Let's avoid computing availableLogicalSpaceShare as much as possible as it's a hot spot in performance tests.
888             if (trackGrowthPotential > 0 || infiniteGrowthPotential) {
889                 LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
890                 LayoutUnit growthShare = infiniteGrowthPotential ? availableLogicalSpaceShare : std::min(availableLogicalSpaceShare, trackGrowthPotential);
891                 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.");
892                 track.tempSize() += growthShare;
893                 availableLogicalSpace -= growthShare;
894             }
895         }
896     }
897
898     if (availableLogicalSpace > 0 && growBeyondGrowthLimitsTracks) {
899         unsigned tracksGrowingBeyondGrowthLimitsSize = growBeyondGrowthLimitsTracks->size();
900         for (unsigned i = 0; i < tracksGrowingBeyondGrowthLimitsSize; ++i) {
901             GridTrack* track = growBeyondGrowthLimitsTracks->at(i);
902             LayoutUnit growthShare = availableLogicalSpace / (tracksGrowingBeyondGrowthLimitsSize - i);
903             track->tempSize() += growthShare;
904             availableLogicalSpace -= growthShare;
905         }
906     }
907
908     for (auto* track : tracks)
909         track->setPlannedSize(track->plannedSize() == infinity ? track->tempSize() : std::max(track->plannedSize(), track->tempSize()));
910 }
911
912 #ifndef NDEBUG
913 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
914 {
915     for (unsigned i = 0; i < tracks.size(); ++i) {
916         const GridTrackSize& trackSize = gridTrackSize(direction, i);
917         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
918         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].baseSize())
919             return false;
920     }
921     return true;
922 }
923 #endif
924
925 void RenderGrid::ensureGridSize(unsigned maximumRowIndex, unsigned maximumColumnIndex)
926 {
927     const unsigned oldRowCount = gridRowCount();
928     if (maximumRowIndex >= oldRowCount) {
929         m_grid.grow(maximumRowIndex + 1);
930         for (unsigned row = oldRowCount; row < gridRowCount(); ++row)
931             m_grid[row].grow(gridColumnCount());
932     }
933
934     if (maximumColumnIndex >= gridColumnCount()) {
935         for (unsigned row = 0; row < gridRowCount(); ++row)
936             m_grid[row].grow(maximumColumnIndex + 1);
937     }
938 }
939
940 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
941 {
942     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
943
944     for (auto& row : coordinate.rows) {
945         for (auto& column : coordinate.columns)
946             m_grid[row.toInt()][column.toInt()].append(&child);
947     }
948     m_gridItemCoordinate.set(&child, coordinate);
949 }
950
951 void RenderGrid::placeItemsOnGrid()
952 {
953     ASSERT(!gridWasPopulated());
954     ASSERT(m_gridItemCoordinate.isEmpty());
955
956     populateExplicitGridAndOrderIterator();
957
958     Vector<RenderBox*> autoMajorAxisAutoGridItems;
959     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
960     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
961         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
962         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
963
964         if (unresolvedRowPositions.requiresAutoPlacement() || unresolvedColumnPositions.requiresAutoPlacement()) {
965
966             bool majorAxisDirectionIsForColumns = autoPlacementMajorAxisDirection() == ForColumns;
967             if ((majorAxisDirectionIsForColumns && unresolvedColumnPositions.requiresAutoPlacement())
968                 || (!majorAxisDirectionIsForColumns && unresolvedRowPositions.requiresAutoPlacement()))
969                 autoMajorAxisAutoGridItems.append(child);
970             else
971                 specifiedMajorAxisAutoGridItems.append(child);
972             continue;
973         }
974         GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
975         GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
976         insertItemIntoGrid(*child, GridCoordinate(rowPositions, columnPositions));
977     }
978
979     ASSERT(gridRowCount() >= GridResolvedPosition::explicitGridRowCount(style()));
980     ASSERT(gridColumnCount() >= GridResolvedPosition::explicitGridColumnCount(style()));
981
982     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
983     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
984 }
985
986 void RenderGrid::populateExplicitGridAndOrderIterator()
987 {
988     OrderIteratorPopulator populator(m_orderIterator);
989     unsigned maximumRowIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridRowCount(style()));
990     unsigned maximumColumnIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridColumnCount(style()));
991
992     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
993         populator.collectChild(*child);
994
995         auto unresolvedRowPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForRows);
996         if (!unresolvedRowPositions.requiresAutoPlacement()) {
997             GridSpan rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedRowPositions, style());
998             maximumRowIndex = std::max(maximumRowIndex, rowPositions.resolvedFinalPosition.next().toInt());
999         } else {
1000             // Grow the grid for items with a definite row span, getting the largest such span.
1001             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
1002             maximumRowIndex = std::max(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
1003         }
1004
1005         auto unresolvedColumnPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *child, ForColumns);
1006         if (!unresolvedColumnPositions.requiresAutoPlacement()) {
1007             GridSpan columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedColumnPositions, style());
1008             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions.resolvedFinalPosition.next().toInt());
1009         } else {
1010             // Grow the grid for items with a definite column span, getting the largest such span.
1011             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
1012             maximumColumnIndex = std::max(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
1013         }
1014     }
1015
1016     m_grid.grow(maximumRowIndex);
1017     for (auto& column : m_grid)
1018         column.grow(maximumColumnIndex);
1019 }
1020
1021 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
1022 {
1023     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
1024     const unsigned endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
1025     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
1026     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
1027 }
1028
1029 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1030 {
1031     bool isForColumns = autoPlacementMajorAxisDirection() == ForColumns;
1032     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1033
1034     // Mapping between the major axis tracks (rows or columns) and the last auto-placed item's position inserted on
1035     // that track. This is needed to implement "sparse" packing for items locked to a given track.
1036     // See http://dev.w3.org/csswg/css-grid/#auto-placement-algo
1037     HashMap<unsigned, unsigned, DefaultHash<unsigned>::Hash, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> minorAxisCursors;
1038
1039     for (auto& autoGridItem : autoGridItems) {
1040         auto unresolvedMajorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
1041         ASSERT(!unresolvedMajorAxisPositions.requiresAutoPlacement());
1042         GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMajorAxisPositions, style());
1043         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1044         unsigned majorAxisInitialPosition = majorAxisPositions.resolvedInitialPosition.toInt();
1045
1046         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions.resolvedInitialPosition.toInt(), isGridAutoFlowDense ? 0 : minorAxisCursors.get(majorAxisInitialPosition));
1047         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1048         if (!emptyGridArea)
1049             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), majorAxisPositions);
1050         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
1051
1052         if (!isGridAutoFlowDense)
1053             minorAxisCursors.set(majorAxisInitialPosition, isForColumns ? emptyGridArea->rows.resolvedInitialPosition.toInt() : emptyGridArea->columns.resolvedInitialPosition.toInt());
1054     }
1055 }
1056
1057 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
1058 {
1059     AutoPlacementCursor autoPlacementCursor = {0, 0};
1060     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
1061
1062     for (auto& autoGridItem : autoGridItems) {
1063         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
1064
1065         if (isGridAutoFlowDense) {
1066             autoPlacementCursor.first = 0;
1067             autoPlacementCursor.second = 0;
1068         }
1069     }
1070 }
1071
1072 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
1073 {
1074     ASSERT(GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()).requiresAutoPlacement());
1075     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
1076
1077     const unsigned endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
1078     unsigned majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
1079     unsigned minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
1080
1081     std::unique_ptr<GridCoordinate> emptyGridArea;
1082     auto unresolvedMinorAxisPositions = GridResolvedPosition::unresolvedSpanFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
1083     if (!unresolvedMinorAxisPositions.requiresAutoPlacement()) {
1084         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(unresolvedMinorAxisPositions, style());
1085
1086         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
1087         if (minorAxisPositions.resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
1088             majorAxisAutoPlacementCursor++;
1089
1090         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
1091             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions.resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
1092             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions.integerSpan(), majorAxisPositions.integerSpan());
1093         }
1094
1095         if (!emptyGridArea)
1096             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1097     } else {
1098         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
1099
1100         for (unsigned majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
1101             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
1102             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
1103
1104             if (emptyGridArea) {
1105                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
1106                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
1107                 const unsigned endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
1108                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
1109                     break;
1110
1111                 // Discard empty grid area as it does not fit in the minor axis direction.
1112                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
1113                 emptyGridArea = nullptr;
1114             }
1115
1116             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
1117             minorAxisAutoPlacementCursor = 0;
1118         }
1119
1120         if (!emptyGridArea)
1121             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
1122     }
1123
1124     insertItemIntoGrid(gridItem, *emptyGridArea);
1125     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
1126     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
1127 }
1128
1129 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
1130 {
1131     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
1132 }
1133
1134 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
1135 {
1136     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
1137 }
1138
1139 void RenderGrid::clearGrid()
1140 {
1141     m_grid.clear();
1142     m_gridItemCoordinate.clear();
1143 }
1144
1145 void RenderGrid::layoutGridItems()
1146 {
1147     placeItemsOnGrid();
1148
1149     GridSizingData sizingData(gridColumnCount(), gridRowCount());
1150     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
1151     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
1152     computeUsedBreadthOfGridTracks(ForRows, sizingData);
1153     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
1154
1155     populateGridPositions(sizingData);
1156
1157     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1158         // Because the grid area cannot be styled, we don't need to adjust
1159         // the grid breadth to account for 'box-sizing'.
1160         Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
1161         Optional<LayoutUnit> oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
1162
1163         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(*child, ForColumns, sizingData.columnTracks);
1164         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(*child, ForRows, sizingData.rowTracks);
1165         if (!oldOverrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalWidth.value() != overrideContainingBlockContentLogicalWidth
1166             || ((!oldOverrideContainingBlockContentLogicalHeight || oldOverrideContainingBlockContentLogicalHeight.value() != overrideContainingBlockContentLogicalHeight)
1167                 && child->hasRelativeLogicalHeight()))
1168             child->setNeedsLayout(MarkOnlyThis);
1169
1170         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
1171         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
1172
1173         LayoutRect oldChildRect = child->frameRect();
1174
1175         // Stretching logic might force a child layout, so we need to run it before the layoutIfNeeded
1176         // call to avoid unnecessary relayouts. This might imply that child margins, needed to correctly
1177         // determine the available space before stretching, are not set yet.
1178         applyStretchAlignmentToChildIfNeeded(*child);
1179
1180         child->layoutIfNeeded();
1181
1182         // We need pending layouts to be done in order to compute auto-margins properly.
1183         updateAutoMarginsInColumnAxisIfNeeded(*child, overrideContainingBlockContentLogicalHeight);
1184
1185         child->setLogicalLocation(findChildLogicalPosition(*child));
1186
1187         // If the child moved, we have to repaint it as well as any floating/positioned
1188         // descendants. An exception is if we need a layout. In this case, we know we're going to
1189         // repaint ourselves (and the child) anyway.
1190         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
1191             child->repaintDuringLayoutIfMoved(oldChildRect);
1192     }
1193
1194     for (auto& row : sizingData.rowTracks)
1195         setLogicalHeight(logicalHeight() + row.baseSize());
1196
1197     // min / max logical height is handled in updateLogicalHeight().
1198     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
1199     if (hasLineIfEmpty()) {
1200         LayoutUnit minHeight = borderAndPaddingLogicalHeight()
1201             + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes)
1202             + scrollbarLogicalHeight();
1203         if (height() < minHeight)
1204             setLogicalHeight(minHeight);
1205     }
1206
1207     clearGrid();
1208 }
1209
1210 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
1211 {
1212     ASSERT(m_gridItemCoordinate.contains(&gridItem));
1213     return m_gridItemCoordinate.get(&gridItem);
1214 }
1215
1216 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1217 {
1218     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1219     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1220     LayoutUnit gridAreaBreadth = 0;
1221     for (auto& trackPosition : span)
1222         gridAreaBreadth += tracks[trackPosition.toInt()].baseSize();
1223     return gridAreaBreadth;
1224 }
1225
1226 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
1227 {
1228     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
1229     m_columnPositions[0] = borderAndPaddingStart();
1230     for (unsigned i = 0; i < m_columnPositions.size() - 1; ++i)
1231         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].baseSize();
1232
1233     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
1234     m_rowPositions[0] = borderAndPaddingBefore();
1235     for (unsigned i = 0; i < m_rowPositions.size() - 1; ++i)
1236         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].baseSize();
1237 }
1238
1239 static inline LayoutUnit computeOverflowAlignmentOffset(OverflowAlignment overflow, LayoutUnit trackBreadth, LayoutUnit childBreadth)
1240 {
1241     LayoutUnit offset = trackBreadth - childBreadth;
1242     switch (overflow) {
1243     case OverflowAlignmentSafe:
1244         // If overflow is 'safe', we have to make sure we don't overflow the 'start'
1245         // edge (potentially cause some data loss as the overflow is unreachable).
1246         return std::max<LayoutUnit>(0, offset);
1247     case OverflowAlignmentTrue:
1248     case OverflowAlignmentDefault:
1249         // If we overflow our alignment container and overflow is 'true' (default), we
1250         // ignore the overflow and just return the value regardless (which may cause data
1251         // loss as we overflow the 'start' edge).
1252         return offset;
1253     }
1254
1255     ASSERT_NOT_REACHED();
1256     return 0;
1257 }
1258
1259 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1260 bool RenderGrid::needToStretchChildLogicalHeight(const RenderBox& child) const
1261 {
1262     if (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch) != ItemPositionStretch)
1263         return false;
1264
1265     return isHorizontalWritingMode() && child.style().height().isAuto();
1266 }
1267
1268 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1269 LayoutUnit RenderGrid::marginLogicalHeightForChild(const RenderBox& child) const
1270 {
1271     return isHorizontalWritingMode() ? child.verticalMarginExtent() : child.horizontalMarginExtent();
1272 }
1273
1274 LayoutUnit RenderGrid::availableAlignmentSpaceForChildBeforeStretching(LayoutUnit gridAreaBreadthForChild, const RenderBox& child) const
1275 {
1276     return gridAreaBreadthForChild - marginLogicalHeightForChild(child);
1277 }
1278
1279 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1280 void RenderGrid::applyStretchAlignmentToChildIfNeeded(RenderBox& child)
1281 {
1282     ASSERT(child.overrideContainingBlockContentLogicalWidth() && child.overrideContainingBlockContentLogicalHeight());
1283
1284     // We clear both width and height override values because we will decide now whether they
1285     // are allowed or not, evaluating the conditions which might have changed since the old
1286     // values were set.
1287     child.clearOverrideSize();
1288
1289     auto& gridStyle = style();
1290     auto& childStyle = child.style();
1291     bool isHorizontalMode = isHorizontalWritingMode();
1292     bool hasAutoSizeInRowAxis = isHorizontalMode ? childStyle.width().isAuto() : childStyle.height().isAuto();
1293     bool allowedToStretchChildAlongRowAxis = hasAutoSizeInRowAxis && !childStyle.marginStartUsing(&gridStyle).isAuto() && !childStyle.marginEndUsing(&gridStyle).isAuto();
1294     if (!allowedToStretchChildAlongRowAxis || RenderStyle::resolveJustification(gridStyle, childStyle, ItemPositionStretch) != ItemPositionStretch) {
1295         bool hasAutoMinSizeInRowAxis = isHorizontalMode ? childStyle.minWidth().isAuto() : childStyle.minHeight().isAuto();
1296         bool canShrinkToFitInRowAxisForChild = !hasAutoMinSizeInRowAxis || child.minPreferredLogicalWidth() <= child.overrideContainingBlockContentLogicalWidth().value();
1297         // TODO(lajava): how to handle orthogonality in this case ?.
1298         // TODO(lajava): grid track sizing and positioning do not support orthogonal modes yet.
1299         if (hasAutoSizeInRowAxis && canShrinkToFitInRowAxisForChild) {
1300             LayoutUnit childWidthToFitContent = std::max(std::min(child.maxPreferredLogicalWidth(), child.overrideContainingBlockContentLogicalWidth().value() - child.marginLogicalWidth()), child.minPreferredLogicalWidth());
1301             LayoutUnit desiredLogicalWidth = child.constrainLogicalHeightByMinMax(childWidthToFitContent, Nullopt);
1302             child.setOverrideLogicalContentWidth(desiredLogicalWidth - child.borderAndPaddingLogicalWidth());
1303             if (desiredLogicalWidth != child.logicalWidth())
1304                 child.setNeedsLayout();
1305         }
1306     }
1307
1308     bool hasAutoSizeInColumnAxis = isHorizontalMode ? childStyle.height().isAuto() : childStyle.width().isAuto();
1309     bool allowedToStretchChildAlongColumnAxis = hasAutoSizeInColumnAxis && !childStyle.marginBeforeUsing(&gridStyle).isAuto() && !childStyle.marginAfterUsing(&gridStyle).isAuto();
1310     if (allowedToStretchChildAlongColumnAxis && RenderStyle::resolveAlignment(gridStyle, childStyle, ItemPositionStretch) == ItemPositionStretch) {
1311         // TODO (lajava): If the child has orthogonal flow, then it already has an override height set, so use it.
1312         // TODO (lajava): grid track sizing and positioning do not support orthogonal modes yet.
1313         if (child.isHorizontalWritingMode() == isHorizontalMode) {
1314             LayoutUnit stretchedLogicalHeight = availableAlignmentSpaceForChildBeforeStretching(child.overrideContainingBlockContentLogicalHeight().value(), child);
1315             LayoutUnit desiredLogicalHeight = child.constrainLogicalHeightByMinMax(stretchedLogicalHeight, Nullopt);
1316             child.setOverrideLogicalContentHeight(desiredLogicalHeight - child.borderAndPaddingLogicalHeight());
1317             if (desiredLogicalHeight != child.logicalHeight()) {
1318                 // TODO (lajava): Can avoid laying out here in some cases. See https://webkit.org/b/87905.
1319                 child.setLogicalHeight(0);
1320                 child.setNeedsLayout();
1321             }
1322         }
1323     }
1324 }
1325
1326 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1327 bool RenderGrid::hasAutoMarginsInColumnAxis(const RenderBox& child) const
1328 {
1329     if (isHorizontalWritingMode())
1330         return child.style().marginTop().isAuto() || child.style().marginBottom().isAuto();
1331     return child.style().marginLeft().isAuto() || child.style().marginRight().isAuto();
1332 }
1333
1334 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1335 bool RenderGrid::hasAutoMarginsInRowAxis(const RenderBox& child) const
1336 {
1337     if (isHorizontalWritingMode())
1338         return child.style().marginLeft().isAuto() || child.style().marginRight().isAuto();
1339     return child.style().marginTop().isAuto() || child.style().marginBottom().isAuto();
1340 }
1341
1342 // FIXME: This logic is shared by RenderFlexibleBox, so it should be moved to RenderBox.
1343 void RenderGrid::updateAutoMarginsInColumnAxisIfNeeded(RenderBox& child, LayoutUnit gridAreaBreadthForChild)
1344 {
1345     ASSERT(!child.isOutOfFlowPositioned());
1346
1347     LayoutUnit availableAlignmentSpace = gridAreaBreadthForChild - child.logicalHeight();
1348     if (availableAlignmentSpace <= 0)
1349         return;
1350
1351     bool isHorizontal = isHorizontalWritingMode();
1352     Length topOrLeft = isHorizontal ? child.style().marginTop() : child.style().marginLeft();
1353     Length bottomOrRight = isHorizontal ? child.style().marginBottom() : child.style().marginRight();
1354     if (topOrLeft.isAuto() && bottomOrRight.isAuto()) {
1355         if (isHorizontal) {
1356             child.setMarginTop(availableAlignmentSpace / 2);
1357             child.setMarginBottom(availableAlignmentSpace / 2);
1358         } else {
1359             child.setMarginLeft(availableAlignmentSpace / 2);
1360             child.setMarginRight(availableAlignmentSpace / 2);
1361         }
1362     } else if (topOrLeft.isAuto()) {
1363         if (isHorizontal)
1364             child.setMarginTop(availableAlignmentSpace);
1365         else
1366             child.setMarginLeft(availableAlignmentSpace);
1367     } else if (bottomOrRight.isAuto()) {
1368         if (isHorizontal)
1369             child.setMarginBottom(availableAlignmentSpace);
1370         else
1371             child.setMarginRight(availableAlignmentSpace);
1372     }
1373 }
1374
1375 GridAxisPosition RenderGrid::columnAxisPositionForChild(const RenderBox& child) const
1376 {
1377     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1378     bool hasSameWritingMode = child.style().writingMode() == style().writingMode();
1379
1380     switch (RenderStyle::resolveAlignment(style(), child.style(), ItemPositionStretch)) {
1381     case ItemPositionSelfStart:
1382         // If orthogonal writing-modes, this computes to 'start'.
1383         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1384         // 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.
1385         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisStart : GridAxisEnd;
1386     case ItemPositionSelfEnd:
1387         // If orthogonal writing-modes, this computes to 'end'.
1388         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1389         // 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.
1390         return (hasOrthogonalWritingMode || hasSameWritingMode) ? GridAxisEnd : GridAxisStart;
1391     case ItemPositionLeft:
1392         // The alignment axis (column axis) and the inline axis are parallell in
1393         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1394         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1395         return GridAxisStart;
1396     case ItemPositionRight:
1397         // The alignment axis (column axis) and the inline axis are parallell in
1398         // orthogonal writing mode. Otherwise this this is equivalent to 'start'.
1399         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1400         return hasOrthogonalWritingMode ? GridAxisEnd : GridAxisStart;
1401     case ItemPositionCenter:
1402         return GridAxisCenter;
1403     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1404     case ItemPositionStart:
1405         return GridAxisStart;
1406     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1407     case ItemPositionEnd:
1408         return GridAxisEnd;
1409     case ItemPositionStretch:
1410         return GridAxisStart;
1411     case ItemPositionBaseline:
1412     case ItemPositionLastBaseline:
1413         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1414         return GridAxisStart;
1415     case ItemPositionAuto:
1416         break;
1417     }
1418
1419     ASSERT_NOT_REACHED();
1420     return GridAxisStart;
1421 }
1422
1423 GridAxisPosition RenderGrid::rowAxisPositionForChild(const RenderBox& child) const
1424 {
1425     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
1426     bool hasSameDirection = child.style().direction() == style().direction();
1427     bool isLTR = style().isLeftToRightDirection();
1428
1429     switch (RenderStyle::resolveJustification(style(), child.style(), ItemPositionStretch)) {
1430     case ItemPositionSelfStart:
1431         // For orthogonal writing-modes, this computes to 'start'
1432         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1433         // self-start is based on the child's direction. That's why we need to check against the grid container's direction.
1434         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisStart : GridAxisEnd;
1435     case ItemPositionSelfEnd:
1436         // For orthogonal writing-modes, this computes to 'start'
1437         // FIXME: grid track sizing and positioning do not support orthogonal modes yet.
1438         return (hasOrthogonalWritingMode || hasSameDirection) ? GridAxisEnd : GridAxisStart;
1439     case ItemPositionLeft:
1440         return isLTR ? GridAxisStart : GridAxisEnd;
1441     case ItemPositionRight:
1442         return isLTR ? GridAxisEnd : GridAxisStart;
1443     case ItemPositionCenter:
1444         return GridAxisCenter;
1445     case ItemPositionFlexStart: // Only used in flex layout, otherwise equivalent to 'start'.
1446     case ItemPositionStart:
1447         return GridAxisStart;
1448     case ItemPositionFlexEnd: // Only used in flex layout, otherwise equivalent to 'end'.
1449     case ItemPositionEnd:
1450         return GridAxisEnd;
1451     case ItemPositionStretch:
1452         return GridAxisStart;
1453     case ItemPositionBaseline:
1454     case ItemPositionLastBaseline:
1455         // FIXME: Implement the previous values. For now, we always 'start' align the child.
1456         return GridAxisStart;
1457     case ItemPositionAuto:
1458         break;
1459     }
1460
1461     ASSERT_NOT_REACHED();
1462     return GridAxisStart;
1463 }
1464
1465 LayoutUnit RenderGrid::rowPositionForChild(const RenderBox& child) const
1466 {
1467     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1468     LayoutUnit startOfRow = m_rowPositions[coordinate.rows.resolvedInitialPosition.toInt()];
1469     LayoutUnit startPosition = startOfRow + marginBeforeForChild(child);
1470     if (hasAutoMarginsInColumnAxis(child))
1471         return startPosition;
1472     GridAxisPosition axisPosition = columnAxisPositionForChild(child);
1473     switch (axisPosition) {
1474     case GridAxisStart:
1475         return startPosition;
1476     case GridAxisEnd:
1477     case GridAxisCenter: {
1478         LayoutUnit endOfRow = m_rowPositions[coordinate.rows.resolvedFinalPosition.next().toInt()];
1479         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveAlignmentOverflow(style(), child.style()), endOfRow - startOfRow, child.logicalHeight() + child.marginLogicalHeight());
1480         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1481     }
1482     }
1483
1484     ASSERT_NOT_REACHED();
1485     return 0;
1486 }
1487
1488
1489 LayoutUnit RenderGrid::columnPositionForChild(const RenderBox& child) const
1490 {
1491     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1492     LayoutUnit startOfColumn = m_columnPositions[coordinate.columns.resolvedInitialPosition.toInt()];
1493     LayoutUnit startPosition = startOfColumn + marginStartForChild(child);
1494     if (hasAutoMarginsInRowAxis(child))
1495         return startPosition;
1496     GridAxisPosition axisPosition = rowAxisPositionForChild(child);
1497     switch (axisPosition) {
1498     case GridAxisStart:
1499         return startPosition;
1500     case GridAxisEnd:
1501     case GridAxisCenter: {
1502         LayoutUnit endOfColumn = m_columnPositions[coordinate.columns.resolvedFinalPosition.next().toInt()];
1503         LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(RenderStyle::resolveJustificationOverflow(style(), child.style()), endOfColumn - startOfColumn, child.logicalWidth() + child.marginLogicalWidth());
1504         return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2);
1505     }
1506     }
1507
1508     ASSERT_NOT_REACHED();
1509     return 0;
1510 }
1511
1512 LayoutPoint RenderGrid::findChildLogicalPosition(const RenderBox& child) const
1513 {
1514     LayoutUnit columnPosition = columnPositionForChild(child);
1515     // We stored m_columnPositions's data ignoring the direction, hence we might need now
1516     // to translate positions from RTL to LTR, as it's more convenient for painting.
1517     if (!style().isLeftToRightDirection())
1518         columnPosition = (m_columnPositions[m_columnPositions.size() - 1] + borderAndPaddingLogicalLeft()) - columnPosition  - child.logicalWidth();
1519
1520     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
1521     return LayoutPoint(columnPosition, rowPositionForChild(child));
1522 }
1523
1524 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1525 {
1526     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1527         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect, PaintAsInlineBlock);
1528 }
1529
1530 const char* RenderGrid::renderName() const
1531 {
1532     if (isFloating())
1533         return "RenderGrid (floating)";
1534     if (isOutOfFlowPositioned())
1535         return "RenderGrid (positioned)";
1536     if (isAnonymous())
1537         return "RenderGrid (generated)";
1538     if (isRelPositioned())
1539         return "RenderGrid (relative positioned)";
1540     return "RenderGrid";
1541 }
1542
1543 } // namespace WebCore
1544
1545 #endif /* ENABLE(CSS_GRID_LAYOUT) */