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