[CSS Grid Layout] Update track sizes after distributing extra space
[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     const LayoutUnit& growthLimitIfNotInfinite() const
77     {
78         ASSERT(isGrowthLimitBiggerThanBaseSize());
79         return (m_growthLimit == infinity) ? m_baseSize : m_growthLimit;
80     }
81
82     const LayoutUnit& plannedSize() const { return m_plannedSize; }
83
84     void setPlannedSize(LayoutUnit plannedSize)
85     {
86         m_plannedSize = plannedSize;
87     }
88
89     LayoutUnit& tempSize() { return m_tempSize; }
90
91 private:
92     bool isGrowthLimitBiggerThanBaseSize() const { return growthLimitIsInfinite() || m_growthLimit >= m_baseSize; }
93
94     void ensureGrowthLimitIsBiggerThanBaseSize()
95     {
96         if (m_growthLimit != infinity && m_growthLimit < m_baseSize)
97             m_growthLimit = m_baseSize;
98     }
99
100     LayoutUnit m_baseSize { 0 };
101     LayoutUnit m_growthLimit { 0 };
102     LayoutUnit m_plannedSize { 0 };
103     LayoutUnit m_tempSize { 0 };
104 };
105
106 struct GridTrackForNormalization {
107     GridTrackForNormalization(const GridTrack& track, double flex)
108         : m_track(&track)
109         , m_flex(flex)
110         , m_normalizedFlexValue(track.baseSize() / flex)
111     {
112     }
113
114     const GridTrack* m_track;
115     double m_flex;
116     LayoutUnit m_normalizedFlexValue;
117 };
118
119 class RenderGrid::GridIterator {
120     WTF_MAKE_NONCOPYABLE(GridIterator);
121 public:
122     // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
123     // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
124     GridIterator(const Vector<Vector<Vector<RenderBox*, 1>>>& grid, GridTrackSizingDirection direction, unsigned fixedTrackIndex, unsigned varyingTrackIndex = 0)
125         : m_grid(grid)
126         , m_direction(direction)
127         , m_rowIndex((direction == ForColumns) ? varyingTrackIndex : fixedTrackIndex)
128         , m_columnIndex((direction == ForColumns) ? fixedTrackIndex : varyingTrackIndex)
129         , m_childIndex(0)
130     {
131         ASSERT(m_rowIndex < m_grid.size());
132         ASSERT(m_columnIndex < m_grid[0].size());
133     }
134
135     RenderBox* nextGridItem()
136     {
137         if (!m_grid.size())
138             return 0;
139
140         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
141         const unsigned endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
142         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
143             const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
144             if (m_childIndex < children.size())
145                 return children[m_childIndex++];
146
147             m_childIndex = 0;
148         }
149         return 0;
150     }
151
152     bool isEmptyAreaEnough(unsigned rowSpan, unsigned columnSpan) const
153     {
154         // Ignore cells outside current grid as we will grow it later if needed.
155         unsigned maxRows = std::min<unsigned>(m_rowIndex + rowSpan, m_grid.size());
156         unsigned maxColumns = std::min<unsigned>(m_columnIndex + columnSpan, m_grid[0].size());
157
158         // This adds a O(N^2) behavior that shouldn't be a big deal as we expect spanning areas to be small.
159         for (unsigned row = m_rowIndex; row < maxRows; ++row) {
160             for (unsigned column = m_columnIndex; column < maxColumns; ++column) {
161                 const Vector<RenderBox*>& children = m_grid[row][column];
162                 if (!children.isEmpty())
163                     return false;
164             }
165         }
166
167         return true;
168     }
169
170     std::unique_ptr<GridCoordinate> nextEmptyGridArea(unsigned fixedTrackSpan, unsigned varyingTrackSpan)
171     {
172         ASSERT(fixedTrackSpan >= 1 && varyingTrackSpan >= 1);
173
174         if (m_grid.isEmpty())
175             return nullptr;
176
177         unsigned rowSpan = (m_direction == ForColumns) ? varyingTrackSpan : fixedTrackSpan;
178         unsigned columnSpan = (m_direction == ForColumns) ? fixedTrackSpan : varyingTrackSpan;
179
180         unsigned& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
181         const unsigned endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
182         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
183             if (isEmptyAreaEnough(rowSpan, columnSpan)) {
184                 std::unique_ptr<GridCoordinate> result = std::make_unique<GridCoordinate>(GridSpan(m_rowIndex, m_rowIndex + rowSpan - 1), GridSpan(m_columnIndex, m_columnIndex + columnSpan - 1));
185                 // Advance the iterator to avoid an infinite loop where we would return the same grid area over and over.
186                 ++varyingTrackIndex;
187                 return result;
188             }
189         }
190         return nullptr;
191     }
192
193 private:
194     const Vector<Vector<Vector<RenderBox*, 1>>>& m_grid;
195     GridTrackSizingDirection m_direction;
196     unsigned m_rowIndex;
197     unsigned m_columnIndex;
198     unsigned m_childIndex;
199 };
200
201 class RenderGrid::GridSizingData {
202     WTF_MAKE_NONCOPYABLE(GridSizingData);
203 public:
204     GridSizingData(unsigned gridColumnCount, unsigned gridRowCount)
205         : columnTracks(gridColumnCount)
206         , rowTracks(gridRowCount)
207     {
208     }
209
210     Vector<GridTrack> columnTracks;
211     Vector<GridTrack> rowTracks;
212     Vector<unsigned> contentSizedTracksIndex;
213
214     // Performance optimization: hold onto these Vectors until the end of Layout to avoid repeated malloc / free.
215     Vector<GridTrack*> filteredTracks;
216     Vector<GridTrack*> growBeyondGrowthLimitsTracks;
217     Vector<GridItemWithSpan> itemsSortedByIncreasingSpan;
218 };
219
220 RenderGrid::RenderGrid(Element& element, Ref<RenderStyle>&& style)
221     : RenderBlock(element, WTF::move(style), 0)
222     , m_orderIterator(*this)
223 {
224     // All of our children must be block level.
225     setChildrenInline(false);
226 }
227
228 RenderGrid::~RenderGrid()
229 {
230 }
231
232 void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
233 {
234     ASSERT(needsLayout());
235
236     if (!relayoutChildren && simplifiedLayout())
237         return;
238
239     // FIXME: Much of this method is boiler plate that matches RenderBox::layoutBlock and Render*FlexibleBox::layoutBlock.
240     // It would be nice to refactor some of the duplicate code.
241     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
242     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
243
244     preparePaginationBeforeBlockLayout(relayoutChildren);
245
246     LayoutSize previousSize = size();
247
248     setLogicalHeight(0);
249     updateLogicalWidth();
250
251     layoutGridItems();
252
253     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
254     updateLogicalHeight();
255
256     if (size() != previousSize)
257         relayoutChildren = true;
258
259     layoutPositionedObjects(relayoutChildren || isRoot());
260
261     computeOverflow(oldClientAfterEdge);
262     statePusher.pop();
263
264     updateLayerTransform();
265
266     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
267     // we overflow or not.
268     updateScrollInfoAfterLayout();
269
270     repainter.repaintAfterLayout();
271
272     clearNeedsLayout();
273 }
274
275 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
276 {
277     bool wasPopulated = gridWasPopulated();
278     if (!wasPopulated)
279         const_cast<RenderGrid*>(this)->placeItemsOnGrid();
280
281     GridSizingData sizingData(gridColumnCount(), gridRowCount());
282     LayoutUnit availableLogicalSpace = 0;
283     const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
284
285     for (auto& column : sizingData.columnTracks) {
286         LayoutUnit minTrackBreadth = column.baseSize();
287         LayoutUnit maxTrackBreadth = column.growthLimit();
288
289         minLogicalWidth += minTrackBreadth;
290         maxLogicalWidth += maxTrackBreadth;
291
292         // FIXME: This should add in the scrollbarWidth (e.g. see RenderFlexibleBox).
293     }
294
295     if (!wasPopulated)
296         const_cast<RenderGrid*>(this)->clearGrid();
297 }
298
299 void RenderGrid::computePreferredLogicalWidths()
300 {
301     ASSERT(preferredLogicalWidthsDirty());
302
303     m_minPreferredLogicalWidth = 0;
304     m_maxPreferredLogicalWidth = 0;
305
306     // FIXME: We don't take our own logical width into account. Once we do, we need to make sure
307     // we apply (and test the interaction with) min-width / max-width.
308
309     computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
310
311     LayoutUnit borderAndPaddingInInlineDirection = borderAndPaddingLogicalWidth();
312     m_minPreferredLogicalWidth += borderAndPaddingInInlineDirection;
313     m_maxPreferredLogicalWidth += borderAndPaddingInInlineDirection;
314
315     setPreferredLogicalWidthsDirty(false);
316 }
317
318 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
319 {
320     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
321     computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
322 }
323
324 bool RenderGrid::gridElementIsShrinkToFit()
325 {
326     return isFloatingOrOutOfFlowPositioned();
327 }
328
329 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
330 {
331     const LayoutUnit initialAvailableLogicalSpace = availableLogicalSpace;
332     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
333     Vector<unsigned> flexibleSizedTracksIndex;
334     sizingData.contentSizedTracksIndex.shrink(0);
335
336     // 1. Initialize per Grid track variables.
337     for (unsigned i = 0; i < tracks.size(); ++i) {
338         GridTrack& track = tracks[i];
339         const GridTrackSize& trackSize = gridTrackSize(direction, i);
340         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
341         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
342
343         track.setBaseSize(computeUsedBreadthOfMinLength(direction, minTrackBreadth));
344         track.setGrowthLimit(computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.baseSize()));
345
346         if (trackSize.isContentSized())
347             sizingData.contentSizedTracksIndex.append(i);
348         if (trackSize.maxTrackBreadth().isFlex())
349             flexibleSizedTracksIndex.append(i);
350     }
351
352     // 2. Resolve content-based TrackSizingFunctions.
353     if (!sizingData.contentSizedTracksIndex.isEmpty())
354         resolveContentBasedTrackSizingFunctions(direction, sizingData);
355
356     for (auto& track : tracks) {
357         ASSERT(!track.growthLimitIsInfinite());
358         availableLogicalSpace -= track.baseSize();
359     }
360
361     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
362
363     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
364         return;
365
366     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until availableLogicalSpace is exhausted.
367     if (!hasUndefinedRemainingSpace) {
368         const unsigned tracksSize = tracks.size();
369         Vector<GridTrack*> tracksForDistribution(tracksSize);
370         for (unsigned i = 0; i < tracksSize; ++i) {
371             tracksForDistribution[i] = tracks.data() + i;
372             tracksForDistribution[i]->setPlannedSize(tracksForDistribution[i]->baseSize());
373         }
374
375         distributeSpaceToTracks(tracksForDistribution, nullptr, &GridTrack::baseSize, availableLogicalSpace);
376
377         for (auto* track : tracksForDistribution)
378             track->setBaseSize(track->plannedSize());
379     } else {
380         for (auto& track : tracks)
381             track.setBaseSize(track.growthLimit());
382     }
383
384     if (flexibleSizedTracksIndex.isEmpty())
385         return;
386
387     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
388     double normalizedFractionBreadth = 0;
389     if (!hasUndefinedRemainingSpace)
390         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, initialAvailableLogicalSpace);
391     else {
392         for (auto trackIndex : flexibleSizedTracksIndex) {
393             const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
394             normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].baseSize() / trackSize.maxTrackBreadth().flex());
395         }
396
397         for (unsigned i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
398             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
399             while (RenderBox* gridItem = iterator.nextGridItem()) {
400                 const GridCoordinate coordinate = cachedGridCoordinate(*gridItem);
401                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
402
403                 // Do not include already processed items.
404                 if (i > 0 && span.resolvedInitialPosition.toInt() <= flexibleSizedTracksIndex[i - 1])
405                     continue;
406
407                 double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(*gridItem, direction, sizingData.columnTracks));
408                 normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
409             }
410         }
411     }
412
413     for (auto trackIndex : flexibleSizedTracksIndex) {
414         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
415         GridTrack& track = tracks[trackIndex];
416         LayoutUnit baseSize = std::max<LayoutUnit>(track.baseSize(), normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
417         track.setBaseSize(baseSize);
418         availableLogicalSpace -= baseSize;
419     }
420 }
421
422 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
423 {
424     if (gridLength.isFlex())
425         return 0;
426
427     const Length& trackLength = gridLength.length();
428     ASSERT(!trackLength.isAuto());
429     if (trackLength.isSpecified())
430         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
431
432     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
433     return 0;
434 }
435
436 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
437 {
438     if (gridLength.isFlex())
439         return usedBreadth;
440
441     const Length& trackLength = gridLength.length();
442     ASSERT(!trackLength.isAuto());
443     if (trackLength.isSpecified()) {
444         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
445         ASSERT(computedBreadth != infinity);
446         return computedBreadth;
447     }
448
449     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
450     return infinity;
451 }
452
453 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
454 {
455     ASSERT(trackLength.isSpecified());
456     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : std::max(LayoutUnit(), computeContentLogicalHeight(style().logicalHeight())));
457 }
458
459 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit spaceToFill) const
460 {
461     LayoutUnit allocatedSpace;
462     Vector<GridTrackForNormalization> tracksForNormalization;
463     for (auto& position : tracksSpan) {
464         GridTrack& track = tracks[position.toInt()];
465         allocatedSpace += track.baseSize();
466
467         const GridTrackSize& trackSize = gridTrackSize(direction, position.toInt());
468         if (!trackSize.maxTrackBreadth().isFlex())
469             continue;
470
471         tracksForNormalization.append(GridTrackForNormalization(track, trackSize.maxTrackBreadth().flex()));
472     }
473
474     // The function is not called if we don't have <flex> grid tracks
475     ASSERT(!tracksForNormalization.isEmpty());
476
477     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
478               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
479                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
480               });
481
482     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
483     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
484     // fit into availableLogicalSpaceIgnoringFractionTracks.
485     double accumulatedFractions = 0;
486     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
487     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = spaceToFill - allocatedSpace;
488
489     for (auto& track : tracksForNormalization) {
490         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
491             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
492             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
493             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
494                 break;
495
496             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
497         }
498
499         accumulatedFractions += track.m_flex;
500         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
501         availableLogicalSpaceIgnoringFractionTracks += track.m_track->baseSize();
502     }
503
504     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
505 }
506
507 GridTrackSize RenderGrid::gridTrackSize(GridTrackSizingDirection direction, unsigned i) const
508 {
509     bool isForColumns = (direction == ForColumns);
510     auto& trackStyles =  isForColumns ? style().gridColumns() : style().gridRows();
511     auto& trackSize = (i >= trackStyles.size()) ? (isForColumns ? style().gridAutoColumns() : style().gridAutoRows()) : trackStyles[i];
512
513     // If the logical width/height of the grid container is indefinite, percentage values are treated as <auto> (or in
514     // the case of minmax() as min-content for the first position and max-content for the second).
515     Length logicalSize = isForColumns ? style().logicalWidth() : style().logicalHeight();
516     if (logicalSize.isIntrinsicOrAuto()) {
517         const GridLength& oldMinTrackBreadth = trackSize.minTrackBreadth();
518         const GridLength& oldMaxTrackBreadth = trackSize.maxTrackBreadth();
519         return GridTrackSize(oldMinTrackBreadth.isPercentage() ? Length(MinContent) : oldMinTrackBreadth, oldMaxTrackBreadth.isPercentage() ? Length(MaxContent) : oldMaxTrackBreadth);
520     }
521
522     return trackSize;
523 }
524
525 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox& child, Vector<GridTrack>& columnTracks)
526 {
527     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
528     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
529     if (child.style().logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
530         child.setNeedsLayout(MarkOnlyThis);
531
532     child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
533     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
534     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
535     child.setOverrideContainingBlockContentLogicalHeight(-1);
536     child.layoutIfNeeded();
537     return child.logicalHeight() + child.marginLogicalHeight();
538 }
539
540 LayoutUnit RenderGrid::minContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
541 {
542     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
543     // FIXME: Properly support orthogonal writing mode.
544     if (hasOrthogonalWritingMode)
545         return 0;
546
547     if (direction == ForColumns) {
548         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
549         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
550         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
551     }
552
553     return logicalContentHeightForChild(child, columnTracks);
554 }
555
556 LayoutUnit RenderGrid::maxContentForChild(RenderBox& child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
557 {
558     bool hasOrthogonalWritingMode = child.isHorizontalWritingMode() != isHorizontalWritingMode();
559     // FIXME: Properly support orthogonal writing mode.
560     if (hasOrthogonalWritingMode)
561         return LayoutUnit();
562
563     if (direction == ForColumns) {
564         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
565         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
566         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
567     }
568
569     return logicalContentHeightForChild(child, columnTracks);
570 }
571
572 class GridItemWithSpan {
573 public:
574     GridItemWithSpan(RenderBox& gridItem, GridCoordinate coordinate, GridTrackSizingDirection direction)
575         : m_gridItem(gridItem)
576         , m_coordinate(coordinate)
577     {
578         const GridSpan& span = (direction == ForRows) ? coordinate.rows : coordinate.columns;
579         m_span = span.resolvedFinalPosition.toInt() - span.resolvedInitialPosition.toInt() + 1;
580     }
581
582     RenderBox& gridItem() const { return m_gridItem; }
583     GridCoordinate coordinate() const { return m_coordinate; }
584 #if !ASSERT_DISABLED
585     size_t span() const { return m_span; }
586 #endif
587
588     bool operator<(const GridItemWithSpan other) const
589     {
590         return m_span < other.m_span;
591     }
592
593 private:
594     std::reference_wrapper<RenderBox> m_gridItem;
595     GridCoordinate m_coordinate;
596     unsigned m_span;
597 };
598
599 bool RenderGrid::spanningItemCrossesFlexibleSizedTracks(const GridCoordinate& coordinate, GridTrackSizingDirection direction) const
600 {
601     const GridSpan itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
602     for (auto trackPosition : itemSpan) {
603         const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
604         if (trackSize.minTrackBreadth().isFlex() || trackSize.maxTrackBreadth().isFlex())
605             return true;
606     }
607
608     return false;
609 }
610
611 static inline unsigned integerSpanForDirection(const GridCoordinate& coordinate, GridTrackSizingDirection direction)
612 {
613     return (direction == ForRows) ? coordinate.rows.integerSpan() : coordinate.columns.integerSpan();
614 }
615
616 struct GridItemsSpanGroupRange {
617     Vector<GridItemWithSpan>::iterator rangeStart;
618     Vector<GridItemWithSpan>::iterator rangeEnd;
619 };
620
621 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
622 {
623     sizingData.itemsSortedByIncreasingSpan.shrink(0);
624     HashSet<RenderBox*> itemsSet;
625     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
626         GridIterator iterator(m_grid, direction, trackIndex);
627         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
628
629         while (RenderBox* gridItem = iterator.nextGridItem()) {
630             if (itemsSet.add(gridItem).isNewEntry) {
631                 const GridCoordinate& coordinate = cachedGridCoordinate(*gridItem);
632                 if (integerSpanForDirection(coordinate, direction) == 1)
633                     resolveContentBasedTrackSizingFunctionsForNonSpanningItems(direction, coordinate, *gridItem, track, sizingData.columnTracks);
634                 else if (!spanningItemCrossesFlexibleSizedTracks(coordinate, direction))
635                     sizingData.itemsSortedByIncreasingSpan.append(GridItemWithSpan(*gridItem, coordinate, direction));
636             }
637         }
638     }
639     std::sort(sizingData.itemsSortedByIncreasingSpan.begin(), sizingData.itemsSortedByIncreasingSpan.end());
640
641     auto it = sizingData.itemsSortedByIncreasingSpan.begin();
642     auto end = sizingData.itemsSortedByIncreasingSpan.end();
643     while (it != end) {
644         GridItemsSpanGroupRange spanGroupRange = { it, std::upper_bound(it, end, *it) };
645         resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, spanGroupRange, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::baseSize, &GridTrack::baseSize, &GridTrack::setBaseSize, &GridTrackSize::hasMinContentMinTrackBreadthAndMinOrMaxContentMaxTrackBreadth);
646         resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, spanGroupRange, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::baseSize, &GridTrack::baseSize, &GridTrack::setBaseSize, &GridTrackSize::hasMaxContentMinTrackBreadthAndMaxContentMaxTrackBreadth);
647         resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, spanGroupRange, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::growthLimit, &GridTrack::growthLimitIfNotInfinite, &GridTrack::setGrowthLimit);
648         resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, spanGroupRange, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::growthLimit, &GridTrack::growthLimitIfNotInfinite, &GridTrack::setGrowthLimit);
649         it = spanGroupRange.rangeEnd;
650     }
651
652     for (auto trackIndex : sizingData.contentSizedTracksIndex) {
653         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
654         if (track.growthLimitIsInfinite())
655             track.setGrowthLimit(track.baseSize());
656     }
657 }
658
659 void RenderGrid::resolveContentBasedTrackSizingFunctionsForNonSpanningItems(GridTrackSizingDirection direction, const GridCoordinate& coordinate, RenderBox& gridItem, GridTrack& track, Vector<GridTrack>& columnTracks)
660 {
661     const GridResolvedPosition trackPosition = (direction == ForColumns) ? coordinate.columns.resolvedInitialPosition : coordinate.rows.resolvedInitialPosition;
662     GridTrackSize trackSize = gridTrackSize(direction, trackPosition.toInt());
663
664     if (trackSize.hasMinContentMinTrackBreadth())
665         track.setBaseSize(std::max(track.baseSize(), minContentForChild(gridItem, direction, columnTracks)));
666     else if (trackSize.hasMaxContentMinTrackBreadth())
667         track.setBaseSize(std::max(track.baseSize(), maxContentForChild(gridItem, direction, columnTracks)));
668
669     if (trackSize.hasMinContentMaxTrackBreadth())
670         track.setGrowthLimit(std::max(track.growthLimit(), minContentForChild(gridItem, direction, columnTracks)));
671     else if (trackSize.hasMaxContentMaxTrackBreadth())
672         track.setGrowthLimit(std::max(track.growthLimit(), maxContentForChild(gridItem, direction, columnTracks)));
673 }
674
675 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, const GridItemsSpanGroupRange& gridItemsWithSpan, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackSize, AccumulatorGetter correctedTrackSize, AccumulatorGrowFunction trackGrowthFunction, FilterFunction growAboveMaxBreadthFilterFunction)
676 {
677     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
678     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
679         GridTrack& track = tracks[trackIndex];
680         track.setPlannedSize((track.*trackSize)());
681     }
682
683     for (auto it = gridItemsWithSpan.rangeStart; it != gridItemsWithSpan.rangeEnd; ++it) {
684         GridItemWithSpan& gridItemWithSpan = *it;
685         ASSERT(gridItemWithSpan.span() > 1);
686         const GridCoordinate& coordinate = gridItemWithSpan.coordinate();
687         const GridSpan& itemSpan = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
688
689         sizingData.filteredTracks.shrink(0);
690         sizingData.growBeyondGrowthLimitsTracks.shrink(0);
691         LayoutUnit spanningTracksSize;
692         for (auto& trackPosition : itemSpan) {
693             const GridTrackSize& trackSize = gridTrackSize(direction, trackPosition.toInt());
694             GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackPosition.toInt()] : sizingData.rowTracks[trackPosition.toInt()];
695             spanningTracksSize += (track.*correctedTrackSize)();
696             if (!(trackSize.*filterFunction)())
697                 continue;
698
699             sizingData.filteredTracks.append(&track);
700
701             if (!growAboveMaxBreadthFilterFunction || (trackSize.*growAboveMaxBreadthFilterFunction)())
702                 sizingData.growBeyondGrowthLimitsTracks.append(&track);
703         }
704
705         if (sizingData.filteredTracks.isEmpty())
706             continue;
707
708         // Specs mandate to floor extraSpace to 0. Instead we directly avoid the function call in those cases as it will be
709         // a noop in terms of track sizing.
710         LayoutUnit extraSpace = (this->*sizingFunction)(gridItemWithSpan.gridItem(), direction, sizingData.columnTracks) - spanningTracksSize;
711         if (extraSpace > 0) {
712             auto* tracksToGrowBeyondGrowthLimits = sizingData.growBeyondGrowthLimitsTracks.isEmpty() ? &sizingData.filteredTracks : &sizingData.growBeyondGrowthLimitsTracks;
713             distributeSpaceToTracks(sizingData.filteredTracks, tracksToGrowBeyondGrowthLimits, correctedTrackSize, extraSpace);
714         }
715     }
716
717     for (const auto& trackIndex : sizingData.contentSizedTracksIndex) {
718         GridTrack& track = tracks[trackIndex];
719         (track.*trackGrowthFunction)(track.plannedSize());
720     }
721 }
722
723 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
724 {
725     // This check ensures that we respect the irreflexivity property of the strict weak ordering required by std::sort
726     // (forall x: NOT x < x).
727     if (track1->growthLimitIsInfinite() && track2->growthLimitIsInfinite())
728         return false;
729
730     if (track1->growthLimitIsInfinite() || track2->growthLimitIsInfinite())
731         return track2->growthLimitIsInfinite();
732
733     return (track1->growthLimit() - track1->baseSize()) < (track2->growthLimit() - track2->baseSize());
734 }
735
736 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, const Vector<GridTrack*>* growBeyondGrowthLimitsTracks, AccumulatorGetter trackGetter, LayoutUnit& availableLogicalSpace)
737 {
738     ASSERT(availableLogicalSpace > 0);
739     std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
740
741     unsigned tracksSize = tracks.size();
742
743     for (unsigned i = 0; i < tracksSize; ++i) {
744         GridTrack& track = *tracks[i];
745         const LayoutUnit& trackBreadth = (track.*trackGetter)();
746         bool infiniteGrowthPotential = track.growthLimitIsInfinite();
747         LayoutUnit trackGrowthPotential = infiniteGrowthPotential ? track.growthLimit() : track.growthLimit() - trackBreadth;
748         track.tempSize() = trackBreadth;
749         // Let's avoid computing availableLogicalSpaceShare as much as possible as it's a hot spot in performance tests.
750         if (trackGrowthPotential > 0 || infiniteGrowthPotential) {
751             LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
752             LayoutUnit growthShare = infiniteGrowthPotential ? availableLogicalSpaceShare : std::min(availableLogicalSpaceShare, trackGrowthPotential);
753             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.");
754             track.tempSize() += growthShare;
755             availableLogicalSpace -= growthShare;
756         }
757     }
758
759     if (availableLogicalSpace > 0 && growBeyondGrowthLimitsTracks) {
760         unsigned tracksGrowingBeyondGrowthLimitsSize = growBeyondGrowthLimitsTracks->size();
761         for (unsigned i = 0; i < tracksGrowingBeyondGrowthLimitsSize; ++i) {
762             GridTrack* track = growBeyondGrowthLimitsTracks->at(i);
763             LayoutUnit growthShare = availableLogicalSpace / (tracksGrowingBeyondGrowthLimitsSize - i);
764             track->tempSize() += growthShare;
765             availableLogicalSpace -= growthShare;
766         }
767     }
768
769     for (auto* track : tracks)
770         track->setPlannedSize(std::max(track->plannedSize(), track->tempSize()));
771 }
772
773 #ifndef NDEBUG
774 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
775 {
776     for (unsigned i = 0; i < tracks.size(); ++i) {
777         const GridTrackSize& trackSize = gridTrackSize(direction, i);
778         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
779         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].baseSize())
780             return false;
781     }
782     return true;
783 }
784 #endif
785
786 void RenderGrid::ensureGridSize(unsigned maximumRowIndex, unsigned maximumColumnIndex)
787 {
788     const unsigned oldRowCount = gridRowCount();
789     if (maximumRowIndex >= oldRowCount) {
790         m_grid.grow(maximumRowIndex + 1);
791         for (unsigned row = oldRowCount; row < gridRowCount(); ++row)
792             m_grid[row].grow(gridColumnCount());
793     }
794
795     if (maximumColumnIndex >= gridColumnCount()) {
796         for (unsigned row = 0; row < gridRowCount(); ++row)
797             m_grid[row].grow(maximumColumnIndex + 1);
798     }
799 }
800
801 void RenderGrid::insertItemIntoGrid(RenderBox& child, const GridCoordinate& coordinate)
802 {
803     ensureGridSize(coordinate.rows.resolvedFinalPosition.toInt(), coordinate.columns.resolvedFinalPosition.toInt());
804
805     for (auto& row : coordinate.rows) {
806         for (auto& column : coordinate.columns)
807             m_grid[row.toInt()][column.toInt()].append(&child);
808     }
809     m_gridItemCoordinate.set(&child, coordinate);
810 }
811
812 void RenderGrid::placeItemsOnGrid()
813 {
814     ASSERT(!gridWasPopulated());
815     ASSERT(m_gridItemCoordinate.isEmpty());
816
817     populateExplicitGridAndOrderIterator();
818
819     Vector<RenderBox*> autoMajorAxisAutoGridItems;
820     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
821     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
822         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
823         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
824         if (!rowPositions || !columnPositions) {
825             GridSpan* majorAxisPositions = (autoPlacementMajorAxisDirection() == ForColumns) ? columnPositions.get() : rowPositions.get();
826             if (!majorAxisPositions)
827                 autoMajorAxisAutoGridItems.append(child);
828             else
829                 specifiedMajorAxisAutoGridItems.append(child);
830             continue;
831         }
832         insertItemIntoGrid(*child, GridCoordinate(*rowPositions, *columnPositions));
833     }
834
835     ASSERT(gridRowCount() >= GridResolvedPosition::explicitGridRowCount(style()));
836     ASSERT(gridColumnCount() >= GridResolvedPosition::explicitGridColumnCount(style()));
837
838     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
839     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
840 }
841
842 void RenderGrid::populateExplicitGridAndOrderIterator()
843 {
844     OrderIteratorPopulator populator(m_orderIterator);
845     unsigned maximumRowIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridRowCount(style()));
846     unsigned maximumColumnIndex = std::max<unsigned>(1, GridResolvedPosition::explicitGridColumnCount(style()));
847
848     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
849         populator.collectChild(*child);
850
851         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
852         std::unique_ptr<GridSpan> rowPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForRows);
853         std::unique_ptr<GridSpan> columnPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *child, ForColumns);
854
855         // |positions| is 0 if we need to run the auto-placement algorithm.
856         if (rowPositions)
857             maximumRowIndex = std::max(maximumRowIndex, rowPositions->resolvedFinalPosition.next().toInt());
858         else {
859             // Grow the grid for items with a definite row span, getting the largest such span.
860             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForRows, GridResolvedPosition(0));
861             maximumRowIndex = std::max(maximumRowIndex, positions.resolvedFinalPosition.next().toInt());
862         }
863
864         if (columnPositions)
865             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->resolvedFinalPosition.next().toInt());
866         else {
867             // Grow the grid for items with a definite column span, getting the largest such span.
868             GridSpan positions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *child, ForColumns, GridResolvedPosition(0));
869             maximumColumnIndex = std::max(maximumColumnIndex, positions.resolvedFinalPosition.next().toInt());
870         }
871     }
872
873     m_grid.grow(maximumRowIndex);
874     for (auto& column : m_grid)
875         column.grow(maximumColumnIndex);
876 }
877
878 std::unique_ptr<GridCoordinate> RenderGrid::createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(const RenderBox& gridItem, GridTrackSizingDirection specifiedDirection, const GridSpan& specifiedPositions) const
879 {
880     GridTrackSizingDirection crossDirection = specifiedDirection == ForColumns ? ForRows : ForColumns;
881     const unsigned endOfCrossDirection = crossDirection == ForColumns ? gridColumnCount() : gridRowCount();
882     GridSpan crossDirectionPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, crossDirection, GridResolvedPosition(endOfCrossDirection));
883     return std::make_unique<GridCoordinate>(specifiedDirection == ForColumns ? crossDirectionPositions : specifiedPositions, specifiedDirection == ForColumns ? specifiedPositions : crossDirectionPositions);
884 }
885
886 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
887 {
888     bool isForColumns = autoPlacementMajorAxisDirection() == ForColumns;
889     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
890
891     // Mapping between the major axis tracks (rows or columns) and the last auto-placed item's position inserted on
892     // that track. This is needed to implement "sparse" packing for items locked to a given track.
893     // See http://dev.w3.org/csswg/css-grid/#auto-placement-algo
894     HashMap<unsigned, unsigned, DefaultHash<unsigned>::Hash, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> minorAxisCursors;
895
896     for (auto& autoGridItem : autoGridItems) {
897         std::unique_ptr<GridSpan> majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), *autoGridItem, autoPlacementMajorAxisDirection());
898         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), *autoGridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
899         unsigned majorAxisInitialPosition = majorAxisPositions->resolvedInitialPosition.toInt();
900
901         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->resolvedInitialPosition.toInt(), isGridAutoFlowDense ? 0 : minorAxisCursors.get(majorAxisInitialPosition));
902         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions->integerSpan(), minorAxisPositions.integerSpan());
903         if (!emptyGridArea)
904             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(*autoGridItem, autoPlacementMajorAxisDirection(), *majorAxisPositions);
905         insertItemIntoGrid(*autoGridItem, *emptyGridArea);
906
907         if (!isGridAutoFlowDense)
908             minorAxisCursors.set(majorAxisInitialPosition, isForColumns ? emptyGridArea->rows.resolvedInitialPosition.toInt() : emptyGridArea->columns.resolvedInitialPosition.toInt());
909     }
910 }
911
912 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
913 {
914     AutoPlacementCursor autoPlacementCursor = {0, 0};
915     bool isGridAutoFlowDense = style().isGridAutoFlowAlgorithmDense();
916
917     for (auto& autoGridItem : autoGridItems) {
918         placeAutoMajorAxisItemOnGrid(*autoGridItem, autoPlacementCursor);
919
920         if (isGridAutoFlowDense) {
921             autoPlacementCursor.first = 0;
922             autoPlacementCursor.second = 0;
923         }
924     }
925 }
926
927 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox& gridItem, AutoPlacementCursor& autoPlacementCursor)
928 {
929     std::unique_ptr<GridSpan> minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMinorAxisDirection());
930     ASSERT(!GridResolvedPosition::resolveGridPositionsFromStyle(style(), gridItem, autoPlacementMajorAxisDirection()));
931     GridSpan majorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMajorAxisDirection(), GridResolvedPosition(0));
932
933     const unsigned endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
934     unsigned majorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.second : autoPlacementCursor.first;
935     unsigned minorAxisAutoPlacementCursor = autoPlacementMajorAxisDirection() == ForColumns ? autoPlacementCursor.first : autoPlacementCursor.second;
936
937     std::unique_ptr<GridCoordinate> emptyGridArea;
938     if (minorAxisPositions) {
939         // Move to the next track in major axis if initial position in minor axis is before auto-placement cursor.
940         if (minorAxisPositions->resolvedInitialPosition.toInt() < minorAxisAutoPlacementCursor)
941             majorAxisAutoPlacementCursor++;
942
943         if (majorAxisAutoPlacementCursor < endOfMajorAxis) {
944             GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisPositions->resolvedInitialPosition.toInt(), majorAxisAutoPlacementCursor);
945             emptyGridArea = iterator.nextEmptyGridArea(minorAxisPositions->integerSpan(), majorAxisPositions.integerSpan());
946         }
947
948         if (!emptyGridArea)
949             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), *minorAxisPositions);
950     } else {
951         GridSpan minorAxisPositions = GridResolvedPosition::resolveGridPositionsFromAutoPlacementPosition(style(), gridItem, autoPlacementMinorAxisDirection(), GridResolvedPosition(0));
952
953         for (unsigned majorAxisIndex = majorAxisAutoPlacementCursor; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
954             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex, minorAxisAutoPlacementCursor);
955             emptyGridArea = iterator.nextEmptyGridArea(majorAxisPositions.integerSpan(), minorAxisPositions.integerSpan());
956
957             if (emptyGridArea) {
958                 // Check that it fits in the minor axis direction, as we shouldn't grow in that direction here (it was already managed in populateExplicitGridAndOrderIterator()).
959                 GridResolvedPosition minorAxisFinalPositionIndex = autoPlacementMinorAxisDirection() == ForColumns ? emptyGridArea->columns.resolvedFinalPosition : emptyGridArea->rows.resolvedFinalPosition;
960                 const unsigned endOfMinorAxis = autoPlacementMinorAxisDirection() == ForColumns ? gridColumnCount() : gridRowCount();
961                 if (minorAxisFinalPositionIndex.toInt() < endOfMinorAxis)
962                     break;
963
964                 // Discard empty grid area as it does not fit in the minor axis direction.
965                 // We don't need to create a new empty grid area yet as we might find a valid one in the next iteration.
966                 emptyGridArea = nullptr;
967             }
968
969             // As we're moving to the next track in the major axis we should reset the auto-placement cursor in the minor axis.
970             minorAxisAutoPlacementCursor = 0;
971         }
972
973         if (!emptyGridArea)
974             emptyGridArea = createEmptyGridAreaAtSpecifiedPositionsOutsideGrid(gridItem, autoPlacementMinorAxisDirection(), minorAxisPositions);
975     }
976
977     insertItemIntoGrid(gridItem, *emptyGridArea);
978     autoPlacementCursor.first = emptyGridArea->rows.resolvedInitialPosition.toInt();
979     autoPlacementCursor.second = emptyGridArea->columns.resolvedInitialPosition.toInt();
980 }
981
982 GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
983 {
984     return style().isGridAutoFlowDirectionColumn() ? ForColumns : ForRows;
985 }
986
987 GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
988 {
989     return style().isGridAutoFlowDirectionColumn() ? ForRows : ForColumns;
990 }
991
992 void RenderGrid::clearGrid()
993 {
994     m_grid.clear();
995     m_gridItemCoordinate.clear();
996 }
997
998 void RenderGrid::layoutGridItems()
999 {
1000     placeItemsOnGrid();
1001
1002     GridSizingData sizingData(gridColumnCount(), gridRowCount());
1003     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
1004     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
1005     computeUsedBreadthOfGridTracks(ForRows, sizingData);
1006     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
1007
1008     populateGridPositions(sizingData);
1009
1010     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1011         // Because the grid area cannot be styled, we don't need to adjust
1012         // the grid breadth to account for 'box-sizing'.
1013         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
1014         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
1015
1016         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(*child, ForColumns, sizingData.columnTracks);
1017         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(*child, ForRows, sizingData.rowTracks);
1018         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && child->hasRelativeLogicalHeight()))
1019             child->setNeedsLayout(MarkOnlyThis);
1020
1021         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
1022         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
1023
1024         LayoutRect oldChildRect = child->frameRect();
1025
1026         // FIXME: Grid items should stretch to fill their cells. Once we
1027         // implement grid-{column,row}-align, we can also shrink to fit. For
1028         // now, just size as if we were a regular child.
1029         child->layoutIfNeeded();
1030
1031         child->setLogicalLocation(findChildLogicalPosition(*child, sizingData));
1032
1033         // If the child moved, we have to repaint it as well as any floating/positioned
1034         // descendants. An exception is if we need a layout. In this case, we know we're going to
1035         // repaint ourselves (and the child) anyway.
1036         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
1037             child->repaintDuringLayoutIfMoved(oldChildRect);
1038     }
1039
1040     for (auto& row : sizingData.rowTracks)
1041         setLogicalHeight(logicalHeight() + row.baseSize());
1042
1043     // min / max logical height is handled in updateLogicalHeight().
1044     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
1045     if (hasLineIfEmpty()) {
1046         LayoutUnit minHeight = borderAndPaddingLogicalHeight()
1047             + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes)
1048             + scrollbarLogicalHeight();
1049         if (height() < minHeight)
1050             setLogicalHeight(minHeight);
1051     }
1052
1053     clearGrid();
1054 }
1055
1056 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox& gridItem) const
1057 {
1058     ASSERT(m_gridItemCoordinate.contains(&gridItem));
1059     return m_gridItemCoordinate.get(&gridItem);
1060 }
1061
1062 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox& child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1063 {
1064     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1065     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1066     LayoutUnit gridAreaBreadth = 0;
1067     for (auto& trackPosition : span)
1068         gridAreaBreadth += tracks[trackPosition.toInt()].baseSize();
1069     return gridAreaBreadth;
1070 }
1071
1072 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
1073 {
1074     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
1075     m_columnPositions[0] = borderAndPaddingStart();
1076     for (unsigned i = 0; i < m_columnPositions.size() - 1; ++i)
1077         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].baseSize();
1078
1079     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
1080     m_rowPositions[0] = borderAndPaddingBefore();
1081     for (unsigned i = 0; i < m_rowPositions.size() - 1; ++i)
1082         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].baseSize();
1083 }
1084
1085 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox& child, const GridSizingData& sizingData)
1086 {
1087     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1088     ASSERT_UNUSED(sizingData, coordinate.columns.resolvedInitialPosition.toInt() < sizingData.columnTracks.size());
1089     ASSERT_UNUSED(sizingData, coordinate.rows.resolvedInitialPosition.toInt() < sizingData.rowTracks.size());
1090
1091     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
1092     return LayoutPoint(m_columnPositions[coordinate.columns.resolvedInitialPosition.toInt()] + marginStartForChild(child), m_rowPositions[coordinate.rows.resolvedInitialPosition.toInt()] + marginBeforeForChild(child));
1093 }
1094
1095 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1096 {
1097     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1098         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect, PaintAsInlineBlock);
1099 }
1100
1101 const char* RenderGrid::renderName() const
1102 {
1103     if (isFloating())
1104         return "RenderGrid (floating)";
1105     if (isOutOfFlowPositioned())
1106         return "RenderGrid (positioned)";
1107     if (isAnonymous())
1108         return "RenderGrid (generated)";
1109     if (isRelPositioned())
1110         return "RenderGrid (relative positioned)";
1111     return "RenderGrid";
1112 }
1113
1114 } // namespace WebCore
1115
1116 #endif /* ENABLE(CSS_GRID_LAYOUT) */