Use is<>() / downcast<>() for Table render objects
[WebKit-https.git] / Source / WebCore / rendering / RenderBox.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26 #include "RenderBox.h"
27
28 #include "Chrome.h"
29 #include "ChromeClient.h"
30 #include "Document.h"
31 #include "EventHandler.h"
32 #include "FloatQuad.h"
33 #include "FloatRoundedRect.h"
34 #include "Frame.h"
35 #include "FrameView.h"
36 #include "GraphicsContext.h"
37 #include "HTMLButtonElement.h"
38 #include "HTMLElement.h"
39 #include "HTMLFrameOwnerElement.h"
40 #include "HTMLInputElement.h"
41 #include "HTMLNames.h"
42 #include "HTMLTextAreaElement.h"
43 #include "HitTestResult.h"
44 #include "InlineElementBox.h"
45 #include "Page.h"
46 #include "PaintInfo.h"
47 #include "RenderBoxRegionInfo.h"
48 #include "RenderFlexibleBox.h"
49 #include "RenderGeometryMap.h"
50 #include "RenderInline.h"
51 #include "RenderIterator.h"
52 #include "RenderLayer.h"
53 #include "RenderLayerCompositor.h"
54 #include "RenderNamedFlowFragment.h"
55 #include "RenderNamedFlowThread.h"
56 #include "RenderTableCell.h"
57 #include "RenderTheme.h"
58 #include "RenderView.h"
59 #include "ScrollbarTheme.h"
60 #include "TransformState.h"
61 #include "htmlediting.h"
62 #include <algorithm>
63 #include <math.h>
64 #include <wtf/StackStats.h>
65
66 #if PLATFORM(IOS)
67 #include "Settings.h"
68 #endif
69
70 namespace WebCore {
71
72 struct SameSizeAsRenderBox : public RenderBoxModelObject {
73     virtual ~SameSizeAsRenderBox() { }
74     LayoutRect frameRect;
75     LayoutBoxExtent marginBox;
76     LayoutUnit preferredLogicalWidths[2];
77     void* pointers[2];
78 };
79
80 COMPILE_ASSERT(sizeof(RenderBox) == sizeof(SameSizeAsRenderBox), RenderBox_should_stay_small);
81
82 using namespace HTMLNames;
83
84 // Used by flexible boxes when flexing this element and by table cells.
85 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
86 static OverrideSizeMap* gOverrideHeightMap = 0;
87 static OverrideSizeMap* gOverrideWidthMap = 0;
88
89 #if ENABLE(CSS_GRID_LAYOUT)
90 // Used by grid elements to properly size their grid items.
91 static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = nullptr;
92 static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = nullptr;
93 #endif
94
95 // Size of border belt for autoscroll. When mouse pointer in border belt,
96 // autoscroll is started.
97 static const int autoscrollBeltSize = 20;
98 static const unsigned backgroundObscurationTestMaxDepth = 4;
99
100 bool RenderBox::s_hadOverflowClip = false;
101
102 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
103 {
104     ASSERT(bodyElementRenderer->isBody());
105     // The <body> only paints its background if the root element has defined a background independent of the body,
106     // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
107     auto documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
108     return documentElementRenderer
109         && !documentElementRenderer->hasBackground()
110         && (documentElementRenderer == bodyElementRenderer->parent());
111 }
112
113 RenderBox::RenderBox(Element& element, PassRef<RenderStyle> style, unsigned baseTypeFlags)
114     : RenderBoxModelObject(element, WTF::move(style), baseTypeFlags)
115     , m_minPreferredLogicalWidth(-1)
116     , m_maxPreferredLogicalWidth(-1)
117     , m_inlineBoxWrapper(0)
118 {
119     setIsBox();
120 }
121
122 RenderBox::RenderBox(Document& document, PassRef<RenderStyle> style, unsigned baseTypeFlags)
123     : RenderBoxModelObject(document, WTF::move(style), baseTypeFlags)
124     , m_minPreferredLogicalWidth(-1)
125     , m_maxPreferredLogicalWidth(-1)
126     , m_inlineBoxWrapper(0)
127 {
128     setIsBox();
129 }
130
131 RenderBox::~RenderBox()
132 {
133     view().unscheduleLazyRepaint(*this);
134     if (hasControlStatesForRenderer(this))
135         removeControlStatesForRenderer(this);
136 }
137
138 RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const
139 {
140     RenderFlowThread* flowThread = flowThreadContainingBlock();
141
142     ASSERT(isRenderView() || (region && flowThread));
143     if (isRenderView())
144         return region;
145
146     // We need to clamp to the block, since we want any lines or blocks that overflow out of the
147     // logical top or logical bottom of the block to size as though the border box in the first and
148     // last regions extended infinitely. Otherwise the lines are going to size according to the regions
149     // they overflow into, which makes no sense when this block doesn't exist in |region| at all.
150     RenderRegion* startRegion = nullptr;
151     RenderRegion* endRegion = nullptr;
152     if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion))
153         return region;
154
155     if (region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent())
156         return startRegion;
157     if (region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent())
158         return endRegion;
159
160     return region;
161 }
162
163 bool RenderBox::hasRegionRangeInFlowThread() const
164 {
165     RenderFlowThread* flowThread = flowThreadContainingBlock();
166     if (!flowThread || !flowThread->hasValidRegionInfo())
167         return false;
168
169     return flowThread->hasCachedRegionRangeForBox(this);
170 }
171
172 LayoutRect RenderBox::clientBoxRectInRegion(RenderRegion* region) const
173 {
174     if (!region)
175         return clientBoxRect();
176
177     LayoutRect clientBox = borderBoxRectInRegion(region);
178     clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
179     clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
180
181     return clientBox;
182 }
183
184 LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
185 {
186     if (!region)
187         return borderBoxRect();
188
189     RenderFlowThread* flowThread = flowThreadContainingBlock();
190     if (!flowThread)
191         return borderBoxRect();
192
193     RenderRegion* startRegion = nullptr;
194     RenderRegion* endRegion = nullptr;
195     if (!flowThread->getRegionRangeForBox(this, startRegion, endRegion)) {
196         // FIXME: In a perfect world this condition should never happen.
197         return borderBoxRect();
198     }
199     
200     ASSERT(flowThread->regionInRange(region, startRegion, endRegion));
201
202     // Compute the logical width and placement in this region.
203     RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
204     if (!boxInfo)
205         return borderBoxRect();
206
207     // We have cached insets.
208     LayoutUnit logicalWidth = boxInfo->logicalWidth();
209     LayoutUnit logicalLeft = boxInfo->logicalLeft();
210         
211     // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
212     // FIXME: Doesn't work right with perpendicular writing modes.
213     const RenderBlock* currentBox = containingBlock();
214     RenderBoxRegionInfo* currentBoxInfo = currentBox->renderBoxRegionInfo(region);
215     while (currentBoxInfo && currentBoxInfo->isShifted()) {
216         if (currentBox->style().direction() == LTR)
217             logicalLeft += currentBoxInfo->logicalLeft();
218         else
219             logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
220         currentBox = currentBox->containingBlock();
221         region = currentBox->clampToStartAndEndRegions(region);
222         currentBoxInfo = currentBox->renderBoxRegionInfo(region);
223     }
224     
225     if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
226         delete boxInfo;
227
228     if (isHorizontalWritingMode())
229         return LayoutRect(logicalLeft, 0, logicalWidth, height());
230     return LayoutRect(0, logicalLeft, width(), logicalWidth);
231 }
232
233 void RenderBox::willBeDestroyed()
234 {
235     if (frame().eventHandler().autoscrollRenderer() == this)
236         frame().eventHandler().stopAutoscrollTimer(true);
237
238     clearOverrideSize();
239 #if ENABLE(CSS_GRID_LAYOUT)
240     clearContainingBlockOverrideSize();
241 #endif
242
243     RenderBlock::removePercentHeightDescendantIfNeeded(*this);
244
245 #if ENABLE(CSS_SHAPES)
246     ShapeOutsideInfo::removeInfo(*this);
247 #endif
248
249     RenderBoxModelObject::willBeDestroyed();
250 }
251
252 RenderBlockFlow* RenderBox::outermostBlockContainingFloatingObject()
253 {
254     ASSERT(isFloating());
255     RenderBlockFlow* parentBlock = nullptr;
256     for (auto& ancestor : ancestorsOfType<RenderBlockFlow>(*this)) {
257         if (ancestor.isRenderView())
258             break;
259         if (!parentBlock || ancestor.containsFloat(*this))
260             parentBlock = &ancestor;
261     }
262     return parentBlock;
263 }
264
265 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
266 {
267     ASSERT(isFloatingOrOutOfFlowPositioned());
268
269     if (documentBeingDestroyed())
270         return;
271
272     if (isFloating()) {
273         if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject()) {
274             parentBlock->markSiblingsWithFloatsForLayout(this);
275             parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
276         }
277     }
278
279     if (isOutOfFlowPositioned())
280         RenderBlock::removePositionedObject(*this);
281 }
282
283 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
284 {
285     s_hadOverflowClip = hasOverflowClip();
286
287     const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
288     if (oldStyle) {
289         // The background of the root element or the body element could propagate up to
290         // the canvas. Issue full repaint, when our style changes substantially.
291         if (diff >= StyleDifferenceRepaint && (isRoot() || isBody())) {
292             view().repaintRootContents();
293             if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
294                 view().compositor().rootFixedBackgroundsChanged();
295         }
296         
297         // When a layout hint happens and an object's position style changes, we have to do a layout
298         // to dirty the render tree using the old position value now.
299         if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) {
300             markContainingBlocksForLayout();
301             if (oldStyle->position() == StaticPosition)
302                 repaint();
303             else if (newStyle.hasOutOfFlowPosition())
304                 parent()->setChildNeedsLayout();
305             if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
306                 removeFloatingOrPositionedChildFromBlockLists();
307         }
308     } else if (isBody())
309         view().repaintRootContents();
310
311     RenderBoxModelObject::styleWillChange(diff, newStyle);
312 }
313
314 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
315 {
316     // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
317     // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
318     // writing mode value before style change here.
319     bool oldHorizontalWritingMode = isHorizontalWritingMode();
320
321     RenderBoxModelObject::styleDidChange(diff, oldStyle);
322
323     const RenderStyle& newStyle = style();
324     if (needsLayout() && oldStyle) {
325         RenderBlock::removePercentHeightDescendantIfNeeded(*this);
326
327         // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
328         // when the positioned object's margin-before is changed. In this case the parent has to get a layout in order to run margin collapsing
329         // to determine the new static position.
330         if (isOutOfFlowPositioned() && newStyle.hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle.marginBefore()
331             && parent() && !parent()->normalChildNeedsLayout())
332             parent()->setChildNeedsLayout();
333     }
334
335     if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
336         && oldHorizontalWritingMode != isHorizontalWritingMode())
337         RenderBlock::clearPercentHeightDescendantsFrom(*this);
338
339     // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
340     // new zoomed coordinate space.
341     if (hasOverflowClip() && oldStyle && oldStyle->effectiveZoom() != newStyle.effectiveZoom()) {
342         if (int left = layer()->scrollXOffset()) {
343             left = (left / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
344             layer()->scrollToXOffset(left);
345         }
346         if (int top = layer()->scrollYOffset()) {
347             top = (top / oldStyle->effectiveZoom()) * newStyle.effectiveZoom();
348             layer()->scrollToYOffset(top);
349         }
350     }
351
352     // Our opaqueness might have changed without triggering layout.
353     if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
354         auto parentToInvalidate = parent();
355         for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
356             parentToInvalidate->invalidateBackgroundObscurationStatus();
357             parentToInvalidate = parentToInvalidate->parent();
358         }
359     }
360
361     bool isBodyRenderer = isBody();
362     bool isRootRenderer = isRoot();
363
364     // Set the text color if we're the body.
365     if (isBodyRenderer)
366         document().setTextColor(newStyle.visitedDependentColor(CSSPropertyColor));
367
368     if (isRootRenderer || isBodyRenderer) {
369         // Propagate the new writing mode and direction up to the RenderView.
370         RenderStyle& viewStyle = view().style();
371         bool viewChangedWritingMode = false;
372         bool rootStyleChanged = false;
373         bool viewStyleChanged = false;
374         RenderObject* rootRenderer = isBodyRenderer ? document().documentElement()->renderer() : nullptr;
375         if (viewStyle.direction() != newStyle.direction() && (isRootRenderer || !document().directionSetOnDocumentElement())) {
376             viewStyle.setDirection(newStyle.direction());
377             viewStyleChanged = true;
378             if (isBodyRenderer) {
379                 rootRenderer->style().setDirection(newStyle.direction());
380                 rootStyleChanged = true;
381             }
382             setNeedsLayoutAndPrefWidthsRecalc();
383         }
384
385         if (viewStyle.writingMode() != newStyle.writingMode() && (isRootRenderer || !document().writingModeSetOnDocumentElement())) {
386             viewStyle.setWritingMode(newStyle.writingMode());
387             viewChangedWritingMode = true;
388             viewStyleChanged = true;
389             view().setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
390             view().markAllDescendantsWithFloatsForLayout();
391             if (isBodyRenderer) {
392                 rootStyleChanged = true;
393                 rootRenderer->style().setWritingMode(newStyle.writingMode());
394                 rootRenderer->setHorizontalWritingMode(newStyle.isHorizontalWritingMode());
395             }
396             setNeedsLayoutAndPrefWidthsRecalc();
397         }
398
399         view().frameView().recalculateScrollbarOverlayStyle();
400         
401         const Pagination& pagination = view().frameView().pagination();
402         if (viewChangedWritingMode && pagination.mode != Pagination::Unpaginated) {
403             viewStyle.setColumnStylesFromPaginationMode(pagination.mode);
404             if (view().multiColumnFlowThread())
405                 view().updateColumnProgressionFromStyle(&viewStyle);
406         }
407         
408         if (viewStyleChanged && view().multiColumnFlowThread())
409             view().updateStylesForColumnChildren();
410         
411         if (rootStyleChanged && is<RenderBlockFlow>(rootRenderer) && downcast<RenderBlockFlow>(*rootRenderer).multiColumnFlowThread())
412             downcast<RenderBlockFlow>(*rootRenderer).updateStylesForColumnChildren();
413     }
414
415 #if ENABLE(CSS_SHAPES)
416     if ((oldStyle && oldStyle->shapeOutside()) || style().shapeOutside())
417         updateShapeOutsideInfoAfterStyleChange(style(), oldStyle);
418 #endif
419 }
420
421 #if ENABLE(CSS_SHAPES)
422 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
423 {
424     const ShapeValue* shapeOutside = style.shapeOutside();
425     const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : nullptr;
426
427     Length shapeMargin = style.shapeMargin();
428     Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
429
430     float shapeImageThreshold = style.shapeImageThreshold();
431     float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
432
433     // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
434     if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
435         return;
436
437     if (!shapeOutside)
438         ShapeOutsideInfo::removeInfo(*this);
439     else
440         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
441
442     if (shapeOutside || shapeOutside != oldShapeOutside)
443         markShapeOutsideDependentsForLayout();
444 }
445 #endif
446
447 void RenderBox::updateFromStyle()
448 {
449     RenderBoxModelObject::updateFromStyle();
450
451     const RenderStyle& styleToUse = style();
452     bool isRootObject = isRoot();
453     bool isViewObject = isRenderView();
454
455     // The root and the RenderView always paint their backgrounds/borders.
456     if (isRootObject || isViewObject)
457         setHasBoxDecorations(true);
458
459     setFloating(!isOutOfFlowPositioned() && styleToUse.isFloating());
460
461     // We also handle <body> and <html>, whose overflow applies to the viewport.
462     if (styleToUse.overflowX() != OVISIBLE && !isRootObject && isRenderBlock()) {
463         bool boxHasOverflowClip = true;
464         if (isBody()) {
465             // Overflow on the body can propagate to the viewport under the following conditions.
466             // (1) The root element is <html>.
467             // (2) We are the primary <body> (can be checked by looking at document.body).
468             // (3) The root element has visible overflow.
469             if (document().documentElement()->hasTagName(htmlTag)
470                 && document().body() == element()
471                 && document().documentElement()->renderer()->style().overflowX() == OVISIBLE) {
472                 boxHasOverflowClip = false;
473             }
474         }
475         
476         // Check for overflow clip.
477         // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
478         if (boxHasOverflowClip) {
479             if (!s_hadOverflowClip)
480                 // Erase the overflow
481                 repaint();
482             setHasOverflowClip();
483         }
484     }
485
486     setHasTransform(styleToUse.hasTransformRelatedProperty());
487     setHasReflection(styleToUse.boxReflect());
488 }
489
490 void RenderBox::layout()
491 {
492     StackStats::LayoutCheckPoint layoutCheckPoint;
493     ASSERT(needsLayout());
494
495     RenderObject* child = firstChild();
496     if (!child) {
497         clearNeedsLayout();
498         return;
499     }
500
501     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), style().isFlippedBlocksWritingMode());
502     while (child) {
503         if (child->needsLayout())
504             downcast<RenderElement>(*child).layout();
505         ASSERT(!child->needsLayout());
506         child = child->nextSibling();
507     }
508     statePusher.pop();
509     invalidateBackgroundObscurationStatus();
510     clearNeedsLayout();
511 }
512
513 // More IE extensions.  clientWidth and clientHeight represent the interior of an object
514 // excluding border and scrollbar.
515 LayoutUnit RenderBox::clientWidth() const
516 {
517     return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
518 }
519
520 LayoutUnit RenderBox::clientHeight() const
521 {
522     return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
523 }
524
525 int RenderBox::pixelSnappedClientWidth() const
526 {
527     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
528     return roundToInt(clientWidth());
529 }
530
531 int RenderBox::pixelSnappedClientHeight() const
532 {
533     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
534     return roundToInt(clientHeight());
535 }
536
537 int RenderBox::pixelSnappedOffsetWidth() const
538 {
539     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
540     return roundToInt(offsetWidth());
541 }
542
543 int RenderBox::pixelSnappedOffsetHeight() const
544 {
545     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
546     return roundToInt(offsetHeight());
547 }
548
549 int RenderBox::scrollWidth() const
550 {
551     if (hasOverflowClip())
552         return layer()->scrollWidth();
553     // For objects with visible overflow, this matches IE.
554     // FIXME: Need to work right with writing modes.
555     if (style().isLeftToRightDirection()) {
556         // FIXME: This should use snappedIntSize() instead with absolute coordinates.
557         return roundToInt(std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()));
558     }
559     return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
560 }
561
562 int RenderBox::scrollHeight() const
563 {
564     if (hasOverflowClip())
565         return layer()->scrollHeight();
566     // For objects with visible overflow, this matches IE.
567     // FIXME: Need to work right with writing modes.
568     // FIXME: This should use snappedIntSize() instead with absolute coordinates.
569     return roundToInt(std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop()));
570 }
571
572 int RenderBox::scrollLeft() const
573 {
574     return hasOverflowClip() ? layer()->scrollXOffset() : 0;
575 }
576
577 int RenderBox::scrollTop() const
578 {
579     return hasOverflowClip() ? layer()->scrollYOffset() : 0;
580 }
581
582 void RenderBox::setScrollLeft(int newLeft)
583 {
584     if (hasOverflowClip())
585         layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
586 }
587
588 void RenderBox::setScrollTop(int newTop)
589 {
590     if (hasOverflowClip())
591         layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
592 }
593
594 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
595 {
596     rects.append(snappedIntRect(accumulatedOffset, size()));
597 }
598
599 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
600 {
601     FloatRect localRect(0, 0, width(), height());
602
603     RenderFlowThread* flowThread = flowThreadContainingBlock();
604     if (flowThread && flowThread->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
605         return;
606
607     quads.append(localToAbsoluteQuad(localRect, 0 /* mode */, wasFixed));
608 }
609
610 void RenderBox::updateLayerTransform()
611 {
612     // Transform-origin depends on box size, so we need to update the layer transform after layout.
613     if (hasLayer())
614         layer()->updateTransform();
615 }
616
617 LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region) const
618 {
619     const RenderStyle& styleToUse = style();
620     if (!styleToUse.logicalMaxWidth().isUndefined())
621         logicalWidth = std::min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse.logicalMaxWidth(), availableWidth, cb, region));
622     return std::max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse.logicalMinWidth(), availableWidth, cb, region));
623 }
624
625 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight) const
626 {
627     const RenderStyle& styleToUse = style();
628     if (!styleToUse.logicalMaxHeight().isUndefined()) {
629         LayoutUnit maxH = computeLogicalHeightUsing(styleToUse.logicalMaxHeight());
630         if (maxH != -1)
631             logicalHeight = std::min(logicalHeight, maxH);
632     }
633     return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse.logicalMinHeight()));
634 }
635
636 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight) const
637 {
638     const RenderStyle& styleToUse = style();
639     if (!styleToUse.logicalMaxHeight().isUndefined()) {
640         LayoutUnit maxH = computeContentLogicalHeight(styleToUse.logicalMaxHeight());
641         if (maxH != -1)
642             logicalHeight = std::min(logicalHeight, maxH);
643     }
644     return std::max(logicalHeight, computeContentLogicalHeight(styleToUse.logicalMinHeight()));
645 }
646
647 RoundedRect::Radii RenderBox::borderRadii() const
648 {
649     RenderStyle& style = this->style();
650     LayoutRect bounds = frameRect();
651
652     unsigned borderLeft = style.borderLeftWidth();
653     unsigned borderTop = style.borderTopWidth();
654     bounds.moveBy(LayoutPoint(borderLeft, borderTop));
655     bounds.contract(borderLeft + style.borderRightWidth(), borderTop + style.borderBottomWidth());
656     return style.getRoundedBorderFor(bounds).radii();
657 }
658
659 IntRect RenderBox::absoluteContentBox() const
660 {
661     // This is wrong with transforms and flipped writing modes.
662     IntRect rect = snappedIntRect(contentBoxRect());
663     FloatPoint absPos = localToAbsolute();
664     rect.move(absPos.x(), absPos.y());
665     return rect;
666 }
667
668 FloatQuad RenderBox::absoluteContentQuad() const
669 {
670     LayoutRect rect = contentBoxRect();
671     return localToAbsoluteQuad(FloatRect(rect));
672 }
673
674 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
675 {
676     LayoutRect box = borderBoundingBox();
677     adjustRectForOutlineAndShadow(box);
678
679     if (repaintContainer != this) {
680         FloatQuad containerRelativeQuad;
681         if (geometryMap)
682             containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
683         else
684             containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
685
686         box = LayoutRect(containerRelativeQuad.boundingBox());
687     }
688     
689     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
690     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
691     box.move(view().layoutDelta());
692
693     return LayoutRect(snapRectToDevicePixels(box, document().deviceScaleFactor()));
694 }
695
696 void RenderBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
697 {
698     if (!size().isEmpty())
699         rects.append(snappedIntRect(additionalOffset, size()));
700 }
701
702 int RenderBox::reflectionOffset() const
703 {
704     if (!style().boxReflect())
705         return 0;
706     if (style().boxReflect()->direction() == ReflectionLeft || style().boxReflect()->direction() == ReflectionRight)
707         return valueForLength(style().boxReflect()->offset(), borderBoxRect().width());
708     return valueForLength(style().boxReflect()->offset(), borderBoxRect().height());
709 }
710
711 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
712 {
713     if (!style().boxReflect())
714         return LayoutRect();
715
716     LayoutRect box = borderBoxRect();
717     LayoutRect result = r;
718     switch (style().boxReflect()->direction()) {
719         case ReflectionBelow:
720             result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
721             break;
722         case ReflectionAbove:
723             result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
724             break;
725         case ReflectionLeft:
726             result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
727             break;
728         case ReflectionRight:
729             result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
730             break;
731     }
732     return result;
733 }
734
735 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
736 {
737     return style().position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
738 }
739
740 bool RenderBox::includeVerticalScrollbarSize() const
741 {
742     return hasOverflowClip() && !layer()->hasOverlayScrollbars()
743         && (style().overflowY() == OSCROLL || style().overflowY() == OAUTO);
744 }
745
746 bool RenderBox::includeHorizontalScrollbarSize() const
747 {
748     return hasOverflowClip() && !layer()->hasOverlayScrollbars()
749         && (style().overflowX() == OSCROLL || style().overflowX() == OAUTO);
750 }
751
752 int RenderBox::verticalScrollbarWidth() const
753 {
754     return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
755 }
756
757 int RenderBox::horizontalScrollbarHeight() const
758 {
759     return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
760 }
761
762 int RenderBox::instrinsicScrollbarLogicalWidth() const
763 {
764     if (!hasOverflowClip())
765         return 0;
766
767     if (isHorizontalWritingMode() && (style().overflowY() == OSCROLL && !hasVerticalScrollbarWithAutoBehavior())) {
768         ASSERT(layer()->hasVerticalScrollbar());
769         return verticalScrollbarWidth();
770     }
771
772     if (!isHorizontalWritingMode() && (style().overflowX() == OSCROLL && !hasHorizontalScrollbarWithAutoBehavior())) {
773         ASSERT(layer()->hasHorizontalScrollbar());
774         return horizontalScrollbarHeight();
775     }
776
777     return 0;
778 }
779
780 bool RenderBox::scrollLayer(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
781 {
782     RenderLayer* boxLayer = layer();
783     if (boxLayer && boxLayer->scroll(direction, granularity, multiplier)) {
784         if (stopElement)
785             *stopElement = element();
786
787         return true;
788     }
789
790     return false;
791 }
792
793 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement, RenderBox* startBox, const IntPoint& wheelEventAbsolutePoint)
794 {
795     if (scrollLayer(direction, granularity, multiplier, stopElement))
796         return true;
797
798     if (stopElement && *stopElement && *stopElement == element())
799         return true;
800
801     RenderBlock* nextScrollBlock = containingBlock();
802     if (nextScrollBlock && nextScrollBlock->isRenderNamedFlowThread()) {
803         ASSERT(startBox);
804         nextScrollBlock = toRenderNamedFlowThread(nextScrollBlock)->fragmentFromAbsolutePointAndBox(wheelEventAbsolutePoint, *startBox);
805     }
806
807     if (nextScrollBlock && !nextScrollBlock->isRenderView())
808         return nextScrollBlock->scroll(direction, granularity, multiplier, stopElement, startBox, wheelEventAbsolutePoint);
809
810     return false;
811 }
812
813 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
814 {
815     bool scrolled = false;
816     
817     RenderLayer* l = layer();
818     if (l) {
819 #if PLATFORM(COCOA)
820         // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
821         if (granularity == ScrollByDocument)
822             scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
823 #endif
824         if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style().isFlippedBlocksWritingMode()), granularity, multiplier))
825             scrolled = true;
826         
827         if (scrolled) {
828             if (stopElement)
829                 *stopElement = element();
830             return true;
831         }
832     }
833
834     if (stopElement && *stopElement && *stopElement == element())
835         return true;
836
837     RenderBlock* b = containingBlock();
838     if (b && !b->isRenderView())
839         return b->logicalScroll(direction, granularity, multiplier, stopElement);
840     return false;
841 }
842
843 bool RenderBox::canBeScrolledAndHasScrollableArea() const
844 {
845     return canBeProgramaticallyScrolled() && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth());
846 }
847
848 bool RenderBox::isScrollableOrRubberbandableBox() const
849 {
850     return canBeScrolledAndHasScrollableArea();
851 }
852
853 bool RenderBox::canBeProgramaticallyScrolled() const
854 {
855     if (isRenderView())
856         return true;
857
858     if (!hasOverflowClip())
859         return false;
860
861     bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
862     if (scrollsOverflow() && hasScrollableOverflow)
863         return true;
864
865     return element() && element()->hasEditableStyle();
866 }
867
868 bool RenderBox::usesCompositedScrolling() const
869 {
870     return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
871 }
872
873 void RenderBox::autoscroll(const IntPoint& position)
874 {
875     if (layer())
876         layer()->autoscroll(position);
877 }
878
879 // There are two kinds of renderer that can autoscroll.
880 bool RenderBox::canAutoscroll() const
881 {
882     if (isRenderView())
883         return view().frameView().isScrollable();
884
885     // Check for a box that can be scrolled in its own right.
886     if (canBeScrolledAndHasScrollableArea())
887         return true;
888
889     return false;
890 }
891
892 // If specified point is in border belt, returned offset denotes direction of
893 // scrolling.
894 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
895 {
896     IntRect box(absoluteBoundingBoxRect());
897     box.move(view().frameView().scrollOffset());
898     IntRect windowBox = view().frameView().contentsToWindow(box);
899
900     IntPoint windowAutoscrollPoint = windowPoint;
901
902     if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
903         windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
904     else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
905         windowAutoscrollPoint.move(autoscrollBeltSize, 0);
906
907     if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
908         windowAutoscrollPoint.move(0, -autoscrollBeltSize);
909     else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
910         windowAutoscrollPoint.move(0, autoscrollBeltSize);
911
912     return windowAutoscrollPoint - windowPoint;
913 }
914
915 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
916 {
917     while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
918         if (renderer->isRenderView() && renderer->document().ownerElement())
919             renderer = renderer->document().ownerElement()->renderer();
920         else
921             renderer = renderer->parent();
922     }
923
924     return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
925 }
926
927 void RenderBox::panScroll(const IntPoint& source)
928 {
929     if (layer())
930         layer()->panScrollFromPoint(source);
931 }
932
933 bool RenderBox::hasVerticalScrollbarWithAutoBehavior() const
934 {
935     bool overflowScrollActsLikeAuto = style().overflowY() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme()->usesOverlayScrollbars();
936     return hasOverflowClip() && (style().overflowY() == OAUTO || style().overflowY() == OOVERLAY || overflowScrollActsLikeAuto);
937 }
938
939 bool RenderBox::hasHorizontalScrollbarWithAutoBehavior() const
940 {
941     bool overflowScrollActsLikeAuto = style().overflowX() == OSCROLL && !style().hasPseudoStyle(SCROLLBAR) && ScrollbarTheme::theme()->usesOverlayScrollbars();
942     return hasOverflowClip() && (style().overflowX() == OAUTO || style().overflowX() == OOVERLAY || overflowScrollActsLikeAuto);
943 }
944
945 bool RenderBox::needsPreferredWidthsRecalculation() const
946 {
947     return style().paddingStart().isPercent() || style().paddingEnd().isPercent();
948 }
949
950 IntSize RenderBox::scrolledContentOffset() const
951 {
952     if (!hasOverflowClip())
953         return IntSize();
954
955     ASSERT(hasLayer());
956     return layer()->scrolledContentOffset();
957 }
958
959 LayoutSize RenderBox::cachedSizeForOverflowClip() const
960 {
961     ASSERT(hasOverflowClip());
962     ASSERT(hasLayer());
963     return layer()->size();
964 }
965
966 void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const
967 {
968     flipForWritingMode(paintRect);
969     paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
970
971     // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
972     if (usesCompositedScrolling()) {
973         flipForWritingMode(paintRect);
974         return;
975     }
976
977     // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
978     // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
979     // anyway if its size does change.
980     LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
981     paintRect = intersection(paintRect, clipRect);
982     flipForWritingMode(paintRect);
983 }
984
985 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
986 {
987     minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
988     maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
989 }
990
991 LayoutUnit RenderBox::minPreferredLogicalWidth() const
992 {
993     if (preferredLogicalWidthsDirty()) {
994 #ifndef NDEBUG
995         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
996 #endif
997         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
998     }
999         
1000     return m_minPreferredLogicalWidth;
1001 }
1002
1003 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
1004 {
1005     if (preferredLogicalWidthsDirty()) {
1006 #ifndef NDEBUG
1007         SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
1008 #endif
1009         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
1010     }
1011         
1012     return m_maxPreferredLogicalWidth;
1013 }
1014
1015 bool RenderBox::hasOverrideHeight() const
1016 {
1017     return gOverrideHeightMap && gOverrideHeightMap->contains(this);
1018 }
1019
1020 bool RenderBox::hasOverrideWidth() const
1021 {
1022     return gOverrideWidthMap && gOverrideWidthMap->contains(this);
1023 }
1024
1025 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
1026 {
1027     if (!gOverrideHeightMap)
1028         gOverrideHeightMap = new OverrideSizeMap();
1029     gOverrideHeightMap->set(this, height);
1030 }
1031
1032 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
1033 {
1034     if (!gOverrideWidthMap)
1035         gOverrideWidthMap = new OverrideSizeMap();
1036     gOverrideWidthMap->set(this, width);
1037 }
1038
1039 void RenderBox::clearOverrideLogicalContentHeight()
1040 {
1041     if (gOverrideHeightMap)
1042         gOverrideHeightMap->remove(this);
1043 }
1044
1045 void RenderBox::clearOverrideLogicalContentWidth()
1046 {
1047     if (gOverrideWidthMap)
1048         gOverrideWidthMap->remove(this);
1049 }
1050
1051 void RenderBox::clearOverrideSize()
1052 {
1053     clearOverrideLogicalContentHeight();
1054     clearOverrideLogicalContentWidth();
1055 }
1056
1057 LayoutUnit RenderBox::overrideLogicalContentWidth() const
1058 {
1059     ASSERT(hasOverrideWidth());
1060     return gOverrideWidthMap->get(this);
1061 }
1062
1063 LayoutUnit RenderBox::overrideLogicalContentHeight() const
1064 {
1065     ASSERT(hasOverrideHeight());
1066     return gOverrideHeightMap->get(this);
1067 }
1068
1069 #if ENABLE(CSS_GRID_LAYOUT)
1070 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
1071 {
1072     ASSERT(hasOverrideContainingBlockLogicalWidth());
1073     return gOverrideContainingBlockLogicalWidthMap->get(this);
1074 }
1075
1076 LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
1077 {
1078     ASSERT(hasOverrideContainingBlockLogicalHeight());
1079     return gOverrideContainingBlockLogicalHeightMap->get(this);
1080 }
1081
1082 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
1083 {
1084     return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1085 }
1086
1087 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1088 {
1089     return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1090 }
1091
1092 void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
1093 {
1094     if (!gOverrideContainingBlockLogicalWidthMap)
1095         gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
1096     gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1097 }
1098
1099 void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
1100 {
1101     if (!gOverrideContainingBlockLogicalHeightMap)
1102         gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
1103     gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1104 }
1105
1106 void RenderBox::clearContainingBlockOverrideSize()
1107 {
1108     if (gOverrideContainingBlockLogicalWidthMap)
1109         gOverrideContainingBlockLogicalWidthMap->remove(this);
1110     clearOverrideContainingBlockContentLogicalHeight();
1111 }
1112
1113 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1114 {
1115     if (gOverrideContainingBlockLogicalHeightMap)
1116         gOverrideContainingBlockLogicalHeightMap->remove(this);
1117 }
1118 #endif // ENABLE(CSS_GRID_LAYOUT)
1119
1120 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1121 {
1122     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1123     if (style().boxSizing() == CONTENT_BOX)
1124         return width + bordersPlusPadding;
1125     return std::max(width, bordersPlusPadding);
1126 }
1127
1128 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1129 {
1130     LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1131     if (style().boxSizing() == CONTENT_BOX)
1132         return height + bordersPlusPadding;
1133     return std::max(height, bordersPlusPadding);
1134 }
1135
1136 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1137 {
1138     if (style().boxSizing() == BORDER_BOX)
1139         width -= borderAndPaddingLogicalWidth();
1140     return std::max<LayoutUnit>(0, width);
1141 }
1142
1143 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1144 {
1145     if (style().boxSizing() == BORDER_BOX)
1146         height -= borderAndPaddingLogicalHeight();
1147     return std::max<LayoutUnit>(0, height);
1148 }
1149
1150 // Hit Testing
1151 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1152 {
1153     LayoutPoint adjustedLocation = accumulatedOffset + location();
1154
1155     // Check kids first.
1156     for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1157         if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1158             updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1159             return true;
1160         }
1161     }
1162
1163     RenderFlowThread* flowThread = flowThreadContainingBlock();
1164     RenderRegion* regionToUse = flowThread ? toRenderNamedFlowFragment(flowThread->currentRegion()) : nullptr;
1165
1166     // If the box is not contained by this region there's no point in going further.
1167     if (regionToUse && !flowThread->objectShouldFragmentInFlowRegion(this, regionToUse))
1168         return false;
1169
1170     // Check our bounds next. For this purpose always assume that we can only be hit in the
1171     // foreground phase (which is true for replaced elements like images).
1172     LayoutRect boundsRect = borderBoxRectInRegion(regionToUse);
1173     boundsRect.moveBy(adjustedLocation);
1174     if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1175         updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1176         if (!result.addNodeToRectBasedTestResult(element(), request, locationInContainer, boundsRect))
1177             return true;
1178     }
1179
1180     return false;
1181 }
1182
1183 // --------------------- painting stuff -------------------------------
1184
1185 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1186 {
1187     if (paintInfo.skipRootBackground())
1188         return;
1189
1190     auto& rootBackgroundRenderer = rendererForRootBackground();
1191     
1192     const FillLayer* bgLayer = rootBackgroundRenderer.style().backgroundLayers();
1193     Color bgColor = rootBackgroundRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor);
1194
1195     paintFillLayers(paintInfo, bgColor, bgLayer, view().backgroundRect(this), BackgroundBleedNone, CompositeSourceOver, &rootBackgroundRenderer);
1196 }
1197
1198 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
1199 {
1200     if (context->paintingDisabled())
1201         return BackgroundBleedNone;
1202
1203     const RenderStyle& style = this->style();
1204
1205     if (!style.hasBackground() || !style.hasBorder() || !style.hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1206         return BackgroundBleedNone;
1207
1208     AffineTransform ctm = context->getCTM();
1209     FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1210
1211     // Because RoundedRect uses IntRect internally the inset applied by the 
1212     // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1213     // layout coordinate, even with subpixel layout enabled. To take that into
1214     // account, we clamp the contextScaling to 1.0 for the following test so
1215     // that borderObscuresBackgroundEdge can only return true if the border
1216     // widths are greater than 2 in both layout coordinates and screen
1217     // coordinates.
1218     // This precaution will become obsolete if RoundedRect is ever promoted to
1219     // a sub-pixel representation.
1220     if (contextScaling.width() > 1) 
1221         contextScaling.setWidth(1);
1222     if (contextScaling.height() > 1) 
1223         contextScaling.setHeight(1);
1224
1225     if (borderObscuresBackgroundEdge(contextScaling))
1226         return BackgroundBleedShrinkBackground;
1227     if (!style.hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1228         return BackgroundBleedBackgroundOverBorder;
1229
1230     return BackgroundBleedUseTransparencyLayer;
1231 }
1232
1233 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1234 {
1235     if (!paintInfo.shouldPaintWithinRoot(*this))
1236         return;
1237
1238     LayoutRect paintRect = borderBoxRectInRegion(currentRenderNamedFlowFragment());
1239     paintRect.moveBy(paintOffset);
1240
1241 #if PLATFORM(IOS)
1242     // Workaround for <rdar://problem/6209763>. Force the painting bounds of checkboxes and radio controls to be square.
1243     if (style().appearance() == CheckboxPart || style().appearance() == RadioPart) {
1244         int width = std::min(paintRect.width(), paintRect.height());
1245         int height = width;
1246         paintRect = IntRect(paintRect.x(), paintRect.y() + (this->height() - height) / 2, width, height); // Vertically center the checkbox, like on desktop
1247     }
1248 #endif
1249     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
1250
1251     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1252     // custom shadows of their own.
1253     if (!boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1254         paintBoxShadow(paintInfo, paintRect, style(), Normal);
1255
1256     GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
1257     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1258         // To avoid the background color bleeding out behind the border, we'll render background and border
1259         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1260         // beginning the layer).
1261         stateSaver.save();
1262         paintInfo.context->clipRoundedRect(style().getRoundedBorderFor(paintRect).pixelSnappedRoundedRectForPainting(document().deviceScaleFactor()));
1263         paintInfo.context->beginTransparencyLayer(1);
1264     }
1265
1266     // If we have a native theme appearance, paint that before painting our background.
1267     // The theme will tell us whether or not we should also paint the CSS background.
1268     ControlStates* controlStates = nullptr;
1269     if (style().hasAppearance()) {
1270         if (hasControlStatesForRenderer(this))
1271             controlStates = controlStatesForRenderer(this);
1272         else {
1273             controlStates = new ControlStates();
1274             addControlStatesForRenderer(this, controlStates);
1275         }
1276     }
1277
1278     bool themePainted = style().hasAppearance() && !theme().paint(*this, controlStates, paintInfo, paintRect);
1279
1280     if (controlStates && controlStates->needsRepaint())
1281         view().scheduleLazyRepaint(*this);
1282
1283     if (!themePainted) {
1284         if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1285             paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1286
1287         paintBackground(paintInfo, paintRect, bleedAvoidance);
1288
1289         if (style().hasAppearance())
1290             theme().paintDecorations(*this, paintInfo, paintRect);
1291     }
1292     paintBoxShadow(paintInfo, paintRect, style(), Inset);
1293
1294     // The theme will tell us whether or not we should also paint the CSS border.
1295     if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style().hasAppearance() || (!themePainted && theme().paintBorderOnly(*this, paintInfo, paintRect))) && style().hasBorder())
1296         paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1297
1298     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1299         paintInfo.context->endTransparencyLayer();
1300 }
1301
1302 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1303 {
1304     if (isRoot()) {
1305         paintRootBoxFillLayers(paintInfo);
1306         return;
1307     }
1308     if (isBody() && skipBodyBackground(this))
1309         return;
1310     if (backgroundIsKnownToBeObscured() && !boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1311         return;
1312     paintFillLayers(paintInfo, style().visitedDependentColor(CSSPropertyBackgroundColor), style().backgroundLayers(), paintRect, bleedAvoidance);
1313 }
1314
1315 bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent) const
1316 {
1317     ASSERT(hasBackground());
1318     LayoutRect backgroundRect = snappedIntRect(borderBoxRect());
1319
1320     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1321     if (backgroundColor.isValid() && backgroundColor.alpha()) {
1322         paintedExtent = backgroundRect;
1323         return true;
1324     }
1325
1326     if (!style().backgroundLayers()->image() || style().backgroundLayers()->next()) {
1327         paintedExtent =  backgroundRect;
1328         return true;
1329     }
1330
1331     BackgroundImageGeometry geometry;
1332     calculateBackgroundImageGeometry(0, style().backgroundLayers(), backgroundRect, geometry);
1333     paintedExtent = geometry.destRect();
1334     return !geometry.hasNonLocalGeometry();
1335 }
1336
1337 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1338 {
1339     if (isBody() && skipBodyBackground(this))
1340         return false;
1341
1342     Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1343     if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
1344         return false;
1345
1346     // If the element has appearance, it might be painted by theme.
1347     // We cannot be sure if theme paints the background opaque.
1348     // In this case it is safe to not assume opaqueness.
1349     // FIXME: May be ask theme if it paints opaque.
1350     if (style().hasAppearance())
1351         return false;
1352     // FIXME: Check the opaqueness of background images.
1353
1354     if (hasClip() || hasClipPath())
1355         return false;
1356
1357     // FIXME: Use rounded rect if border radius is present.
1358     if (style().hasBorderRadius())
1359         return false;
1360     
1361     // FIXME: The background color clip is defined by the last layer.
1362     if (style().backgroundLayers()->next())
1363         return false;
1364     LayoutRect backgroundRect;
1365     switch (style().backgroundClip()) {
1366     case BorderFillBox:
1367         backgroundRect = borderBoxRect();
1368         break;
1369     case PaddingFillBox:
1370         backgroundRect = paddingBoxRect();
1371         break;
1372     case ContentFillBox:
1373         backgroundRect = contentBoxRect();
1374         break;
1375     default:
1376         break;
1377     }
1378     return backgroundRect.contains(localRect);
1379 }
1380
1381 static bool isCandidateForOpaquenessTest(const RenderBox& childBox)
1382 {
1383     const RenderStyle& childStyle = childBox.style();
1384     if (childStyle.position() != StaticPosition && childBox.containingBlock() != childBox.parent())
1385         return false;
1386     if (childStyle.visibility() != VISIBLE)
1387         return false;
1388 #if ENABLE(CSS_SHAPES)
1389     if (childStyle.shapeOutside())
1390         return false;
1391 #endif
1392     if (!childBox.width() || !childBox.height())
1393         return false;
1394     if (RenderLayer* childLayer = childBox.layer()) {
1395         if (childLayer->isComposited())
1396             return false;
1397         // FIXME: Deal with z-index.
1398         if (!childStyle.hasAutoZIndex())
1399             return false;
1400         if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1401             return false;
1402     }
1403     return true;
1404 }
1405
1406 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1407 {
1408     if (!maxDepthToTest)
1409         return false;
1410     for (auto& childBox : childrenOfType<RenderBox>(*this)) {
1411         if (!isCandidateForOpaquenessTest(childBox))
1412             continue;
1413         LayoutPoint childLocation = childBox.location();
1414         if (childBox.isRelPositioned())
1415             childLocation.move(childBox.relativePositionOffset());
1416         LayoutRect childLocalRect = localRect;
1417         childLocalRect.moveBy(-childLocation);
1418         if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1419             // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1420             if (childBox.style().position() == StaticPosition)
1421                 return false;
1422             continue;
1423         }
1424         if (childLocalRect.maxY() > childBox.height() || childLocalRect.maxX() > childBox.width())
1425             continue;
1426         if (childBox.backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1427             return true;
1428         if (childBox.foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1429             return true;
1430     }
1431     return false;
1432 }
1433
1434 bool RenderBox::computeBackgroundIsKnownToBeObscured()
1435 {
1436     // Test to see if the children trivially obscure the background.
1437     // FIXME: This test can be much more comprehensive.
1438     if (!hasBackground())
1439         return false;
1440     // Table and root background painting is special.
1441     if (isTable() || isRoot())
1442         return false;
1443
1444     LayoutRect backgroundRect;
1445     if (!getBackgroundPaintedExtent(backgroundRect))
1446         return false;
1447     return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1448 }
1449
1450 bool RenderBox::backgroundHasOpaqueTopLayer() const
1451 {
1452     const FillLayer* fillLayer = style().backgroundLayers();
1453     if (!fillLayer || fillLayer->clip() != BorderFillBox)
1454         return false;
1455
1456     // Clipped with local scrolling
1457     if (hasOverflowClip() && fillLayer->attachment() == LocalBackgroundAttachment)
1458         return false;
1459
1460     if (fillLayer->hasOpaqueImage(*this) && fillLayer->hasRepeatXY() && fillLayer->image()->canRender(this, style().effectiveZoom()))
1461         return true;
1462
1463     // If there is only one layer and no image, check whether the background color is opaque
1464     if (!fillLayer->next() && !fillLayer->hasImage()) {
1465         Color bgColor = style().visitedDependentColor(CSSPropertyBackgroundColor);
1466         if (bgColor.isValid() && bgColor.alpha() == 255)
1467             return true;
1468     }
1469
1470     return false;
1471 }
1472
1473 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1474 {
1475     if (!paintInfo.shouldPaintWithinRoot(*this) || style().visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
1476         return;
1477
1478     LayoutRect paintRect = LayoutRect(paintOffset, size());
1479     paintMaskImages(paintInfo, paintRect);
1480 }
1481
1482 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1483 {
1484     // Figure out if we need to push a transparency layer to render our mask.
1485     bool pushTransparencyLayer = false;
1486     bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1487     bool flattenCompositingLayers = view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1488     CompositeOperator compositeOp = CompositeSourceOver;
1489
1490     bool allMaskImagesLoaded = true;
1491     
1492     if (!compositedMask || flattenCompositingLayers) {
1493         pushTransparencyLayer = true;
1494         StyleImage* maskBoxImage = style().maskBoxImage().image();
1495         const FillLayer* maskLayers = style().maskLayers();
1496
1497         // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1498         if (maskBoxImage)
1499             allMaskImagesLoaded &= maskBoxImage->isLoaded();
1500
1501         if (maskLayers)
1502             allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1503
1504         paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1505         paintInfo.context->beginTransparencyLayer(1);
1506         compositeOp = CompositeSourceOver;
1507     }
1508
1509     if (allMaskImagesLoaded) {
1510         paintFillLayers(paintInfo, Color(), style().maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1511         paintNinePieceImage(paintInfo.context, paintRect, style(), style().maskBoxImage(), compositeOp);
1512     }
1513     
1514     if (pushTransparencyLayer)
1515         paintInfo.context->endTransparencyLayer();
1516 }
1517
1518 LayoutRect RenderBox::maskClipRect()
1519 {
1520     const NinePieceImage& maskBoxImage = style().maskBoxImage();
1521     if (maskBoxImage.image()) {
1522         LayoutRect borderImageRect = borderBoxRect();
1523         
1524         // Apply outsets to the border box.
1525         borderImageRect.expand(style().maskBoxImageOutsets());
1526         return borderImageRect;
1527     }
1528     
1529     LayoutRect result;
1530     LayoutRect borderBox = borderBoxRect();
1531     for (const FillLayer* maskLayer = style().maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1532         if (maskLayer->image()) {
1533             BackgroundImageGeometry geometry;
1534             // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1535             calculateBackgroundImageGeometry(0, maskLayer, borderBox, geometry);
1536             result.unite(geometry.destRect());
1537         }
1538     }
1539     return result;
1540 }
1541
1542 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1543     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1544 {
1545     Vector<const FillLayer*, 8> layers;
1546     const FillLayer* curLayer = fillLayer;
1547     bool shouldDrawBackgroundInSeparateBuffer = false;
1548     while (curLayer) {
1549         layers.append(curLayer);
1550         // Stop traversal when an opaque layer is encountered.
1551         // FIXME : It would be possible for the following occlusion culling test to be more aggressive 
1552         // on layers with no repeat by testing whether the image covers the layout rect.
1553         // Testing that here would imply duplicating a lot of calculations that are currently done in
1554         // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1555         // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1556         // and pass it down.
1557
1558         if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal)
1559             shouldDrawBackgroundInSeparateBuffer = true;
1560
1561         // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1562         if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(*this) && curLayer->image()->canRender(this, style().effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal)
1563             break;
1564         curLayer = curLayer->next();
1565     }
1566
1567     GraphicsContext* context = paintInfo.context;
1568     if (!context)
1569         shouldDrawBackgroundInSeparateBuffer = false;
1570
1571     BaseBackgroundColorUsage baseBgColorUsage = BaseBackgroundColorUse;
1572
1573     if (shouldDrawBackgroundInSeparateBuffer) {
1574         paintFillLayer(paintInfo, c, *layers.rbegin(), rect, bleedAvoidance, op, backgroundObject, BaseBackgroundColorOnly);
1575         baseBgColorUsage = BaseBackgroundColorSkip;
1576         context->beginTransparencyLayer(1);
1577     }
1578
1579     Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend();
1580     for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it)
1581         paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject, baseBgColorUsage);
1582
1583     if (shouldDrawBackgroundInSeparateBuffer)
1584         context->endTransparencyLayer();
1585 }
1586
1587 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1588     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
1589 {
1590     paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, 0, LayoutSize(), op, backgroundObject, baseBgColorUsage);
1591 }
1592
1593 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1594 {
1595     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1596         if (curLayer->image() && image == curLayer->image()->data())
1597             return true;
1598     }
1599
1600     return false;
1601 }
1602
1603 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1604 {
1605     if (!parent())
1606         return;
1607
1608     if ((style().borderImage().image() && style().borderImage().image()->data() == image) ||
1609         (style().maskBoxImage().image() && style().maskBoxImage().image()->data() == image)) {
1610         repaint();
1611         return;
1612     }
1613
1614 #if ENABLE(CSS_SHAPES)
1615     ShapeValue* shapeOutsideValue = style().shapeOutside();
1616     if (!view().frameView().isInLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1617         ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1618         markShapeOutsideDependentsForLayout();
1619     }
1620 #endif
1621
1622     bool didFullRepaint = repaintLayerRectsForImage(image, style().backgroundLayers(), true);
1623     if (!didFullRepaint)
1624         repaintLayerRectsForImage(image, style().maskLayers(), false);
1625
1626     if (!isComposited())
1627         return;
1628
1629     if (layer()->hasCompositedMask() && layersUseImage(image, style().maskLayers()))
1630         layer()->contentChanged(MaskImageChanged);
1631     if (layersUseImage(image, style().backgroundLayers()))
1632         layer()->contentChanged(BackgroundImageChanged);
1633 }
1634
1635 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1636 {
1637     LayoutRect rendererRect;
1638     RenderBox* layerRenderer = 0;
1639
1640     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1641         if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style().effectiveZoom())) {
1642             // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1643             bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1644             if (!layerRenderer) {
1645                 if (drawingRootBackground) {
1646                     layerRenderer = &view();
1647
1648                     LayoutUnit rw = toRenderView(*layerRenderer).frameView().contentsWidth();
1649                     LayoutUnit rh = toRenderView(*layerRenderer).frameView().contentsHeight();
1650
1651                     rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1652                         -layerRenderer->marginTop(),
1653                         std::max(layerRenderer->width() + layerRenderer->horizontalMarginExtent() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1654                         std::max(layerRenderer->height() + layerRenderer->verticalMarginExtent() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1655                 } else {
1656                     layerRenderer = this;
1657                     rendererRect = borderBoxRect();
1658                 }
1659             }
1660
1661             BackgroundImageGeometry geometry;
1662             layerRenderer->calculateBackgroundImageGeometry(0, curLayer, rendererRect, geometry);
1663             if (geometry.hasNonLocalGeometry()) {
1664                 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1665                 // in order to get the right destRect, just repaint the entire renderer.
1666                 layerRenderer->repaint();
1667                 return true;
1668             }
1669             
1670             LayoutRect rectToRepaint = geometry.destRect();
1671             bool shouldClipToLayer = true;
1672
1673             // If this is the root background layer, we may need to extend the repaintRect if the FrameView has an
1674             // extendedBackground. We should only extend the rect if it is already extending the full width or height
1675             // of the rendererRect.
1676             if (drawingRootBackground && view().frameView().hasExtendedBackgroundRectForPainting()) {
1677                 shouldClipToLayer = false;
1678                 IntRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1679                 if (rectToRepaint.width() == rendererRect.width()) {
1680                     rectToRepaint.move(extendedBackgroundRect.x(), 0);
1681                     rectToRepaint.setWidth(extendedBackgroundRect.width());
1682                 }
1683                 if (rectToRepaint.height() == rendererRect.height()) {
1684                     rectToRepaint.move(0, extendedBackgroundRect.y());
1685                     rectToRepaint.setHeight(extendedBackgroundRect.height());
1686                 }
1687             }
1688
1689             layerRenderer->repaintRectangle(rectToRepaint, shouldClipToLayer);
1690             if (geometry.destRect() == rendererRect)
1691                 return true;
1692         }
1693     }
1694     return false;
1695 }
1696
1697 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1698 {
1699     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1700         return false;
1701         
1702     bool isControlClip = hasControlClip();
1703     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1704     
1705     if (!isControlClip && !isOverflowClip)
1706         return false;
1707     
1708     if (paintInfo.phase == PaintPhaseOutline)
1709         paintInfo.phase = PaintPhaseChildOutlines;
1710     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1711         paintInfo.phase = PaintPhaseBlockBackground;
1712         paintObject(paintInfo, accumulatedOffset);
1713         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1714     }
1715     float deviceScaleFactor = document().deviceScaleFactor();
1716     FloatRect clipRect = snapRectToDevicePixels((isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, currentRenderNamedFlowFragment(), IgnoreOverlayScrollbarSize, paintInfo.phase)), deviceScaleFactor);
1717     paintInfo.context->save();
1718     if (style().hasBorderRadius())
1719         paintInfo.context->clipRoundedRect(style().getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1720     paintInfo.context->clip(clipRect);
1721     return true;
1722 }
1723
1724 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1725 {
1726     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1727
1728     paintInfo.context->restore();
1729     if (originalPhase == PaintPhaseOutline) {
1730         paintInfo.phase = PaintPhaseSelfOutline;
1731         paintObject(paintInfo, accumulatedOffset);
1732         paintInfo.phase = originalPhase;
1733     } else if (originalPhase == PaintPhaseChildBlockBackground)
1734         paintInfo.phase = originalPhase;
1735 }
1736
1737 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1738 {
1739     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1740     // here.
1741     LayoutRect clipRect = borderBoxRectInRegion(region);
1742     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1743     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1744
1745     // Subtract out scrollbars if we have them.
1746      if (layer()) {
1747         if (style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1748             clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1749         clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1750      }
1751
1752     return clipRect;
1753 }
1754
1755 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1756 {
1757     LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1758     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1759
1760     if (!style().clipLeft().isAuto()) {
1761         LayoutUnit c = valueForLength(style().clipLeft(), borderBoxRect.width());
1762         clipRect.move(c, 0);
1763         clipRect.contract(c, 0);
1764     }
1765
1766     // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1767     // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1768
1769     if (!style().clipRight().isAuto())
1770         clipRect.contract(width() - valueForLength(style().clipRight(), width()), 0);
1771
1772     if (!style().clipTop().isAuto()) {
1773         LayoutUnit c = valueForLength(style().clipTop(), borderBoxRect.height());
1774         clipRect.move(0, c);
1775         clipRect.contract(0, c);
1776     }
1777
1778     if (!style().clipBottom().isAuto())
1779         clipRect.contract(0, height() - valueForLength(style().clipBottom(), height()));
1780
1781     return clipRect;
1782 }
1783
1784 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
1785 {    
1786     RenderRegion* containingBlockRegion = 0;
1787     LayoutUnit logicalTopPosition = logicalTop();
1788     if (region) {
1789         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1790         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1791         containingBlockRegion = cb->clampToStartAndEndRegions(region);
1792     }
1793
1794     LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
1795
1796     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1797     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1798     // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1799     // doesn't fit, we can use the line offset, but we need to grow it by the margin to reflect the fact that the margin was
1800     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1801     if (childMarginStart > 0) {
1802         LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
1803         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1804         LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
1805         if (startOffset > startContentSideWithMargin)
1806             result += childMarginStart;
1807         else
1808             result += startOffset - startContentSide;
1809     }
1810     
1811     if (childMarginEnd > 0) {
1812         LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
1813         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1814         LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
1815         if (endOffset > endContentSideWithMargin)
1816             result += childMarginEnd;
1817         else
1818             result += endOffset - endContentSide;
1819     }
1820
1821     return result;
1822 }
1823
1824 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1825 {
1826 #if ENABLE(CSS_GRID_LAYOUT)
1827     if (hasOverrideContainingBlockLogicalWidth())
1828         return overrideContainingBlockContentLogicalWidth();
1829 #endif
1830
1831     RenderBlock* cb = containingBlock();
1832     return cb->availableLogicalWidth();
1833 }
1834
1835 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1836 {
1837 #if ENABLE(CSS_GRID_LAYOUT)
1838     if (hasOverrideContainingBlockLogicalHeight())
1839         return overrideContainingBlockContentLogicalHeight();
1840 #endif
1841
1842     RenderBlock* cb = containingBlock();
1843     return cb->availableLogicalHeight(heightType);
1844 }
1845
1846 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1847 {
1848     if (!region)
1849         return containingBlockLogicalWidthForContent();
1850
1851     RenderBlock* cb = containingBlock();
1852     RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1853     // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1854     // If it should, the following line should call containingBlockLogicalWidthForContent.
1855     LayoutUnit result = cb->availableLogicalWidth();
1856     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1857     if (!boxInfo)
1858         return result;
1859     return std::max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1860 }
1861
1862 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1863 {
1864     RenderBlock* cb = containingBlock();
1865     RenderRegion* containingBlockRegion = 0;
1866     LayoutUnit logicalTopPosition = logicalTop();
1867     if (region) {
1868         LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1869         logicalTopPosition = std::max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1870         containingBlockRegion = cb->clampToStartAndEndRegions(region);
1871     }
1872     return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1873 }
1874
1875 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1876 {
1877 #if ENABLE(CSS_GRID_LAYOUT)
1878     if (hasOverrideContainingBlockLogicalHeight())
1879         return overrideContainingBlockContentLogicalHeight();
1880 #endif
1881
1882     RenderBlock* cb = containingBlock();
1883     if (cb->hasOverrideHeight())
1884         return cb->overrideLogicalContentHeight();
1885
1886     const RenderStyle& containingBlockStyle = cb->style();
1887     Length logicalHeightLength = containingBlockStyle.logicalHeight();
1888
1889     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1890     if (!logicalHeightLength.isFixed()) {
1891         LayoutUnit fillFallbackExtent = containingBlockStyle.isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1892         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1893         return std::min(fillAvailableExtent, fillFallbackExtent);
1894     }
1895
1896     // Use the content box logical height as specified by the style.
1897     return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
1898 }
1899
1900 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1901 {
1902     if (repaintContainer == this)
1903         return;
1904
1905     if (view().layoutStateEnabled() && !repaintContainer) {
1906         LayoutState* layoutState = view().layoutState();
1907         LayoutSize offset = layoutState->m_paintOffset + locationOffset();
1908         if (style().hasInFlowPosition() && layer())
1909             offset += layer()->offsetForInFlowPosition();
1910         transformState.move(offset);
1911         return;
1912     }
1913
1914     bool containerSkipped;
1915     auto o = container(repaintContainer, &containerSkipped);
1916     if (!o)
1917         return;
1918
1919     bool isFixedPos = style().position() == FixedPosition;
1920     bool hasTransform = hasLayer() && layer()->transform();
1921     // If this box has a transform, it acts as a fixed position container for fixed descendants,
1922     // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1923     if (hasTransform && !isFixedPos)
1924         mode &= ~IsFixed;
1925     else if (isFixedPos)
1926         mode |= IsFixed;
1927
1928     if (wasFixed)
1929         *wasFixed = mode & IsFixed;
1930     
1931     LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint(transformState.mappedPoint()));
1932     
1933     bool preserve3D = mode & UseTransforms && (o->style().preserves3D() || style().preserves3D());
1934     if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
1935         TransformationMatrix t;
1936         getTransformFromContainer(o, containerOffset, t);
1937         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1938     } else
1939         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1940
1941     if (containerSkipped) {
1942         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1943         // to just subtract the delta between the repaintContainer and o.
1944         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1945         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1946         return;
1947     }
1948
1949     mode &= ~ApplyContainerFlip;
1950
1951     // For fixed positioned elements inside out-of-flow named flows, we do not want to
1952     // map their position further to regions based on their coordinates inside the named flows.
1953     if (!o->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
1954         o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1955     else
1956         o->mapLocalToContainer(toRenderLayerModelObject(o), transformState, mode, wasFixed);
1957 }
1958
1959 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1960 {
1961     ASSERT(ancestorToStopAt != this);
1962
1963     bool ancestorSkipped;
1964     auto container = this->container(ancestorToStopAt, &ancestorSkipped);
1965     if (!container)
1966         return 0;
1967
1968     bool isFixedPos = style().position() == FixedPosition;
1969     bool hasTransform = hasLayer() && layer()->transform();
1970
1971     LayoutSize adjustmentForSkippedAncestor;
1972     if (ancestorSkipped) {
1973         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1974         // to just subtract the delta between the ancestor and o.
1975         adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(container);
1976     }
1977
1978     bool offsetDependsOnPoint = false;
1979     LayoutSize containerOffset = offsetFromContainer(container, LayoutPoint(), &offsetDependsOnPoint);
1980
1981     bool preserve3D = container->style().preserves3D() || style().preserves3D();
1982     if (shouldUseTransformFromContainer(container)) {
1983         TransformationMatrix t;
1984         getTransformFromContainer(container, containerOffset, t);
1985         t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
1986         
1987         geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform);
1988     } else {
1989         containerOffset += adjustmentForSkippedAncestor;
1990         geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform);
1991     }
1992     
1993     return ancestorSkipped ? ancestorToStopAt : container;
1994 }
1995
1996 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1997 {
1998     bool isFixedPos = style().position() == FixedPosition;
1999     bool hasTransform = hasLayer() && layer()->transform();
2000     if (hasTransform && !isFixedPos) {
2001         // If this box has a transform, it acts as a fixed position container for fixed descendants,
2002         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
2003         mode &= ~IsFixed;
2004     } else if (isFixedPos)
2005         mode |= IsFixed;
2006
2007     RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
2008 }
2009
2010 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint&, bool* offsetDependsOnPoint) const
2011 {
2012     // A region "has" boxes inside it without being their container. 
2013     ASSERT(o == container() || o->isRenderRegion());
2014
2015     LayoutSize offset;    
2016     if (isInFlowPositioned())
2017         offset += offsetForInFlowPosition();
2018
2019     if (!isInline() || isReplaced())
2020         offset += topLeftLocationOffset();
2021
2022     if (o->isBox())
2023         offset -= toRenderBox(o)->scrolledContentOffset();
2024
2025     if (style().position() == AbsolutePosition && o->isInFlowPositioned() && o->isRenderInline())
2026         offset += toRenderInline(o)->offsetForInFlowPositionedInline(this);
2027
2028     if (offsetDependsOnPoint)
2029         *offsetDependsOnPoint |= o->isRenderFlowThread();
2030
2031     return offset;
2032 }
2033
2034 std::unique_ptr<InlineElementBox> RenderBox::createInlineBox()
2035 {
2036     return std::make_unique<InlineElementBox>(*this);
2037 }
2038
2039 void RenderBox::dirtyLineBoxes(bool fullLayout)
2040 {
2041     if (m_inlineBoxWrapper) {
2042         if (fullLayout) {
2043             delete m_inlineBoxWrapper;
2044             m_inlineBoxWrapper = nullptr;
2045         } else
2046             m_inlineBoxWrapper->dirtyLineBoxes();
2047     }
2048 }
2049
2050 void RenderBox::positionLineBox(InlineElementBox& box)
2051 {
2052     if (isOutOfFlowPositioned()) {
2053         // Cache the x position only if we were an INLINE type originally.
2054         bool wasInline = style().isOriginalDisplayInlineType();
2055         if (wasInline) {
2056             // The value is cached in the xPos of the box.  We only need this value if
2057             // our object was inline originally, since otherwise it would have ended up underneath
2058             // the inlines.
2059             RootInlineBox& rootBox = box.root();
2060             rootBox.blockFlow().setStaticInlinePositionForChild(*this, rootBox.lineTopWithLeading(), LayoutUnit::fromFloatRound(box.logicalLeft()));
2061             if (style().hasStaticInlinePosition(box.isHorizontal()))
2062                 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
2063         } else {
2064             // Our object was a block originally, so we make our normal flow position be
2065             // just below the line box (as though all the inlines that came before us got
2066             // wrapped in an anonymous block, which is what would have happened had we been
2067             // in flow).  This value was cached in the y() of the box.
2068             layer()->setStaticBlockPosition(box.logicalTop());
2069             if (style().hasStaticBlockPosition(box.isHorizontal()))
2070                 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
2071         }
2072
2073         // Nuke the box.
2074         box.removeFromParent();
2075         delete &box;
2076         return;
2077     }
2078
2079     if (isReplaced()) {
2080         setLocation(LayoutPoint(box.topLeft()));
2081         setInlineBoxWrapper(&box);
2082     }
2083 }
2084
2085 void RenderBox::deleteLineBoxWrapper()
2086 {
2087     if (m_inlineBoxWrapper) {
2088         if (!documentBeingDestroyed())
2089             m_inlineBoxWrapper->removeFromParent();
2090         delete m_inlineBoxWrapper;
2091         m_inlineBoxWrapper = nullptr;
2092     }
2093 }
2094
2095 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
2096 {
2097     if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
2098         return LayoutRect();
2099
2100     LayoutRect r = visualOverflowRect();
2101
2102     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
2103     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
2104     r.move(view().layoutDelta());
2105     
2106     // We have to use maximalOutlineSize() because a child might have an outline
2107     // that projects outside of our overflowRect.
2108     ASSERT(style().outlineSize() <= view().maximalOutlineSize());
2109     r.inflate(view().maximalOutlineSize());
2110     
2111     computeRectForRepaint(repaintContainer, r);
2112     return r;
2113 }
2114
2115 static inline bool shouldApplyContainersClipAndOffset(const RenderLayerModelObject* repaintContainer, RenderBox* containerBox)
2116 {
2117 #if PLATFORM(IOS)
2118     if (!repaintContainer || repaintContainer != containerBox)
2119         return true;
2120
2121     return !containerBox->hasLayer() || !containerBox->layer()->usesCompositedScrolling();
2122 #else
2123     UNUSED_PARAM(repaintContainer);
2124     UNUSED_PARAM(containerBox);
2125     return true;
2126 #endif
2127 }
2128
2129 void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
2130 {
2131     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2132     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2133     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
2134     // properly even during layout, since the rect remains flipped all the way until the end.
2135     //
2136     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
2137     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
2138     // physical coordinate space of the repaintContainer.
2139     const RenderStyle& styleToUse = style();
2140     // LayoutState is only valid for root-relative, non-fixed position repainting
2141     if (view().layoutStateEnabled() && !repaintContainer && styleToUse.position() != FixedPosition) {
2142         LayoutState* layoutState = view().layoutState();
2143
2144         if (layer() && layer()->transform())
2145             rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2146
2147         // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2148         if (styleToUse.hasInFlowPosition() && layer())
2149             rect.move(layer()->offsetForInFlowPosition());
2150
2151         rect.moveBy(location());
2152         rect.move(layoutState->m_paintOffset);
2153         if (layoutState->m_clipped)
2154             rect.intersect(layoutState->m_clipRect);
2155         return;
2156     }
2157
2158     if (hasReflection())
2159         rect.unite(reflectedRect(rect));
2160
2161     if (repaintContainer == this) {
2162         if (repaintContainer->style().isFlippedBlocksWritingMode())
2163             flipForWritingMode(rect);
2164         return;
2165     }
2166
2167     bool containerSkipped;
2168     auto o = container(repaintContainer, &containerSkipped);
2169     if (!o)
2170         return;
2171     
2172     EPosition position = styleToUse.position();
2173
2174     // This code isn't necessary for in-flow RenderFlowThreads.
2175     // Don't add the location of the region in the flow thread for absolute positioned
2176     // elements because their absolute position already pushes them down through
2177     // the regions so adding this here and then adding the topLeft again would cause
2178     // us to add the height twice.
2179     // The same logic applies for elements flowed directly into the flow thread. Their topLeft member
2180     // will already contain the portion rect of the region.
2181     if (o->isOutOfFlowRenderFlowThread() && position != AbsolutePosition && containingBlock() != flowThreadContainingBlock()) {
2182         RenderRegion* firstRegion = nullptr;
2183         RenderRegion* lastRegion = nullptr;
2184         if (toRenderFlowThread(o)->getRegionRangeForBox(this, firstRegion, lastRegion))
2185             rect.moveBy(firstRegion->flowThreadPortionRect().location());
2186     }
2187
2188     if (isWritingModeRoot() && !isOutOfFlowPositioned())
2189         flipForWritingMode(rect);
2190
2191     LayoutPoint topLeft = rect.location();
2192     topLeft.move(locationOffset());
2193
2194     // We are now in our parent container's coordinate space.  Apply our transform to obtain a bounding box
2195     // in the parent's coordinate space that encloses us.
2196     if (hasLayer() && layer()->transform()) {
2197         fixed = position == FixedPosition;
2198         rect = LayoutRect(encloseRectToDevicePixels(layer()->transform()->mapRect(rect), document().deviceScaleFactor()));
2199         topLeft = rect.location();
2200         topLeft.move(locationOffset());
2201     } else if (position == FixedPosition)
2202         fixed = true;
2203
2204     if (position == AbsolutePosition && o->isInFlowPositioned() && o->isRenderInline())
2205         topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(this);
2206     else if (styleToUse.hasInFlowPosition() && layer()) {
2207         // Apply the relative position offset when invalidating a rectangle.  The layer
2208         // is translated, but the render box isn't, so we need to do this to get the
2209         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
2210         // flag on the RenderObject has been cleared, so use the one on the style().
2211         topLeft += layer()->offsetForInFlowPosition();
2212     }
2213
2214     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2215     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2216     rect.setLocation(topLeft);
2217     if (o->hasOverflowClip()) {
2218         RenderBox* containerBox = toRenderBox(o);
2219         if (shouldApplyContainersClipAndOffset(repaintContainer, containerBox)) {
2220             containerBox->applyCachedClipAndScrollOffsetForRepaint(rect);
2221             if (rect.isEmpty())
2222                 return;
2223         }
2224     }
2225
2226     if (containerSkipped) {
2227         // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2228         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
2229         rect.move(-containerOffset);
2230         return;
2231     }
2232
2233     o->computeRectForRepaint(repaintContainer, rect, fixed);
2234 }
2235
2236 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2237 {
2238     if (oldRect.location() != m_frameRect.location()) {
2239         LayoutRect newRect = m_frameRect;
2240         // The child moved.  Invalidate the object's old and new positions.  We have to do this
2241         // since the object may not have gotten a layout.
2242         m_frameRect = oldRect;
2243         repaint();
2244         repaintOverhangingFloats(true);
2245         m_frameRect = newRect;
2246         repaint();
2247         repaintOverhangingFloats(true);
2248     }
2249 }
2250
2251 void RenderBox::repaintOverhangingFloats(bool)
2252 {
2253 }
2254
2255 void RenderBox::updateLogicalWidth()
2256 {
2257     LogicalExtentComputedValues computedValues;
2258     computeLogicalWidthInRegion(computedValues);
2259
2260     setLogicalWidth(computedValues.m_extent);
2261     setLogicalLeft(computedValues.m_position);
2262     setMarginStart(computedValues.m_margins.m_start);
2263     setMarginEnd(computedValues.m_margins.m_end);
2264 }
2265
2266 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2267 {
2268     computedValues.m_extent = logicalWidth();
2269     computedValues.m_position = logicalLeft();
2270     computedValues.m_margins.m_start = marginStart();
2271     computedValues.m_margins.m_end = marginEnd();
2272
2273     if (isOutOfFlowPositioned()) {
2274         // FIXME: This calculation is not patched for block-flow yet.
2275         // https://bugs.webkit.org/show_bug.cgi?id=46500
2276         computePositionedLogicalWidth(computedValues, region);
2277         return;
2278     }
2279
2280     // If layout is limited to a subtree, the subtree root's logical width does not change.
2281     if (element() && view().frameView().layoutRoot(true) == this)
2282         return;
2283
2284     // The parent box is flexing us, so it has increased or decreased our
2285     // width.  Use the width from the style context.
2286     // FIXME: Account for block-flow in flexible boxes.
2287     // https://bugs.webkit.org/show_bug.cgi?id=46418
2288     if (hasOverrideWidth() && (isRubyRun() || style().borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) {
2289         computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2290         return;
2291     }
2292
2293     // FIXME: Account for block-flow in flexible boxes.
2294     // https://bugs.webkit.org/show_bug.cgi?id=46418
2295     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == VERTICAL);
2296     bool stretching = (parent()->style().boxAlign() == BSTRETCH);
2297     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2298
2299     const RenderStyle& styleToUse = style();
2300     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse.logicalWidth();
2301
2302     RenderBlock* cb = containingBlock();
2303     LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2304     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2305     
2306     if (isInline() && !isInlineBlockOrInlineTable()) {
2307         // just calculate margins
2308         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2309         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2310         if (treatAsReplaced)
2311             computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2312         return;
2313     }
2314
2315     // Width calculations
2316     if (treatAsReplaced)
2317         computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2318     else {
2319         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2320         if (hasPerpendicularContainingBlock)
2321             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2322         LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse.logicalWidth(), containerWidthInInlineDirection, cb, region);
2323         computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2324     }
2325
2326     // Margin calculations.
2327     if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2328         computedValues.m_margins.m_start = minimumValueForLength(styleToUse.marginStart(), containerLogicalWidth);
2329         computedValues.m_margins.m_end = minimumValueForLength(styleToUse.marginEnd(), containerLogicalWidth);
2330     } else {
2331         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2332         if (avoidsFloats() && cb->containsFloats())
2333             containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2334         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2335         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2336             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2337             hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2338     }
2339     
2340     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2341         && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated()
2342 #if ENABLE(CSS_GRID_LAYOUT)
2343         && !cb->isRenderGrid()
2344 #endif
2345         ) {
2346         LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(*this);
2347         bool hasInvertedDirection = cb->style().isLeftToRightDirection() != style().isLeftToRightDirection();
2348         if (hasInvertedDirection)
2349             computedValues.m_margins.m_start = newMargin;
2350         else
2351             computedValues.m_margins.m_end = newMargin;
2352     }
2353 }
2354
2355 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2356 {
2357     LayoutUnit marginStart = 0;
2358     LayoutUnit marginEnd = 0;
2359     return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2360 }
2361
2362 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2363 {
2364     marginStart = minimumValueForLength(style().marginStart(), availableLogicalWidth);
2365     marginEnd = minimumValueForLength(style().marginEnd(), availableLogicalWidth);
2366     return availableLogicalWidth - marginStart - marginEnd;
2367 }
2368
2369 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2370 {
2371     if (logicalWidthLength.type() == FillAvailable)
2372         return fillAvailableMeasure(availableLogicalWidth);
2373
2374     LayoutUnit minLogicalWidth = 0;
2375     LayoutUnit maxLogicalWidth = 0;
2376     computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2377
2378     if (logicalWidthLength.type() == MinContent)
2379         return minLogicalWidth + borderAndPadding;
2380
2381     if (logicalWidthLength.type() == MaxContent)
2382         return maxLogicalWidth + borderAndPadding;
2383
2384     if (logicalWidthLength.type() == FitContent) {
2385         minLogicalWidth += borderAndPadding;
2386         maxLogicalWidth += borderAndPadding;
2387         return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2388     }
2389
2390     ASSERT_NOT_REACHED();
2391     return 0;
2392 }
2393
2394 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2395     const RenderBlock* cb, RenderRegion* region) const
2396 {
2397     if (!logicalWidth.isIntrinsicOrAuto()) {
2398         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2399         return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2400     }
2401
2402     if (logicalWidth.isIntrinsic())
2403         return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2404
2405     LayoutUnit marginStart = 0;
2406     LayoutUnit marginEnd = 0;
2407     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2408
2409     if (shrinkToAvoidFloats() && cb->containsFloats())
2410         logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2411
2412     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2413         return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2414     return logicalWidthResult;
2415 }
2416
2417 static bool flexItemHasStretchAlignment(const RenderBox& flexitem)
2418 {
2419     auto parent = flexitem.parent();
2420     return flexitem.style().alignSelf() == AlignStretch || (flexitem.style().alignSelf() == AlignAuto && parent->style().alignItems() == AlignStretch);
2421 }
2422
2423 static bool isStretchingColumnFlexItem(const RenderBox& flexitem)
2424 {
2425     auto parent = flexitem.parent();
2426     if (parent->isDeprecatedFlexibleBox() && parent->style().boxOrient() == VERTICAL && parent->style().boxAlign() == BSTRETCH)
2427         return true;
2428
2429     // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2430     if (parent->isFlexibleBox() && parent->style().flexWrap() == FlexNoWrap && parent->style().isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2431         return true;
2432     return false;
2433 }
2434
2435 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2436 {
2437     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
2438     // but they allow text to sit on the same line as the marquee.
2439     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2440         return true;
2441
2442     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
2443     // min-width and width.  max-width is only clamped if it is also intrinsic.
2444     Length logicalWidth = (widthType == MaxSize) ? style().logicalMaxWidth() : style().logicalWidth();
2445     if (logicalWidth.type() == Intrinsic)
2446         return true;
2447
2448     // Children of a horizontal marquee do not fill the container by default.
2449     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
2450     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
2451     // block-flow (as well as how marquee overflow should relate to block flow).
2452     // https://bugs.webkit.org/show_bug.cgi?id=46472
2453     if (parent()->style().overflowX() == OMARQUEE) {
2454         EMarqueeDirection dir = parent()->style().marqueeDirection();
2455         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2456             return true;
2457     }
2458
2459     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2460     // In the case of columns that have a stretch alignment, we go ahead and layout at the
2461     // stretched size to avoid an extra layout when applying alignment.
2462     if (parent()->isFlexibleBox()) {
2463         // For multiline columns, we need to apply align-content first, so we can't stretch now.
2464         if (!parent()->style().isColumnFlexDirection() || parent()->style().flexWrap() != FlexNoWrap)
2465             return true;
2466         if (!flexItemHasStretchAlignment(*this))
2467             return true;
2468     }
2469
2470     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
2471     // that don't stretch their kids lay out their children at their intrinsic widths.
2472     // FIXME: Think about block-flow here.
2473     // https://bugs.webkit.org/show_bug.cgi?id=46473
2474     if (parent()->isDeprecatedFlexibleBox() && (parent()->style().boxOrient() == HORIZONTAL || parent()->style().boxAlign() != BSTRETCH))
2475         return true;
2476
2477     // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2478     // stretching column flexbox.
2479     // FIXME: Think about block-flow here.
2480     // https://bugs.webkit.org/show_bug.cgi?id=46473
2481     if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(*this) && element() && (is<HTMLInputElement>(*element()) || is<HTMLSelectElement>(*element()) || is<HTMLButtonElement>(*element()) || is<HTMLTextAreaElement>(*element()) || is<HTMLLegendElement>(*element())))
2482         return true;
2483
2484     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2485         return true;
2486
2487     return false;
2488 }
2489
2490 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2491 {
2492     const RenderStyle& containingBlockStyle = containingBlock->style();
2493     Length marginStartLength = style().marginStartUsing(&containingBlockStyle);
2494     Length marginEndLength = style().marginEndUsing(&containingBlockStyle);
2495
2496     if (isFloating() || isInline()) {
2497         // Inline blocks/tables and floats don't have their margins increased.
2498         marginStart = minimumValueForLength(marginStartLength, containerWidth);
2499         marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2500         return;
2501     }
2502
2503     // Case One: The object is being centered in the containing block's available logical width.
2504     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2505         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style().textAlign() == WEBKIT_CENTER)) {
2506         // Other browsers center the margin box for align=center elements so we match them here.
2507         LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2508         LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2509         LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2510         marginStart = centeredMarginBoxStart + marginStartWidth;
2511         marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2512         return;
2513     } 
2514     
2515     // Case Two: The object is being pushed to the start of the containing block's available logical width.
2516     if (marginEndLength.isAuto() && childWidth < containerWidth) {
2517         marginStart = valueForLength(marginStartLength, containerWidth);
2518         marginEnd = containerWidth - childWidth - marginStart;
2519         return;
2520     } 
2521     
2522     // Case Three: The object is being pushed to the end of the containing block's available logical width.
2523     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_LEFT)
2524         || (containingBlockStyle.isLeftToRightDirection() && containingBlockStyle.textAlign() == WEBKIT_RIGHT));
2525     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2526         marginEnd = valueForLength(marginEndLength, containerWidth);
2527         marginStart = containerWidth - childWidth - marginEnd;
2528         return;
2529     } 
2530     
2531     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
2532     // auto margins will just turn into 0.
2533     marginStart = minimumValueForLength(marginStartLength, containerWidth);
2534     marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2535 }
2536
2537 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2538 {
2539     // Make sure nobody is trying to call this with a null region.
2540     if (!region)
2541         return 0;
2542
2543     // If we have computed our width in this region already, it will be cached, and we can
2544     // just return it.
2545     RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2546     if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2547         return boxInfo;
2548
2549     // No cached value was found, so we have to compute our insets in this region.
2550     // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2551     // support to cover all boxes.
2552     RenderFlowThread* flowThread = flowThreadContainingBlock();
2553     if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style().writingMode() != style().writingMode())
2554         return 0;
2555
2556     LogicalExtentComputedValues computedValues;
2557     computeLogicalWidthInRegion(computedValues, region);
2558
2559     // Now determine the insets based off where this object is supposed to be positioned.
2560     RenderBlock* cb = containingBlock();
2561     RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
2562     RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
2563     LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
2564     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2565     
2566     LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2567     LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2568     LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2569     LayoutUnit logicalLeftInRegion = computedValues.m_position;
2570     LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2571     LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2572     LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2573     LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2574     LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2575
2576     LayoutUnit logicalLeftOffset = 0;
2577     
2578     if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
2579         LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(*this, marginStartInRegion, region);
2580         if (cb->style().isLeftToRightDirection())
2581             logicalLeftDelta += startPositionDelta;
2582         else
2583             logicalRightDelta += startPositionDelta;
2584     }
2585
2586     if (cb->style().isLeftToRightDirection())
2587         logicalLeftOffset += logicalLeftDelta;
2588     else
2589         logicalLeftOffset -= (widthDelta + logicalRightDelta);
2590     
2591     LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2592     bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2593             || (style().isLeftToRightDirection() && logicalLeftOffset)
2594             || (!style().isLeftToRightDirection() && logicalRightOffset);
2595
2596     // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2597     if (cacheFlag == CacheRenderBoxRegionInfo)
2598         return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2599     return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2600 }
2601
2602 static bool shouldFlipBeforeAfterMargins(const RenderStyle& containingBlockStyle, const RenderStyle* childStyle)
2603 {
2604     ASSERT(containingBlockStyle.isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2605     WritingMode childWritingMode = childStyle->writingMode();
2606     bool shouldFlip = false;
2607     switch (containingBlockStyle.writingMode()) {
2608     case TopToBottomWritingMode:
2609         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2610         break;
2611     case BottomToTopWritingMode:
2612         shouldFlip = (childWritingMode == RightToLeftWritingMode);
2613         break;
2614     case RightToLeftWritingMode:
2615         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2616         break;
2617     case LeftToRightWritingMode:
2618         shouldFlip = (childWritingMode == BottomToTopWritingMode);
2619         break;
2620     }
2621
2622     if (!containingBlockStyle.isLeftToRightDirection())
2623         shouldFlip = !shouldFlip;
2624
2625     return shouldFlip;
2626 }
2627
2628 void RenderBox::updateLogicalHeight()
2629 {
2630     LogicalExtentComputedValues computedValues;
2631     computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2632
2633     setLogicalHeight(computedValues.m_extent);
2634     setLogicalTop(computedValues.m_position);
2635     setMarginBefore(computedValues.m_margins.m_before);
2636     setMarginAfter(computedValues.m_margins.m_after);
2637 }
2638
2639 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2640 {
2641     computedValues.m_extent = logicalHeight;
2642     computedValues.m_position = logicalTop;
2643
2644     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2645     if (isTableCell() || (isInline() && !isReplaced()))
2646         return;
2647
2648     Length h;
2649     if (isOutOfFlowPositioned())
2650         computePositionedLogicalHeight(computedValues);
2651     else {
2652         RenderBlock* cb = containingBlock();
2653         bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2654     
2655         if (!hasPerpendicularContainingBlock) {
2656             bool shouldFlipBeforeAfter = cb->style().writingMode() != style().writingMode();
2657             computeBlockDirectionMargins(cb,
2658                 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2659                 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2660         }
2661
2662         // For tables, calculate margins only.
2663         if (isTable()) {
2664             if (hasPerpendicularContainingBlock) {
2665                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2666                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2667                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2668                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2669             }
2670             return;
2671         }
2672
2673         // FIXME: Account for block-flow in flexible boxes.
2674         // https://bugs.webkit.org/show_bug.cgi?id=46418
2675         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL;
2676         bool stretching = parent()->style().boxAlign() == BSTRETCH;
2677         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2678         bool checkMinMaxHeight = false;
2679
2680         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2681         // grab our cached flexible height.
2682         // FIXME: Account for block-flow in flexible boxes.
2683         // https://bugs.webkit.org/show_bug.cgi?id=46418
2684         if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
2685             h = Length(overrideLogicalContentHeight(), Fixed);
2686         else if (treatAsReplaced)
2687             h = Length(computeReplacedLogicalHeight(), Fixed);
2688         else {
2689             h = style().logicalHeight();
2690             checkMinMaxHeight = true;
2691         }
2692
2693         // Block children of horizontal flexible boxes fill the height of the box.
2694         // FIXME: Account for block-flow in flexible boxes.
2695         // https://bugs.webkit.org/show_bug.cgi?id=46418
2696         if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style().boxOrient() == HORIZONTAL
2697                 && parent()->isStretchingChildren()) {
2698             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2699             checkMinMaxHeight = false;
2700         }
2701
2702         LayoutUnit heightResult;
2703         if (checkMinMaxHeight) {
2704             heightResult = computeLogicalHeightUsing(style().logicalHeight());
2705             if (heightResult == -1)
2706                 heightResult = computedValues.m_extent;
2707             heightResult = constrainLogicalHeightByMinMax(heightResult);
2708         } else {
2709             // The only times we don't check min/max height are when a fixed length has
2710             // been given as an override.  Just use that.  The value has already been adjusted
2711             // for box-sizing.
2712             heightResult = h.value() + borderAndPaddingLogicalHeight();
2713         }
2714
2715         computedValues.m_extent = heightResult;
2716         
2717         if (hasPerpendicularContainingBlock) {
2718             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), &style());
2719             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2720                     shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2721                     shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2722         }
2723     }
2724
2725     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2726     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2727     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2728     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2729     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2730     bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
2731         && (isRoot() || (isBody() && document().documentElement()->renderer()->style().logicalHeight().isPercent())) && !isInline();
2732     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2733         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2734         LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2735         if (isRoot())
2736             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2737         else {
2738             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2739             computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2740         }
2741     }
2742 }
2743
2744 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height) const
2745 {
2746     LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height);
2747     if (logicalHeight != -1)
2748         logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2749     return logicalHeight;
2750 }
2751
2752 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height) const
2753 {
2754     LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height);
2755     if (heightIncludingScrollbar == -1)
2756         return -1;
2757     return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2758 }
2759
2760 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height) const
2761 {
2762     if (height.isFixed())
2763         return height.value();
2764     if (height.isPercent())
2765         return computePercentageLogicalHeight(height);
2766     return -1;
2767 }
2768
2769 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock, bool isPerpendicularWritingMode) const
2770 {
2771     // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2772     // and percent heights of children should be resolved against the multicol or paged container.
2773     if (containingBlock->isInFlowRenderFlowThread() && !isPerpendicularWritingMode)
2774         return true;
2775
2776     // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2777     // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2778     if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2779         return false;
2780     return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style().logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2781 }
2782
2783 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2784 {
2785     LayoutUnit availableHeight = -1;
2786     
2787     bool skippedAutoHeightContainingBlock = false;
2788     RenderBlock* cb = containingBlock();
2789     const RenderBox* containingBlockChild = this;
2790     LayoutUnit rootMarginBorderPaddingHeight = 0;
2791     bool isHorizontal = isHorizontalWritingMode();
2792     while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb, isHorizontal != cb->isHorizontalWritingMode())) {
2793         if (cb->isBody() || cb->isRoot())
2794             rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2795         skippedAutoHeightContainingBlock = true;
2796         containingBlockChild = cb;
2797         cb = cb->containingBlock();
2798         cb->addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2799     }
2800
2801     const RenderStyle& cbstyle = cb->style();
2802
2803     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2804     // explicitly specified that can be used for any percentage computations.
2805     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle.logicalHeight().isAuto() || (!cbstyle.logicalTop().isAuto() && !cbstyle.logicalBottom().isAuto()));
2806
2807     bool includeBorderPadding = isTable();
2808
2809     if (isHorizontal != cb->isHorizontalWritingMode())
2810         availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2811 #if ENABLE(CSS_GRID_LAYOUT)
2812     else if (hasOverrideContainingBlockLogicalHeight())
2813         availableHeight = overrideContainingBlockContentLogicalHeight();
2814 #endif
2815     else if (is<RenderTableCell>(*cb)) {
2816         if (!skippedAutoHeightContainingBlock) {
2817             // Table cells violate what the CSS spec says to do with heights. Basically we
2818             // don't care if the cell specified a height or not. We just always make ourselves
2819             // be a percentage of the cell's current content height.
2820             if (!cb->hasOverrideHeight()) {
2821                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2822                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2823                 // While we can't get all cases right, we can at least detect when the cell has a specified
2824                 // height or when the table has a specified height. In these cases we want to initially have
2825                 // no size and allow the flexing of the table or the cell to its specified height to cause us
2826                 // to grow to fill the space. This could end up being wrong in some cases, but it is
2827                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2828                 RenderTableCell& cell = downcast<RenderTableCell>(*cb);
2829                 if (scrollsOverflowY() && (!cell.style().logicalHeight().isAuto() || !cell.table()->style().logicalHeight().isAuto()))
2830                     return 0;
2831                 return -1;
2832             }
2833             availableHeight = cb->overrideLogicalContentHeight();
2834             includeBorderPadding = true;
2835         }
2836     } else if (cbstyle.logicalHeight().isFixed()) {
2837         LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle.logicalHeight().value());
2838         availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight()));
2839     } else if (cbstyle.logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2840         // We need to recur and compute the percentage height for our containing block.
2841         LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle.logicalHeight());
2842         if (heightWithScrollbar != -1) {
2843             LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2844             // We need to adjust for min/max height because this method does not
2845             // handle the min/max of the current block, its caller does. So the
2846             // return value from the recursive call will not have been adjusted
2847             // yet.
2848             LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight());
2849             availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2850         }
2851     } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2852         // Don't allow this to affect the block' height() member variable, since this
2853         // can get called while the block is still laying out its kids.
2854         LogicalExtentComputedValues computedValues;
2855         cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2856         availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2857     } else if (cb->isRenderView())
2858         availableHeight = view().pageOrViewLogicalHeight();
2859
2860     if (availableHeight == -1)
2861         return availableHeight;
2862
2863     availableHeight -= rootMarginBorderPaddingHeight;
2864
2865     LayoutUnit result = valueForLength(height, availableHeight);
2866     if (includeBorderPadding) {
2867         // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2868         // It is necessary to use the border-box to match WinIE's broken
2869         // box model. This is essential for sizing inside
2870         // table cells using percentage heights.
2871         result -= borderAndPaddingLogicalHeight();
2872         return std::max<LayoutUnit>(0, result);
2873     }
2874     return result;
2875 }
2876
2877 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2878 {
2879     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style().logicalWidth()), shouldComputePreferred);
2880 }
2881
2882 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2883 {
2884     LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMinWidth().isPercent()) || style().logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMinWidth());
2885     LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style().logicalMaxWidth().isPercent()) || style().logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style().logicalMaxWidth());
2886     return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2887 }
2888
2889 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2890 {
2891     switch (logicalWidth.type()) {
2892         case Fixed:
2893             return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2894         case MinContent:
2895         case MaxContent: {
2896             // MinContent/MaxContent don't need the availableLogicalWidth argument.
2897             LayoutUnit availableLogicalWidth = 0;
2898             return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2899         }
2900         case FitContent:
2901         case FillAvailable:
2902         case Percent: 
2903         case Calculated: {
2904             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2905             // containing block's block-flow.
2906             // https://bugs.webkit.org/show_bug.cgi?id=46496
2907             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(downcast<RenderBoxModelObject>(container())) : containingBlockLogicalWidthForContent();
2908             Length containerLogicalWidth = containingBlock()->style().logicalWidth();
2909             // FIXME: Handle cases when containing block width is calculated or viewport percent.
2910             // https://bugs.webkit.org/show_bug.cgi?id=91071
2911             if (logicalWidth.isIntrinsic())
2912                 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2913             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2914                 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2915         }
2916         FALLTHROUGH;
2917         case Intrinsic:
2918         case MinIntrinsic:
2919         case Auto:
2920         case Relative:
2921         case Undefined:
2922             return intrinsicLogicalWidth();
2923     }
2924
2925     ASSERT_NOT_REACHED();
2926     return 0;
2927 }
2928
2929 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2930 {
2931     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style().logicalHeight()));
2932 }
2933
2934 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2935 {
2936     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style().logicalMinHeight());
2937     LayoutUnit maxLogicalHeight = style().logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style().logicalMaxHeight());
2938     return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
2939 }
2940
2941 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2942 {
2943     switch (logicalHeight.type()) {
2944         case Fixed:
2945             return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
2946         case Percent:
2947         case Calculated:
2948         {
2949             auto cb = isOutOfFlowPositioned() ? container() : containingBlock();
2950             while (cb->isAnonymous() && !is<RenderView>(*cb)) {
2951                 cb = cb->containingBlock();
2952                 downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2953             }
2954
2955             // FIXME: This calculation is not patched for block-flow yet.
2956             // https://bugs.webkit.org/show_bug.cgi?id=46500
2957             if (cb->isOutOfFlowPositioned() && cb->style().height().isAuto() && !(cb->style().top().isAuto() || cb->style().bottom().isAuto())) {
2958                 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
2959                 RenderBlock& block = downcast<RenderBlock>(*cb);
2960                 LogicalExtentComputedValues computedValues;
2961                 block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
2962                 LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
2963                 LayoutUnit newHeight = block.adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2964                 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
2965             }
2966             
2967             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2968             // containing block's block-flow.
2969             // https://bugs.webkit.org/show_bug.cgi?id=46496
2970             LayoutUnit availableHeight;
2971             if (isOutOfFlowPositioned())
2972                 availableHeight = containingBlockLogicalHeightForPositioned(downcast<RenderBoxModelObject>(cb));
2973             else {
2974                 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
2975                 // It is necessary to use the border-box to match WinIE's broken
2976                 // box model.  This is essential for sizing inside
2977                 // table cells using percentage heights.
2978                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
2979                 // https://bugs.webkit.org/show_bug.cgi?id=46997
2980                 while (cb && !cb->isRenderView() && (cb->style().logicalHeight().isAuto() || cb->style().logicalHeight().isPercent())) {
2981                     if (cb->isTableCell()) {
2982                         // Don't let table cells squeeze percent-height replaced elements
2983                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2984                         availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
2985                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
2986                     }
2987                     downcast<RenderBlock>(*cb).addPercentHeightDescendant(const_cast<RenderBox&>(*this));
2988                     cb = cb->containingBlock();
2989                 }
2990             }
2991             return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
2992         }
2993         default:
2994             return intrinsicLogicalHeight();
2995     }
2996 }
2997
2998 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
2999 {
3000     return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style().logicalHeight(), heightType));
3001 }
3002
3003 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
3004 {
3005     // We need to stop here, since we don't want to increase the height of the table
3006     // artificially.  We're going to rely on this cell getting expanded to some new
3007     // height, and then when we lay out again we'll use the calculation below.
3008     if (isTableCell() && (h.isAuto() || h.isPercent())) {
3009         if (hasOverrideHeight())
3010             return overrideLogicalContentHeight();
3011         return logicalHeight() - borderAndPaddingLogicalHeight();
3012     }
3013
3014     if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
3015         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3016         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
3017         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
3018     }
3019
3020     LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h);
3021     if (heightIncludingScrollbar != -1)
3022         return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
3023
3024     // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
3025     // https://bugs.webkit.org/show_bug.cgi?id=46500
3026     if (is<RenderBlock>(*this) && isOutOfFlowPositioned() && style().height().isAuto() && !(style().top().isAuto() || style().bottom().isAuto())) {
3027         RenderBlock& block = const_cast<RenderBlock&>(downcast<RenderBlock>(*this));
3028         LogicalExtentComputedValues computedValues;
3029         block.computeLogicalHeight(block.logicalHeight(), 0, computedValues);
3030         LayoutUnit newContentHeight = computedValues.m_extent - block.borderAndPaddingLogicalHeight() - block.scrollbarLogicalHeight();
3031         return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
3032     }
3033
3034     // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
3035     LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
3036     if (heightType == ExcludeMarginBorderPadding) {
3037         // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
3038         availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
3039     }
3040     return availableHeight;
3041 }
3042
3043 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
3044 {
3045     if (isTableCell()) {
3046         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
3047         // we may just do it with an extra anonymous block inside the cell.
3048         marginBefore = 0;
3049         marginAfter = 0;
3050         return;
3051     }
3052
3053     // Margins are calculated with respect to the logical width of
3054     // the containing block (8.3)
3055     LayoutUnit cw = containingBlockLogicalWidthForContent();
3056     const RenderStyle& containingBlockStyle = containingBlock->style();
3057     marginBefore = minimumValueForLength(style().marginBeforeUsing(&containingBlockStyle), cw);
3058     marginAfter = minimumValueForLength(style().marginAfterUsing(&containingBlockStyle), cw);
3059 }
3060
3061 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
3062 {
3063     LayoutUnit marginBefore;
3064     LayoutUnit marginAfter;
3065     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
3066     containingBlock->setMarginBeforeForChild(*this, marginBefore);
3067     containingBlock->setMarginAfterForChild(*this, marginAfter);
3068 }
3069
3070 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
3071 {
3072     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3073         return containingBlockLogicalHeightForPositioned(containingBlock, false);
3074
3075     if (is<RenderBox>(*containingBlock)) {
3076         bool isFixedPosition = style().position() == FixedPosition;
3077
3078         RenderFlowThread* flowThread = flowThreadContainingBlock();
3079         if (!flowThread) {
3080             if (isFixedPosition && is<RenderView>(*containingBlock))
3081                 return downcast<RenderView>(*containingBlock).clientLogicalWidthForFixedPosition();
3082
3083             return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3084         }
3085
3086         if (isFixedPosition && is<RenderNamedFlowThread>(*containingBlock))
3087             return containingBlock->view().clientLogicalWidth();
3088
3089         if (!is<RenderBlock>(*containingBlock))
3090             return downcast<RenderBox>(*containingBlock).clientLogicalWidth();
3091
3092         const RenderBlock& cb = downcast<RenderBlock>(*containingBlock);
3093         RenderBoxRegionInfo* boxInfo = nullptr;
3094         if (!region) {
3095             if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
3096                 return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
3097             if (isWritingModeRoot()) {
3098                 LayoutUnit cbPageOffset = cb.offsetFromLogicalTopOfFirstPage();
3099                 RenderRegion* cbRegion = cb.regionAtBlockOffset(cbPageOffset);
3100                 if (cbRegion)
3101                     boxInfo = cb.renderBoxRegionInfo(cbRegion);
3102             }
3103         } else if (region && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3104             RenderRegion* containingBlockRegion = cb.clampToStartAndEndRegions(region);
3105             boxInfo = cb.renderBoxRegionInfo(containingBlockRegion);
3106         }
3107         return (boxInfo) ? std::max<LayoutUnit>(0, cb.clientLogicalWidth() - (cb.logicalWidth() - boxInfo->logicalWidth())) : cb.clientLogicalWidth();
3108     }
3109
3110     ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
3111
3112     const RenderInline* flow = toRenderInline(containingBlock);
3113     InlineFlowBox* first = flow->firstLineBox();
3114     InlineFlowBox* last = flow->lastLineBox();
3115
3116     // If the containing block is empty, return a width of 0.
3117     if (!first || !last)
3118         return 0;
3119
3120     LayoutUnit fromLeft;
3121     LayoutUnit fromRight;
3122     if (containingBlock->style().isLeftToRightDirection()) {
3123         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
3124         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
3125     } else {
3126         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
3127         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
3128     }
3129
3130     return std::max<LayoutUnit>(0, fromRight - fromLeft);
3131 }
3132
3133 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
3134 {
3135     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3136         return containingBlockLogicalWidthForPositioned(containingBlock, nullptr, false);
3137
3138     if (containingBlock->isBox()) {
3139         bool isFixedPosition = style().position() == FixedPosition;
3140
3141         if (isFixedPosition && is<RenderView>(*containingBlock))
3142             return downcast<RenderView>(*containingBlock).clientLogicalHeightForFixedPosition();
3143
3144         const RenderBlock* cb = is<RenderBlock>(*containingBlock) ? downcast<RenderBlock>(containingBlock) : containingBlock->containingBlock();
3145         LayoutUnit result = cb->clientLogicalHeight();
3146         RenderFlowThread* flowThread = flowThreadContainingBlock();
3147         if (flowThread && is<RenderFlowThread>(*containingBlock) && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3148             if (is<RenderNamedFlowThread>(*containingBlock) && isFixedPosition)
3149                 return containingBlock->view().clientLogicalHeight();
3150             return downcast<RenderFlowThread>(*containingBlock).contentLogicalHeightOfFirstRegion();
3151         }
3152         return result;
3153     }
3154         
3155     ASSERT(is<RenderInline>(*containingBlock) && containingBlock->isInFlowPositioned());
3156
3157     const RenderInline& flow = downcast<RenderInline>(*containingBlock);
3158     InlineFlowBox* first = flow.firstLineBox();
3159     InlineFlowBox* last = flow.lastLineBox();
3160
3161     // If the containing block is empty, return a height of 0.
3162     if (!first || !last)
3163         return 0;
3164
3165     LayoutUnit heightResult;
3166     LayoutRect boundingBox = flow.linesBoundingBox();
3167     if (containingBlock->isHorizontalWritingMode())
3168         heightResult = boundingBox.height();
3169     else
3170         heightResult = boundingBox.width();
3171     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
3172     return heightResult;
3173 }
3174
3175 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3176 {
3177     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3178         return;
3179
3180     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3181     if (child->parent()->style().direction() == LTR) {
3182         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
3183         for (auto current = child->parent(); current && current != containerBlock; current = current->container()) {
3184             if (is<RenderBox>(*current)) {
3185                 staticPosition += downcast<RenderBox>(*current).logicalLeft();
3186                 if (region && is<RenderBlock>(*current)) {
3187                     const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3188                     region = currentBlock.clampToStartAndEndRegions(region);
3189                     RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3190                     if (boxInfo)
3191                         staticPosition += boxInfo->logicalLeft();
3192                 }
3193             }
3194         }
3195         logicalLeft.setValue(Fixed, staticPosition);
3196     } else {
3197         RenderBox& enclosingBox = child->parent()->enclosingBox();
3198         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
3199         for (RenderElement* current = &enclosingBox; current; current = current->container()) {
3200             if (is<RenderBox>(*current)) {
3201                 if (current != containerBlock)
3202                     staticPosition -= downcast<RenderBox>(*current).logicalLeft();
3203                 if (current == &enclosingBox)
3204                     staticPosition -= enclosingBox.logicalWidth();
3205                 if (region && is<RenderBlock>(*current)) {
3206                     const RenderBlock& currentBlock = downcast<RenderBlock>(*current);
3207                     region = currentBlock.clampToStartAndEndRegions(region);
3208                     RenderBoxRegionInfo* boxInfo = currentBlock.renderBoxRegionInfo(region);
3209                     if (boxInfo) {
3210                         if (current != containerBlock)
3211                             staticPosition -= currentBlock.logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3212                         if (current == &enclosingBox)
3213                             staticPosition += enclosingBox.logicalWidth() - boxInfo->logicalWidth();
3214                     }
3215                 }
3216             }
3217             if (current == containerBlock)
3218                 break;
3219         }
3220         logicalRight.setValue(Fixed, staticPosition);
3221     }
3222 }
3223
3224 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3225 {
3226     if (isReplaced()) {
3227         // FIXME: Positioned replaced elements inside a flow thread are not working properly
3228         // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3229         computePositionedLogicalWidthReplaced(computedValues);
3230         return;
3231     }
3232
3233     // QUESTIONS
3234     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3235     // the type 'static' in determining whether to calculate the static distance?
3236     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3237
3238     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3239     // than or less than the computed width().  Be careful of box-sizing and
3240     // percentage issues.
3241
3242     // The following is based off of the W3C Working Draft from April 11, 2006 of
3243     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3244     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3245     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3246     // correspond to text from the spec)
3247
3248
3249     // We don't use containingBlock(), since we may be positioned by an enclosing
3250     // relative positioned inline.
3251     const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3252     
3253     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3254
3255     // Use the container block's direction except when calculating the static distance
3256     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3257     // of the CSS 2.1 test suite
3258     TextDirection containerDirection = containerBlock->style().direction();
3259
3260     bool isHorizontal = isHorizontalWritingMode();
3261     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3262     const Length marginLogicalLeft = isHorizontal ? style().marginLeft() : style().marginTop();
3263     const Length marginLogicalRight = isHorizontal ? style().marginRight() : style().marginBottom();
3264
3265     Length logicalLeftLength = style().logicalLeft();
3266     Length logicalRightLength = style().logicalRight();
3267
3268     /*---------------------------------------------------------------------------*\
3269      * For the purposes of this section and the next, the term "static position"
3270      * (of an element) refers, roughly, to the position an element would have had
3271      * in the normal flow. More precisely:
3272      *
3273      * * The static position for 'left' is the distance from the left edge of the
3274      *   containing block to the left margin edge of a hypothetical box that would
3275      *   have been the first box of the element if its 'position' property had
3276      *   been 'static' and 'float' had been 'none'. The value is negative if the
3277      *   hypothetical box is to the left of the containing block.
3278      * * The static position for 'right' is the distance from the right edge of the
3279      *   containing block to the right margin edge of the same hypothetical box as
3280      *   above. The value is positive if the hypothetical box is to the left of the
3281      *   containing block's edge.
3282      *
3283      * But rather than actually calculating the dimensions of that hypothetical box,
3284      * user agents are free to make a guess at its probable position.
3285      *
3286      * For the purposes of calculating the static position, the containing block of
3287      * fixed positioned elements is the initial containing block instead of the
3288      * viewport, and all scrollable boxes should be assumed to be scrolled to their
3289      * origin.
3290     \*---------------------------------------------------------------------------*/
3291
3292     // see FIXME 1
3293     // Calculate the static distance if needed.
3294     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3295     
3296     // Calculate constraint equation values for 'width' case.
3297     computePositionedLogicalWidthUsing(style().logicalWidth(), containerBlock, containerDirection,
3298                                        containerLogicalWidth, bordersPlusPadding,
3299                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3300                                        computedValues);
3301
3302     // Calculate constraint equation values for 'max-width' case.
3303     if (!style().logicalMaxWidth().isUndefined()) {
3304         LogicalExtentComputedValues maxValues;
3305
3306         computePositionedLogicalWidthUsing(style().logicalMaxWidth(), containerBlock, containerDirection,
3307                                            containerLogicalWidth, bordersPlusPadding,
3308                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3309                                            maxValues);
3310
3311         if (computedValues.m_extent > maxValues.m_extent) {
3312             computedValues.m_extent = maxValues.m_extent;
3313             computedValues.m_position = maxValues.m_position;
3314             computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3315             computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3316         }
3317     }
3318
3319     // Calculate constraint equation values for 'min-width' case.
3320     if (!style().logicalMinWidth().isZero() || style().logicalMinWidth().isIntrinsic()) {
3321         LogicalExtentComputedValues minValues;
3322
3323         computePositionedLogicalWidthUsing(style().logicalMinWidth(), containerBlock, containerDirection,
3324                                            containerLogicalWidth, bordersPlusPadding,
3325                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3326                                            minValues);
3327
3328         if (computedValues.m_extent < minValues.m_extent) {
3329             computedValues.m_extent = minValues.m_extent;
3330             computedValues.m_position = minValues.m_position;
3331             computedValues.m_margins.m_start = minValues.m_margins.m_start;
3332             computedValues.m_margins.m_end = minValues.m_margins.m_end;
3333         }
3334     }
3335
3336     computedValues.m_extent += bordersPlusPadding;
3337     
3338     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3339     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3340     RenderFlowThread* flowThread = flowThreadContainingBlock();
3341     if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3342         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3343         LayoutUnit logicalLeftPos = computedValues.m_position;
3344         const RenderBlock& renderBlock = downcast<RenderBlock>(*containerBlock);
3345         LayoutUnit cbPageOffset = renderBlock.offsetFromLogicalTopOfFirstPage();
3346         RenderRegion* cbRegion = renderBlock.regionAtBlockOffset(cbPageOffset);
3347         if (cbRegion) {
3348             RenderBoxRegionInfo* boxInfo = renderBlock.renderBoxRegionInfo(cbRegion);
3349             if (boxInfo) {
3350                 logicalLeftPos += boxInfo->logicalLeft();
3351                 computedValues.m_position = logicalLeftPos;
3352             }
3353         }
3354     }
3355 }
3356
3357 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
3358 {
3359     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3360     // along this axis, then we need to flip the coordinate.  This can only happen if the containing block is both a flipped mode and perpendicular to us.
3361     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style().isFlippedBlocksWritingMode()) {
3362         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3363         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
3364     } else
3365         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
3366 }
3367
3368 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
3369                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3370                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3371                                                    LogicalExtentComputedValues& computedValues) const
3372 {
3373     if (logicalWidth.isIntrinsic())
3374         logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3375
3376     // 'left' and 'right' cannot both be 'auto' because one would of been
3377     // converted to the static position already
3378     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3379
3380     LayoutUnit logicalLeftValue = 0;
3381
3382     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
3383
3384     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3385     bool logicalLeftIsAuto = logicalLeft.isAuto();
3386     bool logicalRightIsAuto = logicalRight.isAuto();
3387     LayoutUnit& marginLogicalLeftValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3388     LayoutUnit& marginLogicalRightValue = style().isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3389
3390     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3391         /*-----------------------------------------------------------------------*\
3392          * If none of the three is 'auto': If both 'margin-left' and 'margin-
3393          * right' are 'auto', solve the equation under the extra constraint that
3394          * the two margins get equal values, unless this would make them negative,
3395          * in which case when direction of the containing block is 'ltr' ('rtl'),
3396          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3397          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3398          * solve the equation for that value. If the values are over-constrained,
3399          * ignore the value for 'left' (in case the 'direction' property of the
3400          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3401          * and solve for that value.
3402         \*-----------------------------------------------------------------------*/
3403         // NOTE:  It is not necessary to solve for 'right' in the over constrained
3404         // case because the value is not used for any further calculations.
3405
3406         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3407         computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3408
3409         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3410
3411         // Margins are now the only unknown
3412         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3413             // Both margins auto, solve for equality
3414             if (availableSpace >= 0) {
3415                 marginLogicalLeftValue = availableSpace / 2; // split the difference
3416                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3417             } else {
3418                 // Use the containing block's direction rather than the parent block's
3419                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3420                 if (containerDirection == LTR) {
3421                     marginLogicalLeftValue = 0;
3422                     marginLogicalRightValue = availableSpace; // will be negative
3423                 } else {
3424                     marginLogicalLeftValue = availableSpace; // will be negative
3425                     marginLogicalRightValue = 0;
3426                 }
3427             }
3428         } else if (marginLogicalLeft.isAuto()) {
3429             // Solve for left margin
3430             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3431             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3432         } else if (marginLogicalRight.isAuto()) {
3433             // Solve for right margin
3434             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3435             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3436         } else {
3437             // Over-constrained, solve for left if direction is RTL
3438             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3439             marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3440
3441             // Use the containing block's direction rather than the parent block's
3442             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3443             if (containerDirection == RTL)
3444                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3445         }
3446     } else {
3447         /*--------------------------------------------------------------------*\
3448          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3449          * to 0, and pick the one of the following six rules that applies.
3450          *
3451          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3452          *    width is shrink-to-fit. Then solve for 'left'
3453          *
3454          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3455          * ------------------------------------------------------------------
3456          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3457          *    the 'direction' property of the containing block is 'ltr' set
3458          *    'left' to the static position, otherwise set 'right' to the
3459          *    static position. Then solve for 'left' (if 'direction is 'rtl')
3460          *    or 'right' (if 'direction' is 'ltr').
3461          * ------------------------------------------------------------------
3462          *
3463          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3464          *    width is shrink-to-fit . Then solve for 'right'
3465          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3466          *    for 'left'
3467          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3468          *    for 'width'
3469          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3470          *    for 'right'
3471          *
3472          * Calculation of the shrink-to-fit width is similar to calculating the
3473          * width of a table cell using the automatic table layout algorithm.
3474          * Roughly: calculate the preferred width by formatting the content
3475          * without breaking lines other than where explicit line breaks occur,
3476          * and also calculate the preferred minimum width, e.g., by trying all
3477          * possible line breaks. CSS 2.1 does not define the exact algorithm.
3478          * Thirdly, calculate the available width: this is found by solving
3479          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3480          * to 0.
3481          *
3482          * Then the shrink-to-fit width is:
3483          * min(max(preferred minimum width, available width), preferred width).
3484         \*--------------------------------------------------------------------*/
3485         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3486         // because the value is not used for any further calculations.
3487
3488         // Calculate margins, 'auto' margins are ignored.
3489         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3490         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3491
3492         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3493
3494         // FIXME: Is there a faster way to find the correct case?
3495         // Use rule/case that applies.
3496         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3497             // RULE 1: (use shrink-to-fit for width, and solve of left)
3498             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3499
3500             // FIXME: would it be better to have shrink-to-fit in one step?
3501             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3502             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3503             LayoutUnit availableWidth = availableSpace - logicalRightValue;
3504             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3505             logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3506         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3507             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3508             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3509
3510             // FIXME: would it be better to have shrink-to-fit in one step?
3511             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3512             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3513             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
3514             computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3515         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3516             // RULE 4: (solve for left)
3517             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3518             logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3519         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3520             // RULE 5: (solve for width)
3521             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3522             computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth));
3523         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3524             // RULE 6: (no need solve for right)
3525             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3526             computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3527         }
3528     }
3529
3530     // Use computed values to calculate the horizontal position.
3531
3532     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
3533     // positioned, inline because right now, it is using the logical left position
3534     // of the first line box when really it should use the last line box.  When
3535     // this is fixed elsewhere, this block should be removed.
3536     if (containerBlock->isRenderInline() && !containerBlock->style().isLeftToRightDirection()) {
3537         const RenderInline* flow = toRenderInline(containerBlock);
3538         InlineFlowBox* firstLine = flow->firstLineBox();
3539         InlineFlowBox* lastLine = flow->lastLineBox();
3540         if (firstLine && lastLine && firstLine != lastLine) {
3541             computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3542             return;
3543         }
3544     }
3545
3546     computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3547     computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3548 }
3549
3550 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3551 {
3552     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3553         return;
3554     
3555     // FIXME: The static distance computation has not been patched for mixed writing modes.
3556     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3557     for (RenderElement* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
3558         if (curr->isBox() && !curr->isTableRow())
3559             staticLogicalTop += toRenderBox(curr)->logicalTop();
3560     }
3561     logicalTop.setValue(Fixed, staticLogicalTop);
3562 }
3563
3564 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3565 {
3566     if (isReplaced()) {
3567         computePositionedLogicalHeightReplaced(computedValues);
3568         return;
3569     }
3570
3571     // The following is based off of the W3C Working Draft from April 11, 2006 of
3572     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3573     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3574     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3575     // correspond to text from the spec)
3576
3577
3578     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3579     const RenderBoxModelObject* containerBlock = downcast<RenderBoxModelObject>(container());
3580
3581     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3582
3583     const RenderStyle& styleToUse = style();
3584     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3585     const Length marginBefore = styleToUse.marginBefore();
3586     const Length marginAfter = styleToUse.marginAfter();
3587     Length logicalTopLength = styleToUse.logicalTop();
3588     Length logicalBottomLength = styleToUse.logicalBottom();
3589
3590     /*---------------------------------------------------------------------------*\
3591      * For the purposes of this section and the next, the term "static position"
3592      * (of an element) refers, roughly, to the position an element would have had
3593      * in the normal flow. More precisely, the static position for 'top' is the
3594      * distance from the top edge of the containing block to the top margin edge
3595      * of a hypothetical box that would have been the first box of the element if
3596      * its 'position' property had been 'static' and 'float' had been 'none'. The
3597      * value is negative if the hypothetical box is above the containing block.
3598      *
3599      * But rather than actually calculating the dimensions of that hypothetical
3600      * box, user agents are free to make a guess at its probable position.
3601      *
3602      * For the purposes of calculating the static position, the containing block
3603      * of fixed positioned elements is the initial containing block instead of
3604      * the viewport.
3605     \*---------------------------------------------------------------------------*/
3606
3607     // see FIXME 1
3608     // Calculate the static distance if needed.
3609     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3610
3611     // Calculate constraint equation values for 'height' case.
3612     LayoutUnit logicalHeight = computedValues.m_extent;
3613     computePositionedLogicalHeightUsing(styleToUse.logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3614                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3615                                         computedValues);
3616
3617     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3618     // see FIXME 2
3619
3620     // Calculate constraint equation values for 'max-height' case.
3621     if (!styleToUse.logicalMaxHeight().isUndefined()) {
3622         LogicalExtentComputedValues maxValues;
3623
3624         computePositionedLogicalHeightUsing(styleToUse.logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3625                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3626                                             maxValues);
3627
3628         if (computedValues.m_extent > maxValues.m_extent) {
3629             computedValues.m_extent = maxValues.m_extent;
3630             computedValues.m_position = maxValues.m_position;
3631             computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3632             computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3633         }
3634     }
3635
3636     // Calculate constraint equation values for 'min-height' case.
3637     if (!styleToUse.logicalMinHeight().isZero()) {
3638         LogicalExtentComputedValues minValues;
3639
3640         computePositionedLogicalHeightUsing(styleToUse.logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3641                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3642                                             minValues);
3643
3644         if (computedValues.m_extent < minValues.m_extent) {
3645             computedValues.m_extent = minValues.m_extent;
3646             computedValues.m_position = minValues.m_position;
3647             computedValues.m_margins.m_before = minValues.m_margins.m_before;
3648             computedValues.m_margins.m_after = minValues.m_margins.m_after;
3649         }
3650     }
3651
3652     // Set final height value.
3653     computedValues.m_extent += bordersPlusPadding;
3654     
3655     // Adjust logicalTop if we need to for perpendicular writing modes in regions.
3656     // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3657     RenderFlowThread* flowThread = flowThreadContainingBlock();
3658     if (flowThread && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode() && is<RenderBlock>(*containerBlock)) {
3659         ASSERT(containerBlock->canHaveBoxInfoInRegion());
3660         LayoutUnit logicalTopPos = computedValues.m_position;
3661         const RenderBlock& renderBox = downcast<RenderBlock>(*containerBlock);
3662         LayoutUnit cbPageOffset = renderBox.offsetFromLogicalTopOfFirstPage() - logicalLeft();
3663         RenderRegion* cbRegion = renderBox.regionAtBlockOffset(cbPageOffset);
3664         if (cbRegion) {
3665             RenderBoxRegionInfo* boxInfo = renderBox.renderBoxRegionInfo(cbRegion);
3666             if (boxInfo) {
3667                 logicalTopPos += boxInfo->logicalLeft();
3668                 computedValues.m_position = logicalTopPos;
3669             }
3670         }
3671     }
3672 }
3673
3674 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3675 {
3676     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3677     // along this axis, then we need to flip the coordinate.  This can only happen if the containing block is both a flipped mode and perpendicular to us.
3678     if ((child->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3679         || (child->style().isFlippedBlocksWritingMode() != containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3680         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3681
3682     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3683     if (containerBlock->style().isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3684         if (child->isHorizontalWritingMode())
3685             logicalTopPos += containerBlock->borderBottom();
3686         else
3687             logicalTopPos += containerBlock->borderRight();
3688     } else {
3689         if (child->isHorizontalWritingMode())
3690             logicalTopPos += containerBlock->borderTop();
3691         else
3692             logicalTopPos += containerBlock->borderLeft();
3693     }
3694 }
3695
3696 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3697                                                     LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3698                                                     Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
3699                                                     LogicalExtentComputedValues& computedValues) const
3700 {
3701     // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
3702     // converted to the static position in computePositionedLogicalHeight()
3703     ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
3704
3705     LayoutUnit logicalHeightValue;
3706     LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
3707
3708     const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
3709
3710     LayoutUnit logicalTopValue = 0;
3711     LayoutUnit resolvedLogicalHeight = 0;
3712
3713     bool logicalHeightIsAuto = logicalHeightLength.isAuto();
3714     bool logicalTopIsAuto = logicalTop.isAuto();
3715     bool logicalBottomIsAuto = logicalBottom.isAuto();
3716
3717     // Height is never unsolved for tables.
3718     if (isTable()) {
3719         resolvedLogicalHeight = contentLogicalHeight;
3720         logicalHeightIsAuto = false;
3721     } else
3722         resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
3723
3724     if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3725         /*-----------------------------------------------------------------------*\
3726          * If none of the three are 'auto': If both 'margin-top' and 'margin-
3727          * bottom' are 'auto', solve the equation under the extra constraint that
3728          * the two margins get equal values. If one of 'margin-top' or 'margin-
3729          * bottom' is 'auto', solve the equation for that value. If the values
3730          * are over-constrained, ignore the value for 'bottom' and solve for that
3731          * value.
3732         \*-----------------------------------------------------------------------*/
3733         // NOTE:  It is not necessary to solve for 'bottom' in the over constrained
3734         // case because the value is not used for any further calculations.
3735
3736         logicalHeightValue = resolvedLogicalHeight;
3737         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3738
3739         const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
3740
3741         // Margins are now the only unknown
3742         if (marginBefore.isAuto() && marginAfter.isAuto()) {
3743             // Both margins auto, solve for equality
3744             // NOTE: This may result in negative values.
3745             computedValues.m_margins.m_before = availableSpace / 2; // split the difference
3746             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
3747         } else if (marginBefore.isAuto()) {
3748             // Solve for top margin
3749             computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3750             computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
3751         } else if (marginAfter.isAuto()) {
3752             // Solve for bottom margin
3753             computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3754             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
3755         } else {
3756             // Over-constrained, (no need solve for bottom)
3757             computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3758             computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3759         }
3760     } else {
3761         /*--------------------------------------------------------------------*\
3762          * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3763          * to 0, and pick the one of the following six rules that applies.
3764          *
3765          * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3766          *    the height is based on the content, and solve for 'top'.
3767          *
3768          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3769          * ------------------------------------------------------------------
3770          * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3771          *    set 'top' to the static position, and solve for 'bottom'.
3772          * ------------------------------------------------------------------
3773          *
3774          * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3775          *    the height is based on the content, and solve for 'bottom'.
3776          * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3777          *    solve for 'top'.
3778          * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3779          *    solve for 'height'.
3780          * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3781          *    solve for 'bottom'.
3782         \*--------------------------------------------------------------------*/
3783         // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3784         // because the value is not used for any further calculations.
3785
3786         // Calculate margins, 'auto' margins are ignored.
3787         computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth);
3788         computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth);