da36c29572722d8942e8745b3d6e56df9e91153a
[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     // FIXME: We should find a way to share OrderValues's initialization code with RenderFlexibleBox.
702     OrderIterator::OrderValues orderValues;
703     size_t maximumRowIndex = std::max<size_t>(1, explicitGridRowCount());
704     size_t maximumColumnIndex = std::max<size_t>(1, explicitGridColumnCount());
705
706     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
707         // Avoid growing the vector for the common-case default value of 0. This optimizes the most common case which is
708         // one or a few values with the default order 0
709         int order = child->style().order();
710         if (orderValues.isEmpty() || orderValues.last() != order)
711             orderValues.append(order);
712
713         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
714         std::unique_ptr<GridSpan> rowPositions = resolveGridPositionsFromStyle(child, ForRows);
715         std::unique_ptr<GridSpan> columnPositions = resolveGridPositionsFromStyle(child, ForColumns);
716
717         // |positions| is 0 if we need to run the auto-placement algorithm. Our estimation ignores
718         // this case as the auto-placement algorithm will grow the grid as needed.
719         if (rowPositions)
720             maximumRowIndex = std::max(maximumRowIndex, rowPositions->finalPositionIndex + 1);
721         if (columnPositions)
722             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->finalPositionIndex + 1);
723     }
724
725     m_grid.grow(maximumRowIndex);
726     for (size_t i = 0; i < m_grid.size(); ++i)
727         m_grid[i].grow(maximumColumnIndex);
728
729     m_orderIterator.setOrderValues(std::move(orderValues));
730 }
731
732 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
733 {
734     for (auto& autoGridItem : autoGridItems) {
735         std::unique_ptr<GridSpan> majorAxisPositions = resolveGridPositionsFromStyle(autoGridItem, autoPlacementMajorAxisDirection());
736         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->initialPositionIndex);
737         if (std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
738             insertItemIntoGrid(autoGridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
739             continue;
740         }
741
742         growGrid(autoPlacementMinorAxisDirection());
743         std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea();
744         ASSERT(emptyGridArea);
745         insertItemIntoGrid(autoGridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
746     }
747 }
748
749 void RenderGrid::placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>& autoGridItems)
750 {
751     for (auto& autoGridItem : autoGridItems)
752         placeAutoMajorAxisItemOnGrid(autoGridItem);
753 }
754
755 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox* gridItem)
756 {
757     std::unique_ptr<GridSpan> minorAxisPositions = resolveGridPositionsFromStyle(gridItem, autoPlacementMinorAxisDirection());
758     ASSERT(!resolveGridPositionsFromStyle(gridItem, autoPlacementMajorAxisDirection()));
759     size_t minorAxisIndex = 0;
760     if (minorAxisPositions) {
761         minorAxisIndex = minorAxisPositions->initialPositionIndex;
762         GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisIndex);
763         if (std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
764             insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
765             return;
766         }
767     } else {
768         const size_t endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
769         for (size_t majorAxisIndex = 0; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
770             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex);
771             if (std::unique_ptr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
772                 insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
773                 return;
774             }
775         }
776     }
777
778     // We didn't find an empty grid area so we need to create an extra major axis line and insert our gridItem in it.
779     const size_t columnIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : minorAxisIndex;
780     const size_t rowIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? minorAxisIndex : gridRowCount();
781     growGrid(autoPlacementMajorAxisDirection());
782     insertItemIntoGrid(gridItem, rowIndex, columnIndex);
783 }
784
785 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
786 {
787     GridAutoFlow flow = style().gridAutoFlow();
788     ASSERT(flow != AutoFlowNone);
789     return (flow == AutoFlowColumn) ? ForColumns : ForRows;
790 }
791
792 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
793 {
794     GridAutoFlow flow = style().gridAutoFlow();
795     ASSERT(flow != AutoFlowNone);
796     return (flow == AutoFlowColumn) ? ForRows : ForColumns;
797 }
798
799 void RenderGrid::clearGrid()
800 {
801     m_grid.clear();
802     m_gridItemCoordinate.clear();
803 }
804
805 void RenderGrid::layoutGridItems()
806 {
807     placeItemsOnGrid();
808
809     GridSizingData sizingData(gridColumnCount(), gridRowCount());
810     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
811     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
812     computeUsedBreadthOfGridTracks(ForRows, sizingData);
813     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
814
815     populateGridPositions(sizingData);
816
817     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
818         // Because the grid area cannot be styled, we don't need to adjust
819         // the grid breadth to account for 'box-sizing'.
820         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
821         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
822
823         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, sizingData.columnTracks);
824         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, sizingData.rowTracks);
825         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && (child->hasRelativeLogicalHeight() || child->hasViewportPercentageLogicalHeight())))
826             child->setNeedsLayout(MarkOnlyThis);
827
828         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
829         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
830
831         LayoutRect oldChildRect = child->frameRect();
832
833         // FIXME: Grid items should stretch to fill their cells. Once we
834         // implement grid-{column,row}-align, we can also shrink to fit. For
835         // now, just size as if we were a regular child.
836         child->layoutIfNeeded();
837
838         child->setLogicalLocation(findChildLogicalPosition(child, sizingData));
839
840         // If the child moved, we have to repaint it as well as any floating/positioned
841         // descendants. An exception is if we need a layout. In this case, we know we're going to
842         // repaint ourselves (and the child) anyway.
843         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
844             child->repaintDuringLayoutIfMoved(oldChildRect);
845     }
846
847     for (size_t i = 0; i < sizingData.rowTracks.size(); ++i)
848         setLogicalHeight(logicalHeight() + sizingData.rowTracks[i].m_usedBreadth);
849
850     // min / max logical height is handled in updateLogicalHeight().
851     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
852     clearGrid();
853 }
854
855 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox* gridItem) const
856 {
857     ASSERT(m_gridItemCoordinate.contains(gridItem));
858     return m_gridItemCoordinate.get(gridItem);
859 }
860
861 GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, GridTrackSizingDirection, size_t initialPosition) const
862 {
863     // FIXME: We don't support spanning with auto positions yet. Once we do, this is wrong. Also we should make
864     // sure the grid can accomodate the new item as we only grow 1 position in a given direction.
865     return GridSpan(initialPosition, initialPosition);
866 }
867
868 static inline bool gridLineDefinedBeforeGridArea(size_t namedGridLineFirstDefinition, const GridCoordinate& gridAreaCoordinates, GridPositionSide side)
869 {
870     switch (side) {
871     case ColumnStartSide:
872         return namedGridLineFirstDefinition < gridAreaCoordinates.columns.initialPositionIndex;
873     case ColumnEndSide:
874         return namedGridLineFirstDefinition < gridAreaCoordinates.columns.finalPositionIndex;
875     case RowStartSide:
876         return namedGridLineFirstDefinition < gridAreaCoordinates.rows.initialPositionIndex;
877     case RowEndSide:
878         return namedGridLineFirstDefinition < gridAreaCoordinates.rows.finalPositionIndex;
879     }
880     ASSERT_NOT_REACHED();
881     return false;
882 }
883
884 static void setNamedLinePositionIfDefinedBeforeArea(GridPosition& position, const NamedGridLinesMap& namedLinesMap, const String& lineName, const GridCoordinate& gridAreaCoordinate, GridPositionSide side)
885 {
886     auto linesIterator = namedLinesMap.find(lineName);
887     if (linesIterator == namedLinesMap.end())
888         return;
889
890     size_t namedGridLineFirstDefinition = GridPosition::adjustGridPositionForSide(linesIterator->value[0], side);
891     if (gridLineDefinedBeforeGridArea(namedGridLineFirstDefinition, gridAreaCoordinate, side))
892         position.setExplicitPosition(1, lineName);
893 }
894
895 void RenderGrid::adjustNamedGridItemPosition(GridPosition& position, GridPositionSide side) const
896 {
897     // The StyleBuilder always treats <custom-ident> as a named grid area. We must decide here if they are going to be
898     // resolved to either a grid area or a grid line.
899     ASSERT(position.isNamedGridArea());
900     const NamedGridAreaMap& gridAreaMap = style().namedGridArea();
901     const NamedGridLinesMap& namedLinesMap = isColumnSide(side) ? style().namedGridColumnLines() : style().namedGridRowLines();
902
903     String namedGridAreaOrGridLine = position.namedGridLine();
904     bool isStartSide = side == ColumnStartSide || side == RowStartSide;
905
906     auto areaIterator = gridAreaMap.find(namedGridAreaOrGridLine);
907     if (areaIterator != gridAreaMap.end()) {
908         String gridLineName = namedGridAreaOrGridLine + (isStartSide ? "-start" : "-end");
909         setNamedLinePositionIfDefinedBeforeArea(position, namedLinesMap, gridLineName, areaIterator->value, side);
910         return;
911     }
912
913     bool hasStartSuffix = namedGridAreaOrGridLine.endsWith("-start");
914     bool hasEndSuffix = namedGridAreaOrGridLine.endsWith("-end");
915     if ((hasStartSuffix && isStartSide) || (hasEndSuffix && !isStartSide)) {
916         size_t suffixLength = hasStartSuffix ? strlen("-start") : strlen("-end");
917         String gridAreaName = namedGridAreaOrGridLine.substring(0, namedGridAreaOrGridLine.length() - suffixLength);
918
919         auto areaIterator = gridAreaMap.find(gridAreaName);
920         if (areaIterator != gridAreaMap.end()) {
921             position.setNamedGridArea(gridAreaName);
922             setNamedLinePositionIfDefinedBeforeArea(position, namedLinesMap, namedGridAreaOrGridLine, areaIterator->value, side);
923             return;
924         }
925     }
926
927     if (namedLinesMap.contains(namedGridAreaOrGridLine))
928         position.setExplicitPosition(1, namedGridAreaOrGridLine);
929     else
930         position.setAutoPosition();
931 }
932
933 void RenderGrid::adjustGridPositionsFromStyle(GridPosition& initialPosition, GridPosition& finalPosition, GridPositionSide initialPositionSide, GridPositionSide finalPositionSide) const
934 {
935     ASSERT(isColumnSide(initialPositionSide) == isColumnSide(finalPositionSide));
936
937     // We must handle the placement error handling code here instead of in the StyleAdjuster because we don't want to
938     // overwrite the specified values.
939     if (initialPosition.isSpan() && finalPosition.isSpan())
940         finalPosition.setAutoPosition();
941
942     if (initialPosition.isNamedGridArea())
943         adjustNamedGridItemPosition(initialPosition, initialPositionSide);
944
945     if (finalPosition.isNamedGridArea())
946         adjustNamedGridItemPosition(finalPosition, finalPositionSide);
947 }
948
949 std::unique_ptr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, GridTrackSizingDirection direction) const
950 {
951     GridPosition initialPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnStart() : gridItem->style().gridItemRowStart();
952     const GridPositionSide initialPositionSide = (direction == ForColumns) ? ColumnStartSide : RowStartSide;
953     GridPosition finalPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnEnd() : gridItem->style().gridItemRowEnd();
954     const GridPositionSide finalPositionSide = (direction == ForColumns) ? ColumnEndSide : RowEndSide;
955
956     adjustGridPositionsFromStyle(initialPosition, finalPosition, initialPositionSide, finalPositionSide);
957
958     if (initialPosition.shouldBeResolvedAgainstOppositePosition() && finalPosition.shouldBeResolvedAgainstOppositePosition()) {
959         if (style().gridAutoFlow() == AutoFlowNone)
960             return std::make_unique<GridSpan>(0, 0);
961
962         // We can't get our grid positions without running the auto placement algorithm.
963         return nullptr;
964     }
965
966     if (initialPosition.shouldBeResolvedAgainstOppositePosition()) {
967         // Infer the position from the final position ('auto / 1' or 'span 2 / 3' case).
968         const size_t finalResolvedPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
969         return resolveGridPositionAgainstOppositePosition(finalResolvedPosition, initialPosition, initialPositionSide);
970     }
971
972     if (finalPosition.shouldBeResolvedAgainstOppositePosition()) {
973         // Infer our position from the initial position ('1 / auto' or '3 / span 2' case).
974         const size_t initialResolvedPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
975         return resolveGridPositionAgainstOppositePosition(initialResolvedPosition, finalPosition, finalPositionSide);
976     }
977
978     size_t resolvedInitialPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
979     size_t resolvedFinalPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
980
981     // If 'grid-row-end' specifies a line at or before that specified by 'grid-row-start', it computes to 'span 1'.
982     if (resolvedFinalPosition < resolvedInitialPosition)
983         resolvedFinalPosition = resolvedInitialPosition;
984
985     return std::make_unique<GridSpan>(resolvedInitialPosition, resolvedFinalPosition);
986 }
987
988 size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& position, GridPositionSide side) const
989 {
990     ASSERT(!position.namedGridLine().isNull());
991
992     const NamedGridLinesMap& gridLinesNames = isColumnSide(side) ? style().namedGridColumnLines() : style().namedGridRowLines();
993     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
994     if (it == gridLinesNames.end()) {
995         if (position.isPositive())
996             return 0;
997         const size_t lastLine = explicitGridSizeForSide(side);
998         return GridPosition::adjustGridPositionForSide(lastLine, side);
999     }
1000
1001     size_t namedGridLineIndex;
1002     if (position.isPositive())
1003         namedGridLineIndex = std::min<size_t>(position.integerPosition(), it->value.size()) - 1;
1004     else
1005         namedGridLineIndex = std::max<int>(it->value.size() - abs(position.integerPosition()), 0);
1006     return GridPosition::adjustGridPositionForSide(it->value[namedGridLineIndex], side);
1007 }
1008
1009 size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, GridPositionSide side) const
1010 {
1011     switch (position.type()) {
1012     case ExplicitPosition: {
1013         ASSERT(position.integerPosition());
1014
1015         if (!position.namedGridLine().isNull())
1016             return resolveNamedGridLinePositionFromStyle(position, side);
1017
1018         // Handle <integer> explicit position.
1019         if (position.isPositive())
1020             return GridPosition::adjustGridPositionForSide(position.integerPosition() - 1, side);
1021
1022         size_t resolvedPosition = abs(position.integerPosition()) - 1;
1023         const size_t endOfTrack = explicitGridSizeForSide(side);
1024
1025         // Per http://lists.w3.org/Archives/Public/www-style/2013Mar/0589.html, we clamp negative value to the first line.
1026         if (endOfTrack < resolvedPosition)
1027             return 0;
1028
1029         return GridPosition::adjustGridPositionForSide(endOfTrack - resolvedPosition, side);
1030     }
1031     case NamedGridAreaPosition:
1032     {
1033         NamedGridAreaMap::const_iterator it = style().namedGridArea().find(position.namedGridLine());
1034         // Unknown grid area should have been computed to 'auto' by now.
1035         ASSERT(it != style().namedGridArea().end());
1036         const GridCoordinate& gridAreaCoordinate = it->value;
1037         switch (side) {
1038         case ColumnStartSide:
1039             return gridAreaCoordinate.columns.initialPositionIndex;
1040         case ColumnEndSide:
1041             return gridAreaCoordinate.columns.finalPositionIndex;
1042         case RowStartSide:
1043             return gridAreaCoordinate.rows.initialPositionIndex;
1044         case RowEndSide:
1045             return gridAreaCoordinate.rows.finalPositionIndex;
1046         }
1047         ASSERT_NOT_REACHED();
1048         return 0;
1049     }
1050     case AutoPosition:
1051     case SpanPosition:
1052         // 'auto' and span depend on the opposite position for resolution (e.g. grid-row: auto / 1 or grid-column: span 3 / "myHeader").
1053         ASSERT_NOT_REACHED();
1054         return 0;
1055     }
1056     ASSERT_NOT_REACHED();
1057     return 0;
1058 }
1059
1060 std::unique_ptr<GridSpan> RenderGrid::resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
1061 {
1062     if (position.isAuto())
1063         return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedOppositePosition);
1064
1065     ASSERT(position.isSpan());
1066     ASSERT(position.spanPosition() > 0);
1067
1068     if (!position.namedGridLine().isNull()) {
1069         // span 2 'c' -> we need to find the appropriate grid line before / after our opposite position.
1070         return resolveNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, side);
1071     }
1072
1073     // 'span 1' is contained inside a single grid track regardless of the direction.
1074     // That's why the CSS span value is one more than the offset we apply.
1075     size_t positionOffset = position.spanPosition() - 1;
1076     if (side == ColumnStartSide || side == RowStartSide) {
1077         size_t initialResolvedPosition = std::max<int>(0, resolvedOppositePosition - positionOffset);
1078         return std::make_unique<GridSpan>(initialResolvedPosition, resolvedOppositePosition);
1079     }
1080
1081     return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedOppositePosition + positionOffset);
1082 }
1083
1084 std::unique_ptr<GridSpan> RenderGrid::resolveNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
1085 {
1086     ASSERT(position.isSpan());
1087     ASSERT(!position.namedGridLine().isNull());
1088     // Negative positions are not allowed per the specification and should have been handled during parsing.
1089     ASSERT(position.spanPosition() > 0);
1090
1091     const NamedGridLinesMap& gridLinesNames = isColumnSide(side) ? style().namedGridColumnLines() : style().namedGridRowLines();
1092     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
1093
1094     // 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).
1095     // See http://lists.w3.org/Archives/Public/www-style/2013Jun/0394.html.
1096     if (it == gridLinesNames.end())
1097         return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedOppositePosition);
1098
1099     if (side == RowStartSide || side == ColumnStartSide)
1100         return resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1101
1102     return resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1103 }
1104
1105 static inline size_t firstNamedGridLineBeforePosition(size_t position, const Vector<size_t>& gridLines)
1106 {
1107     // The grid line inequality needs to be strict (which doesn't match the after / end case) because |position| is
1108     // already converted to an index in our grid representation (ie one was removed from the grid line to account for
1109     // the side).
1110     size_t firstLineBeforePositionIndex = 0;
1111     const size_t* firstLineBeforePosition = std::lower_bound(gridLines.begin(), gridLines.end(), position);
1112     if (firstLineBeforePosition != gridLines.end()) {
1113         if (*firstLineBeforePosition > position && firstLineBeforePosition != gridLines.begin())
1114             --firstLineBeforePosition;
1115
1116         firstLineBeforePositionIndex = firstLineBeforePosition - gridLines.begin();
1117     }
1118     return firstLineBeforePositionIndex;
1119 }
1120
1121 std::unique_ptr<GridSpan> RenderGrid::resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1122 {
1123     size_t gridLineIndex = std::max<int>(0, firstNamedGridLineBeforePosition(resolvedOppositePosition, gridLines) - position.spanPosition() + 1);
1124     size_t resolvedGridLinePosition = gridLines[gridLineIndex];
1125     if (resolvedGridLinePosition > resolvedOppositePosition)
1126         resolvedGridLinePosition = resolvedOppositePosition;
1127     return std::make_unique<GridSpan>(resolvedGridLinePosition, resolvedOppositePosition);
1128 }
1129
1130 std::unique_ptr<GridSpan> RenderGrid::resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1131 {
1132     size_t firstLineAfterOppositePositionIndex = gridLines.size() - 1;
1133     const size_t* firstLineAfterOppositePosition = std::upper_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
1134     if (firstLineAfterOppositePosition != gridLines.end())
1135         firstLineAfterOppositePositionIndex = firstLineAfterOppositePosition - gridLines.begin();
1136
1137     size_t gridLineIndex = std::min(gridLines.size() - 1, firstLineAfterOppositePositionIndex + position.spanPosition() - 1);
1138     size_t resolvedGridLinePosition = GridPosition::adjustGridPositionForRowEndColumnEndSide(gridLines[gridLineIndex]);
1139     if (resolvedGridLinePosition < resolvedOppositePosition)
1140         resolvedGridLinePosition = resolvedOppositePosition;
1141     return std::make_unique<GridSpan>(resolvedOppositePosition, resolvedGridLinePosition);
1142 }
1143
1144 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox* child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1145 {
1146     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1147     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1148     LayoutUnit gridAreaBreadth = 0;
1149     for (size_t trackIndex = span.initialPositionIndex; trackIndex <= span.finalPositionIndex; ++trackIndex)
1150         gridAreaBreadth += tracks[trackIndex].m_usedBreadth;
1151     return gridAreaBreadth;
1152 }
1153
1154 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
1155 {
1156     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
1157     m_columnPositions[0] = borderAndPaddingStart();
1158     for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
1159         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
1160
1161     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
1162     m_rowPositions[0] = borderAndPaddingBefore();
1163     for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
1164         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
1165 }
1166
1167 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const GridSizingData& sizingData)
1168 {
1169     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1170     ASSERT_UNUSED(sizingData, coordinate.columns.initialPositionIndex < sizingData.columnTracks.size());
1171     ASSERT_UNUSED(sizingData, coordinate.rows.initialPositionIndex < sizingData.rowTracks.size());
1172
1173     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
1174     return LayoutPoint(m_columnPositions[coordinate.columns.initialPositionIndex] + marginStartForChild(*child), m_rowPositions[coordinate.rows.initialPositionIndex] + marginBeforeForChild(*child));
1175 }
1176
1177 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1178 {
1179     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1180         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect);
1181 }
1182
1183 const char* RenderGrid::renderName() const
1184 {
1185     if (isFloating())
1186         return "RenderGrid (floating)";
1187     if (isOutOfFlowPositioned())
1188         return "RenderGrid (positioned)";
1189     if (isAnonymous())
1190         return "RenderGrid (generated)";
1191     if (isRelPositioned())
1192         return "RenderGrid (relative positioned)";
1193     return "RenderGrid";
1194 }
1195
1196 } // namespace WebCore
1197
1198 #endif /* ENABLE(CSS_GRID_LAYOUT) */