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