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