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