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