[CSS Grid Layout] handle undefined RemainingSpace in computeUsedBreadthOfGridTracks...
[WebKit-https.git] / Source / WebCore / rendering / RenderGrid.cpp
1 /*
2  * Copyright (C) 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2013 Igalia S.L. All rights reserved.
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 #include "GridCoordinate.h"
31 #include "LayoutRepainter.h"
32 #include "NotImplemented.h"
33 #include "RenderLayer.h"
34 #include "RenderView.h"
35
36 namespace WebCore {
37
38 static const int infinity = -1;
39
40 class GridTrack {
41 public:
42     GridTrack()
43         : m_usedBreadth(0)
44         , m_maxBreadth(0)
45     {
46     }
47
48     void growUsedBreadth(LayoutUnit growth)
49     {
50         ASSERT(growth >= 0);
51         m_usedBreadth += growth;
52     }
53     LayoutUnit usedBreadth() const { return m_usedBreadth; }
54
55     void growMaxBreadth(LayoutUnit growth)
56     {
57         if (m_maxBreadth == infinity)
58             m_maxBreadth = m_usedBreadth + growth;
59         else
60             m_maxBreadth += growth;
61     }
62     LayoutUnit maxBreadthIfNotInfinite() const
63     {
64         return (m_maxBreadth == infinity) ? m_usedBreadth : m_maxBreadth;
65     }
66
67     LayoutUnit m_usedBreadth;
68     LayoutUnit m_maxBreadth;
69 };
70
71 struct GridTrackForNormalization {
72     GridTrackForNormalization(const GridTrack& track, double flex)
73         : m_track(&track)
74         , m_flex(flex)
75         , m_normalizedFlexValue(track.m_usedBreadth / flex)
76     {
77     }
78
79     const GridTrack* m_track;
80     double m_flex;
81     LayoutUnit m_normalizedFlexValue;
82 };
83
84 class RenderGrid::GridIterator {
85     WTF_MAKE_NONCOPYABLE(GridIterator);
86 public:
87     // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
88     // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
89     GridIterator(const Vector<Vector<Vector<RenderBox*, 1>>>& grid, GridTrackSizingDirection direction, size_t fixedTrackIndex)
90         : m_grid(grid)
91         , m_direction(direction)
92         , m_rowIndex((direction == ForColumns) ? 0 : fixedTrackIndex)
93         , m_columnIndex((direction == ForColumns) ? fixedTrackIndex : 0)
94         , m_childIndex(0)
95     {
96         ASSERT(m_rowIndex < m_grid.size());
97         ASSERT(m_columnIndex < m_grid[0].size());
98     }
99
100     RenderBox* nextGridItem()
101     {
102         if (!m_grid.size())
103             return 0;
104
105         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
106         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
107         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
108             const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
109             if (m_childIndex < children.size())
110                 return children[m_childIndex++];
111
112             m_childIndex = 0;
113         }
114         return 0;
115     }
116
117     PassOwnPtr<GridCoordinate> nextEmptyGridArea()
118     {
119         if (m_grid.isEmpty())
120             return nullptr;
121
122         size_t& varyingTrackIndex = (m_direction == ForColumns) ? m_rowIndex : m_columnIndex;
123         const size_t endOfVaryingTrackIndex = (m_direction == ForColumns) ? m_grid.size() : m_grid[0].size();
124         for (; varyingTrackIndex < endOfVaryingTrackIndex; ++varyingTrackIndex) {
125             const Vector<RenderBox*>& children = m_grid[m_rowIndex][m_columnIndex];
126             if (children.isEmpty()) {
127                 OwnPtr<GridCoordinate> result = adoptPtr(new GridCoordinate(GridSpan(m_rowIndex, m_rowIndex), GridSpan(m_columnIndex, m_columnIndex)));
128                 // Advance the iterator to avoid an infinite loop where we would return the same grid area over and over.
129                 ++varyingTrackIndex;
130                 return result.release();
131             }
132         }
133         return nullptr;
134     }
135
136 private:
137     const Vector<Vector<Vector<RenderBox*, 1>>>& m_grid;
138     GridTrackSizingDirection m_direction;
139     size_t m_rowIndex;
140     size_t m_columnIndex;
141     size_t m_childIndex;
142 };
143
144 class RenderGrid::GridSizingData {
145     WTF_MAKE_NONCOPYABLE(GridSizingData);
146 public:
147     GridSizingData(size_t gridColumnCount, size_t gridRowCount)
148         : columnTracks(gridColumnCount)
149         , rowTracks(gridRowCount)
150     {
151     }
152
153     Vector<GridTrack> columnTracks;
154     Vector<GridTrack> rowTracks;
155     Vector<size_t> contentSizedTracksIndex;
156
157     // Performance optimization: hold onto these Vectors until the end of Layout to avoid repeated malloc / free.
158     Vector<LayoutUnit> distributeTrackVector;
159     Vector<GridTrack*> filteredTracks;
160 };
161
162 RenderGrid::RenderGrid(Element& element, PassRef<RenderStyle> style)
163     : RenderBlock(element, std::move(style), 0)
164     , m_orderIterator(*this)
165 {
166     // All of our children must be block level.
167     setChildrenInline(false);
168 }
169
170 RenderGrid::~RenderGrid()
171 {
172 }
173
174 void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
175 {
176     ASSERT(needsLayout());
177
178     if (!relayoutChildren && simplifiedLayout())
179         return;
180
181     // FIXME: Much of this method is boiler plate that matches RenderBox::layoutBlock and Render*FlexibleBox::layoutBlock.
182     // It would be nice to refactor some of the duplicate code.
183     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
184     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
185
186     prepareShapesAndPaginationBeforeBlockLayout(relayoutChildren);
187
188     LayoutSize previousSize = size();
189
190     setLogicalHeight(0);
191     updateLogicalWidth();
192
193     layoutGridItems();
194
195     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
196     updateLogicalHeight();
197
198     if (size() != previousSize)
199         relayoutChildren = true;
200
201     layoutPositionedObjects(relayoutChildren || isRoot());
202
203     updateShapesAfterBlockLayout();
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     return trackStyles[i];
452 }
453
454 size_t RenderGrid::explicitGridColumnCount() const
455 {
456     return style().gridColumns().size();
457 }
458
459 size_t RenderGrid::explicitGridRowCount() const
460 {
461     return style().gridRows().size();
462 }
463
464 size_t RenderGrid::explicitGridSizeForSide(GridPositionSide side) const
465 {
466     return (side == ColumnStartSide || side == ColumnEndSide) ? explicitGridColumnCount() : explicitGridRowCount();
467 }
468
469 LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox* child, Vector<GridTrack>& columnTracks)
470 {
471     LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
472     LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
473     if (child->style().logicalHeight().isPercent() || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
474         child->setNeedsLayout(MarkOnlyThis);
475
476     child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
477     // If |child| has a percentage logical height, we shouldn't let it override its intrinsic height, which is
478     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
479     child->setOverrideContainingBlockContentLogicalHeight(-1);
480     child->layoutIfNeeded();
481     return child->logicalHeight();
482 }
483
484 LayoutUnit RenderGrid::minContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
485 {
486     bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
487     // FIXME: Properly support orthogonal writing mode.
488     if (hasOrthogonalWritingMode)
489         return 0;
490
491     if (direction == ForColumns) {
492         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
493         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
494         return child->minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(*child);
495     }
496
497     return logicalContentHeightForChild(child, columnTracks);
498 }
499
500 LayoutUnit RenderGrid::maxContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
501 {
502     bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
503     // FIXME: Properly support orthogonal writing mode.
504     if (hasOrthogonalWritingMode)
505         return LayoutUnit();
506
507     if (direction == ForColumns) {
508         // FIXME: It's unclear if we should return the intrinsic width or the preferred width.
509         // See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
510         return child->maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(*child);
511     }
512
513     return logicalContentHeightForChild(child, columnTracks);
514 }
515
516 void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData)
517 {
518     // FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track.
519
520     for (size_t i = 0; i < sizingData.contentSizedTracksIndex.size(); ++i) {
521         GridIterator iterator(m_grid, direction, sizingData.contentSizedTracksIndex[i]);
522         while (RenderBox* gridItem = iterator.nextGridItem()) {
523             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
524             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
525             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
526             resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
527         }
528
529         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[i] : sizingData.rowTracks[i];
530         if (track.m_maxBreadth == infinity)
531             track.m_maxBreadth = track.m_usedBreadth;
532     }
533 }
534
535 void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, RenderBox* gridItem, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction)
536 {
537     const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
538     const size_t initialTrackIndex = (direction == ForColumns) ? coordinate.columns.initialPositionIndex : coordinate.rows.initialPositionIndex;
539     const size_t finalTrackIndex = (direction == ForColumns) ? coordinate.columns.finalPositionIndex : coordinate.rows.finalPositionIndex;
540
541     sizingData.filteredTracks.shrink(0);
542     for (size_t trackIndex = initialTrackIndex; trackIndex <= finalTrackIndex; ++trackIndex) {
543         const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
544         if (!(trackSize.*filterFunction)())
545             continue;
546
547         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
548         sizingData.filteredTracks.append(&track);
549     }
550
551     if (sizingData.filteredTracks.isEmpty())
552         return;
553
554     LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItem, direction, sizingData.columnTracks);
555     for (size_t trackIndexForSpace = initialTrackIndex; trackIndexForSpace <= finalTrackIndex; ++trackIndexForSpace) {
556         GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndexForSpace] : sizingData.rowTracks[trackIndexForSpace];
557         additionalBreadthSpace -= (track.*trackGetter)();
558     }
559
560     // FIXME: We should pass different values for |tracksForGrowthAboveMaxBreadth|.
561     distributeSpaceToTracks(sizingData.filteredTracks, &sizingData.filteredTracks, trackGetter, trackGrowthFunction, sizingData, additionalBreadthSpace);
562 }
563
564 static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
565 {
566     return (track1->m_maxBreadth - track1->m_usedBreadth) < (track2->m_maxBreadth - track2->m_usedBreadth);
567 }
568
569 void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
570 {
571     std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
572
573     size_t tracksSize = tracks.size();
574     sizingData.distributeTrackVector.resize(tracksSize);
575
576     for (size_t i = 0; i < tracksSize; ++i) {
577         GridTrack& track = *tracks[i];
578         LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
579         LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
580         LayoutUnit growthShare = std::max(LayoutUnit(), std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth));
581         // We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function.
582         sizingData.distributeTrackVector[i] = trackBreadth + growthShare;
583         availableLogicalSpace -= growthShare;
584     }
585
586     if (availableLogicalSpace > 0 && tracksForGrowthAboveMaxBreadth) {
587         tracksSize = tracksForGrowthAboveMaxBreadth->size();
588         for (size_t i = 0; i < tracksSize; ++i) {
589             LayoutUnit growthShare = availableLogicalSpace / (tracksSize - i);
590             sizingData.distributeTrackVector[i] += growthShare;
591             availableLogicalSpace -= growthShare;
592         }
593     }
594
595     for (size_t i = 0; i < tracksSize; ++i) {
596         LayoutUnit growth = sizingData.distributeTrackVector[i] - (tracks[i]->*trackGetter)();
597         if (growth >= 0)
598             (tracks[i]->*trackGrowthFunction)(growth);
599     }
600 }
601
602 #ifndef NDEBUG
603 bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
604 {
605     for (size_t i = 0; i < tracks.size(); ++i) {
606         const GridTrackSize& trackSize = gridTrackSize(direction, i);
607         const GridLength& minTrackBreadth = trackSize.minTrackBreadth();
608         if (computeUsedBreadthOfMinLength(direction, minTrackBreadth) > tracks[i].m_usedBreadth)
609             return false;
610     }
611     return true;
612 }
613 #endif
614
615 void RenderGrid::growGrid(GridTrackSizingDirection direction)
616 {
617     if (direction == ForColumns) {
618         const size_t oldColumnSize = m_grid[0].size();
619         for (size_t row = 0; row < m_grid.size(); ++row)
620             m_grid[row].grow(oldColumnSize + 1);
621     } else {
622         const size_t oldRowSize = m_grid.size();
623         m_grid.grow(oldRowSize + 1);
624         m_grid[oldRowSize].grow(m_grid[0].size());
625     }
626 }
627
628 void RenderGrid::insertItemIntoGrid(RenderBox* child, const GridCoordinate& coordinate)
629 {
630     for (size_t row = coordinate.rows.initialPositionIndex; row <= coordinate.rows.finalPositionIndex; ++row) {
631         for (size_t column = coordinate.columns.initialPositionIndex; column <= coordinate.columns.finalPositionIndex; ++column)
632             m_grid[row][column].append(child);
633     }
634     m_gridItemCoordinate.set(child, coordinate);
635 }
636
637 void RenderGrid::insertItemIntoGrid(RenderBox* child, size_t rowTrack, size_t columnTrack)
638 {
639     const GridSpan& rowSpan = resolveGridPositionsFromAutoPlacementPosition(child, ForRows, rowTrack);
640     const GridSpan& columnSpan = resolveGridPositionsFromAutoPlacementPosition(child, ForColumns, columnTrack);
641     insertItemIntoGrid(child, GridCoordinate(rowSpan, columnSpan));
642 }
643
644 void RenderGrid::placeItemsOnGrid()
645 {
646     ASSERT(!gridWasPopulated());
647     ASSERT(m_gridItemCoordinate.isEmpty());
648
649     populateExplicitGridAndOrderIterator();
650
651     Vector<RenderBox*> autoMajorAxisAutoGridItems;
652     Vector<RenderBox*> specifiedMajorAxisAutoGridItems;
653     GridAutoFlow autoFlow = style().gridAutoFlow();
654     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next()) {
655         // FIXME: We never re-resolve positions if the grid is grown during auto-placement which may lead auto / <integer>
656         // positions to not match the author's intent. The specification is unclear on what should be done in this case.
657         OwnPtr<GridSpan> rowPositions = resolveGridPositionsFromStyle(child, ForRows);
658         OwnPtr<GridSpan> columnPositions = resolveGridPositionsFromStyle(child, ForColumns);
659         if (!rowPositions || !columnPositions) {
660             GridSpan* majorAxisPositions = (autoPlacementMajorAxisDirection() == ForColumns) ? columnPositions.get() : rowPositions.get();
661             if (!majorAxisPositions)
662                 autoMajorAxisAutoGridItems.append(child);
663             else
664                 specifiedMajorAxisAutoGridItems.append(child);
665             continue;
666         }
667         insertItemIntoGrid(child, GridCoordinate(*rowPositions, *columnPositions));
668     }
669
670     ASSERT(gridRowCount() >= style().gridRows().size());
671     ASSERT(gridColumnCount() >= style().gridColumns().size());
672
673     if (autoFlow == AutoFlowNone) {
674         // If we did collect some grid items, they won't be placed thus never laid out.
675         ASSERT(!autoMajorAxisAutoGridItems.size());
676         ASSERT(!specifiedMajorAxisAutoGridItems.size());
677         return;
678     }
679
680     placeSpecifiedMajorAxisItemsOnGrid(specifiedMajorAxisAutoGridItems);
681     placeAutoMajorAxisItemsOnGrid(autoMajorAxisAutoGridItems);
682 }
683
684 void RenderGrid::populateExplicitGridAndOrderIterator()
685 {
686     // FIXME: We should find a way to share OrderValues's initialization code with RenderFlexibleBox.
687     OrderIterator::OrderValues orderValues;
688     size_t maximumRowIndex = std::max<size_t>(1, explicitGridRowCount());
689     size_t maximumColumnIndex = std::max<size_t>(1, explicitGridColumnCount());
690
691     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
692         // Avoid growing the vector for the common-case default value of 0. This optimizes the most common case which is
693         // one or a few values with the default order 0
694         int order = child->style().order();
695         if (orderValues.isEmpty() || orderValues.last() != order)
696             orderValues.append(order);
697
698         // This function bypasses the cache (cachedGridCoordinate()) as it is used to build it.
699         OwnPtr<GridSpan> rowPositions = resolveGridPositionsFromStyle(child, ForRows);
700         OwnPtr<GridSpan> columnPositions = resolveGridPositionsFromStyle(child, ForColumns);
701
702         // |positions| is 0 if we need to run the auto-placement algorithm. Our estimation ignores
703         // this case as the auto-placement algorithm will grow the grid as needed.
704         if (rowPositions)
705             maximumRowIndex = std::max(maximumRowIndex, rowPositions->finalPositionIndex + 1);
706         if (columnPositions)
707             maximumColumnIndex = std::max(maximumColumnIndex, columnPositions->finalPositionIndex + 1);
708     }
709
710     m_grid.grow(maximumRowIndex);
711     for (size_t i = 0; i < m_grid.size(); ++i)
712         m_grid[i].grow(maximumColumnIndex);
713
714     m_orderIterator.setOrderValues(std::move(orderValues));
715 }
716
717 void RenderGrid::placeSpecifiedMajorAxisItemsOnGrid(Vector<RenderBox*> autoGridItems)
718 {
719     for (size_t i = 0; i < autoGridItems.size(); ++i) {
720         OwnPtr<GridSpan> majorAxisPositions = resolveGridPositionsFromStyle(autoGridItems[i], autoPlacementMajorAxisDirection());
721         GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisPositions->initialPositionIndex);
722         if (OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
723             insertItemIntoGrid(autoGridItems[i], emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
724             continue;
725         }
726
727         growGrid(autoPlacementMinorAxisDirection());
728         OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea();
729         ASSERT(emptyGridArea);
730         insertItemIntoGrid(autoGridItems[i], emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
731     }
732 }
733
734 void RenderGrid::placeAutoMajorAxisItemsOnGrid(Vector<RenderBox*> autoGridItems)
735 {
736     for (size_t i = 0; i < autoGridItems.size(); ++i)
737         placeAutoMajorAxisItemOnGrid(autoGridItems[i]);
738 }
739
740 void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox* gridItem)
741 {
742     OwnPtr<GridSpan> minorAxisPositions = resolveGridPositionsFromStyle(gridItem, autoPlacementMinorAxisDirection());
743     ASSERT(!resolveGridPositionsFromStyle(gridItem, autoPlacementMajorAxisDirection()));
744     size_t minorAxisIndex = 0;
745     if (minorAxisPositions) {
746         minorAxisIndex = minorAxisPositions->initialPositionIndex;
747         GridIterator iterator(m_grid, autoPlacementMinorAxisDirection(), minorAxisIndex);
748         if (OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
749             insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
750             return;
751         }
752     } else {
753         const size_t endOfMajorAxis = (autoPlacementMajorAxisDirection() == ForColumns) ? gridColumnCount() : gridRowCount();
754         for (size_t majorAxisIndex = 0; majorAxisIndex < endOfMajorAxis; ++majorAxisIndex) {
755             GridIterator iterator(m_grid, autoPlacementMajorAxisDirection(), majorAxisIndex);
756             if (OwnPtr<GridCoordinate> emptyGridArea = iterator.nextEmptyGridArea()) {
757                 insertItemIntoGrid(gridItem, emptyGridArea->rows.initialPositionIndex, emptyGridArea->columns.initialPositionIndex);
758                 return;
759             }
760         }
761     }
762
763     // We didn't find an empty grid area so we need to create an extra major axis line and insert our gridItem in it.
764     const size_t columnIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? m_grid[0].size() : minorAxisIndex;
765     const size_t rowIndex = (autoPlacementMajorAxisDirection() == ForColumns) ? minorAxisIndex : m_grid.size();
766     growGrid(autoPlacementMajorAxisDirection());
767     insertItemIntoGrid(gridItem, rowIndex, columnIndex);
768 }
769
770 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
771 {
772     GridAutoFlow flow = style().gridAutoFlow();
773     ASSERT(flow != AutoFlowNone);
774     return (flow == AutoFlowColumn) ? ForColumns : ForRows;
775 }
776
777 RenderGrid::GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
778 {
779     GridAutoFlow flow = style().gridAutoFlow();
780     ASSERT(flow != AutoFlowNone);
781     return (flow == AutoFlowColumn) ? ForRows : ForColumns;
782 }
783
784 void RenderGrid::clearGrid()
785 {
786     m_grid.clear();
787     m_gridItemCoordinate.clear();
788 }
789
790 void RenderGrid::layoutGridItems()
791 {
792     placeItemsOnGrid();
793
794     GridSizingData sizingData(gridColumnCount(), gridRowCount());
795     computeUsedBreadthOfGridTracks(ForColumns, sizingData);
796     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
797     computeUsedBreadthOfGridTracks(ForRows, sizingData);
798     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
799
800     populateGridPositions(sizingData);
801
802     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
803         // Because the grid area cannot be styled, we don't need to adjust
804         // the grid breadth to account for 'box-sizing'.
805         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
806         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
807
808         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, sizingData.columnTracks);
809         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, sizingData.rowTracks);
810         if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && (child->hasRelativeLogicalHeight() || child->hasViewportPercentageLogicalHeight())))
811             child->setNeedsLayout(MarkOnlyThis);
812
813         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
814         child->setOverrideContainingBlockContentLogicalHeight(overrideContainingBlockContentLogicalHeight);
815
816         LayoutRect oldChildRect = child->frameRect();
817
818         // FIXME: Grid items should stretch to fill their cells. Once we
819         // implement grid-{column,row}-align, we can also shrink to fit. For
820         // now, just size as if we were a regular child.
821         child->layoutIfNeeded();
822
823         child->setLogicalLocation(findChildLogicalPosition(child, sizingData));
824
825         // If the child moved, we have to repaint it as well as any floating/positioned
826         // descendants. An exception is if we need a layout. In this case, we know we're going to
827         // repaint ourselves (and the child) anyway.
828         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
829             child->repaintDuringLayoutIfMoved(oldChildRect);
830     }
831
832     for (size_t i = 0; i < sizingData.rowTracks.size(); ++i)
833         setLogicalHeight(logicalHeight() + sizingData.rowTracks[i].m_usedBreadth);
834
835     // FIXME: We should handle min / max logical height.
836
837     setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
838     clearGrid();
839 }
840
841 GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox* gridItem) const
842 {
843     ASSERT(m_gridItemCoordinate.contains(gridItem));
844     return m_gridItemCoordinate.get(gridItem);
845 }
846
847 GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, GridTrackSizingDirection, size_t initialPosition) const
848 {
849     // FIXME: We don't support spanning with auto positions yet. Once we do, this is wrong. Also we should make
850     // sure the grid can accomodate the new item as we only grow 1 position in a given direction.
851     return GridSpan(initialPosition, initialPosition);
852 }
853
854 PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, GridTrackSizingDirection direction) const
855 {
856     const GridPosition& initialPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnStart() : gridItem->style().gridItemRowStart();
857     const GridPositionSide initialPositionSide = (direction == ForColumns) ? ColumnStartSide : RowStartSide;
858     const GridPosition& finalPosition = (direction == ForColumns) ? gridItem->style().gridItemColumnEnd() : gridItem->style().gridItemRowEnd();
859     const GridPositionSide finalPositionSide = (direction == ForColumns) ? ColumnEndSide : RowEndSide;
860
861     // We should NEVER see both spans as they should have been handled during style resolve.
862     ASSERT(!initialPosition.isSpan() || !finalPosition.isSpan());
863
864     if (initialPosition.shouldBeResolvedAgainstOppositePosition() && finalPosition.shouldBeResolvedAgainstOppositePosition()) {
865         if (style().gridAutoFlow() == AutoFlowNone)
866             return adoptPtr(new GridSpan(0, 0));
867
868         // We can't get our grid positions without running the auto placement algorithm.
869         return nullptr;
870     }
871
872     if (initialPosition.shouldBeResolvedAgainstOppositePosition()) {
873         // Infer the position from the final position ('auto / 1' or 'span 2 / 3' case).
874         const size_t finalResolvedPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
875         return resolveGridPositionAgainstOppositePosition(finalResolvedPosition, initialPosition, initialPositionSide);
876     }
877
878     if (finalPosition.shouldBeResolvedAgainstOppositePosition()) {
879         // Infer our position from the initial position ('1 / auto' or '3 / span 2' case).
880         const size_t initialResolvedPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
881         return resolveGridPositionAgainstOppositePosition(initialResolvedPosition, finalPosition, finalPositionSide);
882     }
883
884     size_t resolvedInitialPosition = resolveGridPositionFromStyle(initialPosition, initialPositionSide);
885     size_t resolvedFinalPosition = resolveGridPositionFromStyle(finalPosition, finalPositionSide);
886
887     // If 'grid-row-end' specifies a line at or before that specified by 'grid-row-start', it computes to 'span 1'.
888     if (resolvedFinalPosition < resolvedInitialPosition)
889         resolvedFinalPosition = resolvedInitialPosition;
890
891     return adoptPtr(new GridSpan(resolvedInitialPosition, resolvedFinalPosition));
892 }
893
894 inline static size_t adjustGridPositionForRowEndColumnEndSide(size_t resolvedPosition)
895 {
896     return resolvedPosition ? resolvedPosition - 1 : 0;
897 }
898
899 static size_t adjustGridPositionForSide(size_t resolvedPosition, RenderGrid::GridPositionSide side)
900 {
901     // An item finishing on the N-th line belongs to the N-1-th cell.
902     if (side == RenderGrid::ColumnEndSide || side == RenderGrid::RowEndSide)
903         return adjustGridPositionForRowEndColumnEndSide(resolvedPosition);
904
905     return resolvedPosition;
906 }
907
908 size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& position, GridPositionSide side) const
909 {
910     ASSERT(!position.namedGridLine().isNull());
911
912     const NamedGridLinesMap& gridLinesNames = (side == ColumnStartSide || side == ColumnEndSide) ? style().namedGridColumnLines() : style().namedGridRowLines();
913     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
914     if (it == gridLinesNames.end()) {
915         if (position.isPositive())
916             return 0;
917         const size_t lastLine = explicitGridSizeForSide(side);
918         return adjustGridPositionForSide(lastLine, side);
919     }
920
921     size_t namedGridLineIndex;
922     if (position.isPositive())
923         namedGridLineIndex = std::min<size_t>(position.integerPosition(), it->value.size()) - 1;
924     else
925         namedGridLineIndex = std::max<int>(it->value.size() - abs(position.integerPosition()), 0);
926     return adjustGridPositionForSide(it->value[namedGridLineIndex], side);
927 }
928
929 size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, GridPositionSide side) const
930 {
931     switch (position.type()) {
932     case ExplicitPosition: {
933         ASSERT(position.integerPosition());
934
935         if (!position.namedGridLine().isNull())
936             return resolveNamedGridLinePositionFromStyle(position, side);
937
938         // Handle <integer> explicit position.
939         if (position.isPositive())
940             return adjustGridPositionForSide(position.integerPosition() - 1, side);
941
942         size_t resolvedPosition = abs(position.integerPosition()) - 1;
943         const size_t endOfTrack = explicitGridSizeForSide(side);
944
945         // Per http://lists.w3.org/Archives/Public/www-style/2013Mar/0589.html, we clamp negative value to the first line.
946         if (endOfTrack < resolvedPosition)
947             return 0;
948
949         return adjustGridPositionForSide(endOfTrack - resolvedPosition, side);
950     }
951     case NamedGridAreaPosition:
952     {
953         NamedGridAreaMap::const_iterator it = style().namedGridArea().find(position.namedGridLine());
954         // Unknown grid area should have been computed to 'auto' by now.
955         ASSERT(it != style().namedGridArea().end());
956         const GridCoordinate& gridAreaCoordinate = it->value;
957         switch (side) {
958         case ColumnStartSide:
959             return gridAreaCoordinate.columns.initialPositionIndex;
960         case ColumnEndSide:
961             return gridAreaCoordinate.columns.finalPositionIndex;
962         case RowStartSide:
963             return gridAreaCoordinate.rows.initialPositionIndex;
964         case RowEndSide:
965             return gridAreaCoordinate.rows.finalPositionIndex;
966         }
967         ASSERT_NOT_REACHED();
968         return 0;
969     }
970     case AutoPosition:
971     case SpanPosition:
972         // 'auto' and span depend on the opposite position for resolution (e.g. grid-row: auto / 1 or grid-column: span 3 / "myHeader").
973         ASSERT_NOT_REACHED();
974         return 0;
975     }
976     ASSERT_NOT_REACHED();
977     return 0;
978 }
979
980 PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
981 {
982     if (position.isAuto())
983         return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition);
984
985     ASSERT(position.isSpan());
986     ASSERT(position.spanPosition() > 0);
987
988     if (!position.namedGridLine().isNull()) {
989         // span 2 'c' -> we need to find the appropriate grid line before / after our opposite position.
990         return resolveNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, side);
991     }
992
993     // 'span 1' is contained inside a single grid track regardless of the direction.
994     // That's why the CSS span value is one more than the offset we apply.
995     size_t positionOffset = position.spanPosition() - 1;
996     if (side == ColumnStartSide || side == RowStartSide) {
997         size_t initialResolvedPosition = std::max<int>(0, resolvedOppositePosition - positionOffset);
998         return GridSpan::create(initialResolvedPosition, resolvedOppositePosition);
999     }
1000
1001     return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition + positionOffset);
1002 }
1003
1004 PassOwnPtr<GridSpan> RenderGrid::resolveNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
1005 {
1006     ASSERT(position.isSpan());
1007     ASSERT(!position.namedGridLine().isNull());
1008     // Negative positions are not allowed per the specification and should have been handled during parsing.
1009     ASSERT(position.spanPosition() > 0);
1010
1011     const NamedGridLinesMap& gridLinesNames = (side == ColumnStartSide || side == ColumnEndSide) ? style().namedGridColumnLines() : style().namedGridRowLines();
1012     NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
1013
1014     // 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).
1015     // See http://lists.w3.org/Archives/Public/www-style/2013Jun/0394.html.
1016     if (it == gridLinesNames.end())
1017         return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition);
1018
1019     if (side == RowStartSide || side == ColumnStartSide)
1020         return resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1021
1022     return resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
1023 }
1024
1025 PassOwnPtr<GridSpan> RenderGrid::resolveRowStartColumnStartNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1026 {
1027     // The grid line inequality needs to be strict (which doesn't match the after / end case) because |resolvedOppositePosition|
1028     // is already converted to an index in our grid representation (ie one was removed from the grid line to account for the side).
1029     size_t firstLineBeforeOppositePositionIndex = 0;
1030     const size_t* firstLineBeforeOppositePosition = std::lower_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
1031     if (firstLineBeforeOppositePosition != gridLines.end())
1032         firstLineBeforeOppositePositionIndex = firstLineBeforeOppositePosition - gridLines.begin();
1033
1034     size_t gridLineIndex = std::max<int>(0, firstLineBeforeOppositePositionIndex - position.spanPosition() + 1);
1035     size_t resolvedGridLinePosition = gridLines[gridLineIndex];
1036     if (resolvedGridLinePosition > resolvedOppositePosition)
1037         resolvedGridLinePosition = resolvedOppositePosition;
1038     return GridSpan::create(resolvedGridLinePosition, resolvedOppositePosition);
1039 }
1040
1041 PassOwnPtr<GridSpan> RenderGrid::resolveRowEndColumnEndNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
1042 {
1043     size_t firstLineAfterOppositePositionIndex = gridLines.size() - 1;
1044     const size_t* firstLineAfterOppositePosition = std::upper_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
1045     if (firstLineAfterOppositePosition != gridLines.end())
1046         firstLineAfterOppositePositionIndex = firstLineAfterOppositePosition - gridLines.begin();
1047
1048     size_t gridLineIndex = std::min(gridLines.size() - 1, firstLineAfterOppositePositionIndex + position.spanPosition() - 1);
1049     size_t resolvedGridLinePosition = adjustGridPositionForRowEndColumnEndSide(gridLines[gridLineIndex]);
1050     if (resolvedGridLinePosition < resolvedOppositePosition)
1051         resolvedGridLinePosition = resolvedOppositePosition;
1052     return GridSpan::create(resolvedOppositePosition, resolvedGridLinePosition);
1053 }
1054
1055 LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox* child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
1056 {
1057     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1058     const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
1059     LayoutUnit gridAreaBreadth = 0;
1060     for (size_t trackIndex = span.initialPositionIndex; trackIndex <= span.finalPositionIndex; ++trackIndex)
1061         gridAreaBreadth += tracks[trackIndex].m_usedBreadth;
1062     return gridAreaBreadth;
1063 }
1064
1065 void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
1066 {
1067     m_columnPositions.resizeToFit(sizingData.columnTracks.size() + 1);
1068     m_columnPositions[0] = borderAndPaddingStart();
1069     for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
1070         m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
1071
1072     m_rowPositions.resizeToFit(sizingData.rowTracks.size() + 1);
1073     m_rowPositions[0] = borderAndPaddingBefore();
1074     for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
1075         m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
1076 }
1077
1078 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const GridSizingData& sizingData)
1079 {
1080     const GridCoordinate& coordinate = cachedGridCoordinate(child);
1081     ASSERT_UNUSED(sizingData, coordinate.columns.initialPositionIndex < sizingData.columnTracks.size());
1082     ASSERT_UNUSED(sizingData, coordinate.rows.initialPositionIndex < sizingData.rowTracks.size());
1083
1084     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
1085     return LayoutPoint(m_columnPositions[coordinate.columns.initialPositionIndex] + marginStartForChild(*child), m_rowPositions[coordinate.rows.initialPositionIndex] + marginBeforeForChild(*child));
1086 }
1087
1088 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& forChild, bool usePrintRect)
1089 {
1090     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
1091         paintChild(*child, paintInfo, paintOffset, forChild, usePrintRect);
1092 }
1093
1094 const char* RenderGrid::renderName() const
1095 {
1096     if (isFloating())
1097         return "RenderGrid (floating)";
1098     if (isOutOfFlowPositioned())
1099         return "RenderGrid (positioned)";
1100     if (isAnonymous())
1101         return "RenderGrid (generated)";
1102     if (isRelPositioned())
1103         return "RenderGrid (relative positioned)";
1104     return "RenderGrid";
1105 }
1106
1107 } // namespace WebCore