[CSS Grid Layout] Add ENABLE flag
[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 COMPUTER, 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 "NotImplemented.h"
35 #include "RenderLayer.h"
36 #include "RenderView.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     PassOwnPtr<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                 OwnPtr<GridCoordinate> result = adoptPtr(new 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.release();
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     prepareShapesAndPaginationBeforeBlockLayout(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     updateShapesAfterBlockLayout();
206
207     computeOverflow(oldClientAfterEdge);
208     statePusher.pop();
209
210     updateLayerTransform();
211
212     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
213     // we overflow or not.
214     updateScrollInfoAfterLayout();
215
216     repainter.repaintAfterLayout();
217
218     clearNeedsLayout();
219 }
220
221 void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
222 {
223     const_cast<RenderGrid*>(this)->placeItemsOnGrid();
224
225     GridSizingData sizingData(gridColumnCount(), gridRowCount());
226     LayoutUnit availableLogicalSpace = 0;
227     const_cast<RenderGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
228
229     for (size_t i = 0; i < sizingData.columnTracks.size(); ++i) {
230         LayoutUnit minTrackBreadth = sizingData.columnTracks[i].m_usedBreadth;
231         LayoutUnit maxTrackBreadth = sizingData.columnTracks[i].m_maxBreadth;
232         maxTrackBreadth = std::max(maxTrackBreadth, minTrackBreadth);
233
234         minLogicalWidth += minTrackBreadth;
235         maxLogicalWidth += maxTrackBreadth;
236
237         // FIXME: This should add in the scrollbarWidth (e.g. see RenderFlexibleBox).
238     }
239
240     const_cast<RenderGrid*>(this)->clearGrid();
241 }
242
243 void RenderGrid::computePreferredLogicalWidths()
244 {
245     ASSERT(preferredLogicalWidthsDirty());
246
247     m_minPreferredLogicalWidth = 0;
248     m_maxPreferredLogicalWidth = 0;
249
250     // FIXME: We don't take our own logical width into account. Once we do, we need to make sure
251     // we apply (and test the interaction with) min-width / max-width.
252
253     computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
254
255     LayoutUnit borderAndPaddingInInlineDirection = borderAndPaddingLogicalWidth();
256     m_minPreferredLogicalWidth += borderAndPaddingInInlineDirection;
257     m_maxPreferredLogicalWidth += borderAndPaddingInInlineDirection;
258
259     setPreferredLogicalWidthsDirty(false);
260 }
261
262 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
263 {
264     LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
265     computeUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
266 }
267
268 bool RenderGrid::gridElementIsShrinkToFit()
269 {
270     return isFloatingOrOutOfFlowPositioned();
271 }
272
273 void RenderGrid::computeUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
274 {
275     Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
276     Vector<size_t> flexibleSizedTracksIndex;
277     sizingData.contentSizedTracksIndex.shrink(0);
278
279     // 1. Initialize per Grid track variables.
280     for (size_t i = 0; i < tracks.size(); ++i) {
281         GridTrack& track = tracks[i];
282         const GridTrackSize& trackSize = gridTrackSize(direction, i);
283         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
284         const GridLength& maxTrackBreadth = trackSize.maxTrackBreadth();
285
286         track.m_usedBreadth = computeUsedBreadthOfMinLength(direction, minTrackBreadth);
287         track.m_maxBreadth = computeUsedBreadthOfMaxLength(direction, maxTrackBreadth, track.m_usedBreadth);
288
289         track.m_maxBreadth = std::max(track.m_maxBreadth, track.m_usedBreadth);
290
291         if (trackSize.isContentSized())
292             sizingData.contentSizedTracksIndex.append(i);
293         if (trackSize.maxTrackBreadth().isFlex())
294             flexibleSizedTracksIndex.append(i);
295     }
296
297     // 2. Resolve content-based TrackSizingFunctions.
298     if (!sizingData.contentSizedTracksIndex.isEmpty())
299         resolveContentBasedTrackSizingFunctions(direction, sizingData);
300
301     for (size_t i = 0; i < tracks.size(); ++i) {
302         ASSERT(tracks[i].m_maxBreadth != infinity);
303         availableLogicalSpace -= tracks[i].m_usedBreadth;
304     }
305
306     const bool hasUndefinedRemainingSpace = (direction == ForRows) ? style().logicalHeight().isAuto() : gridElementIsShrinkToFit();
307
308     if (!hasUndefinedRemainingSpace && availableLogicalSpace <= 0)
309         return;
310
311     // 3. Grow all Grid tracks in GridTracks from their UsedBreadth up to their MaxBreadth value until
312     // availableLogicalSpace (RemainingSpace in the specs) is exhausted.
313     const size_t tracksSize = tracks.size();
314     if (!hasUndefinedRemainingSpace) {
315         Vector<GridTrack*> tracksForDistribution(tracksSize);
316         for (size_t i = 0; i < tracksSize; ++i)
317             tracksForDistribution[i] = tracks.data() + i;
318
319         distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
320     } else {
321         for (size_t i = 0; i < tracksSize; ++i)
322             tracks[i].m_usedBreadth = tracks[i].m_maxBreadth;
323     }
324
325     if (flexibleSizedTracksIndex.isEmpty())
326         return;
327
328     // 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
329     double normalizedFractionBreadth = 0;
330     if (!hasUndefinedRemainingSpace)
331         normalizedFractionBreadth = computeNormalizedFractionBreadth(tracks, GridSpan(0, tracks.size() - 1), direction, availableLogicalSpace);
332     else {
333         for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
334             const size_t trackIndex = flexibleSizedTracksIndex[i];
335             const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
336             normalizedFractionBreadth = std::max(normalizedFractionBreadth, tracks[trackIndex].m_usedBreadth / trackSize.maxTrackBreadth().flex());
337         }
338
339         for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
340             GridIterator iterator(m_grid, direction, flexibleSizedTracksIndex[i]);
341             while (RenderBox* gridItem = iterator.nextGridItem()) {
342                 const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
343                 const GridSpan span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
344
345                 // Do not include already processed items.
346                 if (i > 0 && span.initialPositionIndex <= flexibleSizedTracksIndex[i - 1])
347                     continue;
348
349                 double itemNormalizedFlexBreadth = computeNormalizedFractionBreadth(tracks, span, direction, maxContentForChild(gridItem, direction, sizingData.columnTracks));
350                 normalizedFractionBreadth = std::max(normalizedFractionBreadth, itemNormalizedFlexBreadth);
351             }
352         }
353     }
354
355     for (size_t i = 0; i < flexibleSizedTracksIndex.size(); ++i) {
356         const size_t trackIndex = flexibleSizedTracksIndex[i];
357         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
358
359         tracks[trackIndex].m_usedBreadth = std::max<LayoutUnit>(tracks[trackIndex].m_usedBreadth, normalizedFractionBreadth * trackSize.maxTrackBreadth().flex());
360     }
361 }
362
363 LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
364 {
365     if (gridLength.isFlex())
366         return 0;
367
368     const Length& trackLength = gridLength.length();
369     ASSERT(!trackLength.isAuto());
370     if (trackLength.isSpecified())
371         return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
372
373     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
374     return 0;
375 }
376
377 LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
378 {
379     if (gridLength.isFlex())
380         return usedBreadth;
381
382     const Length& trackLength = gridLength.length();
383     ASSERT(!trackLength.isAuto());
384     if (trackLength.isSpecified()) {
385         LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
386         ASSERT(computedBreadth != infinity);
387         return computedBreadth;
388     }
389
390     ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
391     return infinity;
392 }
393
394 LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
395 {
396     ASSERT(trackLength.isSpecified());
397     return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style().logicalHeight()));
398 }
399
400 double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, const GridSpan& tracksSpan, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
401 {
402     // |availableLogicalSpace| already accounts for the used breadths so no need to remove it here.
403
404     Vector<GridTrackForNormalization> tracksForNormalization;
405     for (size_t i = tracksSpan.initialPositionIndex; i <= tracksSpan.finalPositionIndex; ++i) {
406         const GridTrackSize& trackSize = gridTrackSize(direction, i);
407         if (!trackSize.maxTrackBreadth().isFlex())
408             continue;
409
410         tracksForNormalization.append(GridTrackForNormalization(tracks[i], trackSize.maxTrackBreadth().flex()));
411     }
412
413     // The function is not called if we don't have <flex> grid tracks
414     ASSERT(!tracksForNormalization.isEmpty());
415
416     std::sort(tracksForNormalization.begin(), tracksForNormalization.end(),
417               [](const GridTrackForNormalization& track1, const GridTrackForNormalization& track2) {
418                   return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
419               });
420
421     // These values work together: as we walk over our grid tracks, we increase fractionValueBasedOnGridItemsRatio
422     // to match a grid track's usedBreadth to <flex> ratio until the total fractions sized grid tracks wouldn't
423     // fit into availableLogicalSpaceIgnoringFractionTracks.
424     double accumulatedFractions = 0;
425     LayoutUnit fractionValueBasedOnGridItemsRatio = 0;
426     LayoutUnit availableLogicalSpaceIgnoringFractionTracks = availableLogicalSpace;
427
428     for (size_t i = 0; i < tracksForNormalization.size(); ++i) {
429         const GridTrackForNormalization& track = tracksForNormalization[i];
430         if (track.m_normalizedFlexValue > fractionValueBasedOnGridItemsRatio) {
431             // If the normalized flex value (we ordered |tracksForNormalization| by increasing normalized flex value)
432             // will make us overflow our container, then stop. We have the previous step's ratio is the best fit.
433             if (track.m_normalizedFlexValue * accumulatedFractions > availableLogicalSpaceIgnoringFractionTracks)
434                 break;
435
436             fractionValueBasedOnGridItemsRatio = track.m_normalizedFlexValue;
437         }
438
439         accumulatedFractions += track.m_flex;
440         // This item was processed so we re-add its used breadth to the available space to accurately count the remaining space.
441         availableLogicalSpaceIgnoringFractionTracks += track.m_track->m_usedBreadth;
442     }
443
444     return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
445 }
446
447 const GridTrackSize& RenderGrid::gridTrackSize(GridTrackSizingDirection direction, size_t i) const
448 {
449     const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style().gridColumns() : style().gridRows();
450     if (i >= trackStyles.size())
451         return (direction == ForColumns) ? style().gridAutoColumns() : style().gridAutoRows();
452
453     return trackStyles[i];
454 }
455
456 size_t RenderGrid::explicitGridColumnCount() const
457 {
458     return style().gridColumns().size();
459 }
460
461 size_t RenderGrid::explicitGridRowCount() const
462 {
463     return style().gridRows().size();
464 }
465
466 size_t RenderGrid::explicitGridSizeForSide(GridPositionSide side) const
467 {
468     return (side == ColumnStartSide || side == ColumnEndSide) ? explicitGridColumnCount() : explicitGridRowCount();
469 }
470
471 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox* child, Vector<GridTrack>& columnTracks)
472 {
473     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
474     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
475     if (child->style().logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
476         child->setNeedsLayout(MarkOnlyThis);
477
478     child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
479     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
480     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
481     child->setOverrideContainingBlockContentLogicalHeight(-1);
482     child->layoutIfNeeded();
483     return child->logicalHeight();
484 }
485
486 LayoutUnit RenderGrid::minContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
487 {
488     bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
489     // FIXME: Properly support orthogonal writing mode.
490     if (hasOrthogonalWritingMode)
491         return 0;
492
493     if (direction == ForColumns) {
494         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
495         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
496         return child->minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(*child);
497     }
498
499     return logicalContentHeightForChild(child, columnTracks);
500 }
501
502 LayoutUnit RenderGrid::maxContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
503 {
504     bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
505     // FIXME: Properly support orthogonal writing mode.
506     if (hasOrthogonalWritingMode)
507         return LayoutUnit();
508
509     if (direction == ForColumns) {
510         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
511         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
512         return child->maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(*child);
513     }
514
515     return logicalContentHeightForChild(child, columnTracks);
516 }
517
518 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
519 {
520     // FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track.
521
522     for (size_t i = 0; i < sizingData.contentSizedTracksIndex.size(); ++i) {
523         GridIterator iterator(m_grid, direction, sizingData.contentSizedTracksIndex[i]);
524         while (RenderBox* gridItem = iterator.nextGridItem()) {
525             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
526             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
527             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
528             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
529         }
530
531         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[i] : sizingData.rowTracks[i];
532         if (track.m_maxBreadth == infinity)
533             track.m_maxBreadth = track.m_usedBreadth;
534     }
535 }
536
537 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, RenderBox* gridItem, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction)
538 {
539     const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
540     const size_t initialTrackIndex = (direction == ForColumns) ? coordinate.columns.initialPositionIndex : coordinate.rows.initialPositionIndex;
541     const size_t finalTrackIndex = (direction == ForColumns) ? coordinate.columns.finalPositionIndex : coordinate.rows.finalPositionIndex;
542
543     sizingData.filteredTracks.shrink(0);
544     for (size_t trackIndex = initialTrackIndex; trackIndex <= finalTrackIndex; ++trackIndex) {
545         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
546         if (!(trackSize.*filterFunction)())
547             continue;
548
549         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
550         sizingData.filteredTracks.append(&track);
551     }
552
553     if (sizingData.filteredTracks.isEmpty())
554         return;
555
556     LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItem, direction, sizingData.columnTracks);
557     for (size_t trackIndexForSpace = initialTrackIndex; trackIndexForSpace <= finalTrackIndex; ++trackIndexForSpace) {
558         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndexForSpace] : sizingData.rowTracks[trackIndexForSpace];
559         additionalBreadthSpace -= (track.*trackGetter)();
560     }
561
562     // FIXME: We should pass different values for |tracksForGrowthAboveMaxBreadth|.
563     distributeSpaceToTracks(sizingData.filteredTracks, &sizingData.filteredTracks, trackGetter, trackGrowthFunction, sizingData, additionalBreadthSpace);
564 }
565
566 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
567 {
568     return (track1->m_maxBreadth - track1->m_usedBreadth) < (track2->m_maxBreadth - track2->m_usedBreadth);
569 }
570
571 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
572 {
573     std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
574
575     size_t tracksSize = tracks.size();
576     sizingData.distributeTrackVector.resize(tracksSize);
577
578     for (size_t i = 0; i < tracksSize; ++i) {
579         GridTrack& track = *tracks[i];
580         LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
581         LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
582         LayoutUnit growthShare = std::max(LayoutUnit(), std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth));
583         // We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function.
584         sizingData.distributeTrackVector[i] = trackBreadth + growthShare;
585         availableLogicalSpace -= growthShare;
586     }
587
588     if (availableLogicalSpace > 0 && tracksForGrowthAboveMaxBreadth) {
589         tracksSize = tracksForGrowthAboveMaxBreadth->size();
590         for (size_t i = 0; i < tracksSize; ++i) {
591             LayoutUnit growthShare = availableLogicalSpace / (tracksSize - i);
592             sizingData.distributeTrackVector[i] += growthShare;
593             availableLogicalSpace -= growthShare;
594         }
595     }
596
597     for (size_t i = 0; i < tracksSize; ++i) {
598         LayoutUnit growth = sizingData.distributeTrackVector[i] - (tracks[i]->*trackGetter)();
599         if (growth >= 0)
600             (tracks[i]->*trackGrowthFunction)(growth);
601     }
602 }
603
604 #ifndef NDEBUG
605 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
606 {
607     for (size_t i = 0; i < tracks.size(); ++i) {
608         const GridTrackSize& trackSize = gridTrackSize(direction, i);
609         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
610         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].m_usedBreadth)
611             return false;
612     }
613     return true;
614 }
615 #endif
616
617 void RenderGrid::growGrid(GridTrackSizingDirection direction)
618 {
619     if (direction == ForColumns) {
620         const size_t oldColumnSize = m_grid[0].size();
621         for (size_t row = 0; row < m_grid.size(); ++row)
622             m_grid[row].grow(oldColumnSize + 1);
623     } else {
624         const size_t oldRowSize = m_grid.size();
625         m_grid.grow(oldRowSize + 1);
626         m_grid[oldRowSize].grow(m_grid[0].size());
627     }
628 }
629
630 void RenderGrid::insertItemIntoGrid(RenderBox* child, const GridCoordinate& coordinate)
631 {
632     for (size_t row = coordinate.rows.initialPositionIndex; row <= coordinate.rows.finalPositionIndex; ++row) {
633         for (size_t column = coordinate.columns.initialPositionIndex; column <= coordinate.columns.finalPositionIndex; ++column)
634             m_grid[row][column].append(child);
635     }
636     m_gridItemCoordinate.set(child, coordinate);
637 }
638
639 void RenderGrid::insertItemIntoGrid(RenderBox* child, size_t rowTrack, size_t columnTrack)
640 {
641     const GridSpan& rowSpan = resolveGridPositionsFromAutoPlacementPosition(child, ForRows, rowTrack);
642     const GridSpan& columnSpan = resolveGridPositionsFromAutoPlacementPosition(child, ForColumns, columnTrack);
643     insertItemIntoGrid(child, GridCoordinate(rowSpan, columnSpan));
644 }
645
646 void RenderGrid::placeItemsOnGrid()
647 {
648     ASSERT(!gridWasPopulated());
649     ASSERT(m_gridItemCoordinate.isEmpty());
650
651     populateExplicitGridAndOrderIterator();
652
653     Vector<RenderBox*> autoMajorAxisAutoGridItems;
654     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
655     GridAutoFlow autoFlow = style().gridAutoFlow();
656     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
657         // FIXME: We never re-resolve positions if the grid is grown during auto-placement which may lead auto / <integer>
658         // positions to not match the author's intent. The specification is unclear on what should be done in this case.
659         OwnPtr<GridSpan> rowPositions = resolveGridPositionsFromStyle(child, ForRows);
660         OwnPtr<GridSpan> columnPositions = resolveGridPositionsFromStyle(child, ForColumns);
661         if (!rowPositions || !columnPositions) {
662             GridSpan* majorAxisPositions = (autoPlacementMajorAxisDirection() == ForColumns) ? columnPositions.get() : rowPositions.get();
663             if (!majorAxisPositions)
664                 autoMajorAxisAutoGridItems.append(child);
665             else
666                 specifiedMajorAxisAutoGridItems.append(child);
667             continue;
668         }
669         insertItemIntoGrid(child, GridCoordinate(*rowPositions, *columnPositions));
670     }
671
672     ASSERT(gridRowCount() >= style().gridRows().size());
673     ASSERT(gridColumnCount() >= style().gridColumns().size());
674
675     if (autoFlow == AutoFlowNone) {
676         // If we did collect some grid items, they won't be placed thus never laid out.
677         ASSERT(!autoMajorAxisAutoGridItems.size());
678         ASSERT(!specifiedMajorAxisAutoGridItems.size());
679         return;
680     }
681
682     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
683     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
684 }
685
686 void RenderGrid::populateExplicitGridAndOrderIterator()
687 {
688     // FIXME: We should find a way to share OrderValues's initialization code with RenderFlexibleBox.
689     OrderIterator::OrderValues orderValues;
690     size_t maximumRowIndex = std::max<size_t>(1, explicitGridRowCount());
691     size_t maximumColumnIndex = std::max<size_t>(1, explicitGridColumnCount());
692
693     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
694         // Avoid growing the vector for the common-case default value of 0. This optimizes the most common case which is
695         // one or a few values with the default order 0
696         int order = child->style().order();
697         if (orderValues.isEmpty() || orderValues.last() != order)
698             orderValues.append(order);
699
700         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
701         OwnPtr<GridSpan> rowPositions = resolveGridPositionsFromStyle(child, ForRows);
702         OwnPtr<GridSpan> columnPositions = resolveGridPositionsFromStyle(child, ForColumns);
703
704         // |positions| is 0 if we need to run the auto-placement algorithm. Our estimation ignores
705         // this case as the auto-placement algorithm will grow the grid as needed.
706         if (rowPositions)
707             maximumRowIndex = std::max(maximumRowIndex, rowPositions->finalPositionIndex + 1);
708         if (columnPositions)
709             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->finalPositionIndex + 1);
710     }
711
712     m_grid.grow(maximumRowIndex);
713     for (size_t i = 0; i < m_grid.size(); ++i)
714         m_grid[i].grow(maximumColumnIndex);
715
716     m_orderIterator.setOrderValues(std::move(orderValues));
717 }
718
719 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(Vector<RenderBox*> autoGridItems)
720 {
721     for (size_t i = 0; i < autoGridItems.size(); ++i) {
722         OwnPtr<GridSpan> majorAxisPositions = resolveGridPositionsFromStyle(autoGridItems[i], autoPlacementMajorAxisDirection());
723         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->initialPositionIndex);
724         if (OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
725             insertItemIntoGrid(autoGridItems[i], emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
726             continue;
727         }
728
729         growGrid(autoPlacementMinorAxisDirection());
730         OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea();
731         ASSERT(emptyGridArea);
732         insertItemIntoGrid(autoGridItems[i], emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
733     }
734 }
735
736 void RenderGrid::placeAutoMajorAxisItemsOnGrid(Vector<RenderBox*> autoGridItems)
737 {
738     for (size_t i = 0; i < autoGridItems.size(); ++i)
739         placeAutoMajorAxisItemOnGrid(autoGridItems[i]);
740 }
741
742 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox* gridItem)
743 {
744     OwnPtr<GridSpan> minorAxisPositions = resolveGridPositionsFromStyle(gridItem, autoPlacementMinorAxisDirection());
745     ASSERT(!resolveGridPositionsFromStyle(gridItem, autoPlacementMajorAxisDirection()));
746     size_t minorAxisIndex = 0;
747     if (minorAxisPositions) {
748         minorAxisIndex = minorAxisPositions->initialPositionIndex;
749         GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisIndex);
750         if (OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
751             insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
752             return;
753         }
754     } else {
755         const size_t endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
756         for (size_t majorAxisIndex = 0; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
757             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex);
758             if (OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
759                 insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
760                 return;
761             }
762         }
763     }
764
765     // We didn't find an empty grid area so we need to create an extra major axis line and insert our gridItem in it.
766     const size_t columnIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? m_grid[0].size() : minorAxisIndex;
767     const size_t rowIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? minorAxisIndex : m_grid.size();
768     growGrid(autoPlacementMajorAxisDirection());
769     insertItemIntoGrid(gridItem, rowIndex, columnIndex);
770 }
771
772 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
773 {
774     GridAutoFlow flow = style().gridAutoFlow();
775     ASSERT(flow != AutoFlowNone);
776     return (flow == AutoFlowColumn) ? ForColumns : ForRows;
777 }
778
779 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
780 {
781     GridAutoFlow flow = style().gridAutoFlow();
782     ASSERT(flow != AutoFlowNone);
783     return (flow == AutoFlowColumn) ? ForRows : ForColumns;
784 }
785
786 void RenderGrid::clearGrid()
787 {
788     m_grid.clear();
789     m_gridItemCoordinate.clear();
790 }
791
792 void RenderGrid::layoutGridItems()
793 {
794     placeItemsOnGrid();
795
796     GridSizingData sizingData(gridColumnCount(), gridRowCount());
797     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
798     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
799     computeUsedBreadthOfGridTracks(ForRows, sizingData);
800     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
801
802     populateGridPositions(sizingData);
803
804     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
805         // Because the grid area cannot be styled, we don't need to adjust
806         // the grid breadth to account for 'box-sizing'.
807         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
808         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
809
810         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, sizingData.columnTracks);
811         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, sizingData.rowTracks);
812         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && (child->hasRelativeLogicalHeight() || child->hasViewportPercentageLogicalHeight())))
813             child->setNeedsLayout(MarkOnlyThis);
814
815         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
816         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
817
818         LayoutRect oldChildRect = child->frameRect();
819
820         // FIXME: Grid items should stretch to fill their cells. Once we
821         // implement grid-{column,row}-align, we can also shrink to fit. For
822         // now, just size as if we were a regular child.
823         child->layoutIfNeeded();
824
825         child->setLogicalLocation(findChildLogicalPosition(child, sizingData));
826
827         // If the child moved, we have to repaint it as well as any floating/positioned
828         // descendants. An exception is if we need a layout. In this case, we know we're going to
829         // repaint ourselves (and the child) anyway.
830         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
831             child->repaintDuringLayoutIfMoved(oldChildRect);
832     }
833
834     for (size_t i = 0; i < sizingData.rowTracks.size(); ++i)
835         setLogicalHeight(logicalHeight() + sizingData.rowTracks[i].m_usedBreadth);
836
837     // FIXME: We should handle min / max logical height.
838
839     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
840     clearGrid();
841 }
842
843 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox* gridItem) const
844 {
845     ASSERT(m_gridItemCoordinate.contains(gridItem));
846     return m_gridItemCoordinate.get(gridItem);
847 }
848
849 GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, GridTrackSizingDirection, size_t initialPosition) const
850 {
851     // FIXME: We don't support spanning with auto positions yet. Once we do, this is wrong. Also we should make
852     // sure the grid can accomodate the new item as we only grow 1 position in a given direction.
853     return GridSpan(initialPosition, initialPosition);
854 }
855
856 PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, GridTrackSizingDirection direction) const
857 {
858     const GridPosition& initialPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnStart() : gridItem->style().gridItemRowStart();
859     const GridPositionSide initialPositionSide = (direction == ForColumns) ? ColumnStartSide : RowStartSide;
860     const GridPosition& finalPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnEnd() : gridItem->style().gridItemRowEnd();
861     const GridPositionSide finalPositionSide = (direction == ForColumns) ? ColumnEndSide : RowEndSide;
862
863     // We should NEVER see both spans as they should have been handled during style resolve.
864     ASSERT(!initialPosition.isSpan() || !finalPosition.isSpan());
865
866     if (initialPosition.shouldBeResolvedAgainstOppositePosition() && finalPosition.shouldBeResolvedAgainstOppositePosition()) {
867         if (style().gridAutoFlow() == AutoFlowNone)
868             return adoptPtr(new GridSpan(0, 0));
869
870         // We can't get our grid positions without running the auto placement algorithm.
871         return nullptr;
872     }
873
874     if (initialPosition.shouldBeResolvedAgainstOppositePosition()) {
875         // Infer the position from the final position ('auto / 1' or 'span 2 / 3' case).
876         const size_t finalResolvedPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
877         return resolveGridPositionAgainstOppositePosition(finalResolvedPosition, initialPosition, initialPositionSide);
878     }
879
880     if (finalPosition.shouldBeResolvedAgainstOppositePosition()) {
881         // Infer our position from the initial position ('1 / auto' or '3 / span 2' case).
882         const size_t initialResolvedPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
883         return resolveGridPositionAgainstOppositePosition(initialResolvedPosition, finalPosition, finalPositionSide);
884     }
885
886     size_t resolvedInitialPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
887     size_t resolvedFinalPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
888
889     // If 'grid-row-end' specifies a line at or before that specified by 'grid-row-start', it computes to 'span 1'.
890     if (resolvedFinalPosition < resolvedInitialPosition)
891         resolvedFinalPosition = resolvedInitialPosition;
892
893     return adoptPtr(new GridSpan(resolvedInitialPosition, resolvedFinalPosition));
894 }
895
896 inline static size_t adjustGridPositionForRowEndColumnEndSide(size_t resolvedPosition)
897 {
898     return resolvedPosition ? resolvedPosition - 1 : 0;
899 }
900
901 static size_t adjustGridPositionForSide(size_t resolvedPosition, RenderGrid::GridPositionSide side)
902 {
903     // An item finishing on the N-th line belongs to the N-1-th cell.
904     if (side == RenderGrid::ColumnEndSide || side == RenderGrid::RowEndSide)
905         return adjustGridPositionForRowEndColumnEndSide(resolvedPosition);
906
907     return resolvedPosition;
908 }
909
910 size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& position, GridPositionSide side) const
911 {
912     ASSERT(!position.namedGridLine().isNull());
913
914     const NamedGridLinesMap& gridLinesNames = (side == ColumnStartSide || side == ColumnEndSide) ? style().namedGridColumnLines() : style().namedGridRowLines();
915     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
916     if (it == gridLinesNames.end()) {
917         if (position.isPositive())
918             return 0;
919         const size_t lastLine = explicitGridSizeForSide(side);
920         return adjustGridPositionForSide(lastLine, side);
921     }
922
923     size_t namedGridLineIndex;
924     if (position.isPositive())
925         namedGridLineIndex = std::min<size_t>(position.integerPosition(), it->value.size()) - 1;
926     else
927         namedGridLineIndex = std::max<int>(it->value.size() - abs(position.integerPosition()), 0);
928     return adjustGridPositionForSide(it->value[namedGridLineIndex], side);
929 }
930
931 size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, GridPositionSide side) const
932 {
933     switch (position.type()) {
934     case ExplicitPosition: {
935         ASSERT(position.integerPosition());
936
937         if (!position.namedGridLine().isNull())
938             return resolveNamedGridLinePositionFromStyle(position, side);
939
940         // Handle <integer> explicit position.
941         if (position.isPositive())
942             return adjustGridPositionForSide(position.integerPosition() - 1, side);
943
944         size_t resolvedPosition = abs(position.integerPosition()) - 1;
945         const size_t endOfTrack = explicitGridSizeForSide(side);
946
947         // Per http://lists.w3.org/Archives/Public/www-style/2013Mar/0589.html, we clamp negative value to the first line.
948         if (endOfTrack < resolvedPosition)
949             return 0;
950
951         return adjustGridPositionForSide(endOfTrack - resolvedPosition, side);
952     }
953     case NamedGridAreaPosition:
954     {
955         NamedGridAreaMap::const_iterator it = style().namedGridArea().find(position.namedGridLine());
956         // Unknown grid area should have been computed to 'auto' by now.
957         ASSERT(it != style().namedGridArea().end());
958         const GridCoordinate& gridAreaCoordinate = it->value;
959         switch (side) {
960         case ColumnStartSide:
961             return gridAreaCoordinate.columns.initialPositionIndex;
962         case ColumnEndSide:
963             return gridAreaCoordinate.columns.finalPositionIndex;
964         case RowStartSide:
965             return gridAreaCoordinate.rows.initialPositionIndex;
966         case RowEndSide:
967             return gridAreaCoordinate.rows.finalPositionIndex;
968         }
969         ASSERT_NOT_REACHED();
970         return 0;
971     }
972     case AutoPosition:
973     case SpanPosition:
974         // 'auto' and span depend on the opposite position for resolution (e.g. grid-row: auto / 1 or grid-column: span 3 / "myHeader").
975         ASSERT_NOT_REACHED();
976         return 0;
977     }
978     ASSERT_NOT_REACHED();
979     return 0;
980 }
981
982 PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
983 {
984     if (position.isAuto())
985         return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition);
986
987     ASSERT(position.isSpan());
988     ASSERT(position.spanPosition() > 0);
989
990     if (!position.namedGridLine().isNull()) {
991         // span 2 'c' -> we need to find the appropriate grid line before / after our opposite position.
992         return resolveNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, side);
993     }
994
995     // 'span 1' is contained inside a single grid track regardless of the direction.
996     // That's why the CSS span value is one more than the offset we apply.
997     size_t positionOffset = position.spanPosition() - 1;
998     if (side == ColumnStartSide || side == RowStartSide) {
999         size_t initialResolvedPosition = std::max<int>(0, resolvedOppositePosition - positionOffset);
1000         return GridSpan::create(initialResolvedPosition, resolvedOppositePosition);
1001     }
1002
1003     return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition + positionOffset);
1004 }
1005
1006 PassOwnPtr<GridSpan> RenderGrid::resolveNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
1007 {
1008     ASSERT(position.isSpan());
1009     ASSERT(!position.namedGridLine().isNull());
1010     // Negative positions are not allowed per the specification and should have been handled during parsing.
1011     ASSERT(position.spanPosition() > 0);
1012
1013     const NamedGridLinesMap& gridLinesNames = (side == ColumnStartSide || side == ColumnEndSide) ? style().namedGridColumnLines() : style().namedGridRowLines();
1014     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
1015
1016     // 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).
1017     // See http://lists.w3.org/Archives/Public/www-style/2013Jun/0394.html.
1018     if (it == gridLinesNames.end())
1019         return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition);
1020
1021     if (side == RowStartSide || side == ColumnStartSide)
1022         return resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1023
1024     return resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1025 }
1026
1027 PassOwnPtr<GridSpan> RenderGrid::resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1028 {
1029     // The grid line inequality needs to be strict (which doesn't match the after / end case) because |resolvedOppositePosition|
1030     // is already converted to an index in our grid representation (ie one was removed from the grid line to account for the side).
1031     size_t firstLineBeforeOppositePositionIndex = 0;
1032     const size_t* firstLineBeforeOppositePosition = std::lower_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
1033     if (firstLineBeforeOppositePosition != gridLines.end())
1034         firstLineBeforeOppositePositionIndex = firstLineBeforeOppositePosition - gridLines.begin();
1035
1036     size_t gridLineIndex = std::max<int>(0, firstLineBeforeOppositePositionIndex - position.spanPosition() + 1);
1037     size_t resolvedGridLinePosition = gridLines[gridLineIndex];
1038     if (resolvedGridLinePosition > resolvedOppositePosition)
1039         resolvedGridLinePosition = resolvedOppositePosition;
1040     return GridSpan::create(resolvedGridLinePosition, resolvedOppositePosition);
1041 }
1042
1043 PassOwnPtr<GridSpan> RenderGrid::resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1044 {
1045     size_t firstLineAfterOppositePositionIndex = gridLines.size() - 1;
1046     const size_t* firstLineAfterOppositePosition = std::upper_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
1047     if (firstLineAfterOppositePosition != gridLines.end())
1048         firstLineAfterOppositePositionIndex = firstLineAfterOppositePosition - gridLines.begin();
1049
1050     size_t gridLineIndex = std::min(gridLines.size() - 1, firstLineAfterOppositePositionIndex + position.spanPosition() - 1);
1051     size_t resolvedGridLinePosition = adjustGridPositionForRowEndColumnEndSide(gridLines[gridLineIndex]);
1052     if (resolvedGridLinePosition < resolvedOppositePosition)
1053         resolvedGridLinePosition = resolvedOppositePosition;
1054     return GridSpan::create(resolvedOppositePosition, resolvedGridLinePosition);
1055 }
1056
1057 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox* child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1058 {
1059     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1060     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1061     LayoutUnit gridAreaBreadth = 0;
1062     for (size_t trackIndex = span.initialPositionIndex; trackIndex <= span.finalPositionIndex; ++trackIndex)
1063         gridAreaBreadth += tracks[trackIndex].m_usedBreadth;
1064     return gridAreaBreadth;
1065 }
1066
1067 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
1068 {
1069     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
1070     m_columnPositions[0] = borderAndPaddingStart();
1071     for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
1072         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
1073
1074     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
1075     m_rowPositions[0] = borderAndPaddingBefore();
1076     for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
1077         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
1078 }
1079
1080 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const GridSizingData& sizingData)
1081 {
1082     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1083     ASSERT_UNUSED(sizingData, coordinate.columns.initialPositionIndex < sizingData.columnTracks.size());
1084     ASSERT_UNUSED(sizingData, coordinate.rows.initialPositionIndex < sizingData.rowTracks.size());
1085
1086     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
1087     return LayoutPoint(m_columnPositions[coordinate.columns.initialPositionIndex] + marginStartForChild(*child), m_rowPositions[coordinate.rows.initialPositionIndex] + marginBeforeForChild(*child));
1088 }
1089
1090 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1091 {
1092     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1093         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect);
1094 }
1095
1096 const char* RenderGrid::renderName() const
1097 {
1098     if (isFloating())
1099         return "RenderGrid (floating)";
1100     if (isOutOfFlowPositioned())
1101         return "RenderGrid (positioned)";
1102     if (isAnonymous())
1103         return "RenderGrid (generated)";
1104     if (isRelPositioned())
1105         return "RenderGrid (relative positioned)";
1106     return "RenderGrid";
1107 }
1108
1109 } // namespace WebCore
1110
1111 #endif /* ENABLE(CSS_GRID_LAYOUT) */