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