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