Fix the issue that Web Audio test case fails on PR3.
[framework/web/webkit-efl.git] / Source / WebCore / rendering / RenderFlexibleBox.cpp
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "RenderFlexibleBox.h"
33
34 #include "LayoutRepainter.h"
35 #include "RenderLayer.h"
36 #include "RenderView.h"
37 #include <limits>
38 #include <wtf/MathExtras.h>
39
40 namespace WebCore {
41
42 class RenderFlexibleBox::OrderIterator {
43 public:
44     OrderIterator(RenderFlexibleBox* flexibleBox, const OrderHashSet& orderValues)
45         : m_flexibleBox(flexibleBox)
46         , m_currentChild(0)
47         , m_orderValuesIterator(0)
48     {
49         copyToVector(orderValues, m_orderValues);
50         std::sort(m_orderValues.begin(), m_orderValues.end());
51         first();
52     }
53
54     RenderBox* currentChild() { return m_currentChild; }
55
56     RenderBox* first()
57     {
58         reset();
59         return next();
60     }
61
62     RenderBox* next()
63     {
64         do {
65             if (!m_currentChild) {
66                 if (m_orderValuesIterator == m_orderValues.end())
67                     return 0;
68                 if (m_orderValuesIterator) {
69                     ++m_orderValuesIterator;
70                     if (m_orderValuesIterator == m_orderValues.end())
71                         return 0;
72                 } else
73                     m_orderValuesIterator = m_orderValues.begin();
74
75                 m_currentChild = m_flexibleBox->firstChildBox();
76             } else
77                 m_currentChild = m_currentChild->nextSiblingBox();
78         } while (!m_currentChild || m_currentChild->style()->order() != *m_orderValuesIterator);
79
80         return m_currentChild;
81     }
82
83     void reset()
84     {
85         m_currentChild = 0;
86         m_orderValuesIterator = 0;
87     }
88
89 private:
90     RenderFlexibleBox* m_flexibleBox;
91     RenderBox* m_currentChild;
92     Vector<float> m_orderValues;
93     Vector<float>::const_iterator m_orderValuesIterator;
94 };
95
96 struct RenderFlexibleBox::LineContext {
97     LineContext(LayoutUnit crossAxisOffset, LayoutUnit crossAxisExtent, size_t numberOfChildren, LayoutUnit maxAscent)
98         : crossAxisOffset(crossAxisOffset)
99         , crossAxisExtent(crossAxisExtent)
100         , numberOfChildren(numberOfChildren)
101         , maxAscent(maxAscent)
102     {
103     }
104
105     LayoutUnit crossAxisOffset;
106     LayoutUnit crossAxisExtent;
107     size_t numberOfChildren;
108     LayoutUnit maxAscent;
109 };
110
111 struct RenderFlexibleBox::Violation {
112     Violation(RenderBox* child, LayoutUnit childSize)
113         : child(child)
114         , childSize(childSize)
115     {
116     }
117
118     RenderBox* child;
119     LayoutUnit childSize;
120 };
121
122
123 RenderFlexibleBox::RenderFlexibleBox(Node* node)
124     : RenderBlock(node)
125 {
126     setChildrenInline(false); // All of our children must be block-level.
127 }
128
129 RenderFlexibleBox::~RenderFlexibleBox()
130 {
131 }
132
133 const char* RenderFlexibleBox::renderName() const
134 {
135     return "RenderFlexibleBox";
136 }
137
138 static LayoutUnit marginLogicalWidthForChild(RenderBox* child, RenderStyle* parentStyle)
139 {
140     // A margin has three types: fixed, percentage, and auto (variable).
141     // Auto and percentage margins become 0 when computing min/max width.
142     // Fixed margins can be added in as is.
143     Length marginLeft = child->style()->marginStartUsing(parentStyle);
144     Length marginRight = child->style()->marginEndUsing(parentStyle);
145     LayoutUnit margin = 0;
146     if (marginLeft.isFixed())
147         margin += marginLeft.value();
148     if (marginRight.isFixed())
149         margin += marginRight.value();
150     return margin;
151 }
152
153 void RenderFlexibleBox::computePreferredLogicalWidths()
154 {
155     ASSERT(preferredLogicalWidthsDirty());
156
157     RenderStyle* styleToUse = style();
158     // FIXME: This should probably be checking for isSpecified since you should be able to use percentage, calc or viewport relative values for width.
159     if (styleToUse->logicalWidth().isFixed() && styleToUse->logicalWidth().value() > 0)
160         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = computeContentBoxLogicalWidth(styleToUse->logicalWidth().value());
161     else {
162         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = 0;
163
164         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
165             if (child->isOutOfFlowPositioned())
166                 continue;
167
168             LayoutUnit margin = marginLogicalWidthForChild(child, style());
169             bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
170             LayoutUnit minPreferredLogicalWidth = hasOrthogonalWritingMode ? child->logicalHeight() : child->minPreferredLogicalWidth();
171             LayoutUnit maxPreferredLogicalWidth = hasOrthogonalWritingMode ? child->logicalHeight() : child->maxPreferredLogicalWidth();
172             minPreferredLogicalWidth += margin;
173             maxPreferredLogicalWidth += margin;
174             if (!isColumnFlow()) {
175                 m_maxPreferredLogicalWidth += maxPreferredLogicalWidth;
176                 if (isMultiline()) {
177                     // For multiline, the min preferred width is if you put a break between each item.
178                     m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, minPreferredLogicalWidth);
179                 } else
180                     m_minPreferredLogicalWidth += minPreferredLogicalWidth;
181             } else {
182                 m_minPreferredLogicalWidth = std::max(minPreferredLogicalWidth, m_minPreferredLogicalWidth);
183                 if (isMultiline()) {
184                     // For multiline, the max preferred width is if you put a break between each item.
185                     m_maxPreferredLogicalWidth += maxPreferredLogicalWidth;
186                 } else
187                     m_maxPreferredLogicalWidth = std::max(maxPreferredLogicalWidth, m_maxPreferredLogicalWidth);
188             }
189         }
190
191         m_maxPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
192     }
193
194     LayoutUnit scrollbarWidth = 0;
195     if (hasOverflowClip()) {
196         if (isHorizontalWritingMode() && styleToUse->overflowY() == OSCROLL) {
197             layer()->setHasVerticalScrollbar(true);
198             scrollbarWidth = verticalScrollbarWidth();
199         } else if (!isHorizontalWritingMode() && styleToUse->overflowX() == OSCROLL) {
200             layer()->setHasHorizontalScrollbar(true);
201             scrollbarWidth = horizontalScrollbarHeight();
202         }
203     }
204
205     m_maxPreferredLogicalWidth += scrollbarWidth;
206     m_minPreferredLogicalWidth += scrollbarWidth;
207
208     // FIXME: This should probably be checking for isSpecified since you should be able to use percentage, calc or viewport relative values for min-width.
209     if (styleToUse->logicalMinWidth().isFixed() && styleToUse->logicalMinWidth().value() > 0) {
210         m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMinWidth().value()));
211         m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMinWidth().value()));
212     }
213
214     // FIXME: This should probably be checking for isSpecified since you should be able to use percentage, calc or viewport relative values for maxWidth.
215     if (styleToUse->logicalMaxWidth().isFixed()) {
216         m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMaxWidth().value()));
217         m_minPreferredLogicalWidth = std::min(m_minPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMaxWidth().value()));
218     }
219
220     LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
221     m_minPreferredLogicalWidth += borderAndPadding;
222     m_maxPreferredLogicalWidth += borderAndPadding;
223
224     setPreferredLogicalWidthsDirty(false);
225 }
226
227 void RenderFlexibleBox::layoutBlock(bool relayoutChildren, LayoutUnit)
228 {
229     ASSERT(needsLayout());
230
231     if (!relayoutChildren && simplifiedLayout())
232         return;
233
234     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
235     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
236
237     if (inRenderFlowThread()) {
238         // Regions changing widths can force us to relayout our children.
239         if (logicalWidthChangedInRegions())
240             relayoutChildren = true;
241     }
242     computeInitialRegionRangeForBlock();
243
244     LayoutSize previousSize = size();
245
246     setLogicalHeight(0);
247     computeLogicalWidth();
248
249     m_overflow.clear();
250
251     // For overflow:scroll blocks, ensure we have both scrollbars in place always.
252     if (scrollsOverflow()) {
253         if (style()->overflowX() == OSCROLL)
254             layer()->setHasHorizontalScrollbar(true);
255         if (style()->overflowY() == OSCROLL)
256             layer()->setHasVerticalScrollbar(true);
257     }
258
259     WTF::Vector<LineContext> lineContexts;
260     OrderHashSet orderValues;
261     computeMainAxisPreferredSizes(relayoutChildren, orderValues);
262     m_orderIterator = adoptPtr(new OrderIterator(this, orderValues));
263     layoutFlexItems(*m_orderIterator, lineContexts);
264
265     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
266     computeLogicalHeight();
267     repositionLogicalHeightDependentFlexItems(*m_orderIterator, lineContexts, oldClientAfterEdge);
268
269     if (size() != previousSize)
270         relayoutChildren = true;
271
272     layoutPositionedObjects(relayoutChildren || isRoot());
273
274     computeRegionRangeForBlock();
275
276     // FIXME: css3/flexbox/repaint-rtl-column.html seems to repaint more overflow than it needs to.
277     computeOverflow(oldClientAfterEdge);
278     statePusher.pop();
279
280     updateLayerTransform();
281
282     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
283     // we overflow or not.
284     if (hasOverflowClip())
285         layer()->updateScrollInfoAfterLayout();
286
287     repainter.repaintAfterLayout();
288
289     setNeedsLayout(false);
290 }
291
292 void RenderFlexibleBox::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
293 {
294     ASSERT(m_orderIterator);
295
296     for (RenderBox* child = m_orderIterator->first(); child; child = m_orderIterator->next()) {
297         if (!paintChild(child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
298             return;
299     }
300 }
301
302 void RenderFlexibleBox::repositionLogicalHeightDependentFlexItems(OrderIterator& iterator, WTF::Vector<LineContext>& lineContexts, LayoutUnit& oldClientAfterEdge)
303 {
304     LayoutUnit crossAxisStartEdge = lineContexts.isEmpty() ? ZERO_LAYOUT_UNIT : lineContexts[0].crossAxisOffset;
305     alignFlexLines(iterator, lineContexts);
306
307     // If we have a single line flexbox, the line height is all the available space.
308     // For flex-direction: row, this means we need to use the height, so we do this after calling computeLogicalHeight.
309     if (!isMultiline() && lineContexts.size() == 1)
310         lineContexts[0].crossAxisExtent = crossAxisContentExtent();
311     alignChildren(iterator, lineContexts);
312
313     if (style()->flexWrap() == FlexWrapReverse) {
314         if (isHorizontalFlow())
315             oldClientAfterEdge = clientLogicalBottom();
316         flipForWrapReverse(iterator, lineContexts, crossAxisStartEdge);
317     }
318
319     // direction:rtl + flex-direction:column means the cross-axis direction is flipped.
320     flipForRightToLeftColumn(iterator);
321 }
322
323 bool RenderFlexibleBox::hasOrthogonalFlow(RenderBox* child) const
324 {
325     // FIXME: If the child is a flexbox, then we need to check isHorizontalFlow.
326     return isHorizontalFlow() != child->isHorizontalWritingMode();
327 }
328
329 bool RenderFlexibleBox::isColumnFlow() const
330 {
331     return style()->isColumnFlexDirection();
332 }
333
334 bool RenderFlexibleBox::isHorizontalFlow() const
335 {
336     if (isHorizontalWritingMode())
337         return !isColumnFlow();
338     return isColumnFlow();
339 }
340
341 bool RenderFlexibleBox::isLeftToRightFlow() const
342 {
343     if (isColumnFlow())
344         return style()->writingMode() == TopToBottomWritingMode || style()->writingMode() == LeftToRightWritingMode;
345     return style()->isLeftToRightDirection() ^ (style()->flexDirection() == FlowRowReverse);
346 }
347
348 bool RenderFlexibleBox::isMultiline() const
349 {
350     return style()->flexWrap() != FlexNoWrap;
351 }
352
353 Length RenderFlexibleBox::flexBasisForChild(RenderBox* child) const
354 {
355     Length flexLength = child->style()->flexBasis();
356     if (flexLength.isAuto())
357         flexLength = isHorizontalFlow() ? child->style()->width() : child->style()->height();
358     return flexLength;
359 }
360
361 Length RenderFlexibleBox::crossAxisLength() const
362 {
363     return isHorizontalFlow() ? style()->height() : style()->width();
364 }
365
366 void RenderFlexibleBox::setCrossAxisExtent(LayoutUnit extent)
367 {
368     if (isHorizontalFlow())
369         setHeight(extent);
370     else
371         setWidth(extent);
372 }
373
374 LayoutUnit RenderFlexibleBox::crossAxisExtentForChild(RenderBox* child)
375 {
376     return isHorizontalFlow() ? child->height() : child->width();
377 }
378
379 LayoutUnit RenderFlexibleBox::mainAxisExtentForChild(RenderBox* child)
380 {
381     return isHorizontalFlow() ? child->width() : child->height();
382 }
383
384 LayoutUnit RenderFlexibleBox::crossAxisExtent() const
385 {
386     return isHorizontalFlow() ? height() : width();
387 }
388
389 LayoutUnit RenderFlexibleBox::mainAxisExtent() const
390 {
391     return isHorizontalFlow() ? width() : height();
392 }
393
394 LayoutUnit RenderFlexibleBox::crossAxisContentExtent() const
395 {
396     return isHorizontalFlow() ? contentHeight() : contentWidth();
397 }
398
399 LayoutUnit RenderFlexibleBox::mainAxisContentExtent()
400 {
401     if (isColumnFlow())
402         return std::max(LayoutUnit(0), computeContentLogicalHeightUsing(MainOrPreferredSize, style()->logicalHeight()));
403     return contentLogicalWidth();
404 }
405
406 WritingMode RenderFlexibleBox::transformedWritingMode() const
407 {
408     WritingMode mode = style()->writingMode();
409     if (!isColumnFlow())
410         return mode;
411
412     switch (mode) {
413     case TopToBottomWritingMode:
414     case BottomToTopWritingMode:
415         return style()->isLeftToRightDirection() ? LeftToRightWritingMode : RightToLeftWritingMode;
416     case LeftToRightWritingMode:
417     case RightToLeftWritingMode:
418         return style()->isLeftToRightDirection() ? TopToBottomWritingMode : BottomToTopWritingMode;
419     }
420     ASSERT_NOT_REACHED();
421     return TopToBottomWritingMode;
422 }
423
424 LayoutUnit RenderFlexibleBox::flowAwareBorderStart() const
425 {
426     if (isHorizontalFlow())
427         return isLeftToRightFlow() ? borderLeft() : borderRight();
428     return isLeftToRightFlow() ? borderTop() : borderBottom();
429 }
430
431 LayoutUnit RenderFlexibleBox::flowAwareBorderEnd() const
432 {
433     if (isHorizontalFlow())
434         return isLeftToRightFlow() ? borderRight() : borderLeft();
435     return isLeftToRightFlow() ? borderBottom() : borderTop();
436 }
437
438 LayoutUnit RenderFlexibleBox::flowAwareBorderBefore() const
439 {
440     switch (transformedWritingMode()) {
441     case TopToBottomWritingMode:
442         return borderTop();
443     case BottomToTopWritingMode:
444         return borderBottom();
445     case LeftToRightWritingMode:
446         return borderLeft();
447     case RightToLeftWritingMode:
448         return borderRight();
449     }
450     ASSERT_NOT_REACHED();
451     return borderTop();
452 }
453
454 LayoutUnit RenderFlexibleBox::flowAwareBorderAfter() const
455 {
456     switch (transformedWritingMode()) {
457     case TopToBottomWritingMode:
458         return borderBottom();
459     case BottomToTopWritingMode:
460         return borderTop();
461     case LeftToRightWritingMode:
462         return borderRight();
463     case RightToLeftWritingMode:
464         return borderLeft();
465     }
466     ASSERT_NOT_REACHED();
467     return borderTop();
468 }
469
470 LayoutUnit RenderFlexibleBox::flowAwarePaddingStart() const
471 {
472     if (isHorizontalFlow())
473         return isLeftToRightFlow() ? paddingLeft() : paddingRight();
474     return isLeftToRightFlow() ? paddingTop() : paddingBottom();
475 }
476
477 LayoutUnit RenderFlexibleBox::flowAwarePaddingEnd() const
478 {
479     if (isHorizontalFlow())
480         return isLeftToRightFlow() ? paddingRight() : paddingLeft();
481     return isLeftToRightFlow() ? paddingBottom() : paddingTop();
482 }
483
484 LayoutUnit RenderFlexibleBox::flowAwarePaddingBefore() const
485 {
486     switch (transformedWritingMode()) {
487     case TopToBottomWritingMode:
488         return paddingTop();
489     case BottomToTopWritingMode:
490         return paddingBottom();
491     case LeftToRightWritingMode:
492         return paddingLeft();
493     case RightToLeftWritingMode:
494         return paddingRight();
495     }
496     ASSERT_NOT_REACHED();
497     return paddingTop();
498 }
499
500 LayoutUnit RenderFlexibleBox::flowAwarePaddingAfter() const
501 {
502     switch (transformedWritingMode()) {
503     case TopToBottomWritingMode:
504         return paddingBottom();
505     case BottomToTopWritingMode:
506         return paddingTop();
507     case LeftToRightWritingMode:
508         return paddingRight();
509     case RightToLeftWritingMode:
510         return paddingLeft();
511     }
512     ASSERT_NOT_REACHED();
513     return paddingTop();
514 }
515
516 LayoutUnit RenderFlexibleBox::flowAwareMarginStartForChild(RenderBox* child) const
517 {
518     if (isHorizontalFlow())
519         return isLeftToRightFlow() ? child->marginLeft() : child->marginRight();
520     return isLeftToRightFlow() ? child->marginTop() : child->marginBottom();
521 }
522
523 LayoutUnit RenderFlexibleBox::flowAwareMarginEndForChild(RenderBox* child) const
524 {
525     if (isHorizontalFlow())
526         return isLeftToRightFlow() ? child->marginRight() : child->marginLeft();
527     return isLeftToRightFlow() ? child->marginBottom() : child->marginTop();
528 }
529
530 LayoutUnit RenderFlexibleBox::flowAwareMarginBeforeForChild(RenderBox* child) const
531 {
532     switch (transformedWritingMode()) {
533     case TopToBottomWritingMode:
534         return child->marginTop();
535     case BottomToTopWritingMode:
536         return child->marginBottom();
537     case LeftToRightWritingMode:
538         return child->marginLeft();
539     case RightToLeftWritingMode:
540         return child->marginRight();
541     }
542     ASSERT_NOT_REACHED();
543     return marginTop();
544 }
545
546 LayoutUnit RenderFlexibleBox::flowAwareMarginAfterForChild(RenderBox* child) const
547 {
548     switch (transformedWritingMode()) {
549     case TopToBottomWritingMode:
550         return child->marginBottom();
551     case BottomToTopWritingMode:
552         return child->marginTop();
553     case LeftToRightWritingMode:
554         return child->marginRight();
555     case RightToLeftWritingMode:
556         return child->marginLeft();
557     }
558     ASSERT_NOT_REACHED();
559     return marginBottom();
560 }
561
562 LayoutUnit RenderFlexibleBox::crossAxisMarginExtentForChild(RenderBox* child) const
563 {
564     return isHorizontalFlow() ? child->marginHeight() : child->marginWidth();
565 }
566
567 LayoutUnit RenderFlexibleBox::crossAxisScrollbarExtent() const
568 {
569     return isHorizontalFlow() ? horizontalScrollbarHeight() : verticalScrollbarWidth();
570 }
571
572 LayoutPoint RenderFlexibleBox::flowAwareLocationForChild(RenderBox* child) const
573 {
574     return isHorizontalFlow() ? child->location() : child->location().transposedPoint();
575 }
576
577 void RenderFlexibleBox::setFlowAwareLocationForChild(RenderBox* child, const LayoutPoint& location)
578 {
579     if (isHorizontalFlow())
580         child->setLocation(location);
581     else
582         child->setLocation(location.transposedPoint());
583 }
584
585 LayoutUnit RenderFlexibleBox::mainAxisBorderAndPaddingExtentForChild(RenderBox* child) const
586 {
587     return isHorizontalFlow() ? child->borderAndPaddingWidth() : child->borderAndPaddingHeight();
588 }
589
590 LayoutUnit RenderFlexibleBox::mainAxisScrollbarExtentForChild(RenderBox* child) const
591 {
592     return isHorizontalFlow() ? child->verticalScrollbarWidth() : child->horizontalScrollbarHeight();
593 }
594
595 LayoutUnit RenderFlexibleBox::preferredMainAxisContentExtentForChild(RenderBox* child)
596 {
597     Length flexBasis = flexBasisForChild(child);
598     if (flexBasis.isAuto()) {
599         LayoutUnit mainAxisExtent = hasOrthogonalFlow(child) ? child->logicalHeight() : child->maxPreferredLogicalWidth();
600         return mainAxisExtent - mainAxisBorderAndPaddingExtentForChild(child);
601     }
602     return std::max(LayoutUnit(0), minimumValueForLength(flexBasis, mainAxisContentExtent(), view()));
603 }
604
605 LayoutUnit RenderFlexibleBox::computeAvailableFreeSpace(LayoutUnit preferredMainAxisExtent)
606 {
607     LayoutUnit contentExtent = 0;
608     if (!isColumnFlow())
609         contentExtent = mainAxisContentExtent();
610     else if (hasOverrideHeight())
611         contentExtent = overrideLogicalContentHeight();
612     else {
613         LayoutUnit heightResult = computeContentLogicalHeightUsing(MainOrPreferredSize, style()->logicalHeight());
614         if (heightResult == -1)
615             heightResult = preferredMainAxisExtent;
616         LayoutUnit minHeight = computeContentLogicalHeightUsing(MinSize, style()->logicalMinHeight()); // Leave as -1 if unset.
617         LayoutUnit maxHeight = style()->logicalMaxHeight().isUndefined() ? heightResult : computeContentLogicalHeightUsing(MaxSize, style()->logicalMaxHeight());
618         if (maxHeight == -1)
619             maxHeight = heightResult;
620         heightResult = std::min(maxHeight, heightResult);
621         heightResult = std::max(minHeight, heightResult);
622         contentExtent = heightResult;
623     }
624
625     return contentExtent - preferredMainAxisExtent;
626 }
627
628 void RenderFlexibleBox::layoutFlexItems(OrderIterator& iterator, WTF::Vector<LineContext>& lineContexts)
629 {
630     OrderedFlexItemList orderedChildren;
631     LayoutUnit preferredMainAxisExtent;
632     float totalFlexGrow;
633     float totalWeightedFlexShrink;
634     LayoutUnit minMaxAppliedMainAxisExtent;
635
636     LayoutUnit crossAxisOffset = flowAwareBorderBefore() + flowAwarePaddingBefore();
637     while (computeNextFlexLine(iterator, orderedChildren, preferredMainAxisExtent, totalFlexGrow, totalWeightedFlexShrink, minMaxAppliedMainAxisExtent)) {
638         LayoutUnit availableFreeSpace = computeAvailableFreeSpace(preferredMainAxisExtent);
639         FlexSign flexSign = (minMaxAppliedMainAxisExtent < preferredMainAxisExtent + availableFreeSpace) ? PositiveFlexibility : NegativeFlexibility;
640         InflexibleFlexItemSize inflexibleItems;
641         WTF::Vector<LayoutUnit> childSizes;
642         while (!resolveFlexibleLengths(flexSign, orderedChildren, availableFreeSpace, totalFlexGrow, totalWeightedFlexShrink, inflexibleItems, childSizes)) {
643             ASSERT(totalFlexGrow >= 0 && totalWeightedFlexShrink >= 0);
644             ASSERT(inflexibleItems.size() > 0);
645         }
646
647         layoutAndPlaceChildren(crossAxisOffset, orderedChildren, childSizes, availableFreeSpace, lineContexts);
648     }
649 }
650
651 LayoutUnit RenderFlexibleBox::autoMarginOffsetInMainAxis(const OrderedFlexItemList& children, LayoutUnit& availableFreeSpace)
652 {
653     if (availableFreeSpace <= 0)
654         return 0;
655
656     int numberOfAutoMargins = 0;
657     bool isHorizontal = isHorizontalFlow();
658     for (size_t i = 0; i < children.size(); ++i) {
659         RenderBox* child = children[i];
660         if (child->isOutOfFlowPositioned())
661             continue;
662         if (isHorizontal) {
663             if (child->style()->marginLeft().isAuto())
664                 ++numberOfAutoMargins;
665             if (child->style()->marginRight().isAuto())
666                 ++numberOfAutoMargins;
667         } else {
668             if (child->style()->marginTop().isAuto())
669                 ++numberOfAutoMargins;
670             if (child->style()->marginBottom().isAuto())
671                 ++numberOfAutoMargins;
672         }
673     }
674     if (!numberOfAutoMargins)
675         return 0;
676
677     LayoutUnit sizeOfAutoMargin = availableFreeSpace / numberOfAutoMargins;
678     availableFreeSpace = 0;
679     return sizeOfAutoMargin;
680 }
681
682 void RenderFlexibleBox::updateAutoMarginsInMainAxis(RenderBox* child, LayoutUnit autoMarginOffset)
683 {
684     if (isHorizontalFlow()) {
685         if (child->style()->marginLeft().isAuto())
686             child->setMarginLeft(autoMarginOffset);
687         if (child->style()->marginRight().isAuto())
688             child->setMarginRight(autoMarginOffset);
689     } else {
690         if (child->style()->marginTop().isAuto())
691             child->setMarginTop(autoMarginOffset);
692         if (child->style()->marginBottom().isAuto())
693             child->setMarginBottom(autoMarginOffset);
694     }
695 }
696
697 bool RenderFlexibleBox::hasAutoMarginsInCrossAxis(RenderBox* child)
698 {
699     if (isHorizontalFlow())
700         return child->style()->marginTop().isAuto() || child->style()->marginBottom().isAuto();
701     return child->style()->marginLeft().isAuto() || child->style()->marginRight().isAuto();
702 }
703
704 LayoutUnit RenderFlexibleBox::availableAlignmentSpaceForChild(LayoutUnit lineCrossAxisExtent, RenderBox* child)
705 {
706     LayoutUnit childCrossExtent = 0;
707     if (!child->isOutOfFlowPositioned())
708         childCrossExtent = crossAxisMarginExtentForChild(child) + crossAxisExtentForChild(child);
709     return lineCrossAxisExtent - childCrossExtent;
710 }
711
712 bool RenderFlexibleBox::updateAutoMarginsInCrossAxis(RenderBox* child, LayoutUnit availableAlignmentSpace)
713 {
714     bool isHorizontal = isHorizontalFlow();
715     Length start = isHorizontal ? child->style()->marginTop() : child->style()->marginLeft();
716     Length end = isHorizontal ? child->style()->marginBottom() : child->style()->marginRight();
717     if (start.isAuto() && end.isAuto()) {
718         adjustAlignmentForChild(child, availableAlignmentSpace / 2);
719         if (isHorizontal) {
720             child->setMarginTop(availableAlignmentSpace / 2);
721             child->setMarginBottom(availableAlignmentSpace / 2);
722         } else {
723             child->setMarginLeft(availableAlignmentSpace / 2);
724             child->setMarginRight(availableAlignmentSpace / 2);
725         }
726         return true;
727     }
728     if (start.isAuto()) {
729         adjustAlignmentForChild(child, availableAlignmentSpace);
730         if (isHorizontal)
731             child->setMarginTop(availableAlignmentSpace);
732         else
733             child->setMarginLeft(availableAlignmentSpace);
734         return true;
735     }
736     if (end.isAuto()) {
737         if (isHorizontal)
738             child->setMarginBottom(availableAlignmentSpace);
739         else
740             child->setMarginRight(availableAlignmentSpace);
741         return true;
742     }
743     return false;
744 }
745
746 LayoutUnit RenderFlexibleBox::marginBoxAscentForChild(RenderBox* child)
747 {
748     LayoutUnit ascent = child->firstLineBoxBaseline();
749     if (ascent == -1)
750         ascent = crossAxisExtentForChild(child) + flowAwareMarginAfterForChild(child);
751     return ascent + flowAwareMarginBeforeForChild(child);
752 }
753
754 void RenderFlexibleBox::computeMainAxisPreferredSizes(bool relayoutChildren, OrderHashSet& orderValues)
755 {
756     LayoutUnit flexboxAvailableContentExtent = mainAxisContentExtent();
757     RenderView* renderView = view();
758     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
759         orderValues.add(child->style()->order());
760
761         if (child->isOutOfFlowPositioned())
762             continue;
763
764         child->clearOverrideSize();
765         // Only need to layout here if we will need to get the logicalHeight of the child in computeNextFlexLine.
766         Length childMainAxisMin = isHorizontalFlow() ? child->style()->minWidth() : child->style()->minHeight();
767         if (hasOrthogonalFlow(child) && (flexBasisForChild(child).isAuto() || childMainAxisMin.isAuto())) {
768             if (!relayoutChildren)
769                 child->setChildNeedsLayout(true);
770             child->layoutIfNeeded();
771         }
772
773         // Before running the flex algorithm, 'auto' has a margin of 0.
774         // Also, if we're not auto sizing, we don't do a layout that computes the start/end margins.
775         if (isHorizontalFlow()) {
776             child->setMarginLeft(minimumValueForLength(child->style()->marginLeft(), flexboxAvailableContentExtent, renderView));
777             child->setMarginRight(minimumValueForLength(child->style()->marginRight(), flexboxAvailableContentExtent, renderView));
778         } else {
779             child->setMarginTop(minimumValueForLength(child->style()->marginTop(), flexboxAvailableContentExtent, renderView));
780             child->setMarginBottom(minimumValueForLength(child->style()->marginBottom(), flexboxAvailableContentExtent, renderView));
781         }
782     }
783 }
784
785 LayoutUnit RenderFlexibleBox::lineBreakLength()
786 {
787     if (!isColumnFlow())
788         return mainAxisContentExtent();
789
790     LayoutUnit height = computeContentLogicalHeightUsing(MainOrPreferredSize, style()->logicalHeight());
791     if (height == -1)
792         height = MAX_LAYOUT_UNIT;
793     LayoutUnit maxHeight = computeContentLogicalHeightUsing(MaxSize, style()->logicalMaxHeight());
794     if (maxHeight != -1)
795         height = std::min(height, maxHeight);
796     return height;
797 }
798
799 LayoutUnit RenderFlexibleBox::adjustChildSizeForMinAndMax(RenderBox* child, LayoutUnit childSize, LayoutUnit flexboxAvailableContentExtent)
800 {
801     Length max = isHorizontalFlow() ? child->style()->maxWidth() : child->style()->maxHeight();
802     Length min = isHorizontalFlow() ? child->style()->minWidth() : child->style()->minHeight();
803     RenderView* renderView = view();
804     // FIXME: valueForLength isn't quite right in quirks mode: percentage heights should check parents until a value is found.
805     // https://bugs.webkit.org/show_bug.cgi?id=81809
806     if (max.isSpecified() && childSize > valueForLength(max, flexboxAvailableContentExtent, renderView))
807         childSize = valueForLength(max, flexboxAvailableContentExtent, renderView);
808
809     if (min.isSpecified() && childSize < valueForLength(min, flexboxAvailableContentExtent, renderView))
810         return valueForLength(min, flexboxAvailableContentExtent, renderView);
811
812     // FIXME: Support min/max sizes of fit-content, max-content and fill-available.
813     if (min.isAuto()) {
814         LayoutUnit minContent = hasOrthogonalFlow(child) ? child->logicalHeight() : child->minPreferredLogicalWidth();
815         minContent -= mainAxisBorderAndPaddingExtentForChild(child);
816         return std::max(childSize, minContent);
817     }
818
819     return childSize;
820 }
821
822 bool RenderFlexibleBox::computeNextFlexLine(OrderIterator& iterator, OrderedFlexItemList& orderedChildren, LayoutUnit& preferredMainAxisExtent, float& totalFlexGrow, float& totalWeightedFlexShrink, LayoutUnit& minMaxAppliedMainAxisExtent)
823 {
824     orderedChildren.clear();
825     preferredMainAxisExtent = 0;
826     totalFlexGrow = totalWeightedFlexShrink = 0;
827     minMaxAppliedMainAxisExtent = 0;
828
829     if (!iterator.currentChild())
830         return false;
831
832     LayoutUnit flexboxAvailableContentExtent = mainAxisContentExtent();
833     LayoutUnit lineBreak = lineBreakLength();
834
835     for (RenderBox* child = iterator.currentChild(); child; child = iterator.next()) {
836         if (child->isOutOfFlowPositioned()) {
837             orderedChildren.append(child);
838             continue;
839         }
840
841         LayoutUnit childMainAxisExtent = preferredMainAxisContentExtentForChild(child);
842         LayoutUnit childMainAxisMarginBoxExtent = mainAxisBorderAndPaddingExtentForChild(child) + childMainAxisExtent;
843         childMainAxisMarginBoxExtent += isHorizontalFlow() ? child->marginWidth() : child->marginHeight();
844
845         if (isMultiline() && preferredMainAxisExtent + childMainAxisMarginBoxExtent > lineBreak && orderedChildren.size() > 0)
846             break;
847         orderedChildren.append(child);
848         preferredMainAxisExtent += childMainAxisMarginBoxExtent;
849         totalFlexGrow += child->style()->flexGrow();
850         totalWeightedFlexShrink += child->style()->flexShrink() * childMainAxisExtent;
851
852         LayoutUnit childMinMaxAppliedMainAxisExtent = adjustChildSizeForMinAndMax(child, childMainAxisExtent, flexboxAvailableContentExtent);
853         minMaxAppliedMainAxisExtent += childMinMaxAppliedMainAxisExtent - childMainAxisExtent + childMainAxisMarginBoxExtent;
854     }
855     return true;
856 }
857
858 void RenderFlexibleBox::freezeViolations(const WTF::Vector<Violation>& violations, LayoutUnit& availableFreeSpace, float& totalFlexGrow, float& totalWeightedFlexShrink, InflexibleFlexItemSize& inflexibleItems)
859 {
860     for (size_t i = 0; i < violations.size(); ++i) {
861         RenderBox* child = violations[i].child;
862         LayoutUnit childSize = violations[i].childSize;
863         LayoutUnit preferredChildSize = preferredMainAxisContentExtentForChild(child);
864         availableFreeSpace -= childSize - preferredChildSize;
865         totalFlexGrow -= child->style()->flexGrow();
866         totalWeightedFlexShrink -= child->style()->flexShrink() * preferredChildSize;
867         inflexibleItems.set(child, childSize);
868     }
869 }
870
871 // Returns true if we successfully ran the algorithm and sized the flex items.
872 bool RenderFlexibleBox::resolveFlexibleLengths(FlexSign flexSign, const OrderedFlexItemList& children, LayoutUnit& availableFreeSpace, float& totalFlexGrow, float& totalWeightedFlexShrink, InflexibleFlexItemSize& inflexibleItems, WTF::Vector<LayoutUnit>& childSizes)
873 {
874     childSizes.clear();
875     LayoutUnit flexboxAvailableContentExtent = mainAxisContentExtent();
876     LayoutUnit totalViolation = 0;
877     LayoutUnit usedFreeSpace = 0;
878     WTF::Vector<Violation> minViolations;
879     WTF::Vector<Violation> maxViolations;
880     for (size_t i = 0; i < children.size(); ++i) {
881         RenderBox* child = children[i];
882         if (child->isOutOfFlowPositioned()) {
883             childSizes.append(0);
884             continue;
885         }
886
887         if (inflexibleItems.contains(child))
888             childSizes.append(inflexibleItems.get(child));
889         else {
890             LayoutUnit preferredChildSize = preferredMainAxisContentExtentForChild(child);
891             LayoutUnit childSize = preferredChildSize;
892             if (availableFreeSpace > 0 && totalFlexGrow > 0 && flexSign == PositiveFlexibility && isfinite(totalFlexGrow))
893                 childSize += roundedLayoutUnit(availableFreeSpace * child->style()->flexGrow() / totalFlexGrow);
894             else if (availableFreeSpace < 0 && totalWeightedFlexShrink > 0 && flexSign == NegativeFlexibility && isfinite(totalWeightedFlexShrink))
895                 childSize += roundedLayoutUnit(availableFreeSpace * child->style()->flexShrink() * preferredChildSize / totalWeightedFlexShrink);
896
897             LayoutUnit adjustedChildSize = adjustChildSizeForMinAndMax(child, childSize, flexboxAvailableContentExtent);
898             childSizes.append(adjustedChildSize);
899             usedFreeSpace += adjustedChildSize - preferredChildSize;
900
901             LayoutUnit violation = adjustedChildSize - childSize;
902             if (violation > 0)
903                 minViolations.append(Violation(child, adjustedChildSize));
904             else if (violation < 0)
905                 maxViolations.append(Violation(child, adjustedChildSize));
906             totalViolation += violation;
907         }
908     }
909
910     if (totalViolation)
911         freezeViolations(totalViolation < 0 ? maxViolations : minViolations, availableFreeSpace, totalFlexGrow, totalWeightedFlexShrink, inflexibleItems);
912     else
913         availableFreeSpace -= usedFreeSpace;
914
915     return !totalViolation;
916 }
917
918 static LayoutUnit initialJustifyContentOffset(LayoutUnit availableFreeSpace, EJustifyContent justifyContent, unsigned numberOfChildren)
919 {
920     if (justifyContent == JustifyFlexEnd)
921         return availableFreeSpace;
922     if (justifyContent == JustifyCenter)
923         return availableFreeSpace / 2;
924     if (justifyContent == JustifySpaceAround) {
925         if (availableFreeSpace > 0 && numberOfChildren)
926             return availableFreeSpace / (2 * numberOfChildren);
927         if (availableFreeSpace < 0)
928             return availableFreeSpace / 2;
929     }
930     return 0;
931 }
932
933 static LayoutUnit justifyContentSpaceBetweenChildren(LayoutUnit availableFreeSpace, EJustifyContent justifyContent, unsigned numberOfChildren)
934 {
935     if (availableFreeSpace > 0 && numberOfChildren > 1) {
936         if (justifyContent == JustifySpaceBetween)
937             return availableFreeSpace / (numberOfChildren - 1);
938         if (justifyContent == JustifySpaceAround)
939             return availableFreeSpace / numberOfChildren;
940     }
941     return 0;
942 }
943
944 void RenderFlexibleBox::setLogicalOverrideSize(RenderBox* child, LayoutUnit childPreferredSize)
945 {
946     if (hasOrthogonalFlow(child))
947         child->setOverrideLogicalContentHeight(childPreferredSize - child->borderAndPaddingLogicalHeight());
948     else
949         child->setOverrideLogicalContentWidth(childPreferredSize - child->borderAndPaddingLogicalWidth());
950 }
951
952 void RenderFlexibleBox::prepareChildForPositionedLayout(RenderBox* child, LayoutUnit mainAxisOffset, LayoutUnit crossAxisOffset, PositionedLayoutMode layoutMode)
953 {
954     ASSERT(child->isOutOfFlowPositioned());
955     child->containingBlock()->insertPositionedObject(child);
956     RenderLayer* childLayer = child->layer();
957     LayoutUnit inlinePosition = isColumnFlow() ? crossAxisOffset : mainAxisOffset;
958     if (layoutMode == FlipForRowReverse && style()->flexDirection() == FlowRowReverse)
959         inlinePosition = mainAxisExtent() - mainAxisOffset;
960     childLayer->setStaticInlinePosition(inlinePosition); // FIXME: Not right for regions.
961
962     LayoutUnit staticBlockPosition = isColumnFlow() ? mainAxisOffset : crossAxisOffset;
963     if (childLayer->staticBlockPosition() != staticBlockPosition) {
964         childLayer->setStaticBlockPosition(staticBlockPosition);
965         if (child->style()->hasStaticBlockPosition(style()->isHorizontalWritingMode()))
966             child->setChildNeedsLayout(true, MarkOnlyThis);
967     }
968 }
969
970 static EAlignItems alignmentForChild(RenderBox* child)
971 {
972     EAlignItems align = child->style()->alignSelf();
973     if (align == AlignAuto)
974         align = child->parent()->style()->alignItems();
975
976     if (child->parent()->style()->flexWrap() == FlexWrapReverse) {
977         if (align == AlignFlexStart)
978             align = AlignFlexEnd;
979         else if (align == AlignFlexEnd)
980             align = AlignFlexStart;
981     }
982
983     return align;
984 }
985
986 void RenderFlexibleBox::layoutAndPlaceChildren(LayoutUnit& crossAxisOffset, const OrderedFlexItemList& children, const WTF::Vector<LayoutUnit>& childSizes, LayoutUnit availableFreeSpace, WTF::Vector<LineContext>& lineContexts)
987 {
988     ASSERT(childSizes.size() == children.size());
989
990     LayoutUnit autoMarginOffset = autoMarginOffsetInMainAxis(children, availableFreeSpace);
991     LayoutUnit mainAxisOffset = flowAwareBorderStart() + flowAwarePaddingStart();
992     mainAxisOffset += initialJustifyContentOffset(availableFreeSpace, style()->justifyContent(), childSizes.size());
993     if (style()->flexDirection() == FlowRowReverse)
994         mainAxisOffset += isHorizontalFlow() ? verticalScrollbarWidth() : horizontalScrollbarHeight();
995
996     LayoutUnit totalMainExtent = mainAxisExtent();
997     LayoutUnit maxAscent = 0, maxDescent = 0; // Used when align-items: baseline.
998     LayoutUnit maxChildCrossAxisExtent = 0;
999     bool shouldFlipMainAxis = !isColumnFlow() && !isLeftToRightFlow();
1000     for (size_t i = 0; i < children.size(); ++i) {
1001         RenderBox* child = children[i];
1002         if (child->isOutOfFlowPositioned()) {
1003             prepareChildForPositionedLayout(child, mainAxisOffset, crossAxisOffset, FlipForRowReverse);
1004             mainAxisOffset += justifyContentSpaceBetweenChildren(availableFreeSpace, style()->justifyContent(), childSizes.size());
1005             continue;
1006         }
1007         LayoutUnit childPreferredSize = childSizes[i] + mainAxisBorderAndPaddingExtentForChild(child);
1008         setLogicalOverrideSize(child, childPreferredSize);
1009         // FIXME: Can avoid laying out here in some cases. See https://webkit.org/b/87905.
1010         child->setChildNeedsLayout(true);
1011         child->layoutIfNeeded();
1012
1013         updateAutoMarginsInMainAxis(child, autoMarginOffset);
1014
1015         LayoutUnit childCrossAxisMarginBoxExtent;
1016         if (alignmentForChild(child) == AlignBaseline && !hasAutoMarginsInCrossAxis(child)) {
1017             LayoutUnit ascent = marginBoxAscentForChild(child);
1018             LayoutUnit descent = (crossAxisMarginExtentForChild(child) + crossAxisExtentForChild(child)) - ascent;
1019
1020             maxAscent = std::max(maxAscent, ascent);
1021             maxDescent = std::max(maxDescent, descent);
1022
1023             childCrossAxisMarginBoxExtent = maxAscent + maxDescent;
1024         } else
1025             childCrossAxisMarginBoxExtent = crossAxisExtentForChild(child) + crossAxisMarginExtentForChild(child);
1026         if (!isColumnFlow() && style()->logicalHeight().isAuto())
1027             setLogicalHeight(std::max(logicalHeight(), crossAxisOffset + flowAwareBorderAfter() + flowAwarePaddingAfter() + childCrossAxisMarginBoxExtent + crossAxisScrollbarExtent()));
1028         maxChildCrossAxisExtent = std::max(maxChildCrossAxisExtent, childCrossAxisMarginBoxExtent);
1029
1030         mainAxisOffset += flowAwareMarginStartForChild(child);
1031
1032         LayoutUnit childMainExtent = mainAxisExtentForChild(child);
1033         LayoutPoint childLocation(shouldFlipMainAxis ? totalMainExtent - mainAxisOffset - childMainExtent : mainAxisOffset,
1034             crossAxisOffset + flowAwareMarginBeforeForChild(child));
1035
1036         // FIXME: Supporting layout deltas.
1037         setFlowAwareLocationForChild(child, childLocation);
1038         mainAxisOffset += childMainExtent + flowAwareMarginEndForChild(child);
1039
1040         mainAxisOffset += justifyContentSpaceBetweenChildren(availableFreeSpace, style()->justifyContent(), childSizes.size());
1041     }
1042
1043     if (isColumnFlow())
1044         setLogicalHeight(mainAxisOffset + flowAwareBorderEnd() + flowAwarePaddingEnd() + scrollbarLogicalHeight());
1045
1046     if (style()->flexDirection() == FlowColumnReverse) {
1047         // We have to do an extra pass for column-reverse to reposition the flex items since the start depends
1048         // on the height of the flexbox, which we only know after we've positioned all the flex items.
1049         computeLogicalHeight();
1050         layoutColumnReverse(children, childSizes, crossAxisOffset, availableFreeSpace);
1051     }
1052
1053     lineContexts.append(LineContext(crossAxisOffset, maxChildCrossAxisExtent, children.size(), maxAscent));
1054     crossAxisOffset += maxChildCrossAxisExtent;
1055 }
1056
1057 void RenderFlexibleBox::layoutColumnReverse(const OrderedFlexItemList& children, const WTF::Vector<LayoutUnit>& childSizes, LayoutUnit crossAxisOffset, LayoutUnit availableFreeSpace)
1058 {
1059     // This is similar to the logic in layoutAndPlaceChildren, except we place the children
1060     // starting from the end of the flexbox. We also don't need to layout anything since we're
1061     // just moving the children to a new position.
1062     LayoutUnit mainAxisOffset = logicalHeight() - flowAwareBorderEnd() - flowAwarePaddingEnd();
1063     mainAxisOffset -= initialJustifyContentOffset(availableFreeSpace, style()->justifyContent(), childSizes.size());
1064     mainAxisOffset -= isHorizontalFlow() ? verticalScrollbarWidth() : horizontalScrollbarHeight();
1065
1066     for (size_t i = 0; i < children.size(); ++i) {
1067         RenderBox* child = children[i];
1068         if (child->isOutOfFlowPositioned()) {
1069             child->layer()->setStaticBlockPosition(mainAxisOffset);
1070             mainAxisOffset -= justifyContentSpaceBetweenChildren(availableFreeSpace, style()->justifyContent(), childSizes.size());
1071             continue;
1072         }
1073         mainAxisOffset -= mainAxisExtentForChild(child) + flowAwareMarginEndForChild(child);
1074
1075         LayoutRect oldRect = child->frameRect();
1076         setFlowAwareLocationForChild(child, LayoutPoint(mainAxisOffset, crossAxisOffset + flowAwareMarginBeforeForChild(child)));
1077         if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
1078             child->repaintDuringLayoutIfMoved(oldRect);
1079
1080         mainAxisOffset -= flowAwareMarginStartForChild(child);
1081         mainAxisOffset -= justifyContentSpaceBetweenChildren(availableFreeSpace, style()->justifyContent(), childSizes.size());
1082     }
1083 }
1084
1085 static LayoutUnit initialAlignContentOffset(LayoutUnit availableFreeSpace, EAlignContent alignContent, unsigned numberOfLines)
1086 {
1087     if (alignContent == AlignContentFlexEnd)
1088         return availableFreeSpace;
1089     if (alignContent == AlignContentCenter)
1090         return availableFreeSpace / 2;
1091     if (alignContent == AlignContentSpaceAround) {
1092         if (availableFreeSpace > 0 && numberOfLines)
1093             return availableFreeSpace / (2 * numberOfLines);
1094         if (availableFreeSpace < 0)
1095             return availableFreeSpace / 2;
1096     }
1097     return 0;
1098 }
1099
1100 static LayoutUnit alignContentSpaceBetweenChildren(LayoutUnit availableFreeSpace, EAlignContent alignContent, unsigned numberOfLines)
1101 {
1102     if (availableFreeSpace > 0 && numberOfLines > 1) {
1103         if (alignContent == AlignContentSpaceBetween)
1104             return availableFreeSpace / (numberOfLines - 1);
1105         if (alignContent == AlignContentSpaceAround || alignContent == AlignContentStretch)
1106             return availableFreeSpace / numberOfLines;
1107     }
1108     return 0;
1109 }
1110
1111 void RenderFlexibleBox::alignFlexLines(OrderIterator& iterator, WTF::Vector<LineContext>& lineContexts)
1112 {
1113     if (!isMultiline() || style()->alignContent() == AlignContentFlexStart)
1114         return;
1115
1116     LayoutUnit availableCrossAxisSpace = crossAxisContentExtent();
1117     for (size_t i = 0; i < lineContexts.size(); ++i)
1118         availableCrossAxisSpace -= lineContexts[i].crossAxisExtent;
1119
1120     RenderBox* child = iterator.first();
1121     LayoutUnit lineOffset = initialAlignContentOffset(availableCrossAxisSpace, style()->alignContent(), lineContexts.size());
1122     for (unsigned lineNumber = 0; lineNumber < lineContexts.size(); ++lineNumber) {
1123         lineContexts[lineNumber].crossAxisOffset += lineOffset;
1124         for (size_t childNumber = 0; childNumber < lineContexts[lineNumber].numberOfChildren; ++childNumber, child = iterator.next())
1125             adjustAlignmentForChild(child, lineOffset);
1126
1127         if (style()->alignContent() == AlignContentStretch && availableCrossAxisSpace > 0)
1128             lineContexts[lineNumber].crossAxisExtent += availableCrossAxisSpace / static_cast<unsigned>(lineContexts.size());
1129
1130         lineOffset += alignContentSpaceBetweenChildren(availableCrossAxisSpace, style()->alignContent(), lineContexts.size());
1131     }
1132 }
1133
1134 void RenderFlexibleBox::adjustAlignmentForChild(RenderBox* child, LayoutUnit delta)
1135 {
1136     if (child->isOutOfFlowPositioned()) {
1137         LayoutUnit staticInlinePosition = child->layer()->staticInlinePosition();
1138         LayoutUnit staticBlockPosition = child->layer()->staticBlockPosition();
1139         LayoutUnit mainAxis = isColumnFlow() ? staticBlockPosition : staticInlinePosition;
1140         LayoutUnit crossAxis = isColumnFlow() ? staticInlinePosition : staticBlockPosition;
1141         crossAxis += delta;
1142         prepareChildForPositionedLayout(child, mainAxis, crossAxis, NoFlipForRowReverse);
1143         return;
1144     }
1145
1146     LayoutRect oldRect = child->frameRect();
1147     setFlowAwareLocationForChild(child, flowAwareLocationForChild(child) + LayoutSize(0, delta));
1148
1149     // If the child moved, we have to repaint it as well as any floating/positioned
1150     // descendants. An exception is if we need a layout. In this case, we know we're going to
1151     // repaint ourselves (and the child) anyway.
1152     if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
1153         child->repaintDuringLayoutIfMoved(oldRect);
1154 }
1155
1156 void RenderFlexibleBox::alignChildren(OrderIterator& iterator, const WTF::Vector<LineContext>& lineContexts)
1157 {
1158     // Keep track of the space between the baseline edge and the after edge of the box for each line.
1159     WTF::Vector<LayoutUnit> minMarginAfterBaselines;
1160
1161     RenderBox* child = iterator.first();
1162     for (size_t lineNumber = 0; lineNumber < lineContexts.size(); ++lineNumber) {
1163         LayoutUnit minMarginAfterBaseline = MAX_LAYOUT_UNIT;
1164         LayoutUnit lineCrossAxisExtent = lineContexts[lineNumber].crossAxisExtent;
1165         LayoutUnit maxAscent = lineContexts[lineNumber].maxAscent;
1166
1167         for (size_t childNumber = 0; childNumber < lineContexts[lineNumber].numberOfChildren; ++childNumber, child = iterator.next()) {
1168             ASSERT(child);
1169             if (updateAutoMarginsInCrossAxis(child, availableAlignmentSpaceForChild(lineCrossAxisExtent, child)))
1170                 continue;
1171
1172             switch (alignmentForChild(child)) {
1173             case AlignAuto:
1174                 ASSERT_NOT_REACHED();
1175                 break;
1176             case AlignStretch: {
1177                 applyStretchAlignmentToChild(child, lineCrossAxisExtent);
1178                 // Since wrap-reverse flips cross start and cross end, strech children should be aligned with the cross end.
1179                 if (style()->flexWrap() == FlexWrapReverse)
1180                     adjustAlignmentForChild(child, availableAlignmentSpaceForChild(lineCrossAxisExtent, child));
1181                 break;
1182             }
1183             case AlignFlexStart:
1184                 break;
1185             case AlignFlexEnd:
1186                 adjustAlignmentForChild(child, availableAlignmentSpaceForChild(lineCrossAxisExtent, child));
1187                 break;
1188             case AlignCenter:
1189                 adjustAlignmentForChild(child, availableAlignmentSpaceForChild(lineCrossAxisExtent, child) / 2);
1190                 break;
1191             case AlignBaseline: {
1192                 LayoutUnit ascent = marginBoxAscentForChild(child);
1193                 LayoutUnit startOffset = maxAscent - ascent;
1194                 adjustAlignmentForChild(child, startOffset);
1195
1196                 if (style()->flexWrap() == FlexWrapReverse)
1197                     minMarginAfterBaseline = std::min(minMarginAfterBaseline, availableAlignmentSpaceForChild(lineCrossAxisExtent, child) - startOffset);
1198                 break;
1199             }
1200             }
1201         }
1202         minMarginAfterBaselines.append(minMarginAfterBaseline);
1203     }
1204
1205     if (style()->flexWrap() != FlexWrapReverse)
1206         return;
1207
1208     // wrap-reverse flips the cross axis start and end. For baseline alignment, this means we
1209     // need to align the after edge of baseline elements with the after edge of the flex line.
1210     child = iterator.first();
1211     for (size_t lineNumber = 0; lineNumber < lineContexts.size(); ++lineNumber) {
1212         LayoutUnit minMarginAfterBaseline = minMarginAfterBaselines[lineNumber];
1213         for (size_t childNumber = 0; childNumber < lineContexts[lineNumber].numberOfChildren; ++childNumber, child = iterator.next()) {
1214             ASSERT(child);
1215             if (alignmentForChild(child) == AlignBaseline && !hasAutoMarginsInCrossAxis(child) && minMarginAfterBaseline)
1216                 adjustAlignmentForChild(child, minMarginAfterBaseline);
1217         }
1218     }
1219 }
1220
1221 void RenderFlexibleBox::applyStretchAlignmentToChild(RenderBox* child, LayoutUnit lineCrossAxisExtent)
1222 {
1223     if (!isColumnFlow() && child->style()->logicalHeight().isAuto()) {
1224         LayoutUnit logicalHeightBefore = child->logicalHeight();
1225         LayoutUnit stretchedLogicalHeight = child->logicalHeight() + availableAlignmentSpaceForChild(lineCrossAxisExtent, child);
1226
1227         child->setLogicalHeight(stretchedLogicalHeight);
1228         child->computeLogicalHeight();
1229
1230         // FIXME: Can avoid laying out here in some cases. See https://webkit.org/b/87905.
1231         if (child->logicalHeight() != logicalHeightBefore) {
1232             child->setOverrideLogicalContentHeight(child->logicalHeight() - child->borderAndPaddingLogicalHeight());
1233             child->setLogicalHeight(0);
1234             child->setChildNeedsLayout(true);
1235             child->layoutIfNeeded();
1236         }
1237     } else if (isColumnFlow() && child->style()->logicalWidth().isAuto() && isMultiline()) {
1238         // FIXME: Handle min-width and max-width.
1239         LayoutUnit childWidth = lineCrossAxisExtent - crossAxisMarginExtentForChild(child);
1240         child->setOverrideLogicalContentWidth(std::max(ZERO_LAYOUT_UNIT, childWidth));
1241         child->setChildNeedsLayout(true);
1242         child->layoutIfNeeded();
1243     }
1244 }
1245
1246 void RenderFlexibleBox::flipForRightToLeftColumn(OrderIterator& iterator)
1247 {
1248     if (style()->isLeftToRightDirection() || !isColumnFlow())
1249         return;
1250
1251     LayoutUnit crossExtent = crossAxisExtent();
1252     for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
1253         if (child->isOutOfFlowPositioned())
1254             continue;
1255         LayoutPoint location = flowAwareLocationForChild(child);
1256         location.setY(crossExtent - crossAxisExtentForChild(child) - location.y());
1257         setFlowAwareLocationForChild(child, location);
1258     }
1259 }
1260
1261 void RenderFlexibleBox::flipForWrapReverse(OrderIterator& iterator, const WTF::Vector<LineContext>& lineContexts, LayoutUnit crossAxisStartEdge)
1262 {
1263     LayoutUnit contentExtent = crossAxisContentExtent();
1264     RenderBox* child = iterator.first();
1265     for (size_t lineNumber = 0; lineNumber < lineContexts.size(); ++lineNumber) {
1266         for (size_t childNumber = 0; childNumber < lineContexts[lineNumber].numberOfChildren; ++childNumber, child = iterator.next()) {
1267             ASSERT(child);
1268             LayoutUnit lineCrossAxisExtent = lineContexts[lineNumber].crossAxisExtent;
1269             LayoutUnit originalOffset = lineContexts[lineNumber].crossAxisOffset - crossAxisStartEdge;
1270             LayoutUnit newOffset = contentExtent - originalOffset - lineCrossAxisExtent;
1271             adjustAlignmentForChild(child, newOffset - originalOffset);
1272         }
1273     }
1274 }
1275
1276 }