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