vw/vh units used as font/line-height values don't scale with the viewport
[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 "LayoutRepainter.h"
34 #include "RenderLayer.h"
35 #include "RenderView.h"
36 #include <wtf/NeverDestroyed.h>
37
38 namespace WebCore {
39
40 static const int infinity = -1;
41
42 class GridTrack {
43 public:
44     GridTrack()
45         : m_usedBreadth(0)
46         , m_maxBreadth(0)
47     {
48     }
49
50     void growUsedBreadth(LayoutUnit growth)
51     {
52         ASSERT(growth >= 0);
53         m_usedBreadth += growth;
54     }
55     LayoutUnit usedBreadth() const { return m_usedBreadth; }
56
57     void growMaxBreadth(LayoutUnit growth)
58     {
59         if (m_maxBreadth == infinity)
60             m_maxBreadth = m_usedBreadth + growth;
61         else
62             m_maxBreadth += growth;
63     }
64     LayoutUnit maxBreadthIfNotInfinite() const
65     {
66         return (m_maxBreadth == infinity) ? m_usedBreadth : m_maxBreadth;
67     }
68
69     LayoutUnit m_usedBreadth;
70     LayoutUnit m_maxBreadth;
71 };
72
73 struct GridTrackForNormalization {
74     GridTrackForNormalization(const GridTrack& track, double flex)
75         : m_track(&track)
76         , m_flex(flex)
77         , m_normalizedFlexValue(track.m_usedBreadth / flex)
78     {
79     }
80
81     const GridTrack* m_track;
82     double m_flex;
83     LayoutUnit m_normalizedFlexValue;
84 };
85
86 class RenderGrid::GridIterator {
87     WTF_MAKE_NONCOPYABLE(GridIterator);
88 public:
89     // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
90     // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
91     GridIterator(const Vector<Vector<Vector<RenderBox*, 1>>>& grid, GridTrackSizingDirection direction, size_t fixedTrackIndex)
92         : m_grid(grid)
93         , m_direction(direction)
94         , m_rowIndex((direction == ForColumns) ? 0 : fixedTrackIndex)
95         , m_columnIndex((direction == ForColumns) ? fixedTrackIndex : 0)
96         , m_childIndex(0)
97     {
98         ASSERT(m_rowIndex < m_grid.size());
99         ASSERT(m_columnIndex < m_grid[0].size());
100     }
101
102     RenderBox* nextGridItem()
103     {
104         if (!m_grid.size())
105             return 0;
106
107         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
108         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
109         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
110             const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
111             if (m_childIndex < children.size())
112                 return children[m_childIndex++];
113
114             m_childIndex = 0;
115         }
116         return 0;
117     }
118
119     std::unique_ptr<GridCoordinate> nextEmptyGridArea()
120     {
121         if (m_grid.isEmpty())
122             return nullptr;
123
124         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
125         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
126         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
127             const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
128             if (children.isEmpty()) {
129                 std::unique_ptr<GridCoordinate> result = std::make_unique<GridCoordinate>(GridSpan(m_rowIndex, m_rowIndex), GridSpan(m_columnIndex, m_columnIndex));
130                 // Advance the iterator to avoid an infinite loop where we would return the same grid area over and over.
131                 ++varyingTrackIndex;
132                 return result;
133             }
134         }
135         return nullptr;
136     }
137
138 private:
139     const Vector<Vector<Vector<RenderBox*, 1>>>& m_grid;
140     GridTrackSizingDirection m_direction;
141     size_t m_rowIndex;
142     size_t m_columnIndex;
143     size_t m_childIndex;
144 };
145
146 class RenderGrid::GridSizingData {
147     WTF_MAKE_NONCOPYABLE(GridSizingData);
148 public:
149     GridSizingData(size_t gridColumnCount, size_t gridRowCount)
150         : columnTracks(gridColumnCount)
151         , rowTracks(gridRowCount)
152     {
153     }
154
155     Vector<GridTrack> columnTracks;
156     Vector<GridTrack> rowTracks;
157     Vector<size_t> contentSizedTracksIndex;
158
159     // Performance optimization: hold onto these Vectors until the end of Layout to avoid repeated malloc / free.
160     Vector<LayoutUnit> distributeTrackVector;
161     Vector<GridTrack*> filteredTracks;
162 };
163
164 RenderGrid::RenderGrid(Element& element, PassRef<RenderStyle> style)
165     : RenderBlock(element, std::move(style), 0)
166     , m_orderIterator(*this)
167 {
168     // All of our children must be block level.
169     setChildrenInline(false);
170 }
171
172 RenderGrid::~RenderGrid()
173 {
174 }
175
176 void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
177 {
178     ASSERT(needsLayout());
179
180     if (!relayoutChildren && simplifiedLayout())
181         return;
182
183     // FIXME: Much of this method is boiler plate that matches RenderBox::layoutBlock and Render*FlexibleBox::layoutBlock.
184     // It would be nice to refactor some of the duplicate code.
185     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
186     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
187
188     preparePaginationBeforeBlockLayout(relayoutChildren);
189
190     LayoutSize previousSize = size();
191
192     setLogicalHeight(0);
193     updateLogicalWidth();
194
195     layoutGridItems();
196
197     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
198     updateLogicalHeight();
199
200     if (size() != previousSize)
201         relayoutChildren = true;
202
203     layoutPositionedObjects(relayoutChildren || isRoot());
204
205     computeOverflow(oldClientAfterEdge);
206     statePusher.pop();
207
208     updateLayerTransform();
209
210     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
211     // we overflow or not.
212     updateScrollInfoAfterLayout();
213
214     repainter.repaintAfterLayout();
215
216     clearNeedsLayout();
217 }
218
219 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
220 {
221     const_cast<RenderGrid*>(this)->placeItemsOnGrid();
222
223     GridSizingData sizingData(gridColumnCount(), gridRowCount());
224     LayoutUnit availableLogicalSpace = 0;
225     const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
226
227     for (size_t i = 0; i < sizingData.columnTracks.size(); ++i) {
228         LayoutUnit minTrackBreadth = sizingData.columnTracks[i].m_usedBreadth;
229         LayoutUnit maxTrackBreadth = sizingData.columnTracks[i].m_maxBreadth;
230         maxTrackBreadth = std::max(maxTrackBreadth, minTrackBreadth);
231
232         minLogicalWidth += minTrackBreadth;
233         maxLogicalWidth += maxTrackBreadth;
234
235         // FIXME: This should add in the scrollbarWidth (e.g. see RenderFlexibleBox).
236     }
237
238     const_cast<RenderGrid*>(this)->clearGrid();
239 }
240
241 void RenderGrid::computePreferredLogicalWidths()
242 {
243     ASSERT(preferredLogicalWidthsDirty());
244
245     m_minPreferredLogicalWidth = 0;
246     m_maxPreferredLogicalWidth = 0;
247
248     // FIXME: We don't take our own logical width into account. Once we do, we need to make sure
249     // we apply (and test the interaction with) min-width / max-width.
250
251     computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
252
253     LayoutUnit borderAndPaddingInInlineDirection = borderAndPaddingLogicalWidth();
254     m_minPreferredLogicalWidth += borderAndPaddingInInlineDirection;
255     m_maxPreferredLogicalWidth += borderAndPaddingInInlineDirection;
256
257     setPreferredLogicalWidthsDirty(false);
258 }
259
260 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
261 {
262     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
263     computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
264 }
265
266 bool RenderGrid::gridElementIsShrinkToFit()
267 {
268     return isFloatingOrOutOfFlowPositioned();
269 }
270
271 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
272 {
273     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
274     Vector<size_t> flexibleSizedTracksIndex;
275     sizingData.contentSizedTracksIndex.shrink(0);
276
277     // 1. Initialize per Grid track variables.
278     for (size_t i = 0; i < tracks.size(); ++i) {
279         GridTrack& track = tracks[i];
280         const GridTrackSize& trackSize = gridTrackSize(direction, i);
281         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
282         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
283
284         track.m_usedBreadth = computeUsedBreadthOfMinLength(direction, minTrackBreadth);
285         track.m_maxBreadth = computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.m_usedBreadth);
286
287         track.m_maxBreadth = std::max(track.m_maxBreadth, track.m_usedBreadth);
288
289         if (trackSize.isContentSized())
290             sizingData.contentSizedTracksIndex.append(i);
291         if (trackSize.maxTrackBreadth().isFlex())
292             flexibleSizedTracksIndex.append(i);
293     }
294
295     // 2. Resolve content-based TrackSizingFunctions.
296     if (!sizingData.contentSizedTracksIndex.isEmpty())
297         resolveContentBasedTrackSizingFunctions(direction, sizingData);
298
299     for (size_t i = 0; i < tracks.size(); ++i) {
300         ASSERT(tracks[i].m_maxBreadth != infinity);
301         availableLogicalSpace -= tracks[i].m_usedBreadth;
302     }
303
304     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
305
306     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
307         return;
308
309     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until
310     // availableLogicalSpace (RemainingSpace in the specs) is exhausted.
311     const size_t tracksSize = tracks.size();
312     if (!hasUndefinedRemainingSpace) {
313         Vector<GridTrack*> tracksForDistribution(tracksSize);
314         for (size_t i = 0; i < tracksSize; ++i)
315             tracksForDistribution[i] = tracks.data() + i;
316
317         distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
318     } else {
319         for (size_t i = 0; i < tracksSize; ++i)
320             tracks[i].m_usedBreadth = tracks[i].m_maxBreadth;
321     }
322
323     if (flexibleSizedTracksIndex.isEmpty())
324         return;
325
326     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
327     double normalizedFractionBreadth = 0;
328     if (!hasUndefinedRemainingSpace)
329         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, availableLogicalSpace);
330     else {
331         for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
332             const size_t trackIndex = flexibleSizedTracksIndex[i];
333             const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
334             normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].m_usedBreadth / trackSize.maxTrackBreadth().flex());
335         }
336
337         for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
338             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
339             while (RenderBox* gridItem = iterator.nextGridItem()) {
340                 const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
341                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
342
343                 // Do not include already processed items.
344                 if (i > 0 && span.initialPositionIndex <= flexibleSizedTracksIndex[i - 1])
345                     continue;
346
347                 double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(gridItem, direction, sizingData.columnTracks));
348                 normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
349             }
350         }
351     }
352
353     for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
354         const size_t trackIndex = flexibleSizedTracksIndex[i];
355         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
356
357         tracks[trackIndex].m_usedBreadth = std::max<LayoutUnit>(tracks[trackIndex].m_usedBreadth, normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
358     }
359 }
360
361 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
362 {
363     if (gridLength.isFlex())
364         return 0;
365
366     const Length& trackLength = gridLength.length();
367     ASSERT(!trackLength.isAuto());
368     if (trackLength.isSpecified())
369         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
370
371     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
372     return 0;
373 }
374
375 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
376 {
377     if (gridLength.isFlex())
378         return usedBreadth;
379
380     const Length& trackLength = gridLength.length();
381     ASSERT(!trackLength.isAuto());
382     if (trackLength.isSpecified()) {
383         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
384         ASSERT(computedBreadth != infinity);
385         return computedBreadth;
386     }
387
388     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
389     return infinity;
390 }
391
392 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
393 {
394     ASSERT(trackLength.isSpecified());
395     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style().logicalHeight()));
396 }
397
398 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
399 {
400     // |availableLogicalSpace| already accounts for the used breadths so no need to remove it here.
401
402     Vector<GridTrackForNormalization> tracksForNormalization;
403     for (size_t i = tracksSpan.initialPositionIndex; i <= tracksSpan.finalPositionIndex; ++i) {
404         const GridTrackSize& trackSize = gridTrackSize(direction, i);
405         if (!trackSize.maxTrackBreadth().isFlex())
406             continue;
407
408         tracksForNormalization.append(GridTrackForNormalization(tracks[i], trackSize.maxTrackBreadth().flex()));
409     }
410
411     // The function is not called if we don't have <flex> grid tracks
412     ASSERT(!tracksForNormalization.isEmpty());
413
414     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
415               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
416                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
417               });
418
419     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
420     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
421     // fit into availableLogicalSpaceIgnoringFractionTracks.
422     double accumulatedFractions = 0;
423     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
424     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = availableLogicalSpace;
425
426     for (size_t i = 0; i < tracksForNormalization.size(); ++i) {
427         const GridTrackForNormalization& track = tracksForNormalization[i];
428         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
429             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
430             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
431             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
432                 break;
433
434             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
435         }
436
437         accumulatedFractions += track.m_flex;
438         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
439         availableLogicalSpaceIgnoringFractionTracks += track.m_track->m_usedBreadth;
440     }
441
442     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
443 }
444
445 const GridTrackSize& RenderGrid::gridTrackSize(GridTrackSizingDirection direction, size_t i) const
446 {
447     const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style().gridColumns() : style().gridRows();
448     if (i >= trackStyles.size())
449         return (direction == ForColumns) ? style().gridAutoColumns() : style().gridAutoRows();
450
451     const GridTrackSize& trackSize = trackStyles[i];
452     // If the logical width/height of the grid container is indefinite, percentage values are treated as <auto>.
453     if (trackSize.isPercentage()) {
454         Length logicalSize = direction == ForColumns ? style().logicalWidth() : style().logicalHeight();
455         if (logicalSize.isIntrinsicOrAuto()) {
456             static NeverDestroyed<GridTrackSize> autoTrackSize(Auto);
457             return autoTrackSize.get();
458         }
459     }
460
461     return trackSize;
462 }
463
464 size_t RenderGrid::explicitGridColumnCount() const
465 {
466     return style().gridColumns().size();
467 }
468
469 size_t RenderGrid::explicitGridRowCount() const
470 {
471     return style().gridRows().size();
472 }
473
474 static inline bool isColumnSide(GridPositionSide side)
475 {
476     return side == ColumnStartSide || side == ColumnEndSide;
477 }
478
479 size_t RenderGrid::explicitGridSizeForSide(GridPositionSide side) const
480 {
481     return isColumnSide(side) ? explicitGridColumnCount() : explicitGridRowCount();
482 }
483
484 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox* child, Vector<GridTrack>& columnTracks)
485 {
486     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
487     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
488     if (child->style().logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
489         child->setNeedsLayout(MarkOnlyThis);
490
491     child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
492     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
493     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
494     child->setOverrideContainingBlockContentLogicalHeight(-1);
495     child->layoutIfNeeded();
496     return child->logicalHeight() + child->marginLogicalHeight();
497 }
498
499 LayoutUnit RenderGrid::minContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
500 {
501     bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
502     // FIXME: Properly support orthogonal writing mode.
503     if (hasOrthogonalWritingMode)
504         return 0;
505
506     if (direction == ForColumns) {
507         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
508         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
509         return child->minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(*child);
510     }
511
512     return logicalContentHeightForChild(child, columnTracks);
513 }
514
515 LayoutUnit RenderGrid::maxContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
516 {
517     bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
518     // FIXME: Properly support orthogonal writing mode.
519     if (hasOrthogonalWritingMode)
520         return LayoutUnit();
521
522     if (direction == ForColumns) {
523         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
524         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
525         return child->maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(*child);
526     }
527
528     return logicalContentHeightForChild(child, columnTracks);
529 }
530
531 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
532 {
533     // FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track.
534
535     for (size_t i = 0; i < sizingData.contentSizedTracksIndex.size(); ++i) {
536         GridIterator iterator(m_grid, direction, sizingData.contentSizedTracksIndex[i]);
537         while (RenderBox* gridItem = iterator.nextGridItem()) {
538             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
539             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
540             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
541             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
542         }
543
544         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[i] : sizingData.rowTracks[i];
545         if (track.m_maxBreadth == infinity)
546             track.m_maxBreadth = track.m_usedBreadth;
547     }
548 }
549
550 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, RenderBox* gridItem, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction)
551 {
552     const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
553     const size_t initialTrackIndex = (direction == ForColumns) ? coordinate.columns.initialPositionIndex : coordinate.rows.initialPositionIndex;
554     const size_t finalTrackIndex = (direction == ForColumns) ? coordinate.columns.finalPositionIndex : coordinate.rows.finalPositionIndex;
555
556     sizingData.filteredTracks.shrink(0);
557     for (size_t trackIndex = initialTrackIndex; trackIndex <= finalTrackIndex; ++trackIndex) {
558         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
559         if (!(trackSize.*filterFunction)())
560             continue;
561
562         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
563         sizingData.filteredTracks.append(&track);
564     }
565
566     if (sizingData.filteredTracks.isEmpty())
567         return;
568
569     LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItem, direction, sizingData.columnTracks);
570     for (size_t trackIndexForSpace = initialTrackIndex; trackIndexForSpace <= finalTrackIndex; ++trackIndexForSpace) {
571         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndexForSpace] : sizingData.rowTracks[trackIndexForSpace];
572         additionalBreadthSpace -= (track.*trackGetter)();
573     }
574
575     // FIXME: We should pass different values for |tracksForGrowthAboveMaxBreadth|.
576     distributeSpaceToTracks(sizingData.filteredTracks, &sizingData.filteredTracks, trackGetter, trackGrowthFunction, sizingData, additionalBreadthSpace);
577 }
578
579 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
580 {
581     return (track1->m_maxBreadth - track1->m_usedBreadth) < (track2->m_maxBreadth - track2->m_usedBreadth);
582 }
583
584 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
585 {
586     std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
587
588     size_t tracksSize = tracks.size();
589     sizingData.distributeTrackVector.resize(tracksSize);
590
591     for (size_t i = 0; i < tracksSize; ++i) {
592         GridTrack& track = *tracks[i];
593         LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
594         LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
595         LayoutUnit growthShare = std::max(LayoutUnit(), std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth));
596         // We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function.
597         sizingData.distributeTrackVector[i] = trackBreadth + growthShare;
598         availableLogicalSpace -= growthShare;
599     }
600
601     if (availableLogicalSpace > 0 && tracksForGrowthAboveMaxBreadth) {
602         tracksSize = tracksForGrowthAboveMaxBreadth->size();
603         for (size_t i = 0; i < tracksSize; ++i) {
604             LayoutUnit growthShare = availableLogicalSpace / (tracksSize - i);
605             sizingData.distributeTrackVector[i] += growthShare;
606             availableLogicalSpace -= growthShare;
607         }
608     }
609
610     for (size_t i = 0; i < tracksSize; ++i) {
611         LayoutUnit growth = sizingData.distributeTrackVector[i] - (tracks[i]->*trackGetter)();
612         if (growth >= 0)
613             (tracks[i]->*trackGrowthFunction)(growth);
614     }
615 }
616
617 #ifndef NDEBUG
618 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
619 {
620     for (size_t i = 0; i < tracks.size(); ++i) {
621         const GridTrackSize& trackSize = gridTrackSize(direction, i);
622         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
623         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].m_usedBreadth)
624             return false;
625     }
626     return true;
627 }
628 #endif
629
630 void RenderGrid::growGrid(GridTrackSizingDirection direction)
631 {
632     if (direction == ForColumns) {
633         const size_t oldColumnSize = gridColumnCount();
634         for (size_t row = 0; row < gridRowCount(); ++row)
635             m_grid[row].grow(oldColumnSize + 1);
636     } else {
637         const size_t oldRowSize = gridRowCount();
638         m_grid.grow(oldRowSize + 1);
639         m_grid[oldRowSize].grow(gridColumnCount());
640     }
641 }
642
643 void RenderGrid::insertItemIntoGrid(RenderBox* child, const GridCoordinate& coordinate)
644 {
645     for (size_t row = coordinate.rows.initialPositionIndex; row <= coordinate.rows.finalPositionIndex; ++row) {
646         for (size_t column = coordinate.columns.initialPositionIndex; column <= coordinate.columns.finalPositionIndex; ++column)
647             m_grid[row][column].append(child);
648     }
649     m_gridItemCoordinate.set(child, coordinate);
650 }
651
652 void RenderGrid::insertItemIntoGrid(RenderBox* child, size_t rowTrack, size_t columnTrack)
653 {
654     const GridSpan& rowSpan = resolveGridPositionsFromAutoPlacementPosition(child, ForRows, rowTrack);
655     const GridSpan& columnSpan = resolveGridPositionsFromAutoPlacementPosition(child, ForColumns, columnTrack);
656     insertItemIntoGrid(child, GridCoordinate(rowSpan, columnSpan));
657 }
658
659 void RenderGrid::placeItemsOnGrid()
660 {
661     ASSERT(!gridWasPopulated());
662     ASSERT(m_gridItemCoordinate.isEmpty());
663
664     populateExplicitGridAndOrderIterator();
665
666     Vector<RenderBox*> autoMajorAxisAutoGridItems;
667     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
668     GridAutoFlow autoFlow = style().gridAutoFlow();
669     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
670         // FIXME: We never re-resolve positions if the grid is grown during auto-placement which may lead auto / <integer>
671         // positions to not match the author's intent. The specification is unclear on what should be done in this case.
672         std::unique_ptr<GridSpan> rowPositions = resolveGridPositionsFromStyle(child, ForRows);
673         std::unique_ptr<GridSpan> columnPositions = resolveGridPositionsFromStyle(child, ForColumns);
674         if (!rowPositions || !columnPositions) {
675             GridSpan* majorAxisPositions = (autoPlacementMajorAxisDirection() == ForColumns) ? columnPositions.get() : rowPositions.get();
676             if (!majorAxisPositions)
677                 autoMajorAxisAutoGridItems.append(child);
678             else
679                 specifiedMajorAxisAutoGridItems.append(child);
680             continue;
681         }
682         insertItemIntoGrid(child, GridCoordinate(*rowPositions, *columnPositions));
683     }
684
685     ASSERT(gridRowCount() >= style().gridRows().size());
686     ASSERT(gridColumnCount() >= style().gridColumns().size());
687
688     if (autoFlow == AutoFlowNone) {
689         // If we did collect some grid items, they won't be placed thus never laid out.
690         ASSERT(!autoMajorAxisAutoGridItems.size());
691         ASSERT(!specifiedMajorAxisAutoGridItems.size());
692         return;
693     }
694
695     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
696     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
697 }
698
699 void RenderGrid::populateExplicitGridAndOrderIterator()
700 {
701     OrderIteratorPopulator populator(m_orderIterator);
702     size_t maximumRowIndex = std::max<size_t>(1, explicitGridRowCount());
703     size_t maximumColumnIndex = std::max<size_t>(1, explicitGridColumnCount());
704
705     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
706         populator.collectChild(*child);
707
708         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
709         std::unique_ptr<GridSpan> rowPositions = resolveGridPositionsFromStyle(child, ForRows);
710         std::unique_ptr<GridSpan> columnPositions = resolveGridPositionsFromStyle(child, ForColumns);
711
712         // |positions| is 0 if we need to run the auto-placement algorithm. Our estimation ignores
713         // this case as the auto-placement algorithm will grow the grid as needed.
714         if (rowPositions)
715             maximumRowIndex = std::max(maximumRowIndex, rowPositions->finalPositionIndex + 1);
716         if (columnPositions)
717             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->finalPositionIndex + 1);
718     }
719
720     m_grid.grow(maximumRowIndex);
721     for (size_t i = 0; i < m_grid.size(); ++i)
722         m_grid[i].grow(maximumColumnIndex);
723 }
724
725 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
726 {
727     for (auto& autoGridItem : autoGridItems) {
728         std::unique_ptr<GridSpan> majorAxisPositions = resolveGridPositionsFromStyle(autoGridItem, autoPlacementMajorAxisDirection());
729         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->initialPositionIndex);
730         if (std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
731             insertItemIntoGrid(autoGridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
732             continue;
733         }
734
735         growGrid(autoPlacementMinorAxisDirection());
736         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea();
737         ASSERT(emptyGridArea);
738         insertItemIntoGrid(autoGridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
739     }
740 }
741
742 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
743 {
744     for (auto& autoGridItem : autoGridItems)
745         placeAutoMajorAxisItemOnGrid(autoGridItem);
746 }
747
748 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox* gridItem)
749 {
750     std::unique_ptr<GridSpan> minorAxisPositions = resolveGridPositionsFromStyle(gridItem, autoPlacementMinorAxisDirection());
751     ASSERT(!resolveGridPositionsFromStyle(gridItem, autoPlacementMajorAxisDirection()));
752     size_t minorAxisIndex = 0;
753     if (minorAxisPositions) {
754         minorAxisIndex = minorAxisPositions->initialPositionIndex;
755         GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisIndex);
756         if (std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
757             insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
758             return;
759         }
760     } else {
761         const size_t endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
762         for (size_t majorAxisIndex = 0; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
763             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex);
764             if (std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
765                 insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
766                 return;
767             }
768         }
769     }
770
771     // We didn't find an empty grid area so we need to create an extra major axis line and insert our gridItem in it.
772     const size_t columnIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : minorAxisIndex;
773     const size_t rowIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? minorAxisIndex : gridRowCount();
774     growGrid(autoPlacementMajorAxisDirection());
775     insertItemIntoGrid(gridItem, rowIndex, columnIndex);
776 }
777
778 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
779 {
780     GridAutoFlow flow = style().gridAutoFlow();
781     ASSERT(flow != AutoFlowNone);
782     return (flow == AutoFlowColumn) ? ForColumns : ForRows;
783 }
784
785 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
786 {
787     GridAutoFlow flow = style().gridAutoFlow();
788     ASSERT(flow != AutoFlowNone);
789     return (flow == AutoFlowColumn) ? ForRows : ForColumns;
790 }
791
792 void RenderGrid::clearGrid()
793 {
794     m_grid.clear();
795     m_gridItemCoordinate.clear();
796 }
797
798 void RenderGrid::layoutGridItems()
799 {
800     placeItemsOnGrid();
801
802     GridSizingData sizingData(gridColumnCount(), gridRowCount());
803     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
804     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
805     computeUsedBreadthOfGridTracks(ForRows, sizingData);
806     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
807
808     populateGridPositions(sizingData);
809
810     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
811         // Because the grid area cannot be styled, we don't need to adjust
812         // the grid breadth to account for 'box-sizing'.
813         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
814         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
815
816         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, sizingData.columnTracks);
817         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, sizingData.rowTracks);
818         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && child->hasRelativeLogicalHeight()))
819             child->setNeedsLayout(MarkOnlyThis);
820
821         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
822         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
823
824         LayoutRect oldChildRect = child->frameRect();
825
826         // FIXME: Grid items should stretch to fill their cells. Once we
827         // implement grid-{column,row}-align, we can also shrink to fit. For
828         // now, just size as if we were a regular child.
829         child->layoutIfNeeded();
830
831         child->setLogicalLocation(findChildLogicalPosition(child, sizingData));
832
833         // If the child moved, we have to repaint it as well as any floating/positioned
834         // descendants. An exception is if we need a layout. In this case, we know we're going to
835         // repaint ourselves (and the child) anyway.
836         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
837             child->repaintDuringLayoutIfMoved(oldChildRect);
838     }
839
840     for (size_t i = 0; i < sizingData.rowTracks.size(); ++i)
841         setLogicalHeight(logicalHeight() + sizingData.rowTracks[i].m_usedBreadth);
842
843     // min / max logical height is handled in updateLogicalHeight().
844     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
845     clearGrid();
846 }
847
848 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox* gridItem) const
849 {
850     ASSERT(m_gridItemCoordinate.contains(gridItem));
851     return m_gridItemCoordinate.get(gridItem);
852 }
853
854 GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, GridTrackSizingDirection, size_t initialPosition) const
855 {
856     // FIXME: We don't support spanning with auto positions yet. Once we do, this is wrong. Also we should make
857     // sure the grid can accomodate the new item as we only grow 1 position in a given direction.
858     return GridSpan(initialPosition, initialPosition);
859 }
860
861 static inline bool gridLineDefinedBeforeGridArea(size_t namedGridLineFirstDefinition, const GridCoordinate& gridAreaCoordinates, GridPositionSide side)
862 {
863     switch (side) {
864     case ColumnStartSide:
865         return namedGridLineFirstDefinition < gridAreaCoordinates.columns.initialPositionIndex;
866     case ColumnEndSide:
867         return namedGridLineFirstDefinition < gridAreaCoordinates.columns.finalPositionIndex;
868     case RowStartSide:
869         return namedGridLineFirstDefinition < gridAreaCoordinates.rows.initialPositionIndex;
870     case RowEndSide:
871         return namedGridLineFirstDefinition < gridAreaCoordinates.rows.finalPositionIndex;
872     }
873     ASSERT_NOT_REACHED();
874     return false;
875 }
876
877 static void setNamedLinePositionIfDefinedBeforeArea(GridPosition& position, const NamedGridLinesMap& namedLinesMap, const String& lineName, const GridCoordinate& gridAreaCoordinate, GridPositionSide side)
878 {
879     auto linesIterator = namedLinesMap.find(lineName);
880     if (linesIterator == namedLinesMap.end())
881         return;
882
883     size_t namedGridLineFirstDefinition = GridPosition::adjustGridPositionForSide(linesIterator->value[0], side);
884     if (gridLineDefinedBeforeGridArea(namedGridLineFirstDefinition, gridAreaCoordinate, side))
885         position.setExplicitPosition(1, lineName);
886 }
887
888 void RenderGrid::adjustNamedGridItemPosition(GridPosition& position, GridPositionSide side) const
889 {
890     // The StyleBuilder always treats <custom-ident> as a named grid area. We must decide here if they are going to be
891     // resolved to either a grid area or a grid line.
892     ASSERT(position.isNamedGridArea());
893     const NamedGridAreaMap& gridAreaMap = style().namedGridArea();
894     const NamedGridLinesMap& namedLinesMap = isColumnSide(side) ? style().namedGridColumnLines() : style().namedGridRowLines();
895
896     String namedGridAreaOrGridLine = position.namedGridLine();
897     bool isStartSide = side == ColumnStartSide || side == RowStartSide;
898
899     auto areaIterator = gridAreaMap.find(namedGridAreaOrGridLine);
900     if (areaIterator != gridAreaMap.end()) {
901         String gridLineName = namedGridAreaOrGridLine + (isStartSide ? "-start" : "-end");
902         setNamedLinePositionIfDefinedBeforeArea(position, namedLinesMap, gridLineName, areaIterator->value, side);
903         return;
904     }
905
906     bool hasStartSuffix = namedGridAreaOrGridLine.endsWith("-start");
907     bool hasEndSuffix = namedGridAreaOrGridLine.endsWith("-end");
908     if ((hasStartSuffix && isStartSide) || (hasEndSuffix && !isStartSide)) {
909         size_t suffixLength = hasStartSuffix ? strlen("-start") : strlen("-end");
910         String gridAreaName = namedGridAreaOrGridLine.substring(0, namedGridAreaOrGridLine.length() - suffixLength);
911
912         auto areaIterator = gridAreaMap.find(gridAreaName);
913         if (areaIterator != gridAreaMap.end()) {
914             position.setNamedGridArea(gridAreaName);
915             setNamedLinePositionIfDefinedBeforeArea(position, namedLinesMap, namedGridAreaOrGridLine, areaIterator->value, side);
916             return;
917         }
918     }
919
920     if (namedLinesMap.contains(namedGridAreaOrGridLine))
921         position.setExplicitPosition(1, namedGridAreaOrGridLine);
922     else
923         position.setAutoPosition();
924 }
925
926 void RenderGrid::adjustGridPositionsFromStyle(GridPosition& initialPosition, GridPosition& finalPosition, GridPositionSide initialPositionSide, GridPositionSide finalPositionSide) const
927 {
928     ASSERT(isColumnSide(initialPositionSide) == isColumnSide(finalPositionSide));
929
930     // We must handle the placement error handling code here instead of in the StyleAdjuster because we don't want to
931     // overwrite the specified values.
932     if (initialPosition.isSpan() && finalPosition.isSpan())
933         finalPosition.setAutoPosition();
934
935     if (initialPosition.isNamedGridArea())
936         adjustNamedGridItemPosition(initialPosition, initialPositionSide);
937
938     if (finalPosition.isNamedGridArea())
939         adjustNamedGridItemPosition(finalPosition, finalPositionSide);
940 }
941
942 std::unique_ptr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, GridTrackSizingDirection direction) const
943 {
944     GridPosition initialPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnStart() : gridItem->style().gridItemRowStart();
945     const GridPositionSide initialPositionSide = (direction == ForColumns) ? ColumnStartSide : RowStartSide;
946     GridPosition finalPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnEnd() : gridItem->style().gridItemRowEnd();
947     const GridPositionSide finalPositionSide = (direction == ForColumns) ? ColumnEndSide : RowEndSide;
948
949     adjustGridPositionsFromStyle(initialPosition, finalPosition, initialPositionSide, finalPositionSide);
950
951     if (initialPosition.shouldBeResolvedAgainstOppositePosition() && finalPosition.shouldBeResolvedAgainstOppositePosition()) {
952         if (style().gridAutoFlow() == AutoFlowNone)
953             return std::make_unique<GridSpan>(0, 0);
954
955         // We can't get our grid positions without running the auto placement algorithm.
956         return nullptr;
957     }
958
959     if (initialPosition.shouldBeResolvedAgainstOppositePosition()) {
960         // Infer the position from the final position ('auto / 1' or 'span 2 / 3' case).
961         const size_t finalResolvedPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
962         return resolveGridPositionAgainstOppositePosition(finalResolvedPosition, initialPosition, initialPositionSide);
963     }
964
965     if (finalPosition.shouldBeResolvedAgainstOppositePosition()) {
966         // Infer our position from the initial position ('1 / auto' or '3 / span 2' case).
967         const size_t initialResolvedPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
968         return resolveGridPositionAgainstOppositePosition(initialResolvedPosition, finalPosition, finalPositionSide);
969     }
970
971     size_t resolvedInitialPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
972     size_t resolvedFinalPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
973
974     // If 'grid-row-end' specifies a line at or before that specified by 'grid-row-start', it computes to 'span 1'.
975     if (resolvedFinalPosition < resolvedInitialPosition)
976         resolvedFinalPosition = resolvedInitialPosition;
977
978     return std::make_unique<GridSpan>(resolvedInitialPosition, resolvedFinalPosition);
979 }
980
981 size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& position, GridPositionSide side) const
982 {
983     ASSERT(!position.namedGridLine().isNull());
984
985     const NamedGridLinesMap& gridLinesNames = isColumnSide(side) ? style().namedGridColumnLines() : style().namedGridRowLines();
986     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
987     if (it == gridLinesNames.end()) {
988         if (position.isPositive())
989             return 0;
990         const size_t lastLine = explicitGridSizeForSide(side);
991         return GridPosition::adjustGridPositionForSide(lastLine, side);
992     }
993
994     size_t namedGridLineIndex;
995     if (position.isPositive())
996         namedGridLineIndex = std::min<size_t>(position.integerPosition(), it->value.size()) - 1;
997     else
998         namedGridLineIndex = std::max<int>(it->value.size() - abs(position.integerPosition()), 0);
999     return GridPosition::adjustGridPositionForSide(it->value[namedGridLineIndex], side);
1000 }
1001
1002 size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, GridPositionSide side) const
1003 {
1004     switch (position.type()) {
1005     case ExplicitPosition: {
1006         ASSERT(position.integerPosition());
1007
1008         if (!position.namedGridLine().isNull())
1009             return resolveNamedGridLinePositionFromStyle(position, side);
1010
1011         // Handle <integer> explicit position.
1012         if (position.isPositive())
1013             return GridPosition::adjustGridPositionForSide(position.integerPosition() - 1, side);
1014
1015         size_t resolvedPosition = abs(position.integerPosition()) - 1;
1016         const size_t endOfTrack = explicitGridSizeForSide(side);
1017
1018         // Per http://lists.w3.org/Archives/Public/www-style/2013Mar/0589.html, we clamp negative value to the first line.
1019         if (endOfTrack < resolvedPosition)
1020             return 0;
1021
1022         return GridPosition::adjustGridPositionForSide(endOfTrack - resolvedPosition, side);
1023     }
1024     case NamedGridAreaPosition:
1025     {
1026         NamedGridAreaMap::const_iterator it = style().namedGridArea().find(position.namedGridLine());
1027         // Unknown grid area should have been computed to 'auto' by now.
1028         ASSERT(it != style().namedGridArea().end());
1029         const GridCoordinate& gridAreaCoordinate = it->value;
1030         switch (side) {
1031         case ColumnStartSide:
1032             return gridAreaCoordinate.columns.initialPositionIndex;
1033         case ColumnEndSide:
1034             return gridAreaCoordinate.columns.finalPositionIndex;
1035         case RowStartSide:
1036             return gridAreaCoordinate.rows.initialPositionIndex;
1037         case RowEndSide:
1038             return gridAreaCoordinate.rows.finalPositionIndex;
1039         }
1040         ASSERT_NOT_REACHED();
1041         return 0;
1042     }
1043     case AutoPosition:
1044     case SpanPosition:
1045         // 'auto' and span depend on the opposite position for resolution (e.g. grid-row: auto / 1 or grid-column: span 3 / "myHeader").
1046         ASSERT_NOT_REACHED();
1047         return 0;
1048     }
1049     ASSERT_NOT_REACHED();
1050     return 0;
1051 }
1052
1053 std::unique_ptr<GridSpan> RenderGrid::resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
1054 {
1055     if (position.isAuto())
1056         return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedOppositePosition);
1057
1058     ASSERT(position.isSpan());
1059     ASSERT(position.spanPosition() > 0);
1060
1061     if (!position.namedGridLine().isNull()) {
1062         // span 2 'c' -> we need to find the appropriate grid line before / after our opposite position.
1063         return resolveNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, side);
1064     }
1065
1066     // 'span 1' is contained inside a single grid track regardless of the direction.
1067     // That's why the CSS span value is one more than the offset we apply.
1068     size_t positionOffset = position.spanPosition() - 1;
1069     if (side == ColumnStartSide || side == RowStartSide) {
1070         size_t initialResolvedPosition = std::max<int>(0, resolvedOppositePosition - positionOffset);
1071         return std::make_unique<GridSpan>(initialResolvedPosition, resolvedOppositePosition);
1072     }
1073
1074     return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedOppositePosition + positionOffset);
1075 }
1076
1077 std::unique_ptr<GridSpan> RenderGrid::resolveNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
1078 {
1079     ASSERT(position.isSpan());
1080     ASSERT(!position.namedGridLine().isNull());
1081     // Negative positions are not allowed per the specification and should have been handled during parsing.
1082     ASSERT(position.spanPosition() > 0);
1083
1084     const NamedGridLinesMap& gridLinesNames = isColumnSide(side) ? style().namedGridColumnLines() : style().namedGridRowLines();
1085     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
1086
1087     // If there is no named grid line of that name, we resolve the position to 'auto' (which is equivalent to 'span 1' in this case).
1088     // See http://lists.w3.org/Archives/Public/www-style/2013Jun/0394.html.
1089     if (it == gridLinesNames.end())
1090         return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedOppositePosition);
1091
1092     if (side == RowStartSide || side == ColumnStartSide)
1093         return resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1094
1095     return resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1096 }
1097
1098 static inline size_t firstNamedGridLineBeforePosition(size_t position, const Vector<size_t>& gridLines)
1099 {
1100     // The grid line inequality needs to be strict (which doesn't match the after / end case) because |position| is
1101     // already converted to an index in our grid representation (ie one was removed from the grid line to account for
1102     // the side).
1103     size_t firstLineBeforePositionIndex = 0;
1104     const size_t* firstLineBeforePosition = std::lower_bound(gridLines.begin(), gridLines.end(), position);
1105     if (firstLineBeforePosition != gridLines.end()) {
1106         if (*firstLineBeforePosition > position && firstLineBeforePosition != gridLines.begin())
1107             --firstLineBeforePosition;
1108
1109         firstLineBeforePositionIndex = firstLineBeforePosition - gridLines.begin();
1110     }
1111     return firstLineBeforePositionIndex;
1112 }
1113
1114 std::unique_ptr<GridSpan> RenderGrid::resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1115 {
1116     size_t gridLineIndex = std::max<int>(0, firstNamedGridLineBeforePosition(resolvedOppositePosition, gridLines) - position.spanPosition() + 1);
1117     size_t resolvedGridLinePosition = gridLines[gridLineIndex];
1118     if (resolvedGridLinePosition > resolvedOppositePosition)
1119         resolvedGridLinePosition = resolvedOppositePosition;
1120     return std::make_unique<GridSpan>(resolvedGridLinePosition, resolvedOppositePosition);
1121 }
1122
1123 std::unique_ptr<GridSpan> RenderGrid::resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1124 {
1125     size_t firstLineAfterOppositePositionIndex = gridLines.size() - 1;
1126     const size_t* firstLineAfterOppositePosition = std::upper_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
1127     if (firstLineAfterOppositePosition != gridLines.end())
1128         firstLineAfterOppositePositionIndex = firstLineAfterOppositePosition - gridLines.begin();
1129
1130     size_t gridLineIndex = std::min(gridLines.size() - 1, firstLineAfterOppositePositionIndex + position.spanPosition() - 1);
1131     size_t resolvedGridLinePosition = GridPosition::adjustGridPositionForRowEndColumnEndSide(gridLines[gridLineIndex]);
1132     if (resolvedGridLinePosition < resolvedOppositePosition)
1133         resolvedGridLinePosition = resolvedOppositePosition;
1134     return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedGridLinePosition);
1135 }
1136
1137 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox* child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1138 {
1139     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1140     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1141     LayoutUnit gridAreaBreadth = 0;
1142     for (size_t trackIndex = span.initialPositionIndex; trackIndex <= span.finalPositionIndex; ++trackIndex)
1143         gridAreaBreadth += tracks[trackIndex].m_usedBreadth;
1144     return gridAreaBreadth;
1145 }
1146
1147 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
1148 {
1149     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
1150     m_columnPositions[0] = borderAndPaddingStart();
1151     for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
1152         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
1153
1154     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
1155     m_rowPositions[0] = borderAndPaddingBefore();
1156     for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
1157         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
1158 }
1159
1160 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const GridSizingData& sizingData)
1161 {
1162     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1163     ASSERT_UNUSED(sizingData, coordinate.columns.initialPositionIndex < sizingData.columnTracks.size());
1164     ASSERT_UNUSED(sizingData, coordinate.rows.initialPositionIndex < sizingData.rowTracks.size());
1165
1166     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
1167     return LayoutPoint(m_columnPositions[coordinate.columns.initialPositionIndex] + marginStartForChild(*child), m_rowPositions[coordinate.rows.initialPositionIndex] + marginBeforeForChild(*child));
1168 }
1169
1170 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1171 {
1172     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1173         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect);
1174 }
1175
1176 const char* RenderGrid::renderName() const
1177 {
1178     if (isFloating())
1179         return "RenderGrid (floating)";
1180     if (isOutOfFlowPositioned())
1181         return "RenderGrid (positioned)";
1182     if (isAnonymous())
1183         return "RenderGrid (generated)";
1184     if (isRelPositioned())
1185         return "RenderGrid (relative positioned)";
1186     return "RenderGrid";
1187 }
1188
1189 } // namespace WebCore
1190
1191 #endif /* ENABLE(CSS_GRID_LAYOUT) */