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