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 * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
27 #include "core/rendering/RenderBox.h"
29 #include "core/HTMLNames.h"
30 #include "core/dom/Document.h"
31 #include "core/editing/htmlediting.h"
32 #include "core/frame/FrameHost.h"
33 #include "core/frame/FrameView.h"
34 #include "core/frame/LocalFrame.h"
35 #include "core/frame/PinchViewport.h"
36 #include "core/frame/Settings.h"
37 #include "core/html/HTMLElement.h"
38 #include "core/html/HTMLFrameElementBase.h"
39 #include "core/html/HTMLFrameOwnerElement.h"
40 #include "core/page/AutoscrollController.h"
41 #include "core/page/EventHandler.h"
42 #include "core/page/Page.h"
43 #include "core/paint/BackgroundImageGeometry.h"
44 #include "core/paint/BoxPainter.h"
45 #include "core/rendering/HitTestResult.h"
46 #include "core/rendering/PaintInfo.h"
47 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
48 #include "core/rendering/RenderFlexibleBox.h"
49 #include "core/rendering/RenderGeometryMap.h"
50 #include "core/rendering/RenderGrid.h"
51 #include "core/rendering/RenderInline.h"
52 #include "core/rendering/RenderLayer.h"
53 #include "core/rendering/RenderListBox.h"
54 #include "core/rendering/RenderListMarker.h"
55 #include "core/rendering/RenderTableCell.h"
56 #include "core/rendering/RenderView.h"
57 #include "core/rendering/compositing/RenderLayerCompositor.h"
58 #include "platform/LengthFunctions.h"
59 #include "platform/geometry/FloatQuad.h"
60 #include "platform/geometry/TransformState.h"
66 using namespace HTMLNames;
68 // Used by flexible boxes when flexing this element and by table cells.
69 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
71 // Used by grid elements to properly size their grid items.
72 // FIXME: Move these into RenderBoxRareData.
73 static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = 0;
74 static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0;
77 // Size of border belt for autoscroll. When mouse pointer in border belt,
78 // autoscroll is started.
79 static const int autoscrollBeltSize = 20;
80 static const unsigned backgroundObscurationTestMaxDepth = 4;
82 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
84 ASSERT(bodyElementRenderer->isBody());
85 // The <body> only paints its background if the root element has defined a background independent of the body,
86 // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
87 RenderObject* documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
88 return documentElementRenderer
89 && !documentElementRenderer->hasBackground()
90 && (documentElementRenderer == bodyElementRenderer->parent());
93 RenderBox::RenderBox(ContainerNode* node)
94 : RenderBoxModelObject(node)
95 , m_intrinsicContentLogicalHeight(-1)
96 , m_minPreferredLogicalWidth(-1)
97 , m_maxPreferredLogicalWidth(-1)
102 void RenderBox::willBeDestroyed()
105 clearContainingBlockOverrideSize();
107 RenderBlock::removePercentHeightDescendantIfNeeded(this);
109 ShapeOutsideInfo::removeInfo(*this);
111 RenderBoxModelObject::willBeDestroyed();
114 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
116 ASSERT(isFloatingOrOutOfFlowPositioned());
118 if (documentBeingDestroyed())
122 RenderBlockFlow* parentBlockFlow = 0;
123 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
124 if (curr->isRenderBlockFlow()) {
125 RenderBlockFlow* currBlockFlow = toRenderBlockFlow(curr);
126 if (!parentBlockFlow || currBlockFlow->containsFloat(this))
127 parentBlockFlow = currBlockFlow;
131 if (parentBlockFlow) {
132 parentBlockFlow->markSiblingsWithFloatsForLayout(this);
133 parentBlockFlow->markAllDescendantsWithFloatsForLayout(this, false);
137 if (isOutOfFlowPositioned())
138 RenderBlock::removePositionedObject(this);
141 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
143 RenderStyle* oldStyle = style();
145 // The background of the root element or the body element could propagate up to
146 // the canvas. Just dirty the entire canvas when our style changes substantially.
147 if ((diff.needsPaintInvalidation() || diff.needsLayout()) && node()
148 && (isHTMLHtmlElement(*node()) || isHTMLBodyElement(*node()))) {
149 view()->setShouldDoFullPaintInvalidation();
151 if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground())
152 view()->compositor()->setNeedsUpdateFixedBackground();
155 // When a layout hint happens and an object's position style changes, we have to do a layout
156 // to dirty the render tree using the old position value now.
157 if (diff.needsFullLayout() && parent() && oldStyle->position() != newStyle.position()) {
158 markContainingBlocksForLayout();
159 if (oldStyle->position() == StaticPosition)
160 setShouldDoFullPaintInvalidation();
161 else if (newStyle.hasOutOfFlowPosition())
162 parent()->setChildNeedsLayout();
163 if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
164 removeFloatingOrPositionedChildFromBlockLists();
166 // FIXME: This branch runs when !oldStyle, which means that layout was never called
167 // so what's the point in invalidating the whole view that we never painted?
168 } else if (isBody()) {
169 view()->setShouldDoFullPaintInvalidation();
172 RenderBoxModelObject::styleWillChange(diff, newStyle);
175 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
177 // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
178 // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
179 // writing mode value before style change here.
180 bool oldHorizontalWritingMode = isHorizontalWritingMode();
182 RenderBoxModelObject::styleDidChange(diff, oldStyle);
184 RenderStyle* newStyle = style();
185 if (needsLayout() && oldStyle)
186 RenderBlock::removePercentHeightDescendantIfNeeded(this);
188 if (RenderBlock::hasPercentHeightContainerMap() && slowFirstChild()
189 && oldHorizontalWritingMode != isHorizontalWritingMode())
190 RenderBlock::clearPercentHeightDescendantsFrom(this);
192 // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
193 // new zoomed coordinate space.
194 if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) {
195 if (int left = layer()->scrollableArea()->scrollXOffset()) {
196 left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
197 layer()->scrollableArea()->scrollToXOffset(left);
199 if (int top = layer()->scrollableArea()->scrollYOffset()) {
200 top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
201 layer()->scrollableArea()->scrollToYOffset(top);
205 // Our opaqueness might have changed without triggering layout.
206 if (diff.needsPaintInvalidation()) {
207 RenderObject* parentToInvalidate = parent();
208 for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
209 parentToInvalidate->invalidateBackgroundObscurationStatus();
210 parentToInvalidate = parentToInvalidate->parent();
214 if (isDocumentElement() || isBody()) {
215 document().view()->recalculateScrollbarOverlayStyle();
216 document().view()->recalculateCustomScrollbarStyle();
218 updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle);
219 updateGridPositionAfterStyleChange(oldStyle);
222 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
224 const ShapeValue* shapeOutside = style.shapeOutside();
225 const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : RenderStyle::initialShapeOutside();
227 Length shapeMargin = style.shapeMargin();
228 Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
230 float shapeImageThreshold = style.shapeImageThreshold();
231 float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
233 // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
234 if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
238 ShapeOutsideInfo::removeInfo(*this);
240 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
242 if (shapeOutside || shapeOutside != oldShapeOutside)
243 markShapeOutsideDependentsForLayout();
246 void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle* oldStyle)
248 if (!oldStyle || !parent() || !parent()->isRenderGrid())
251 if (oldStyle->gridColumnStart() == style()->gridColumnStart()
252 && oldStyle->gridColumnEnd() == style()->gridColumnEnd()
253 && oldStyle->gridRowStart() == style()->gridRowStart()
254 && oldStyle->gridRowEnd() == style()->gridRowEnd()
255 && oldStyle->order() == style()->order()
256 && oldStyle->hasOutOfFlowPosition() == style()->hasOutOfFlowPosition())
259 // It should be possible to not dirty the grid in some cases (like moving an explicitly placed grid item).
260 // For now, it's more simple to just always recompute the grid.
261 toRenderGrid(parent())->dirtyGrid();
264 void RenderBox::updateFromStyle()
266 RenderBoxModelObject::updateFromStyle();
268 RenderStyle* styleToUse = style();
269 bool isRootObject = isDocumentElement();
270 bool isViewObject = isRenderView();
271 bool rootLayerScrolls = document().settings() && document().settings()->rootLayerScrolls();
273 // The root and the RenderView always paint their backgrounds/borders.
274 if (isRootObject || isViewObject)
275 setHasBoxDecorationBackground(true);
277 setFloating(!isOutOfFlowPositioned() && styleToUse->isFloating());
279 bool boxHasOverflowClip = false;
280 if (!styleToUse->isOverflowVisible() && isRenderBlock() && (rootLayerScrolls || !isViewObject)) {
281 // If overflow has been propagated to the viewport, it has no effect here.
282 if (node() != document().viewportDefiningElement())
283 boxHasOverflowClip = true;
286 if (boxHasOverflowClip != hasOverflowClip()) {
287 // FIXME: This shouldn't be required if we tracked the visual overflow
288 // generated by positioned children or self painting layers. crbug.com/345403
289 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling())
290 child->setMayNeedPaintInvalidation(true);
293 setHasOverflowClip(boxHasOverflowClip);
295 setHasTransformRelatedProperty(styleToUse->hasTransformRelatedProperty());
296 setHasReflection(styleToUse->boxReflect());
299 void RenderBox::layout()
301 ASSERT(needsLayout());
303 RenderObject* child = slowFirstChild();
309 LayoutState state(*this, locationOffset());
311 child->layoutIfNeeded();
312 ASSERT(!child->needsLayout());
313 child = child->nextSibling();
315 invalidateBackgroundObscurationStatus();
319 // More IE extensions. clientWidth and clientHeight represent the interior of an object
320 // excluding border and scrollbar.
321 LayoutUnit RenderBox::clientWidth() const
323 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
326 LayoutUnit RenderBox::clientHeight() const
328 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
331 int RenderBox::pixelSnappedClientWidth() const
333 return snapSizeToPixel(clientWidth(), x() + clientLeft());
336 int RenderBox::pixelSnappedClientHeight() const
338 return snapSizeToPixel(clientHeight(), y() + clientTop());
341 int RenderBox::pixelSnappedOffsetWidth() const
343 return snapSizeToPixel(offsetWidth(), x() + clientLeft());
346 int RenderBox::pixelSnappedOffsetHeight() const
348 return snapSizeToPixel(offsetHeight(), y() + clientTop());
351 LayoutUnit RenderBox::scrollWidth() const
353 if (hasOverflowClip())
354 return layer()->scrollableArea()->scrollWidth();
355 // For objects with visible overflow, this matches IE.
356 // FIXME: Need to work right with writing modes.
357 if (style()->isLeftToRightDirection())
358 return std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft());
359 return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
362 LayoutUnit RenderBox::scrollHeight() const
364 if (hasOverflowClip())
365 return layer()->scrollableArea()->scrollHeight();
366 // For objects with visible overflow, this matches IE.
367 // FIXME: Need to work right with writing modes.
368 return std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop());
371 LayoutUnit RenderBox::scrollLeft() const
373 return hasOverflowClip() ? layer()->scrollableArea()->scrollXOffset() : 0;
376 LayoutUnit RenderBox::scrollTop() const
378 return hasOverflowClip() ? layer()->scrollableArea()->scrollYOffset() : 0;
381 int RenderBox::pixelSnappedScrollWidth() const
383 return snapSizeToPixel(scrollWidth(), x() + clientLeft());
386 int RenderBox::pixelSnappedScrollHeight() const
388 if (hasOverflowClip())
389 return layer()->scrollableArea()->scrollHeight();
390 // For objects with visible overflow, this matches IE.
391 // FIXME: Need to work right with writing modes.
392 return snapSizeToPixel(scrollHeight(), y() + clientTop());
395 void RenderBox::setScrollLeft(LayoutUnit newLeft)
397 // This doesn't hit in any tests, but since the equivalent code in setScrollTop
398 // does, presumably this code does as well.
399 DisableCompositingQueryAsserts disabler;
401 if (hasOverflowClip())
402 layer()->scrollableArea()->scrollToXOffset(newLeft, ScrollOffsetClamped);
405 void RenderBox::setScrollTop(LayoutUnit newTop)
407 // Hits in compositing/overflow/do-not-assert-on-invisible-composited-layers.html
408 DisableCompositingQueryAsserts disabler;
410 if (hasOverflowClip())
411 layer()->scrollableArea()->scrollToYOffset(newTop, ScrollOffsetClamped);
414 void RenderBox::scrollToOffset(const DoubleSize& offset)
416 ASSERT(hasOverflowClip());
418 // This doesn't hit in any tests, but since the equivalent code in setScrollTop
419 // does, presumably this code does as well.
420 DisableCompositingQueryAsserts disabler;
421 layer()->scrollableArea()->scrollToOffset(offset, ScrollOffsetClamped);
424 static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
426 // If scrollbars aren't explicitly forbidden, permit scrolling.
427 if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
430 // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
431 if (frameView->wasScrolledByUser())
434 // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
435 // like navigation to an anchor.
436 Page* page = frameView->frame().page();
439 return !page->autoscrollController().autoscrollInProgress();
442 void RenderBox::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
444 // Presumably the same issue as in setScrollTop. See crbug.com/343132.
445 DisableCompositingQueryAsserts disabler;
447 RenderBox* parentBox = 0;
448 LayoutRect newRect = rect;
450 bool restrictedByLineClamp = false;
452 parentBox = parent()->enclosingBox();
453 restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
456 if (hasOverflowClip() && !restrictedByLineClamp) {
457 // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
458 // This will prevent us from revealing text hidden by the slider in Safari RSS.
459 newRect = layer()->scrollableArea()->exposeRect(rect, alignX, alignY);
460 } else if (!parentBox && canBeProgramaticallyScrolled()) {
461 if (FrameView* frameView = this->frameView()) {
462 HTMLFrameOwnerElement* ownerElement = document().ownerElement();
464 if (ownerElement && ownerElement->renderer()) {
465 HTMLFrameElementBase* frameElementBase = isHTMLFrameElementBase(*ownerElement) ? toHTMLFrameElementBase(ownerElement) : 0;
466 if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
467 LayoutRect viewRect = frameView->visibleContentRect();
468 LayoutRect exposeRect = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
470 double xOffset = exposeRect.x();
471 double yOffset = exposeRect.y();
472 // Adjust offsets if they're outside of the allowable range.
473 xOffset = std::max(0.0, std::min<double>(frameView->contentsWidth(), xOffset));
474 yOffset = std::max(0.0, std::min<double>(frameView->contentsHeight(), yOffset));
476 frameView->setScrollPosition(DoublePoint(xOffset, yOffset));
477 if (frameView->safeToPropagateScrollToParent()) {
478 parentBox = ownerElement->renderer()->enclosingBox();
479 // FIXME: This doesn't correctly convert the rect to
480 // absolute coordinates in the parent.
481 newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
482 newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
488 if (frame()->settings()->pinchVirtualViewportEnabled()) {
489 PinchViewport& pinchViewport = frame()->page()->frameHost().pinchViewport();
490 LayoutRect r = ScrollAlignment::getRectToExpose(LayoutRect(pinchViewport.visibleRectInDocument()), rect, alignX, alignY);
491 pinchViewport.scrollIntoView(r);
493 LayoutRect viewRect = frameView->visibleContentRect();
494 LayoutRect r = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
495 frameView->setScrollPosition(DoublePoint(r.location()));
501 if (frame()->page()->autoscrollController().autoscrollInProgress())
502 parentBox = enclosingScrollableBox();
505 parentBox->scrollRectToVisible(newRect, alignX, alignY);
508 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
510 rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
513 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
515 quads.append(localToAbsoluteQuad(FloatRect(0, 0, width().toFloat(), height().toFloat()), 0 /* mode */, wasFixed));
518 void RenderBox::updateLayerTransformAfterLayout()
520 // Transform-origin depends on box size, so we need to update the layer transform after layout.
522 layer()->updateTransformationMatrix();
525 LayoutUnit RenderBox::constrainLogicalWidthByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb) const
527 RenderStyle* styleToUse = style();
528 if (!styleToUse->logicalMaxWidth().isMaxSizeNone())
529 logicalWidth = std::min(logicalWidth, computeLogicalWidthUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb));
530 return std::max(logicalWidth, computeLogicalWidthUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb));
533 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
535 RenderStyle* styleToUse = style();
536 if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
537 LayoutUnit maxH = computeLogicalHeightUsing(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
539 logicalHeight = std::min(logicalHeight, maxH);
541 return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse->logicalMinHeight(), intrinsicContentHeight));
544 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
546 RenderStyle* styleToUse = style();
547 if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
548 LayoutUnit maxH = computeContentLogicalHeight(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
550 logicalHeight = std::min(logicalHeight, maxH);
552 return std::max(logicalHeight, computeContentLogicalHeight(styleToUse->logicalMinHeight(), intrinsicContentHeight));
555 IntRect RenderBox::absoluteContentBox() const
557 // This is wrong with transforms and flipped writing modes.
558 IntRect rect = pixelSnappedIntRect(contentBoxRect());
559 FloatPoint absPos = localToAbsolute();
560 rect.move(absPos.x(), absPos.y());
564 FloatQuad RenderBox::absoluteContentQuad() const
566 LayoutRect rect = contentBoxRect();
567 return localToAbsoluteQuad(FloatRect(rect));
570 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*) const
572 if (!size().isEmpty())
573 rects.append(LayoutRect(additionalOffset, size()));
576 bool RenderBox::canResize() const
578 // We need a special case for <iframe> because they never have
579 // hasOverflowClip(). However, they do "implicitly" clip their contents, so
580 // we want to allow resizing them also.
581 return (hasOverflowClip() || isRenderIFrame()) && style()->resize() != RESIZE_NONE;
584 void RenderBox::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
586 LayoutPoint adjustedLayerOffset = layerOffset + locationOffset();
587 RenderBoxModelObject::addLayerHitTestRects(layerRects, currentLayer, adjustedLayerOffset, containerRect);
590 void RenderBox::computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint& layerOffset) const
592 if (!size().isEmpty())
593 rects.append(LayoutRect(layerOffset, size()));
596 int RenderBox::reflectionOffset() const
598 if (!style()->boxReflect())
600 if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
601 return valueForLength(style()->boxReflect()->offset(), borderBoxRect().width());
602 return valueForLength(style()->boxReflect()->offset(), borderBoxRect().height());
605 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
607 if (!style()->boxReflect())
610 LayoutRect box = borderBoxRect();
611 LayoutRect result = r;
612 switch (style()->boxReflect()->direction()) {
613 case ReflectionBelow:
614 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
616 case ReflectionAbove:
617 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
620 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
622 case ReflectionRight:
623 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
629 int RenderBox::verticalScrollbarWidth() const
631 if (!hasOverflowClip() || style()->overflowY() == OOVERLAY)
634 return layer()->scrollableArea()->verticalScrollbarWidth();
637 int RenderBox::horizontalScrollbarHeight() const
639 if (!hasOverflowClip() || style()->overflowX() == OOVERLAY)
642 return layer()->scrollableArea()->horizontalScrollbarHeight();
645 int RenderBox::instrinsicScrollbarLogicalWidth() const
647 if (!hasOverflowClip())
650 if (isHorizontalWritingMode() && style()->overflowY() == OSCROLL) {
651 ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasVerticalScrollbar());
652 return verticalScrollbarWidth();
655 if (!isHorizontalWritingMode() && style()->overflowX() == OSCROLL) {
656 ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasHorizontalScrollbar());
657 return horizontalScrollbarHeight();
663 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float delta)
665 // Presumably the same issue as in setScrollTop. See crbug.com/343132.
666 DisableCompositingQueryAsserts disabler;
668 // Logical scroll is a higher level concept, all directions by here must be physical
669 ASSERT(!isLogical(direction));
671 if (!layer() || !layer()->scrollableArea())
674 return layer()->scrollableArea()->scroll(direction, granularity, delta);
677 bool RenderBox::canBeScrolledAndHasScrollableArea() const
679 return canBeProgramaticallyScrolled() && (pixelSnappedScrollHeight() != pixelSnappedClientHeight() || pixelSnappedScrollWidth() != pixelSnappedClientWidth());
682 bool RenderBox::canBeProgramaticallyScrolled() const
684 Node* node = this->node();
685 if (node && node->isDocumentNode())
688 if (!hasOverflowClip())
691 bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
692 if (scrollsOverflow() && hasScrollableOverflow)
695 return node && node->hasEditableStyle();
698 bool RenderBox::usesCompositedScrolling() const
700 return hasOverflowClip() && hasLayer() && layer()->scrollableArea()->usesCompositedScrolling();
703 void RenderBox::autoscroll(const IntPoint& position)
705 LocalFrame* frame = this->frame();
709 FrameView* frameView = frame->view();
713 IntPoint currentDocumentPosition = frameView->windowToContents(position);
714 scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
717 // There are two kinds of renderer that can autoscroll.
718 bool RenderBox::canAutoscroll() const
720 if (node() && node()->isDocumentNode())
721 return view()->frameView()->isScrollable();
723 // Check for a box that can be scrolled in its own right.
724 return canBeScrolledAndHasScrollableArea();
727 // If specified point is in border belt, returned offset denotes direction of
729 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
734 FrameView* frameView = frame()->view();
738 IntRect box(absoluteBoundingBoxRect());
739 box.move(view()->frameView()->scrollOffset());
740 IntRect windowBox = view()->frameView()->contentsToWindow(box);
742 IntPoint windowAutoscrollPoint = windowPoint;
744 if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
745 windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
746 else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
747 windowAutoscrollPoint.move(autoscrollBeltSize, 0);
749 if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
750 windowAutoscrollPoint.move(0, -autoscrollBeltSize);
751 else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
752 windowAutoscrollPoint.move(0, autoscrollBeltSize);
754 return windowAutoscrollPoint - windowPoint;
757 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
759 while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
760 if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document().ownerElement())
761 renderer = renderer->document().ownerElement()->renderer();
763 renderer = renderer->parent();
766 return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
769 static inline int adjustedScrollDelta(int beginningDelta)
771 // This implemention matches Firefox's.
772 // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
773 const int speedReducer = 12;
775 int adjustedDelta = beginningDelta / speedReducer;
776 if (adjustedDelta > 1)
777 adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
778 else if (adjustedDelta < -1)
779 adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
781 return adjustedDelta;
784 static inline IntSize adjustedScrollDelta(const IntSize& delta)
786 return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
789 void RenderBox::panScroll(const IntPoint& sourcePoint)
791 LocalFrame* frame = this->frame();
795 IntPoint lastKnownMousePosition = frame->eventHandler().lastKnownMousePosition();
797 // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
798 static IntPoint previousMousePosition;
799 if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
800 lastKnownMousePosition = previousMousePosition;
802 previousMousePosition = lastKnownMousePosition;
804 IntSize delta = lastKnownMousePosition - sourcePoint;
806 if (abs(delta.width()) <= FrameView::noPanScrollRadius) // at the center we let the space for the icon
808 if (abs(delta.height()) <= FrameView::noPanScrollRadius)
810 scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
813 void RenderBox::scrollByRecursively(const DoubleSize& delta, ScrollOffsetClamping clamp)
818 bool restrictedByLineClamp = false;
820 restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
822 if (hasOverflowClip() && !restrictedByLineClamp) {
823 DoubleSize newScrollOffset = layer()->scrollableArea()->adjustedScrollOffset() + delta;
824 layer()->scrollableArea()->scrollToOffset(newScrollOffset, clamp);
826 // If this layer can't do the scroll we ask the next layer up that can scroll to try
827 DoubleSize remainingScrollOffset = newScrollOffset - layer()->scrollableArea()->adjustedScrollOffset();
828 if (!remainingScrollOffset.isZero() && parent()) {
829 if (RenderBox* scrollableBox = enclosingScrollableBox())
830 scrollableBox->scrollByRecursively(remainingScrollOffset, clamp);
832 LocalFrame* frame = this->frame();
833 if (frame && frame->page())
834 frame->page()->autoscrollController().updateAutoscrollRenderer();
836 } else if (view()->frameView()) {
837 // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
838 // have an overflow clip. Which means that it is a document node that can be scrolled.
839 // FIXME: Pass in DoubleSize. crbug.com/414283.
840 view()->frameView()->scrollBy(flooredIntSize(delta));
842 // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement?
843 // https://bugs.webkit.org/show_bug.cgi?id=28237
847 bool RenderBox::needsPreferredWidthsRecalculation() const
849 return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent();
852 IntSize RenderBox::scrolledContentOffset() const
854 ASSERT(hasOverflowClip());
856 // FIXME: Return DoubleSize here. crbug.com/414283.
857 return flooredIntSize(layer()->scrollableArea()->scrollOffset());
860 void RenderBox::applyCachedClipAndScrollOffsetForPaintInvalidation(LayoutRect& paintRect) const
863 ASSERT(hasOverflowClip());
865 flipForWritingMode(paintRect);
866 paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
868 // Do not clip scroll layer contents because the compositor expects the whole layer
869 // to be always invalidated in-time.
870 if (usesCompositedScrolling()) {
871 flipForWritingMode(paintRect);
875 // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
876 // layer's size instead. Even if the layer's size is wrong, the layer itself will issue paint invalidations
877 // anyway if its size does change.
878 LayoutRect clipRect(LayoutPoint(), layer()->size());
879 paintRect = intersection(paintRect, clipRect);
880 flipForWritingMode(paintRect);
883 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
885 minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
886 maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
889 LayoutUnit RenderBox::minPreferredLogicalWidth() const
891 if (preferredLogicalWidthsDirty()) {
893 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
895 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
898 return m_minPreferredLogicalWidth;
901 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
903 if (preferredLogicalWidthsDirty()) {
905 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
907 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
910 return m_maxPreferredLogicalWidth;
913 bool RenderBox::hasOverrideHeight() const
915 return m_rareData && m_rareData->m_overrideLogicalContentHeight != -1;
918 bool RenderBox::hasOverrideWidth() const
920 return m_rareData && m_rareData->m_overrideLogicalContentWidth != -1;
923 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
926 ensureRareData().m_overrideLogicalContentHeight = height;
929 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
932 ensureRareData().m_overrideLogicalContentWidth = width;
935 void RenderBox::clearOverrideLogicalContentHeight()
938 m_rareData->m_overrideLogicalContentHeight = -1;
941 void RenderBox::clearOverrideLogicalContentWidth()
944 m_rareData->m_overrideLogicalContentWidth = -1;
947 void RenderBox::clearOverrideSize()
949 clearOverrideLogicalContentHeight();
950 clearOverrideLogicalContentWidth();
953 LayoutUnit RenderBox::overrideLogicalContentWidth() const
955 ASSERT(hasOverrideWidth());
956 return m_rareData->m_overrideLogicalContentWidth;
959 LayoutUnit RenderBox::overrideLogicalContentHeight() const
961 ASSERT(hasOverrideHeight());
962 return m_rareData->m_overrideLogicalContentHeight;
965 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
967 ASSERT(hasOverrideContainingBlockLogicalWidth());
968 return gOverrideContainingBlockLogicalWidthMap->get(this);
971 LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
973 ASSERT(hasOverrideContainingBlockLogicalHeight());
974 return gOverrideContainingBlockLogicalHeightMap->get(this);
977 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
979 return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
982 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
984 return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
987 void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
989 if (!gOverrideContainingBlockLogicalWidthMap)
990 gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
991 gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
994 void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
996 if (!gOverrideContainingBlockLogicalHeightMap)
997 gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
998 gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1001 void RenderBox::clearContainingBlockOverrideSize()
1003 if (gOverrideContainingBlockLogicalWidthMap)
1004 gOverrideContainingBlockLogicalWidthMap->remove(this);
1005 clearOverrideContainingBlockContentLogicalHeight();
1008 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1010 if (gOverrideContainingBlockLogicalHeightMap)
1011 gOverrideContainingBlockLogicalHeightMap->remove(this);
1014 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1016 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1017 if (style()->boxSizing() == CONTENT_BOX)
1018 return width + bordersPlusPadding;
1019 return std::max(width, bordersPlusPadding);
1022 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1024 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1025 if (style()->boxSizing() == CONTENT_BOX)
1026 return height + bordersPlusPadding;
1027 return std::max(height, bordersPlusPadding);
1030 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1032 if (style()->boxSizing() == BORDER_BOX)
1033 width -= borderAndPaddingLogicalWidth();
1034 return std::max<LayoutUnit>(0, width);
1037 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1039 if (style()->boxSizing() == BORDER_BOX)
1040 height -= borderAndPaddingLogicalHeight();
1041 return std::max<LayoutUnit>(0, height);
1045 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1047 LayoutPoint adjustedLocation = accumulatedOffset + location();
1049 // Check kids first.
1050 for (RenderObject* child = slowLastChild(); child; child = child->previousSibling()) {
1051 if ((!child->hasLayer() || !toRenderLayerModelObject(child)->layer()->isSelfPaintingLayer()) && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1052 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1057 // Check our bounds next. For this purpose always assume that we can only be hit in the
1058 // foreground phase (which is true for replaced elements like images).
1059 LayoutRect boundsRect = borderBoxRect();
1060 boundsRect.moveBy(adjustedLocation);
1061 if (visibleToHitTestRequest(request) && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1062 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1063 if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
1070 void RenderBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1072 BoxPainter(*this).paint(paintInfo, paintOffset);
1076 void RenderBox::paintBoxDecorationBackground(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1078 BoxPainter(*this).paintBoxDecorationBackground(paintInfo, paintOffset);
1082 bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent)
1084 ASSERT(hasBackground());
1085 LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect());
1087 Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
1088 if (backgroundColor.alpha()) {
1089 paintedExtent = backgroundRect;
1093 if (!style()->backgroundLayers().image() || style()->backgroundLayers().next()) {
1094 paintedExtent = backgroundRect;
1098 BackgroundImageGeometry geometry;
1099 BoxPainter::calculateBackgroundImageGeometry(*this, 0, style()->backgroundLayers(), backgroundRect, geometry);
1100 if (geometry.hasNonLocalGeometry())
1102 paintedExtent = geometry.destRect();
1106 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1108 if (isBody() && skipBodyBackground(this))
1111 Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
1112 if (backgroundColor.hasAlpha())
1115 // If the element has appearance, it might be painted by theme.
1116 // We cannot be sure if theme paints the background opaque.
1117 // In this case it is safe to not assume opaqueness.
1118 // FIXME: May be ask theme if it paints opaque.
1119 if (style()->hasAppearance())
1121 // FIXME: Check the opaqueness of background images.
1123 // FIXME: Use rounded rect if border radius is present.
1124 if (style()->hasBorderRadius())
1126 // FIXME: The background color clip is defined by the last layer.
1127 if (style()->backgroundLayers().next())
1129 LayoutRect backgroundRect;
1130 switch (style()->backgroundClip()) {
1132 backgroundRect = borderBoxRect();
1134 case PaddingFillBox:
1135 backgroundRect = paddingBoxRect();
1137 case ContentFillBox:
1138 backgroundRect = contentBoxRect();
1143 return backgroundRect.contains(localRect);
1146 static bool isCandidateForOpaquenessTest(RenderBox* childBox)
1148 RenderStyle* childStyle = childBox->style();
1149 if (childStyle->position() != StaticPosition && childBox->containingBlock() != childBox->parent())
1151 if (childStyle->visibility() != VISIBLE || childStyle->shapeOutside())
1153 if (!childBox->width() || !childBox->height())
1155 if (RenderLayer* childLayer = childBox->layer()) {
1156 // FIXME: perhaps this could be less conservative?
1157 if (childLayer->compositingState() != NotComposited)
1159 // FIXME: Deal with z-index.
1160 if (!childStyle->hasAutoZIndex())
1162 if (childLayer->hasTransformRelatedProperty() || childLayer->isTransparent() || childLayer->hasFilter())
1164 if (childBox->hasOverflowClip() && childStyle->hasBorderRadius())
1170 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1172 if (!maxDepthToTest)
1174 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
1175 if (!child->isBox())
1177 RenderBox* childBox = toRenderBox(child);
1178 if (!isCandidateForOpaquenessTest(childBox))
1180 LayoutPoint childLocation = childBox->location();
1181 if (childBox->isRelPositioned())
1182 childLocation.move(childBox->relativePositionOffset());
1183 LayoutRect childLocalRect = localRect;
1184 childLocalRect.moveBy(-childLocation);
1185 if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1186 // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1187 if (childBox->style()->position() == StaticPosition)
1191 if (childLocalRect.maxY() > childBox->height() || childLocalRect.maxX() > childBox->width())
1193 if (childBox->backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1195 if (childBox->foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1201 bool RenderBox::computeBackgroundIsKnownToBeObscured()
1203 // Test to see if the children trivially obscure the background.
1204 // FIXME: This test can be much more comprehensive.
1205 if (!hasBackground())
1207 // Table and root background painting is special.
1208 if (isTable() || isDocumentElement())
1210 // FIXME: box-shadow is painted while background painting.
1211 if (style()->boxShadow())
1213 LayoutRect backgroundRect;
1214 if (!getBackgroundPaintedExtent(backgroundRect))
1216 return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1219 bool RenderBox::backgroundHasOpaqueTopLayer() const
1221 const FillLayer& fillLayer = style()->backgroundLayers();
1222 if (fillLayer.clip() != BorderFillBox)
1225 // Clipped with local scrolling
1226 if (hasOverflowClip() && fillLayer.attachment() == LocalBackgroundAttachment)
1229 if (fillLayer.hasOpaqueImage(this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(*this, style()->effectiveZoom()))
1232 // If there is only one layer and no image, check whether the background color is opaque
1233 if (!fillLayer.next() && !fillLayer.hasImage()) {
1234 Color bgColor = resolveColor(CSSPropertyBackgroundColor);
1235 if (bgColor.alpha() == 255)
1242 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1244 BoxPainter(*this).paintMask(paintInfo, paintOffset);
1247 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1249 BoxPainter(*this).paintClippingMask(paintInfo, paintOffset);
1252 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1257 AllowPaintInvalidationScope scoper(frameView());
1259 if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1260 (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1261 setShouldDoFullPaintInvalidation();
1265 ShapeValue* shapeOutsideValue = style()->shapeOutside();
1266 if (!frameView()->isInPerformLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1267 ShapeOutsideInfo& info = ShapeOutsideInfo::ensureInfo(*this);
1268 if (!info.isComputingShape()) {
1269 info.markShapeAsDirty();
1270 markShapeOutsideDependentsForLayout();
1274 if (!paintInvalidationLayerRectsForImage(image, style()->backgroundLayers(), true))
1275 paintInvalidationLayerRectsForImage(image, style()->maskLayers(), false);
1278 bool RenderBox::paintInvalidationLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground)
1280 Vector<RenderObject*> layerRenderers;
1282 // A background of the body or document must extend to the total visible size of the document. This means the union of the
1283 // view and document bounds, since it can be the case that the view is larger than the document and vice-versa.
1284 // http://dev.w3.org/csswg/css-backgrounds/#the-background
1285 if (drawingBackground && (isDocumentElement() || (isBody() && !document().documentElement()->renderer()->hasBackground()))) {
1286 layerRenderers.append(document().documentElement()->renderer());
1287 layerRenderers.append(view());
1288 if (view()->frameView())
1289 view()->frameView()->setNeedsFullPaintInvalidation();
1291 layerRenderers.append(this);
1293 for (const FillLayer* curLayer = &layers; curLayer; curLayer = curLayer->next()) {
1294 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(*this, style()->effectiveZoom())) {
1295 for (RenderObject* layerRenderer : layerRenderers)
1296 layerRenderer->setShouldDoFullPaintInvalidation();
1303 PaintInvalidationReason RenderBox::invalidatePaintIfNeeded(const PaintInvalidationState& paintInvalidationState, const RenderLayerModelObject& newPaintInvalidationContainer)
1305 PaintInvalidationReason reason = RenderBoxModelObject::invalidatePaintIfNeeded(paintInvalidationState, newPaintInvalidationContainer);
1307 // If we are set to do a full paint invalidation that means the RenderView will be
1308 // issue paint invalidations. We can then skip issuing of paint invalidations for the child
1309 // renderers as they'll be covered by the RenderView.
1310 if (!view()->doingFullPaintInvalidation() && !isFullPaintInvalidationReason(reason)) {
1311 invalidatePaintForOverflowIfNeeded();
1313 // Issue paint invalidations for any scrollbars if there is a scrollable area for this renderer.
1314 if (ScrollableArea* area = scrollableArea()) {
1315 if (area->hasVerticalBarDamage())
1316 invalidatePaintRectangle(area->verticalBarDamage());
1317 if (area->hasHorizontalBarDamage())
1318 invalidatePaintRectangle(area->horizontalBarDamage());
1322 // This is for the next invalidatePaintIfNeeded so must be at the end.
1323 savePreviousBorderBoxSizeIfNeeded();
1327 void RenderBox::clearPaintInvalidationState(const PaintInvalidationState& paintInvalidationState)
1329 RenderBoxModelObject::clearPaintInvalidationState(paintInvalidationState);
1331 if (ScrollableArea* area = scrollableArea())
1332 area->resetScrollbarDamage();
1336 bool RenderBox::paintInvalidationStateIsDirty() const
1338 if (ScrollableArea* area = scrollableArea()) {
1339 if (area->hasVerticalBarDamage() || area->hasHorizontalBarDamage())
1342 return RenderBoxModelObject::paintInvalidationStateIsDirty();
1346 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy relevancy)
1348 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1350 LayoutRect clipRect = borderBoxRect();
1351 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1352 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1354 if (!hasOverflowClip())
1357 // Subtract out scrollbars if we have them.
1358 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1359 clipRect.move(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), 0);
1360 clipRect.contract(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), layer()->scrollableArea()->horizontalScrollbarHeight(relevancy));
1365 LayoutRect RenderBox::clipRect(const LayoutPoint& location)
1367 LayoutRect borderBoxRect = this->borderBoxRect();
1368 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1370 if (!style()->clipLeft().isAuto()) {
1371 LayoutUnit c = valueForLength(style()->clipLeft(), borderBoxRect.width());
1372 clipRect.move(c, 0);
1373 clipRect.contract(c, 0);
1376 if (!style()->clipRight().isAuto())
1377 clipRect.contract(width() - valueForLength(style()->clipRight(), width()), 0);
1379 if (!style()->clipTop().isAuto()) {
1380 LayoutUnit c = valueForLength(style()->clipTop(), borderBoxRect.height());
1381 clipRect.move(0, c);
1382 clipRect.contract(0, c);
1385 if (!style()->clipBottom().isAuto())
1386 clipRect.contract(0, height() - valueForLength(style()->clipBottom(), height()));
1391 static LayoutUnit portionOfMarginNotConsumedByFloat(LayoutUnit childMargin, LayoutUnit contentSide, LayoutUnit offset)
1393 if (childMargin <= 0)
1395 LayoutUnit contentSideWithMargin = contentSide + childMargin;
1396 if (offset > contentSideWithMargin)
1398 return offset - contentSide;
1401 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb) const
1403 LayoutUnit logicalTopPosition = logicalTop();
1404 LayoutUnit startOffsetForContent = cb->startOffsetForContent();
1405 LayoutUnit endOffsetForContent = cb->endOffsetForContent();
1406 LayoutUnit startOffsetForLine = cb->startOffsetForLine(logicalTopPosition, false);
1407 LayoutUnit endOffsetForLine = cb->endOffsetForLine(logicalTopPosition, false);
1409 // If there aren't any floats constraining us then allow the margins to shrink/expand the width as much as they want.
1410 if (startOffsetForContent == startOffsetForLine && endOffsetForContent == endOffsetForLine)
1411 return cb->availableLogicalWidthForLine(logicalTopPosition, false) - childMarginStart - childMarginEnd;
1413 LayoutUnit width = cb->availableLogicalWidthForLine(logicalTopPosition, false) - std::max<LayoutUnit>(0, childMarginStart) - std::max<LayoutUnit>(0, childMarginEnd);
1414 // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1415 // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1416 // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1417 // 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
1418 // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1419 width += portionOfMarginNotConsumedByFloat(childMarginStart, startOffsetForContent, startOffsetForLine);
1420 width += portionOfMarginNotConsumedByFloat(childMarginEnd, endOffsetForContent, endOffsetForLine);
1424 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1426 if (hasOverrideContainingBlockLogicalWidth())
1427 return overrideContainingBlockContentLogicalWidth();
1429 RenderBlock* cb = containingBlock();
1430 return cb->availableLogicalWidth();
1433 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1435 if (hasOverrideContainingBlockLogicalHeight())
1436 return overrideContainingBlockContentLogicalHeight();
1438 RenderBlock* cb = containingBlock();
1439 return cb->availableLogicalHeight(heightType);
1442 LayoutUnit RenderBox::containingBlockAvailableLineWidth() const
1444 RenderBlock* cb = containingBlock();
1445 if (cb->isRenderBlockFlow())
1446 return toRenderBlockFlow(cb)->availableLogicalWidthForLine(logicalTop(), false, availableLogicalHeight(IncludeMarginBorderPadding));
1450 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1452 if (hasOverrideContainingBlockLogicalHeight())
1453 return overrideContainingBlockContentLogicalHeight();
1455 RenderBlock* cb = containingBlock();
1456 if (cb->hasOverrideHeight())
1457 return cb->overrideLogicalContentHeight();
1459 RenderStyle* containingBlockStyle = cb->style();
1460 Length logicalHeightLength = containingBlockStyle->logicalHeight();
1462 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1463 if (!logicalHeightLength.isFixed()) {
1464 LayoutUnit fillFallbackExtent = containingBlockStyle->isHorizontalWritingMode()
1465 ? view()->frameView()->unscaledVisibleContentSize().height()
1466 : view()->frameView()->unscaledVisibleContentSize().width();
1467 LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1468 return std::min(fillAvailableExtent, fillFallbackExtent);
1471 // Use the content box logical height as specified by the style.
1472 return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
1475 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
1477 if (paintInvalidationContainer == this)
1480 if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer)) {
1481 LayoutSize offset = paintInvalidationState->paintOffset() + locationOffset();
1482 if (style()->hasInFlowPosition() && layer())
1483 offset += layer()->offsetForInFlowPosition();
1484 transformState.move(offset);
1488 bool containerSkipped;
1489 RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
1493 bool isFixedPos = style()->position() == FixedPosition;
1494 bool hasTransform = hasLayer() && layer()->transform();
1495 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1496 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1497 if (hasTransform && !isFixedPos)
1499 else if (isFixedPos)
1503 *wasFixed = mode & IsFixed;
1505 LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1507 bool preserve3D = mode & UseTransforms && (o->style()->preserves3D() || style()->preserves3D());
1508 if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
1509 TransformationMatrix t;
1510 getTransformFromContainer(o, containerOffset, t);
1511 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1513 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1515 if (containerSkipped) {
1516 // There can't be a transform between paintInvalidationContainer and o, because transforms create containers, so it should be safe
1517 // to just subtract the delta between the paintInvalidationContainer and o.
1518 LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
1519 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1523 mode &= ~ApplyContainerFlip;
1525 o->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed);
1528 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1530 bool isFixedPos = style()->position() == FixedPosition;
1531 bool hasTransform = hasLayer() && layer()->transform();
1532 if (hasTransform && !isFixedPos) {
1533 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1534 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1536 } else if (isFixedPos)
1539 RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
1542 LayoutSize RenderBox::offsetFromContainer(const RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
1544 ASSERT(o == container());
1547 if (isRelPositioned())
1548 offset += offsetForInFlowPosition();
1550 if (!isInline() || isReplaced()) {
1551 if (!style()->hasOutOfFlowPosition() && o->hasColumns()) {
1552 const RenderBlock* block = toRenderBlock(o);
1553 LayoutRect columnRect(frameRect());
1554 block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1555 offset += toSize(columnRect.location());
1556 LayoutPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
1557 offset = toLayoutSize(block->flipForWritingModeIncludingColumns(toLayoutPoint(offset)));
1558 offset += o->columnOffset(columnPoint);
1559 offset = block->flipForWritingMode(offset);
1561 if (offsetDependsOnPoint)
1562 *offsetDependsOnPoint = true;
1564 offset += topLeftLocationOffset();
1565 if (o->isRenderFlowThread()) {
1566 // So far the point has been in flow thread coordinates (i.e. as if everything in
1567 // the fragmentation context lived in one tall single column). Convert it to a
1568 // visual point now.
1569 LayoutPoint pointInContainer = point + offset;
1570 offset += o->columnOffset(pointInContainer);
1571 if (offsetDependsOnPoint)
1572 *offsetDependsOnPoint = true;
1577 if (o->hasOverflowClip())
1578 offset -= toRenderBox(o)->scrolledContentOffset();
1580 if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1581 offset += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
1586 InlineBox* RenderBox::createInlineBox()
1588 return new InlineBox(*this);
1591 void RenderBox::dirtyLineBoxes(bool fullLayout)
1593 if (inlineBoxWrapper()) {
1595 inlineBoxWrapper()->destroy();
1597 m_rareData->m_inlineBoxWrapper = 0;
1599 inlineBoxWrapper()->dirtyLineBoxes();
1604 void RenderBox::positionLineBox(InlineBox* box)
1606 if (isOutOfFlowPositioned()) {
1607 // Cache the x position only if we were an INLINE type originally.
1608 bool wasInline = style()->isOriginalDisplayInlineType();
1610 // The value is cached in the xPos of the box. We only need this value if
1611 // our object was inline originally, since otherwise it would have ended up underneath
1613 RootInlineBox& root = box->root();
1614 root.block().setStaticInlinePositionForChild(this, LayoutUnit::fromFloatRound(box->logicalLeft()));
1615 if (style()->hasStaticInlinePosition(box->isHorizontal()))
1616 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1618 // Our object was a block originally, so we make our normal flow position be
1619 // just below the line box (as though all the inlines that came before us got
1620 // wrapped in an anonymous block, which is what would have happened had we been
1621 // in flow). This value was cached in the y() of the box.
1622 layer()->setStaticBlockPosition(box->logicalTop());
1623 if (style()->hasStaticBlockPosition(box->isHorizontal()))
1624 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1627 if (container()->isRenderInline())
1628 moveWithEdgeOfInlineContainerIfNecessary(box->isHorizontal());
1631 box->remove(DontMarkLineBoxes);
1633 } else if (isReplaced()) {
1634 setLocation(roundedLayoutPoint(box->topLeft()));
1635 setInlineBoxWrapper(box);
1639 void RenderBox::moveWithEdgeOfInlineContainerIfNecessary(bool isHorizontal)
1641 ASSERT(isOutOfFlowPositioned() && container()->isRenderInline() && container()->isRelPositioned());
1642 // If this object is inside a relative positioned inline and its inline position is an explicit offset from the edge of its container
1643 // then it will need to move if its inline container has changed width. We do not track if the width has changed
1644 // but if we are here then we are laying out lines inside it, so it probably has - mark our object for layout so that it can
1645 // move to the new offset created by the new width.
1646 if (!normalChildNeedsLayout() && !style()->hasStaticInlinePosition(isHorizontal))
1647 setChildNeedsLayout(MarkOnlyThis);
1650 void RenderBox::deleteLineBoxWrapper()
1652 if (inlineBoxWrapper()) {
1653 if (!documentBeingDestroyed())
1654 inlineBoxWrapper()->remove();
1655 inlineBoxWrapper()->destroy();
1657 m_rareData->m_inlineBoxWrapper = 0;
1661 LayoutRect RenderBox::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1663 if (style()->visibility() != VISIBLE) {
1664 RenderLayer* layer = enclosingLayer();
1665 layer->updateDescendantDependentFlags();
1666 if (layer->subtreeIsInvisible())
1667 return LayoutRect();
1670 LayoutRect r = visualOverflowRect();
1671 mapRectToPaintInvalidationBacking(paintInvalidationContainer, r, paintInvalidationState);
1675 void RenderBox::mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect& rect, const PaintInvalidationState* paintInvalidationState) const
1677 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1678 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1679 // offset corner for the enclosing container). This allows for a fully RL or BT document to issue paint invalidations
1680 // properly even during layout, since the rect remains flipped all the way until the end.
1682 // RenderView::computeRectForPaintInvalidation then converts the rect to physical coordinates. We also convert to
1683 // physical when we hit a paintInvalidationContainer boundary. Therefore the final rect returned is always in the
1684 // physical coordinate space of the paintInvalidationContainer.
1685 RenderStyle* styleToUse = style();
1687 EPosition position = styleToUse->position();
1689 // We need to inflate the paint invalidation rect before we use paintInvalidationState,
1690 // else we would forget to inflate it for the current renderer. FIXME: If these were
1691 // included into the visual overflow for repaint, we wouldn't have this issue.
1692 inflatePaintInvalidationRectForReflectionAndFilter(rect);
1694 if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer) && position != FixedPosition) {
1695 if (layer() && layer()->transform())
1696 rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
1698 // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
1699 if (styleToUse->hasInFlowPosition() && layer())
1700 rect.move(layer()->offsetForInFlowPosition());
1702 rect.moveBy(location());
1703 rect.move(paintInvalidationState->paintOffset());
1704 if (paintInvalidationState->isClipped())
1705 rect.intersect(paintInvalidationState->clipRect());
1709 if (paintInvalidationContainer == this) {
1710 if (paintInvalidationContainer->style()->slowIsFlippedBlocksWritingMode())
1711 flipForWritingMode(rect);
1715 bool containerSkipped;
1716 RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
1720 if (isWritingModeRoot())
1721 flipForWritingMode(rect);
1723 LayoutPoint topLeft = rect.location();
1724 topLeft.move(locationOffset());
1726 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
1727 // in the parent's coordinate space that encloses us.
1728 if (hasLayer() && layer()->transform()) {
1729 rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
1730 topLeft = rect.location();
1731 topLeft.move(locationOffset());
1734 if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline()) {
1735 topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
1736 } else if (styleToUse->hasInFlowPosition() && layer()) {
1737 // Apply the relative position offset when invalidating a rectangle. The layer
1738 // is translated, but the render box isn't, so we need to do this to get the
1739 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
1740 // flag on the RenderObject has been cleared, so use the one on the style().
1741 topLeft += layer()->offsetForInFlowPosition();
1744 if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isRenderBlockFlow()) {
1745 LayoutRect paintInvalidationRect(topLeft, rect.size());
1746 toRenderBlock(o)->adjustRectForColumns(paintInvalidationRect);
1747 topLeft = paintInvalidationRect.location();
1748 rect = paintInvalidationRect;
1751 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1752 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1753 rect.setLocation(topLeft);
1754 if (o->hasOverflowClip()) {
1755 RenderBox* containerBox = toRenderBox(o);
1756 containerBox->applyCachedClipAndScrollOffsetForPaintInvalidation(rect);
1761 if (containerSkipped) {
1762 // If the paintInvalidationContainer is below o, then we need to map the rect into paintInvalidationContainer's coordinates.
1763 LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
1764 rect.move(-containerOffset);
1765 // If the paintInvalidationContainer is fixed, then the rect is already in its coordinates so doesn't need viewport-adjusting.
1766 if (paintInvalidationContainer->style()->position() != FixedPosition && o->isRenderView())
1767 toRenderView(o)->adjustViewportConstrainedOffset(rect, RenderView::viewportConstrainedPosition(position));
1771 if (o->isRenderView())
1772 toRenderView(o)->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, RenderView::viewportConstrainedPosition(position), paintInvalidationState);
1774 o->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
1777 void RenderBox::inflatePaintInvalidationRectForReflectionAndFilter(LayoutRect& paintInvalidationRect) const
1779 if (hasReflection())
1780 paintInvalidationRect.unite(reflectedRect(paintInvalidationRect));
1782 if (style()->hasFilter())
1783 style()->filterOutsets().expandRect(paintInvalidationRect);
1786 void RenderBox::invalidatePaintForOverhangingFloats(bool)
1790 void RenderBox::updateLogicalWidth()
1792 LogicalExtentComputedValues computedValues;
1793 computeLogicalWidth(computedValues);
1795 setLogicalWidth(computedValues.m_extent);
1796 setLogicalLeft(computedValues.m_position);
1797 setMarginStart(computedValues.m_margins.m_start);
1798 setMarginEnd(computedValues.m_margins.m_end);
1801 static float getMaxWidthListMarker(const RenderBox* renderer)
1805 Node* parentNode = renderer->generatingNode();
1807 ASSERT(isHTMLOListElement(parentNode) || isHTMLUListElement(parentNode));
1808 ASSERT(renderer->style()->textAutosizingMultiplier() != 1);
1811 for (RenderObject* child = renderer->slowFirstChild(); child; child = child->nextSibling()) {
1812 if (!child->isListItem())
1815 RenderBox* listItem = toRenderBox(child);
1816 for (RenderObject* itemChild = listItem->slowFirstChild(); itemChild; itemChild = itemChild->nextSibling()) {
1817 if (!itemChild->isListMarker())
1819 RenderBox* itemMarker = toRenderBox(itemChild);
1820 // Make sure to compute the autosized width.
1821 if (itemMarker->needsLayout())
1822 itemMarker->layout();
1823 maxWidth = std::max<float>(maxWidth, toRenderListMarker(itemMarker)->logicalWidth().toFloat());
1830 void RenderBox::computeLogicalWidth(LogicalExtentComputedValues& computedValues) const
1832 computedValues.m_extent = logicalWidth();
1833 computedValues.m_position = logicalLeft();
1834 computedValues.m_margins.m_start = marginStart();
1835 computedValues.m_margins.m_end = marginEnd();
1837 if (isOutOfFlowPositioned()) {
1838 // FIXME: This calculation is not patched for block-flow yet.
1839 // https://bugs.webkit.org/show_bug.cgi?id=46500
1840 computePositionedLogicalWidth(computedValues);
1844 // If layout is limited to a subtree, the subtree root's logical width does not change.
1845 if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1848 // The parent box is flexing us, so it has increased or decreased our
1849 // width. Use the width from the style context.
1850 // FIXME: Account for block-flow in flexible boxes.
1851 // https://bugs.webkit.org/show_bug.cgi?id=46418
1852 if (hasOverrideWidth() && parent()->isFlexibleBoxIncludingDeprecated()) {
1853 computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
1857 // FIXME: Account for block-flow in flexible boxes.
1858 // https://bugs.webkit.org/show_bug.cgi?id=46418
1859 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1860 bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1861 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1863 RenderStyle* styleToUse = style();
1864 Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse->logicalWidth();
1866 RenderBlock* cb = containingBlock();
1867 LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContent());
1868 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1870 if (isInline() && !isInlineBlockOrInlineTable()) {
1871 // just calculate margins
1872 computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
1873 computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
1874 if (treatAsReplaced)
1875 computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
1879 // Width calculations
1880 if (treatAsReplaced)
1881 computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
1883 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
1884 if (hasPerpendicularContainingBlock)
1885 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1886 LayoutUnit preferredWidth = computeLogicalWidthUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb);
1887 computedValues.m_extent = constrainLogicalWidthByMinMax(preferredWidth, containerWidthInInlineDirection, cb);
1890 // Margin calculations.
1891 computeMarginsForDirection(InlineDirection, cb, containerLogicalWidth, computedValues.m_extent, computedValues.m_margins.m_start,
1892 computedValues.m_margins.m_end, style()->marginStart(), style()->marginEnd());
1894 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
1895 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated() && !cb->isRenderGrid()) {
1896 LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(this);
1897 bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
1898 if (hasInvertedDirection)
1899 computedValues.m_margins.m_start = newMargin;
1901 computedValues.m_margins.m_end = newMargin;
1904 if (styleToUse->textAutosizingMultiplier() != 1 && styleToUse->marginStart().type() == Fixed) {
1905 Node* parentNode = generatingNode();
1906 if (parentNode && (isHTMLOListElement(*parentNode) || isHTMLUListElement(*parentNode))) {
1907 // Make sure the markers in a list are properly positioned (i.e. not chopped off) when autosized.
1908 const float adjustedMargin = (1 - 1.0 / styleToUse->textAutosizingMultiplier()) * getMaxWidthListMarker(this);
1909 bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
1910 if (hasInvertedDirection)
1911 computedValues.m_margins.m_end += adjustedMargin;
1913 computedValues.m_margins.m_start += adjustedMargin;
1918 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
1920 LayoutUnit marginStart = 0;
1921 LayoutUnit marginEnd = 0;
1922 return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
1925 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
1927 marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth);
1928 marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth);
1929 return availableLogicalWidth - marginStart - marginEnd;
1932 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(const Length& logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
1934 if (logicalWidthLength.type() == FillAvailable)
1935 return fillAvailableMeasure(availableLogicalWidth);
1937 LayoutUnit minLogicalWidth = 0;
1938 LayoutUnit maxLogicalWidth = 0;
1939 computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
1941 if (logicalWidthLength.type() == MinContent)
1942 return minLogicalWidth + borderAndPadding;
1944 if (logicalWidthLength.type() == MaxContent)
1945 return maxLogicalWidth + borderAndPadding;
1947 if (logicalWidthLength.type() == FitContent) {
1948 minLogicalWidth += borderAndPadding;
1949 maxLogicalWidth += borderAndPadding;
1950 return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
1953 ASSERT_NOT_REACHED();
1957 LayoutUnit RenderBox::computeLogicalWidthUsing(SizeType widthType, const Length& logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* cb) const
1959 if (!logicalWidth.isIntrinsicOrAuto()) {
1960 // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
1961 return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
1964 if (logicalWidth.isIntrinsic())
1965 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
1967 LayoutUnit marginStart = 0;
1968 LayoutUnit marginEnd = 0;
1969 LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
1971 if (shrinkToAvoidFloats() && cb->isRenderBlockFlow() && toRenderBlockFlow(cb)->containsFloats())
1972 logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb)));
1974 if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(logicalWidth))
1975 return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
1976 return logicalWidthResult;
1979 static bool columnFlexItemHasStretchAlignment(const RenderObject* flexitem)
1981 RenderObject* parent = flexitem->parent();
1982 // auto margins mean we don't stretch. Note that this function will only be used for
1983 // widths, so we don't have to check marginBefore/marginAfter.
1984 ASSERT(parent->style()->isColumnFlexDirection());
1985 if (flexitem->style()->marginStart().isAuto() || flexitem->style()->marginEnd().isAuto())
1987 return flexitem->style()->alignSelf() == ItemPositionStretch || (flexitem->style()->alignSelf() == ItemPositionAuto && parent->style()->alignItems() == ItemPositionStretch);
1990 static bool isStretchingColumnFlexItem(const RenderObject* flexitem)
1992 RenderObject* parent = flexitem->parent();
1993 if (parent->isDeprecatedFlexibleBox() && parent->style()->boxOrient() == VERTICAL && parent->style()->boxAlign() == BSTRETCH)
1996 // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
1997 if (parent->isFlexibleBox() && parent->style()->flexWrap() == FlexNoWrap && parent->style()->isColumnFlexDirection() && columnFlexItemHasStretchAlignment(flexitem))
2002 bool RenderBox::sizesLogicalWidthToFitContent(const Length& logicalWidth) const
2004 if (isFloating() || isInlineBlockOrInlineTable())
2007 if (logicalWidth.type() == Intrinsic)
2010 // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2011 // In the case of columns that have a stretch alignment, we go ahead and layout at the
2012 // stretched size to avoid an extra layout when applying alignment.
2013 if (parent()->isFlexibleBox()) {
2014 // For multiline columns, we need to apply align-content first, so we can't stretch now.
2015 if (!parent()->style()->isColumnFlexDirection() || parent()->style()->flexWrap() != FlexNoWrap)
2017 if (!columnFlexItemHasStretchAlignment(this))
2021 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
2022 // that don't stretch their kids lay out their children at their intrinsic widths.
2023 // FIXME: Think about block-flow here.
2024 // https://bugs.webkit.org/show_bug.cgi?id=46473
2025 if (parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
2028 // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2029 // stretching column flexbox.
2030 // FIXME: Think about block-flow here.
2031 // https://bugs.webkit.org/show_bug.cgi?id=46473
2032 if (logicalWidth.isAuto() && !isStretchingColumnFlexItem(this) && autoWidthShouldFitContent())
2035 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2041 bool RenderBox::autoWidthShouldFitContent() const
2043 return node() && (isHTMLInputElement(*node()) || isHTMLSelectElement(*node()) || isHTMLButtonElement(*node())
2044 || isHTMLTextAreaElement(*node()) || (isHTMLLegendElement(*node()) && !style()->hasOutOfFlowPosition()));
2047 void RenderBox::computeMarginsForDirection(MarginDirection flowDirection, const RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd, Length marginStartLength, Length marginEndLength) const
2049 if (flowDirection == BlockDirection || isFloating() || isInline()) {
2050 if (isTableCell() && flowDirection == BlockDirection) {
2051 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
2052 // we may just do it with an extra anonymous block inside the cell.
2058 // Margins are calculated with respect to the logical width of
2059 // the containing block (8.3)
2060 // Inline blocks/tables and floats don't have their margins increased.
2061 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2062 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2066 if (containingBlock->isFlexibleBox()) {
2067 // We need to let flexbox handle the margin adjustment - otherwise, flexbox
2068 // will think we're wider than we actually are and calculate line sizes wrong.
2069 // See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
2070 if (marginStartLength.isAuto())
2071 marginStartLength.setValue(0);
2072 if (marginEndLength.isAuto())
2073 marginEndLength.setValue(0);
2076 LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2077 LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2079 LayoutUnit availableWidth = containerWidth;
2080 if (avoidsFloats() && containingBlock->isRenderBlockFlow() && toRenderBlockFlow(containingBlock)->containsFloats()) {
2081 availableWidth = containingBlockAvailableLineWidth();
2082 if (shrinkToAvoidFloats() && availableWidth < containerWidth) {
2083 marginStart = std::max<LayoutUnit>(0, marginStartWidth);
2084 marginEnd = std::max<LayoutUnit>(0, marginEndWidth);
2088 // CSS 2.1 (10.3.3): "If 'width' is not 'auto' and 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width'
2089 // (plus any of 'margin-left' or 'margin-right' that are not 'auto') is larger than the width of the containing block, then any 'auto'
2090 // values for 'margin-left' or 'margin-right' are, for the following rules, treated as zero.
2091 LayoutUnit marginBoxWidth = childWidth + (!style()->width().isAuto() ? marginStartWidth + marginEndWidth : LayoutUnit());
2093 // CSS 2.1: "If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element
2094 // with respect to the edges of the containing block."
2095 const RenderStyle* containingBlockStyle = containingBlock->style();
2096 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && marginBoxWidth < availableWidth)
2097 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlockStyle->textAlign() == WEBKIT_CENTER)) {
2098 // Other browsers center the margin box for align=center elements so we match them here.
2099 LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (availableWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2100 marginStart = centeredMarginBoxStart + marginStartWidth;
2101 marginEnd = availableWidth - childWidth - marginStart + marginEndWidth;
2105 // CSS 2.1: "If there is exactly one value specified as 'auto', its used value follows from the equality."
2106 if (marginEndLength.isAuto() && marginBoxWidth < availableWidth) {
2107 marginStart = marginStartWidth;
2108 marginEnd = availableWidth - childWidth - marginStart;
2112 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
2113 || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
2114 if ((marginStartLength.isAuto() && marginBoxWidth < availableWidth) || pushToEndFromTextAlign) {
2115 marginEnd = marginEndWidth;
2116 marginStart = availableWidth - childWidth - marginEnd;
2120 // Either no auto margins, or our margin box width is >= the container width, auto margins will just turn into 0.
2121 marginStart = marginStartWidth;
2122 marginEnd = marginEndWidth;
2125 void RenderBox::updateLogicalHeight()
2127 m_intrinsicContentLogicalHeight = contentLogicalHeight();
2129 LogicalExtentComputedValues computedValues;
2130 computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2132 setLogicalHeight(computedValues.m_extent);
2133 setLogicalTop(computedValues.m_position);
2134 setMarginBefore(computedValues.m_margins.m_before);
2135 setMarginAfter(computedValues.m_margins.m_after);
2138 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2140 computedValues.m_extent = logicalHeight;
2141 computedValues.m_position = logicalTop;
2143 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2144 if (isTableCell() || (isInline() && !isReplaced()))
2148 if (isOutOfFlowPositioned())
2149 computePositionedLogicalHeight(computedValues);
2151 RenderBlock* cb = containingBlock();
2153 // If we are perpendicular to our containing block then we need to resolve our block-start and block-end margins so that if they
2154 // are 'auto' we are centred or aligned within the inline flow containing block: this is done by computing the margins as though they are inline.
2155 // Note that as this is the 'sizing phase' we are using our own writing mode rather than the containing block's. We use the containing block's
2156 // writing mode when figuring out the block-direction margins for positioning in |computeAndSetBlockDirectionMargins| (i.e. margin collapsing etc.).
2157 // See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
2158 MarginDirection flowDirection = isHorizontalWritingMode() != cb->isHorizontalWritingMode() ? InlineDirection : BlockDirection;
2160 // For tables, calculate margins only.
2162 computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
2163 computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
2167 // FIXME: Account for block-flow in flexible boxes.
2168 // https://bugs.webkit.org/show_bug.cgi?id=46418
2169 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
2170 bool stretching = parent()->style()->boxAlign() == BSTRETCH;
2171 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2172 bool checkMinMaxHeight = false;
2174 // The parent box is flexing us, so it has increased or decreased our height. We have to
2175 // grab our cached flexible height.
2176 // FIXME: Account for block-flow in flexible boxes.
2177 // https://bugs.webkit.org/show_bug.cgi?id=46418
2178 if (hasOverrideHeight() && (parent()->isFlexibleBoxIncludingDeprecated() || parent()->isRenderGrid()))
2179 h = Length(overrideLogicalContentHeight(), Fixed);
2180 else if (treatAsReplaced)
2181 h = Length(computeReplacedLogicalHeight(), Fixed);
2183 h = style()->logicalHeight();
2184 checkMinMaxHeight = true;
2187 // Block children of horizontal flexible boxes fill the height of the box.
2188 // FIXME: Account for block-flow in flexible boxes.
2189 // https://bugs.webkit.org/show_bug.cgi?id=46418
2190 if (h.isAuto() && inHorizontalBox && toRenderDeprecatedFlexibleBox(parent())->isStretchingChildren()) {
2191 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2192 checkMinMaxHeight = false;
2195 LayoutUnit heightResult;
2196 if (checkMinMaxHeight) {
2197 heightResult = computeLogicalHeightUsing(style()->logicalHeight(), computedValues.m_extent - borderAndPaddingLogicalHeight());
2198 if (heightResult == -1)
2199 heightResult = computedValues.m_extent;
2200 heightResult = constrainLogicalHeightByMinMax(heightResult, computedValues.m_extent - borderAndPaddingLogicalHeight());
2202 // The only times we don't check min/max height are when a fixed length has
2203 // been given as an override. Just use that. The value has already been adjusted
2205 ASSERT(h.isFixed());
2206 heightResult = h.value() + borderAndPaddingLogicalHeight();
2209 computedValues.m_extent = heightResult;
2210 computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
2211 computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
2214 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2215 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2216 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2217 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2218 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2219 bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
2220 && (isDocumentElement() || (isBody() && document().documentElement()->renderer()->style()->logicalHeight().isPercent())) && !isInline();
2221 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2222 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2223 LayoutUnit visibleHeight = view()->viewLogicalHeightForPercentages();
2224 if (isDocumentElement())
2225 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2227 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2228 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2233 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
2235 LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
2236 if (logicalHeight != -1)
2237 logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2238 return logicalHeight;
2241 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height, LayoutUnit intrinsicContentHeight) const
2243 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
2244 if (heightIncludingScrollbar == -1)
2246 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2249 LayoutUnit RenderBox::computeIntrinsicLogicalContentHeightUsing(const Length& logicalHeightLength, LayoutUnit intrinsicContentHeight, LayoutUnit borderAndPadding) const
2251 // FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
2252 // If that happens, this code will have to change.
2253 if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
2255 return intrinsicSize().height();
2256 if (m_intrinsicContentLogicalHeight != -1)
2257 return m_intrinsicContentLogicalHeight;
2258 return intrinsicContentHeight;
2260 if (logicalHeightLength.isFillAvailable())
2261 return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2262 ASSERT_NOT_REACHED();
2266 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
2268 // FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
2269 // If that happens, this code will have to change.
2270 if (height.isIntrinsic()) {
2271 if (intrinsicContentHeight == -1)
2272 return -1; // Intrinsic height isn't available.
2273 return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2275 if (height.isFixed())
2276 return height.value();
2277 if (height.isPercent())
2278 return computePercentageLogicalHeight(height);
2282 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const
2284 // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2285 // and percent heights of children should be resolved against the multicol or paged container.
2286 if (containingBlock->isRenderFlowThread())
2289 // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2290 // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2291 if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2293 return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style()->logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2296 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2298 LayoutUnit availableHeight = -1;
2300 bool skippedAutoHeightContainingBlock = false;
2301 RenderBlock* cb = containingBlock();
2302 const RenderBox* containingBlockChild = this;
2303 LayoutUnit rootMarginBorderPaddingHeight = 0;
2304 while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb)) {
2305 if (cb->isBody() || cb->isDocumentElement())
2306 rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2307 skippedAutoHeightContainingBlock = true;
2308 containingBlockChild = cb;
2309 cb = cb->containingBlock();
2311 cb->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2313 RenderStyle* cbstyle = cb->style();
2315 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2316 // explicitly specified that can be used for any percentage computations.
2317 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle->logicalHeight().isAuto() || (!cbstyle->logicalTop().isAuto() && !cbstyle->logicalBottom().isAuto()));
2319 bool includeBorderPadding = isTable();
2321 if (isHorizontalWritingMode() != cb->isHorizontalWritingMode())
2322 availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2323 else if (hasOverrideContainingBlockLogicalHeight())
2324 availableHeight = overrideContainingBlockContentLogicalHeight();
2325 else if (cb->isTableCell()) {
2326 if (!skippedAutoHeightContainingBlock) {
2327 // Table cells violate what the CSS spec says to do with heights. Basically we
2328 // don't care if the cell specified a height or not. We just always make ourselves
2329 // be a percentage of the cell's current content height.
2330 if (!cb->hasOverrideHeight()) {
2331 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2332 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2333 // While we can't get all cases right, we can at least detect when the cell has a specified
2334 // height or when the table has a specified height. In these cases we want to initially have
2335 // no size and allow the flexing of the table or the cell to its specified height to cause us
2336 // to grow to fill the space. This could end up being wrong in some cases, but it is
2337 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2338 RenderTableCell* cell = toRenderTableCell(cb);
2339 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2343 availableHeight = cb->overrideLogicalContentHeight();
2344 includeBorderPadding = true;
2346 } else if (cbstyle->logicalHeight().isFixed()) {
2347 LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle->logicalHeight().value());
2348 availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), -1));
2349 } else if (cbstyle->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2350 // We need to recur and compute the percentage height for our containing block.
2351 LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle->logicalHeight());
2352 if (heightWithScrollbar != -1) {
2353 LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2354 // We need to adjust for min/max height because this method does not
2355 // handle the min/max of the current block, its caller does. So the
2356 // return value from the recursive call will not have been adjusted
2358 LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
2359 availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2361 } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2362 // Don't allow this to affect the block' height() member variable, since this
2363 // can get called while the block is still laying out its kids.
2364 LogicalExtentComputedValues computedValues;
2365 cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2366 availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2367 } else if (cb->isRenderView())
2368 availableHeight = view()->viewLogicalHeightForPercentages();
2370 if (availableHeight == -1)
2371 return availableHeight;
2373 availableHeight -= rootMarginBorderPaddingHeight;
2375 if (isTable() && isOutOfFlowPositioned())
2376 availableHeight += cb->paddingLogicalHeight();
2378 LayoutUnit result = valueForLength(height, availableHeight);
2379 if (includeBorderPadding) {
2380 // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2381 // It is necessary to use the border-box to match WinIE's broken
2382 // box model. This is essential for sizing inside
2383 // table cells using percentage heights.
2384 result -= borderAndPaddingLogicalHeight();
2385 return std::max<LayoutUnit>(0, result);
2390 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2392 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), shouldComputePreferred);
2395 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2397 LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMinWidth().isPercent()) || style()->logicalMinWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2398 LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMaxWidth().isPercent()) || style()->logicalMaxWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2399 return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2402 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(const Length& logicalWidth) const
2404 switch (logicalWidth.type()) {
2406 return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2409 // MinContent/MaxContent don't need the availableLogicalWidth argument.
2410 LayoutUnit availableLogicalWidth = 0;
2411 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2417 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2418 // containing block's block-flow.
2419 // https://bugs.webkit.org/show_bug.cgi?id=46496
2420 const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2421 Length containerLogicalWidth = containingBlock()->style()->logicalWidth();
2422 // FIXME: Handle cases when containing block width is calculated or viewport percent.
2423 // https://bugs.webkit.org/show_bug.cgi?id=91071
2424 if (logicalWidth.isIntrinsic())
2425 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2426 if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2427 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2434 return intrinsicLogicalWidth();
2441 ASSERT_NOT_REACHED();
2445 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2447 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2450 bool RenderBox::logicalHeightComputesAsNone(SizeType sizeType) const
2452 ASSERT(sizeType == MinSize || sizeType == MaxSize);
2453 Length logicalHeight = sizeType == MinSize ? style()->logicalMinHeight() : style()->logicalMaxHeight();
2454 Length initialLogicalHeight = sizeType == MinSize ? RenderStyle::initialMinSize() : RenderStyle::initialMaxSize();
2456 if (logicalHeight == initialLogicalHeight)
2459 if (!logicalHeight.isPercent() || isOutOfFlowPositioned())
2462 // Anonymous block boxes are ignored when resolving percentage values that would refer to it:
2463 // the closest non-anonymous ancestor box is used instead.
2464 RenderBlock* containingBlock = this->containingBlock();
2465 while (containingBlock->isAnonymous())
2466 containingBlock = containingBlock->containingBlock();
2468 return containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight();
2471 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2473 // If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned,
2474 // the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').
2475 LayoutUnit minLogicalHeight;
2476 if (!logicalHeightComputesAsNone(MinSize))
2477 minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2478 LayoutUnit maxLogicalHeight = logicalHeight;
2479 if (!logicalHeightComputesAsNone(MaxSize))
2480 maxLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2481 return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
2484 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(const Length& logicalHeight) const
2486 switch (logicalHeight.type()) {
2488 return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
2492 RenderObject* cb = isOutOfFlowPositioned() ? container() : containingBlock();
2493 while (cb->isAnonymous())
2494 cb = cb->containingBlock();
2495 if (cb->isRenderBlock())
2496 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2498 // FIXME: This calculation is not patched for block-flow yet.
2499 // https://bugs.webkit.org/show_bug.cgi?id=46500
2500 if (cb->isOutOfFlowPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2501 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
2502 RenderBlock* block = toRenderBlock(cb);
2503 LogicalExtentComputedValues computedValues;
2504 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2505 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2506 LayoutUnit newHeight = block->adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2507 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
2510 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2511 // containing block's block-flow.
2512 // https://bugs.webkit.org/show_bug.cgi?id=46496
2513 LayoutUnit availableHeight;
2514 if (isOutOfFlowPositioned())
2515 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2517 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
2518 // It is necessary to use the border-box to match WinIE's broken
2519 // box model. This is essential for sizing inside
2520 // table cells using percentage heights.
2521 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
2522 // https://bugs.webkit.org/show_bug.cgi?id=46997
2523 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2524 if (cb->isTableCell()) {
2525 // Don't let table cells squeeze percent-height replaced elements
2526 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2527 availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
2528 return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
2530 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2531 cb = cb->containingBlock();
2534 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
2540 return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingHeight()));
2542 return intrinsicLogicalHeight();
2546 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
2548 // http://www.w3.org/TR/CSS2/visudet.html#propdef-height - We are interested in the content height.
2549 return constrainContentBoxLogicalHeightByMinMax(availableLogicalHeightUsing(style()->logicalHeight(), heightType), -1);
2552 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
2555 return isHorizontalWritingMode() ? toRenderView(this)->frameView()->unscaledVisibleContentSize().height() : toRenderView(this)->frameView()->unscaledVisibleContentSize().width();
2557 // We need to stop here, since we don't want to increase the height of the table
2558 // artificially. We're going to rely on this cell getting expanded to some new
2559 // height, and then when we lay out again we'll use the calculation below.
2560 if (isTableCell() && (h.isAuto() || h.isPercent())) {
2561 if (hasOverrideHeight())
2562 return overrideLogicalContentHeight();
2563 return logicalHeight() - borderAndPaddingLogicalHeight();
2566 if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
2567 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2568 LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2569 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
2572 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h, -1);
2573 if (heightIncludingScrollbar != -1)
2574 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2576 // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
2577 // https://bugs.webkit.org/show_bug.cgi?id=46500
2578 if (isRenderBlock() && isOutOfFlowPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2579 RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2580 LogicalExtentComputedValues computedValues;
2581 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2582 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2583 return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2586 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2587 LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
2588 if (heightType == ExcludeMarginBorderPadding) {
2589 // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
2590 availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
2592 return availableHeight;
2595 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
2597 LayoutUnit marginBefore;
2598 LayoutUnit marginAfter;
2599 computeMarginsForDirection(BlockDirection, containingBlock, containingBlockLogicalWidthForContent(), logicalHeight(), marginBefore, marginAfter,
2600 style()->marginBeforeUsing(containingBlock->style()),
2601 style()->marginAfterUsing(containingBlock->style()));
2602 // Note that in this 'positioning phase' of the layout we are using the containing block's writing mode rather than our own when calculating margins.
2603 // See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
2604 containingBlock->setMarginBeforeForChild(this, marginBefore);
2605 containingBlock->setMarginAfterForChild(this, marginAfter);
2608 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2610 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2611 return containingBlockLogicalHeightForPositioned(containingBlock, false);
2613 // Use viewport as container for top-level fixed-position elements.
2614 if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
2615 const RenderView* view = toRenderView(containingBlock);
2616 if (FrameView* frameView = view->frameView()) {
2617 LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2618 return containingBlock->isHorizontalWritingMode() ? viewportRect.width() : viewportRect.height();
2622 if (containingBlock->isBox())
2623 return toRenderBox(containingBlock)->clientLogicalWidth();
2625 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2627 const RenderInline* flow = toRenderInline(containingBlock);
2628 InlineFlowBox* first = flow->firstLineBox();
2629 InlineFlowBox* last = flow->lastLineBox();
2631 // If the containing block is empty, return a width of 0.
2632 if (!first || !last)
2635 LayoutUnit fromLeft;
2636 LayoutUnit fromRight;
2637 if (containingBlock->style()->isLeftToRightDirection()) {
2638 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2639 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2641 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2642 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2645 return std::max<LayoutUnit>(0, fromRight - fromLeft);
2648 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2650 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2651 return containingBlockLogicalWidthForPositioned(containingBlock, false);
2653 // Use viewport as container for top-level fixed-position elements.
2654 if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
2655 const RenderView* view = toRenderView(containingBlock);
2656 if (FrameView* frameView = view->frameView()) {
2657 LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2658 return containingBlock->isHorizontalWritingMode() ? viewportRect.height() : viewportRect.width();
2662 if (containingBlock->isBox()) {
2663 const RenderBlock* cb = containingBlock->isRenderBlock() ?
2664 toRenderBlock(containingBlock) : containingBlock->containingBlock();
2665 return cb->clientLogicalHeight();
2668 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2670 const RenderInline* flow = toRenderInline(containingBlock);
2671 InlineFlowBox* first = flow->firstLineBox();
2672 InlineFlowBox* last = flow->lastLineBox();
2674 // If the containing block is empty, return a height of 0.
2675 if (!first || !last)
2678 LayoutUnit heightResult;
2679 LayoutRect boundingBox = flow->linesBoundingBox();
2680 if (containingBlock->isHorizontalWritingMode())
2681 heightResult = boundingBox.height();
2683 heightResult = boundingBox.width();
2684 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2685 return heightResult;
2688 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2690 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2693 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2694 if (child->parent()->style()->direction() == LTR) {
2695 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2696 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2697 if (curr->isBox()) {
2698 staticPosition += toRenderBox(curr)->logicalLeft();
2699 if (toRenderBox(curr)->isRelPositioned())
2700 staticPosition += toRenderBox(curr)->relativePositionOffset().width();
2701 } else if (curr->isInline()) {
2702 if (curr->isRelPositioned()) {
2703 if (!curr->style()->logicalLeft().isAuto())
2704 staticPosition += curr->style()->logicalLeft().value();
2706 staticPosition -= curr->style()->logicalRight().value();
2710 logicalLeft.setValue(Fixed, staticPosition);
2712 RenderBox* enclosingBox = child->parent()->enclosingBox();
2713 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
2714 for (RenderObject* curr = child->parent(); curr; curr = curr->container()) {
2715 if (curr->isBox()) {
2716 if (curr != containerBlock) {
2717 staticPosition -= toRenderBox(curr)->logicalLeft();
2718 if (toRenderBox(curr)->isRelPositioned())
2719 staticPosition -= toRenderBox(curr)->relativePositionOffset().width();
2721 if (curr == enclosingBox)
2722 staticPosition -= enclosingBox->logicalWidth();
2723 } else if (curr->isInline()) {
2724 if (curr->isRelPositioned()) {
2725 if (!curr->style()->logicalLeft().isAuto())
2726 staticPosition -= curr->style()->logicalLeft().value();
2728 staticPosition += curr->style()->logicalRight().value();
2731 if (curr == containerBlock)
2734 logicalRight.setValue(Fixed, staticPosition);
2738 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues) const
2741 computePositionedLogicalWidthReplaced(computedValues);
2746 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
2747 // the type 'static' in determining whether to calculate the static distance?
2748 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2750 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
2751 // than or less than the computed width(). Be careful of box-sizing and
2752 // percentage issues.
2754 // The following is based off of the W3C Working Draft from April 11, 2006 of
2755 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2756 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2757 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2758 // correspond to text from the spec)
2761 // We don't use containingBlock(), since we may be positioned by an enclosing
2762 // relative positioned inline.
2763 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2765 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
2767 // Use the container block's direction except when calculating the static distance
2768 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
2769 // of the CSS 2.1 test suite
2770 TextDirection containerDirection = containerBlock->style()->direction();
2772 bool isHorizontal = isHorizontalWritingMode();
2773 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2774 const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2775 const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2777 Length logicalLeftLength = style()->logicalLeft();
2778 Length logicalRightLength = style()->logicalRight();
2780 /*---------------------------------------------------------------------------*\
2781 * For the purposes of this section and the next, the term "static position"
2782 * (of an element) refers, roughly, to the position an element would have had
2783 * in the normal flow. More precisely:
2785 * * The static position for 'left' is the distance from the left edge of the
2786 * containing block to the left margin edge of a hypothetical box that would
2787 * have been the first box of the element if its 'position' property had
2788 * been 'static' and 'float' had been 'none'. The value is negative if the
2789 * hypothetical box is to the left of the containing block.
2790 * * The static position for 'right' is the distance from the right edge of the
2791 * containing block to the right margin edge of the same hypothetical box as
2792 * above. The value is positive if the hypothetical box is to the left of the
2793 * containing block's edge.
2795 * But rather than actually calculating the dimensions of that hypothetical box,
2796 * user agents are free to make a guess at its probable position.
2798 * For the purposes of calculating the static position, the containing block of
2799 * fixed positioned elements is the initial containing block instead of the
2800 * viewport, and all scrollable boxes should be assumed to be scrolled to their
2802 \*---------------------------------------------------------------------------*/
2805 // Calculate the static distance if needed.
2806 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth);
2808 // Calculate constraint equation values for 'width' case.
2809 computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2810 containerLogicalWidth, bordersPlusPadding,
2811 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2814 // Calculate constraint equation values for 'max-width' case.
2815 if (!style()->logicalMaxWidth().isMaxSizeNone()) {
2816 LogicalExtentComputedValues maxValues;
2818 computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2819 containerLogicalWidth, bordersPlusPadding,
2820 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2823 if (computedValues.m_extent > maxValues.m_extent) {
2824 computedValues.m_extent = maxValues.m_extent;
2825 computedValues.m_position = maxValues.m_position;
2826 computedValues.m_margins.m_start = maxValues.m_margins.m_start;
2827 computedValues.m_margins.m_end = maxValues.m_margins.m_end;
2831 // Calculate constraint equation values for 'min-width' case.
2832 if (!style()->logicalMinWidth().isZero() || style()->logicalMinWidth().isIntrinsic()) {
2833 LogicalExtentComputedValues minValues;
2835 computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2836 containerLogicalWidth, bordersPlusPadding,
2837 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2840 if (computedValues.m_extent < minValues.m_extent) {
2841 computedValues.m_extent = minValues.m_extent;
2842 computedValues.m_position = minValues.m_position;
2843 computedValues.m_margins.m_start = minValues.m_margins.m_start;
2844 computedValues.m_margins.m_end = minValues.m_margins.m_end;
2848 computedValues.m_extent += bordersPlusPadding;
2851 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2853 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2854 // 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.
2855 if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->slowIsFlippedBlocksWritingMode()) {
2856 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2857 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2859 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2863 void RenderBox::shrinkToFitWidth(const LayoutUnit availableSpace, const LayoutUnit logicalLeftValue, const LayoutUnit bordersPlusPadding, LogicalExtentComputedValues& computedValues) const
2865 // FIXME: would it be better to have shrink-to-fit in one step?
2866 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2867 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2868 LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2869 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
2872 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2873 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2874 const Length& logicalLeft, const Length& logicalRight, const Length& marginLogicalLeft,
2875 const Length& marginLogicalRight, LogicalExtentComputedValues& computedValues) const
2877 if (logicalWidth.isIntrinsic())
2878 logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
2880 // 'left' and 'right' cannot both be 'auto' because one would of been
2881 // converted to the static position already
2882 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2884 LayoutUnit logicalLeftValue = 0;
2886 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
2888 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2889 bool logicalLeftIsAuto = logicalLeft.isAuto();
2890 bool logicalRightIsAuto = logicalRight.isAuto();
2891 LayoutUnit& marginLogicalLeftValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
2892 LayoutUnit& marginLogicalRightValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
2893 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2894 /*-----------------------------------------------------------------------*\
2895 * If none of the three is 'auto': If both 'margin-left' and 'margin-
2896 * right' are 'auto', solve the equation under the extra constraint that
2897 * the two margins get equal values, unless this would make them negative,
2898 * in which case when direction of the containing block is 'ltr' ('rtl'),
2899 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2900 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2901 * solve the equation for that value. If the values are over-constrained,
2902 * ignore the value for 'left' (in case the 'direction' property of the
2903 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2904 * and solve for that value.
2905 \*-----------------------------------------------------------------------*/
2906 // NOTE: It is not necessary to solve for 'right' in the over constrained
2907 // case because the value is not used for any further calculations.
2909 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
2910 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
2912 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
2914 // Margins are now the only unknown
2915 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2916 // Both margins auto, solve for equality
2917 if (availableSpace >= 0) {
2918 marginLogicalLeftValue = availableSpace / 2; // split the difference
2919 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2921 // Use the containing block's direction rather than the parent block's
2922 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2923 if (containerDirection == LTR) {
2924 marginLogicalLeftValue = 0;
2925 marginLogicalRightValue = availableSpace; // will be negative
2927 marginLogicalLeftValue = availableSpace; // will be negative
2928 marginLogicalRightValue = 0;
2931 } else if (marginLogicalLeft.isAuto()) {
2932 // Solve for left margin
2933 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
2934 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
2935 } else if (marginLogicalRight.isAuto()) {
2936 // Solve for right margin
2937 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
2938 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
2940 // Over-constrained, solve for left if direction is RTL
2941 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
2942 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
2944 // Use the containing block's direction rather than the parent block's
2945 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2946 if (containerDirection == RTL)
2947 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
2950 /*--------------------------------------------------------------------*\
2951 * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
2952 * to 0, and pick the one of the following six rules that applies.
2954 * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
2955 * width is shrink-to-fit. Then solve for 'left'
2957 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2958 * ------------------------------------------------------------------
2959 * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
2960 * the 'direction' property of the containing block is 'ltr' set
2961 * 'left' to the static position, otherwise set 'right' to the
2962 * static position. Then solve for 'left' (if 'direction is 'rtl')
2963 * or 'right' (if 'direction' is 'ltr').
2964 * ------------------------------------------------------------------
2966 * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
2967 * width is shrink-to-fit . Then solve for 'right'
2968 * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
2970 * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
2972 * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
2975 * Calculation of the shrink-to-fit width is similar to calculating the
2976 * width of a table cell using the automatic table layout algorithm.
2977 * Roughly: calculate the preferred width by formatting the content
2978 * without breaking lines other than where explicit line breaks occur,
2979 * and also calculate the preferred minimum width, e.g., by trying all
2980 * possible line breaks. CSS 2.1 does not define the exact algorithm.
2981 * Thirdly, calculate the available width: this is found by solving
2982 * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
2985 * Then the shrink-to-fit width is:
2986 * min(max(preferred minimum width, available width), preferred width).
2987 \*--------------------------------------------------------------------*/
2988 // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
2989 // because the value is not used for any further calculations.
2991 // Calculate margins, 'auto' margins are ignored.
2992 marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
2993 marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
2995 const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
2997 // FIXME: Is there a faster way to find the correct case?
2998 // Use rule/case that applies.
2999 if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3000 // RULE 1: (use shrink-to-fit for width, and solve of left)
3001 LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3003 // FIXME: would it be better to have shrink-to-fit in one step?
3004 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3005 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3006 LayoutUnit availableWidth = availableSpace - logicalRightValue;
3007 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3008 logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3009 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3010 // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3011 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3013 shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
3014 } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3015 // RULE 4: (solve for left)
3016 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3017 logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3018 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3019 // RULE 5: (solve for width)
3020 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3021 if (autoWidthShouldFitContent())
3022 shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
3024 computedValues.m_extent = std::max<LayoutUnit>(0, availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth)));
3025 } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3026 // RULE 6: (no need solve for right)
3027 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3028 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3032 // Use computed values to calculate the horizontal position.
3034 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3035 // positioned, inline because right now, it is using the logical left position
3036 // of the first line box when really it should use the last line box. When
3037 // this is fixed elsewhere, this block should be removed.
3038 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3039 const RenderInline* flow = toRenderInline(containerBlock);
3040 InlineFlowBox* firstLine = flow->firstLineBox();
3041 InlineFlowBox* lastLine = flow->lastLineBox();
3042 if (firstLine && lastLine && firstLine != lastLine) {
3043 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3048 if (containerBlock->isBox() && toRenderBox(containerBlock)->scrollsOverflowY() && containerBlock->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
3049 logicalLeftValue = logicalLeftValue + toRenderBox(containerBlock)->verticalScrollbarWidth();
3052 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3053 computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3056 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3058 if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3061 // FIXME: The static distance computation has not been patched for mixed writing modes.
3062 LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3063 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
3064 if (curr->isBox() && !curr->isTableRow())
3065 staticLogicalTop += toRenderBox(curr)->logicalTop();
3067 logicalTop.setValue(Fixed, staticLogicalTop);
3070 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3073 computePositionedLogicalHeightReplaced(computedValues);
3077 // The following is based off of the W3C Working Draft from April 11, 2006 of
3078 // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3079 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3080 // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3081 // correspond to text from the spec)
3084 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3085 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3087 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3089 RenderStyle* styleToUse = style();
3090 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3091 const Length marginBefore = styleToUse->marginBefore();
3092 const Length marginAfter = styleToUse->marginAfter();
3093 Length logicalTopLength = styleToUse->logicalTop();
3094 Length logicalBottomLength = styleToUse->logicalBottom();
3096 /*---------------------------------------------------------------------------*\
3097 * For the purposes of this section and the next, the term "static position"
3098 * (of an element) refers, roughly, to the position an element would have had
3099 * in the normal flow. More precisely, the static position for 'top' is the
3100 * distance from the top edge of the containing block to the top margin edge
3101 * of a hypothetical box that would have been the first box of the element if
3102 * its 'position' property had been 'static' and 'float' had been 'none'. The
3103 * value is negative if the hypothetical box is above the containing block.
3105 * But rather than actually calculating the dimensions of that hypothetical
3106 * box, user agents are free to make a guess at its probable position.
3108 * For the purposes of calculating the static position, the containing block
3109 * of fixed positioned elements is the initial containing block instead of
3111 \*---------------------------------------------------------------------------*/
3114 // Calculate the static distance if needed.
3115 computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3117 // Calculate constraint equation values for 'height' case.
3118 LayoutUnit logicalHeight = computedValues.m_extent;
3119 computePositionedLogicalHeightUsing(styleToUse->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3120 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3123 // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3126 // Calculate constraint equation values for 'max-height' case.
3127 if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
3128 LogicalExtentComputedValues maxValues;
3130 computePositionedLogicalHeightUsing(styleToUse->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3131 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3134 if (computedValues.m_extent > maxValues.m_extent) {
3135 computedValues.m_extent = maxValues.m_extent;
3136 computedValues.m_position = maxValues.m_position;
3137 computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3138 computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3142 // Calculate constraint equation values for 'min-height' case.
3143 if (!styleToUse->logicalMinHeight().isZero() || styleToUse->logicalMinHeight().isIntrinsic()) {
3144 LogicalExtentComputedValues minValues;
3146 computePositionedLogicalHeightUsing(styleToUse->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3147 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3150 if (computedValues.m_extent < minValues.m_extent) {
3151 computedValues.m_extent = minValues.m_extent;
3152 computedValues.m_position = minValues.m_position;
3153 computedValues.m_margins.m_before = minValues.m_margins.m_before;
3154 computedValues.m_margins.m_after = minValues.m_margins.m_after;
3158 // Set final height value.
3159 computedValues.m_extent += bordersPlusPadding;
3162 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3164 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3165 // 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.
3166 if ((child->style()->slowIsFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3167 || (child->style()->slowIsFlippedBlocksWritingMode() != containerBlock->style()->slowIsFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3168 logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3170 // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3171 if (containerBlock->style()->slowIsFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3172 if (child->isHorizontalWritingMode())
3173 logicalTopPos += containerBlock->borderBottom();
3175 logicalTopPos += containerBlock->borderRight();
3177 if (child->isHorizontalWritingMode())
3178 logicalTopPos += containerBlock->borderTop();
3180 logicalTopPos += containerBlock->borderLeft();
3184 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3185 LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3186 const Length& logicalTop, const Length& logicalBottom, const Length& marginBefore,
3187 const Length& marginAfter, LogicalExtentComputedValues& computedValues) const
3189 // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
3190 // converted to the static position in computePositionedLogicalHeight()
3191 ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
3193 LayoutUnit logicalHeightValue;
3194 LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
3196 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3198 LayoutUnit logicalTopValue = 0;
3200 bool logicalHeightIsAuto = logicalHeightLength.isAuto();
3201 bool logicalTopIsAuto = logicalTop.isAuto();
3202 bool logicalBottomIsAuto = logicalBottom.isAuto();
3204 LayoutUnit resolvedLogicalHeight;
3205 // Height is never unsolved for tables.
3207 resolvedLogicalHeight = contentLogicalHeight;
3208 logicalHeightIsAuto = false;
3210 if (logicalHeightLength.isIntrinsic())
3211 resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding);
3213 resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
3216 if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3217 /*-----------------------------------------------------------------------*\
3218 * If none of the three are 'auto': If both 'margin-top' and 'margin-
3219 * bottom' are 'auto', solve the equation under the extra constraint that
3220 * the two margins get equal values. If one of 'margin-top' or 'margin-
3221 * bottom' is 'auto', solve the equation for that value. If the values
3222 * are over-constrained, ignore the value for 'bottom' and solve for that
3224 \*-----------------------------------------------------------------------*/
3225 // NOTE: It is not necessary to solve for 'bottom' in the over constrained
3226 // case because the value is not used for any further calculations.
3228 logicalHeightValue = resolvedLogicalHeight;
3229 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3231 const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
3233 // Margins are now the only unknown
3234 if (marginBefore.isAuto() && marginAfter.isAuto()) {
3235 // Both margins auto, solve for equality
3236 // NOTE: This may result in negative values.
3237 computedValues.m_margins.m_before = availableSpace / 2; // split the difference
3238 computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
3239 } else if (marginBefore.isAuto()) {
3240 // Solve for top margin
3241 computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3242 computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
3243 } else if (marginAfter.isAuto()) {
3244 // Solve for bottom margin
3245 computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3246 computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
3248 // Over-constrained, (no need solve for bottom)
3249 computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3250 computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3253 /*--------------------------------------------------------------------*\
3254 * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3255 * to 0, and pick the one of the following six rules that applies.
3257 * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3258 * the height is based on the content, and solve for 'top'.
3260 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3261 * ------------------------------------------------------------------
3262 * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3263 * set 'top' to the static position, and solve for 'bottom'.
3264 * ------------------------------------------------------------------
3266 * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3267 * the height is based on the content, and solve for 'bottom'.
3268 * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3270 * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3271 * solve for 'height'.
3272 * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3273 * solve for 'bottom'.
3274 \*--------------------------------------------------------------------*/
3275 // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3276 // because the value is not used for any further calculations.
3278 // Calculate margins, 'auto' margins are ignored.
3279 computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth);
3280 computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth);
3282 const LayoutUnit availableSpace = containerLogicalHeight - (computedValues.m_margins.m_before + computedValues.m_margins.m_after + bordersPlusPadding);
3284 // Use rule/case that applies.
3285 if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3286 // RULE 1: (height is content based, solve of top)
3287 logicalHeightValue = contentLogicalHeight;
3288 logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
3289 } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
3290 // RULE 3: (height is content based, no need solve of bottom)
3291 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3292 logicalHeightValue = contentLogicalHeight;
3293 } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3294 // RULE 4: (solve of top)
3295 logicalHeightValue = resolvedLogicalHeight;
3296 logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
3297 } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3298 // RULE 5: (solve of height)
3299 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3300 logicalHeightValue = std::max<LayoutUnit>(0, availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight)));
3301 } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
3302 // RULE 6: (no need solve of bottom)
3303 logicalHeightValue = resolvedLogicalHeight;
3304 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3307 computedValues.m_extent = logicalHeightValue;
3309 // Use computed values to calculate the vertical position.
3310 computedValues.m_position = logicalTopValue + computedValues.m_margins.m_before;
3311 computeLogicalTopPositionedOffset(computedValues.m_position, this, logicalHeightValue, containerBlock, containerLogicalHeight);
3314 void RenderBox::computePositionedLogicalWidthReplaced(LogicalExtentComputedValues& computedValues) const
3316 // The following is based off of the W3C Working Draft from April 11, 2006 of
3317 // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
3318 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
3319 // (block-style-comments in this function correspond to text from the spec and
3320 // the numbers correspond to numbers in spec)
3322 // We don't use containingBlock(), since we may be positioned by an enclosing
3323 // relative positioned inline.
3324 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3326 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
3327 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3329 // To match WinIE, in quirks mode use the parent's 'direction' property
3330 // instead of the the container block's.
3331 TextDirection containerDirection = containerBlock->style()->direction();
3333 // Variables to solve.
3334 bool isHorizontal = isHorizontalWritingMode();
3335 Length logicalLeft = style()->logicalLeft();
3336 Length logicalRight = style()->logicalRight();
3337 Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3338 Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3339 LayoutUnit& marginLogicalLeftAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3340 LayoutUnit& marginLogicalRightAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3342 /*-----------------------------------------------------------------------*\
3343 * 1. The used value of 'width' is determined as for inline replaced
3345 \*-----------------------------------------------------------------------*/
3346 // NOTE: This value of width is final in that the min/max width calculations
3347 // are dealt with in computeReplacedWidth(). This means that the steps to produce
3348 // correct max/min in the non-replaced version, are not necessary.
3349 computedValues.m_extent = computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth();
3351 const LayoutUnit availableSpace = containerLogicalWidth - computedValues.m_extent;
3353 /*-----------------------------------------------------------------------*\
3354 * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
3355 * of the containing block is 'ltr', set 'left' to the static position;
3356 * else if 'direction' is 'rtl', set 'right' to the static position.
3357 \*-----------------------------------------------------------------------*/
3359 computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth);
3361 /*-----------------------------------------------------------------------*\
3362 * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
3363 * or 'margin-right' with '0'.
3364 \*-----------------------------------------------------------------------*/
3365 if (logicalLeft.isAuto() || logicalRight.isAuto()) {
3366 if (marginLogicalLeft.isAuto())
3367 marginLogicalLeft.setValue(Fixed, 0);
3368 if (marginLogicalRight.isAuto())
3369 marginLogicalRight.setValue(Fixed, 0);
3372 /*-----------------------------------------------------------------------*\
3373 * 4. If at this point both 'margin-left' and 'margin-right' are still
3374 * 'auto', solve the equation under the extra constraint that the two
3375 * margins must get equal values, unless this would make them negative,
3376 * in which case when the direction of the containing block is 'ltr'
3377 * ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
3378 * 'margin-right' ('margin-left').
3379 \*-----------------------------------------------------------------------*/
3380 LayoutUnit logicalLeftValue = 0;
3381 LayoutUnit logicalRightValue = 0;
3383 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3384 // 'left' and 'right' cannot be 'auto' due to step 3
3385 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3387 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3388 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3390 LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
3391 if (difference > 0) {
3392 marginLogicalLeftAlias = difference / 2; // split the difference
3393 marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
3395 // Use the containing block's direction rather than the parent block's
3396 // per CSS 2.1 reference test abspos-replaced-width-margin-000.
3397 if (containerDirection == LTR) {
3398 marginLogicalLeftAlias = 0;
3399 marginLogicalRightAlias = difference; // will be negative
3401 marginLogicalLeftAlias = difference; // will be negative
3402 marginLogicalRightAlias = 0;
3406 /*-----------------------------------------------------------------------*\
3407 * 5. If at this point there is an 'auto' left, solve the equation for
3409 \*-----------------------------------------------------------------------*/
3410 } else if (logicalLeft.isAuto()) {
3411 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3412 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3413 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3416 logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3417 } else if (logicalRight.isAuto()) {
3418 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3419 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3420 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3422 // Solve for 'right'
3423 logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3424 } else if (marginLogicalLeft.isAuto()) {
3425 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3426 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3427 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3429 // Solve for 'margin-left'
3430 marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
3431 } else if (marginLogicalRight.isAuto()) {
3432 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3433 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3434 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3436 // Solve for 'margin-right'
3437 marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
3439 // Nothing is 'auto', just calculate the values.
3440 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3441 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3442 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3443 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3444 // If the containing block is right-to-left, then push the left position as far to the right as possible
3445 if (containerDirection == RTL) {
3446 int totalLogicalWidth = computedValues.m_extent + logicalLeftValue + logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias;
3447 logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
3451 /*-----------------------------------------------------------------------*\
3452 * 6. If at this point the values are over-constrained, ignore the value
3453 * for either 'left' (in case the 'direction' property of the
3454 * containing block is 'rtl') or 'right' (in case 'direction' is
3455 * 'ltr') and solve for that value.
3456 \*-----------------------------------------------------------------------*/
3457 // NOTE: Constraints imposed by the width of the containing block and its content have already been accounted for above.
3459 // FIXME: Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space, so that
3460 // can make the result here rather complicated to compute.
3462 // Use computed values to calculate the horizontal position.
3464 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3465 // positioned, inline containing block because right now, it is using the logical left position
3466 // of the first line box when really it should use the last line box. When
3467 // this is fixed elsewhere, this block should be removed.
3468 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3469 const RenderInline* flow = toRenderInline(containerBlock);
3470 InlineFlowBox* firstLine = flow->firstLineBox();
3471 InlineFlowBox* lastLine = flow->lastLineBox();
3472 if (firstLine && lastLine && firstLine != lastLine) {
3473 computedValues.m_position = logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3478 LayoutUnit logicalLeftPos = logicalLeftValue + marginLogicalLeftAlias;
3479 computeLogicalLeftPositionedOffset(logicalLeftPos, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3480 computedValues.m_position = logicalLeftPos;
3483 void RenderBox::computePositionedLogicalHeightReplaced(LogicalExtentComputedValues& computedValues) const
3485 // The following is based off of the W3C Working Draft from April 11, 2006 of
3486 // CSS 2.1: Section 10.6.5 "Absolutely positioned, replaced elements"
3487 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-height>
3488 // (block-style-comments in this function correspond to text from the spec and
3489 // the numbers correspond to numbers in spec)
3491 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3492 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3494 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3495 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3497 // Variables to solve.
3498 Length marginBefore = style()->marginBefore();
3499 Length marginAfter = style()->marginAfter();
3500 LayoutUnit& marginBeforeAlias = computedValues.m_margins.m_before;
3501 LayoutUnit& marginAfterAlias = computedValues.m_margins.m_after;
3503 Length logicalTop = style()->logicalTop();
3504 Length logicalBottom = style()->logicalBottom();
3506 /*-----------------------------------------------------------------------*\
3507 * 1. The used value of 'height' is determined as for inline replaced
3509 \*-----------------------------------------------------------------------*/
3510 // NOTE: This value of height is final in that the min/max height calculations
3511 // are dealt with in computeReplacedHeight(). This means that the steps to produce
3512 // correct max/min in the non-replaced version, are not necessary.
3513 computedValues.m_extent = computeReplacedLogicalHeight() + borderAndPaddingLogicalHeight();
3514 const LayoutUnit availableSpace = containerLogicalHeight - computedValues.m_extent;
3516 /*-----------------------------------------------------------------------*\
3517 * 2. If both 'top' and 'bottom' have the value 'auto', replace 'top'
3518 * with the element's static position.
3519 \*-----------------------------------------------------------------------*/
3521 computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
3523 /*-----------------------------------------------------------------------*\
3524 * 3. If 'bottom' is 'auto', replace any 'auto' on 'margin-top' or
3525 * 'margin-bottom' with '0'.
3526 \*-----------------------------------------------------------------------*/
3527 // FIXME: The spec. says that this step should only be taken when bottom is
3528 // auto, but if only top is auto, this makes step 4 impossible.
3529 if (logicalTop.isAuto() || logicalBottom.isAuto()) {
3530 if (marginBefore.isAuto())
3531 marginBefore.setValue(Fixed, 0);
3532 if (marginAfter.isAuto())
3533 marginAfter.setValue(Fixed, 0);
3536 /*-----------------------------------------------------------------------*\
3537 * 4. If at this point both 'margin-top' and 'margin-bottom' are still
3538 * 'auto', solve the equation under the extra constraint that the two
3539 * margins must get equal values.
3540 \*-----------------------------------------------------------------------*/
3541 LayoutUnit logicalTopValue = 0;
3542 LayoutUnit logicalBottomValue = 0;
3544 if (marginBefore.isAuto() && marginAfter.isAuto()) {
3545 // 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
3546 ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
3548 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3549 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3551 LayoutUnit difference = availableSpace - (logicalTopValue + logicalBottomValue);
3552 // NOTE: This may result in negative values.
3553 marginBeforeAlias = difference / 2; // split the difference
3554 marginAfterAlias = difference - marginBeforeAlias; // account for odd valued differences
3556 /*-----------------------------------------------------------------------*\
3557 * 5. If at this point there is only one 'auto' left, solve the equation
3559 \*-----------------------------------------------------------------------*/
3560 } else if (logicalTop.isAuto()) {
3561 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3562 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3563 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3566 logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
3567 } else if (logicalBottom.isAuto()) {
3568 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3569 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3570 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3572 // Solve for 'bottom'
3573 // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3575 } else if (marginBefore.isAuto()) {
3576 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3577 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3578 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3580 // Solve for 'margin-top'
3581 marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
3582 } else if (marginAfter.isAuto()) {
3583 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3584 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3585 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3587 // Solve for 'margin-bottom'
3588 marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
3590 // Nothing is 'auto', just calculate the values.
3591 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3592 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3593 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3594 // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3598 /*-----------------------------------------------------------------------*\
3599 * 6. If at this point the values are over-constrained, ignore the value
3600 * for 'bottom' and solve for that value.
3601 \*-----------------------------------------------------------------------*/
3602 // NOTE: It is not necessary to do this step because we don't end up using
3603 // the value of 'bottom' regardless of whether the values are over-constrained
3606 // Use computed values to calculate the vertical position.
3607 LayoutUnit logicalTopPos = logicalTopValue + marginBeforeAlias;
3608 computeLogicalTopPositionedOffset(logicalTopPos, this, computedValues.m_extent, containerBlock, containerLogicalHeight);
3609 computedValues.m_position = logicalTopPos;
3612 LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
3614 // VisiblePositions at offsets inside containers either a) refer to the positions before/after
3615 // those containers (tables and select elements) or b) refer to the position inside an empty block.
3616 // They never refer to children.
3617 // FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.
3619 LayoutRect rect(location(), LayoutSize(caretWidth, height()));
3620 bool ltr = box ? box->isLeftToRightDirection() : style()->isLeftToRightDirection();
3622 if ((!caretOffset) ^ ltr)
3623 rect.move(LayoutSize(width() - caretWidth, 0));
3626 RootInlineBox& rootBox = box->root();
3627 LayoutUnit top = rootBox.lineTop();
3629 rect.setHeight(rootBox.lineBottom() - top);
3632 // If height of box is smaller than font height, use the latter one,
3633 // otherwise the caret might become invisible.
3635 // Also, if the box is not a replaced element, always use the font height.
3636 // This prevents the "big caret" bug described in:
3637 // <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
3639 // FIXME: ignoring :first-line, missing good reason to take care of
3640 LayoutUnit fontHeight = style()->fontMetrics().height();
3641 if (fontHeight > rect.height() || (!isReplaced() && !isTable()))
3642 rect.setHeight(fontHeight);
3644 if (extraWidthToEndOfLine)
3645 *extraWidthToEndOfLine = x() + width() - rect.maxX();
3647 // Move to local coords
3648 rect.moveBy(-location());
3650 // FIXME: Border/padding should be added for all elements but this workaround
3651 // is needed because we use offsets inside an "atomic" element to represent
3652 // positions before and after the element in deprecated editing offsets.
3653 if (node() && !(editingIgnoresContent(node()) || isRenderedTableElement(node()))) {
3654 rect.setX(rect.x() + borderLeft() + paddingLeft());
3655 rect.setY(rect.y() + paddingTop() + borderTop());
3658 if (!isHorizontalWritingMode())
3659 return rect.transposedRect();
3664 PositionWithAffinity RenderBox::positionForPoint(const LayoutPoint& point)
3666 // no children...return this render object's element, if there is one, and offset 0
3667 RenderObject* firstChild = slowFirstChild();
3669 return createPositionWithAffinity(nonPseudoNode() ? firstPositionInOrBeforeNode(nonPseudoNode()) : Position());
3671 if (isTable() && nonPseudoNode()) {
3672 LayoutUnit right = contentWidth() + borderAndPaddingWidth();
3673 LayoutUnit bottom = contentHeight() + borderAndPaddingHeight();
3675 if (point.x() < 0 || point.x() > right || point.y() < 0 || point.y() > bottom) {
3676 if (point.x() <= right / 2)
3677 return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
3678 return createPositionWithAffinity(lastPositionInOrAfterNode(nonPseudoNode()));
3682 // Pass off to the closest child.
3683 LayoutUnit minDist = LayoutUnit::max();
3684 RenderBox* closestRenderer = 0;
3685 LayoutPoint adjustedPoint = point;
3687 adjustedPoint.moveBy(location());
3689 for (RenderObject* renderObject = firstChild; renderObject; renderObject = renderObject->nextSibling()) {
3690 if ((!renderObject->slowFirstChild() && !renderObject->isInline() && !renderObject->isRenderBlockFlow() )
3691 || renderObject->style()->visibility() != VISIBLE)
3694 if (!renderObject->isBox())
3697 RenderBox* renderer = toRenderBox(renderObject);
3699 LayoutUnit top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? LayoutUnit() : renderer->y());
3700 LayoutUnit bottom = top + renderer->contentHeight();
3701 LayoutUnit left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? LayoutUnit() : renderer->x());
3702 LayoutUnit right = left + renderer->contentWidth();
3704 if (point.x() <= right && point.x() >= left && point.y() <= top && point.y() >= bottom) {
3705 if (renderer->isTableRow())
3706 return renderer->positionForPoint(point + adjustedPoint - renderer->locationOffset());
3707 return renderer->positionForPoint(point - renderer->locationOffset());
3710 // Find the distance from (x, y) to the box. Split the space around the box into 8 pieces
3711 // and use a different compare depending on which piece (x, y) is in.
3713 if (point.x() > right) {
3714 if (point.y() < top)
3715 cmp = LayoutPoint(right, top);
3716 else if (point.y() > bottom)
3717 cmp = LayoutPoint(right, bottom);
3719 cmp = LayoutPoint(right, point.y());
3720 } else if (point.x() < left) {
3721 if (point.y() < top)
3722 cmp = LayoutPoint(left, top);
3723 else if (point.y() > bottom)
3724 cmp = LayoutPoint(left, bottom);
3726 cmp = LayoutPoint(left, point.y());
3728 if (point.y() < top)
3729 cmp = LayoutPoint(point.x(), top);
3731 cmp = LayoutPoint(point.x(), bottom);
3734 LayoutSize difference = cmp - point;
3736 LayoutUnit dist = difference.width() * difference.width() + difference.height() * difference.height();
3737 if (dist < minDist) {
3738 closestRenderer = renderer;
3743 if (closestRenderer)
3744 return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset());
3745 return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
3748 bool RenderBox::shrinkToAvoidFloats() const
3750 // Floating objects don't shrink. Objects that don't avoid floats don't shrink.
3751 if (isInline() || !avoidsFloats() || isFloating())
3754 // Only auto width objects can possibly shrink to avoid floats.
3755 return style()->width().isAuto();
3758 static bool isReplacedElement(Node* node)
3760 // Checkboxes and radioboxes are not isReplaced() nor do they have their own renderer in which to override avoidFloats().
3761 return node && node->isElementNode() && toElement(node)->isFormControlElement();
3764 bool RenderBox::avoidsFloats() const
3766 return isReplaced() || isReplacedElement(node()) || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isFlexItemIncludingDeprecated();
3769 bool RenderBox::hasNonCompositedScrollbars() const
3771 if (RenderLayer* layer = this->layer()) {
3772 if (RenderLayerScrollableArea* scrollableArea = layer->scrollableArea()) {
3773 if (scrollableArea->hasHorizontalScrollbar() && !scrollableArea->layerForHorizontalScrollbar())
3775 if (scrollableArea->hasVerticalScrollbar() && !scrollableArea->layerForVerticalScrollbar())
3782 PaintInvalidationReason RenderBox::paintInvalidationReason(const RenderLayerModelObject& paintInvalidationContainer,
3783 const LayoutRect& oldBounds, const LayoutPoint& oldLocation, const LayoutRect& newBounds, const LayoutPoint& newLocation) const
3785 PaintInvalidationReason invalidationReason = RenderBoxModelObject::paintInvalidationReason(paintInvalidationContainer, oldBounds, oldLocation, newBounds, newLocation);
3786 if (isFullPaintInvalidationReason(invalidationReason))
3787 return invalidationReason;
3789 // If the transform is not identity or translation, incremental invalidation is not applicable
3790 // because the difference between oldBounds and newBounds doesn't cover all area needing invalidation.
3791 // FIXME: Should also consider ancestor transforms since paintInvalidationContainer. crbug.com/426111.
3792 if (invalidationReason == PaintInvalidationIncremental
3793 && paintInvalidationContainer != this
3794 && hasLayer() && layer()->transform() && !layer()->transform()->isIdentityOrTranslation())
3795 return PaintInvalidationBoundsChange;
3797 if (!style()->hasBackground() && !style()->hasBoxDecorations()) {
3798 // We could let incremental invalidation cover non-composited scrollbars, but just
3799 // do a full invalidation because incremental invalidation will go away with slimming paint.
3800 if (invalidationReason == PaintInvalidationIncremental && hasNonCompositedScrollbars())
3801 return PaintInvalidationBorderBoxChange;
3802 return invalidationReason;
3805 LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
3806 LayoutSize newBorderBoxSize = size();
3808 if (oldBorderBoxSize == newBorderBoxSize)
3809 return invalidationReason;
3811 // See another hasNonCompositedScrollbars() callsite above.
3812 if (hasNonCompositedScrollbars())
3813 return PaintInvalidationBorderBoxChange;
3815 // FIXME: Implement correct incremental invalidation for visual overflowing effects.
3816 if (style()->hasVisualOverflowingEffect() || style()->hasAppearance() || style()->hasFilter())
3817 return PaintInvalidationBorderBoxChange;
3819 if (style()->hasBorderRadius()) {
3820 // If a border-radius exists and width/height is smaller than radius width/height,
3821 // we need to fully invalidate to cover the changed radius.
3822 RoundedRect oldRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), oldBorderBoxSize));
3823 RoundedRect newRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), newBorderBoxSize));
3824 if (oldRoundedRect.radii() != newRoundedRect.radii())
3825 return PaintInvalidationBorderBoxChange;
3828 if (oldBorderBoxSize.width() != newBorderBoxSize.width() && mustInvalidateBackgroundOrBorderPaintOnWidthChange())
3829 return PaintInvalidationBorderBoxChange;
3830 if (oldBorderBoxSize.height() != newBorderBoxSize.height() && mustInvalidateBackgroundOrBorderPaintOnHeightChange())
3831 return PaintInvalidationBorderBoxChange;
3833 return PaintInvalidationIncremental;
3836 void RenderBox::incrementallyInvalidatePaint(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& oldBounds, const LayoutRect& newBounds, const LayoutPoint& positionFromPaintInvalidationBacking)
3838 RenderObject::incrementallyInvalidatePaint(paintInvalidationContainer, oldBounds, newBounds, positionFromPaintInvalidationBacking);
3840 bool hasBoxDecorations = style()->hasBoxDecorations();
3841 if (!style()->hasBackground() && !hasBoxDecorations)
3844 LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
3845 LayoutSize newBorderBoxSize = size();
3847 // If border box size didn't change, RenderObject's incrementallyInvalidatePaint() is good.
3848 if (oldBorderBoxSize == newBorderBoxSize)
3851 // If size of the paint invalidation rect equals to size of border box, RenderObject::incrementallyInvalidatePaint()
3852 // is good for boxes having background without box decorations.
3853 ASSERT(oldBounds.location() == newBounds.location()); // Otherwise we won't do incremental invalidation.
3854 if (!hasBoxDecorations
3855 && positionFromPaintInvalidationBacking == newBounds.location()
3856 && oldBorderBoxSize == oldBounds.size()
3857 && newBorderBoxSize == newBounds.size())
3860 // Invalidate the right delta part and the right border of the old or new box which has smaller width.
3861 LayoutUnit deltaWidth = absoluteValue(oldBorderBoxSize.width() - newBorderBoxSize.width());
3863 LayoutUnit smallerWidth = std::min(oldBorderBoxSize.width(), newBorderBoxSize.width());
3864 LayoutUnit borderTopRightRadiusWidth = valueForLength(style()->borderTopRightRadius().width(), smallerWidth);
3865 LayoutUnit borderBottomRightRadiusWidth = valueForLength(style()->borderBottomRightRadius().width(), smallerWidth);
3866 LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight(), std::max(borderTopRightRadiusWidth, borderBottomRightRadiusWidth));
3867 LayoutRect rightDeltaRect(positionFromPaintInvalidationBacking.x() + smallerWidth - borderWidth,
3868 positionFromPaintInvalidationBacking.y(),
3869 deltaWidth + borderWidth,
3870 std::max(oldBorderBoxSize.height(), newBorderBoxSize.height()));
3871 invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, rightDeltaRect, oldBounds, newBounds);
3874 // Invalidate the bottom delta part and the bottom border of the old or new box which has smaller height.
3875 LayoutUnit deltaHeight = absoluteValue(oldBorderBoxSize.height() - newBorderBoxSize.height());
3877 LayoutUnit smallerHeight = std::min(oldBorderBoxSize.height(), newBorderBoxSize.height());
3878 LayoutUnit borderBottomLeftRadiusHeight = valueForLength(style()->borderBottomLeftRadius().height(), smallerHeight);
3879 LayoutUnit borderBottomRightRadiusHeight = valueForLength(style()->borderBottomRightRadius().height(), smallerHeight);
3880 LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom(), std::max(borderBottomLeftRadiusHeight, borderBottomRightRadiusHeight));
3881 LayoutRect bottomDeltaRect(positionFromPaintInvalidationBacking.x(),
3882 positionFromPaintInvalidationBacking.y() + smallerHeight - borderHeight,
3883 std::max(oldBorderBoxSize.width(), newBorderBoxSize.width()),
3884 deltaHeight + borderHeight);
3885 invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, bottomDeltaRect, oldBounds, newBounds);
3889 void RenderBox::invalidatePaintRectClippedByOldAndNewBounds(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& rect, const LayoutRect& oldBounds, const LayoutRect& newBounds)
3893 LayoutRect rectClippedByOldBounds = intersection(rect, oldBounds);
3894 LayoutRect rectClippedByNewBounds = intersection(rect, newBounds);
3895 // Invalidate only once if the clipped rects equal.
3896 if (rectClippedByOldBounds == rectClippedByNewBounds) {
3897 invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, PaintInvalidationIncremental);
3900 // Invalidate the bigger one if one contains another. Otherwise invalidate both.
3901 if (!rectClippedByNewBounds.contains(rectClippedByOldBounds))
3902 invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, PaintInvalidationIncremental);
3903 if (!rectClippedByOldBounds.contains(rectClippedByNewBounds))
3904 invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByNewBounds, PaintInvalidationIncremental);
3907 void RenderBox::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutScope)
3909 ASSERT(!needsLayout());
3910 // If fragmentation height has changed, we need to lay out. No need to enter the renderer if it
3911 // is childless, though.
3912 if (view()->layoutState()->pageLogicalHeightChanged() && slowFirstChild())
3913 layoutScope.setChildNeedsLayout(this);
3916 void RenderBox::addVisualEffectOverflow()
3918 if (!style()->hasVisualOverflowingEffect())
3921 // Add in the final overflow with shadows, outsets and outline combined.
3922 LayoutRect visualEffectOverflow = borderBoxRect();
3923 visualEffectOverflow.expand(computeVisualEffectOverflowExtent());
3924 addVisualOverflow(visualEffectOverflow);
3927 LayoutBoxExtent RenderBox::computeVisualEffectOverflowExtent() const
3929 ASSERT(style()->hasVisualOverflowingEffect());
3936 if (style()->boxShadow()) {
3937 style()->getBoxShadowExtent(top, right, bottom, left);
3939 // Box shadow extent's top and left are negative when extend to left and top direction, respectively.
3940 // Negate to make them positive.
3945 if (style()->hasBorderImageOutsets()) {
3946 LayoutBoxExtent borderOutsets = style()->borderImageOutsets();
3947 top = std::max(top, borderOutsets.top());
3948 right = std::max(right, borderOutsets.right());
3949 bottom = std::max(bottom, borderOutsets.bottom());
3950 left = std::max(left, borderOutsets.left());
3953 if (style()->hasOutline()) {
3954 if (style()->outlineStyleIsAuto()) {
3955 // The result focus ring rects are in coordinates of this object's border box.
3956 Vector<LayoutRect> focusRingRects;
3957 addFocusRingRects(focusRingRects, LayoutPoint(), this);
3958 LayoutRect rect = unionRect(focusRingRects);
3960 int outlineSize = GraphicsContext::focusRingOutsetExtent(style()->outlineOffset(), style()->outlineWidth());
3961 top = std::max(top, -rect.y() + outlineSize);
3962 right = std::max(right, rect.maxX() - width() + outlineSize);
3963 bottom = std::max(bottom, rect.maxY() - height() + outlineSize);
3964 left = std::max(left, -rect.x() + outlineSize);
3966 LayoutUnit outlineSize = style()->outlineSize();
3967 top = std::max(top, outlineSize);
3968 right = std::max(right, outlineSize);
3969 bottom = std::max(bottom, outlineSize);
3970 left = std::max(left, outlineSize);
3974 return LayoutBoxExtent(top, right, bottom, left);
3977 void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta)
3979 // Never allow flow threads to propagate overflow up to a parent.
3980 if (child->isRenderFlowThread())
3983 // Only propagate layout overflow from the child if the child isn't clipping its overflow. If it is, then
3984 // its overflow is internal to it, and we don't care about it. layoutOverflowRectForPropagation takes care of this
3985 // and just propagates the border box rect instead.
3986 LayoutRect childLayoutOverflowRect = child->layoutOverflowRectForPropagation(style());
3987 childLayoutOverflowRect.move(delta);
3988 addLayoutOverflow(childLayoutOverflowRect);
3990 // Add in visual overflow from the child. Even if the child clips its overflow, it may still
3991 // have visual overflow of its own set from box shadows or reflections. It is unnecessary to propagate this
3992 // overflow if we are clipping our own overflow.
3993 if (child->hasSelfPaintingLayer())
3995 LayoutRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
3996 childVisualOverflowRect.move(delta);
3997 addContentsVisualOverflow(childVisualOverflowRect);
4000 void RenderBox::addLayoutOverflow(const LayoutRect& rect)
4002 LayoutRect clientBox = noOverflowRect();
4003 if (clientBox.contains(rect) || rect.isEmpty())
4006 // For overflow clip objects, we don't want to propagate overflow into unreachable areas.
4007 LayoutRect overflowRect(rect);
4008 if (hasOverflowClip() || isRenderView()) {
4009 // Overflow is in the block's coordinate space and thus is flipped for horizontal-bt and vertical-rl
4010 // writing modes. At this stage that is actually a simplification, since we can treat horizontal-tb/bt as the same
4011 // and vertical-lr/rl as the same.
4012 bool hasTopOverflow = !style()->isLeftToRightDirection() && !isHorizontalWritingMode();
4013 bool hasLeftOverflow = !style()->isLeftToRightDirection() && isHorizontalWritingMode();
4014 if (isFlexibleBox() && style()->isReverseFlexDirection()) {
4015 RenderFlexibleBox* flexibleBox = toRenderFlexibleBox(this);
4016 if (flexibleBox->isHorizontalFlow())
4017 hasLeftOverflow = true;
4019 hasTopOverflow = true;
4022 if (!hasTopOverflow)
4023 overflowRect.shiftYEdgeTo(std::max(overflowRect.y(), clientBox.y()));
4025 overflowRect.shiftMaxYEdgeTo(std::min(overflowRect.maxY(), clientBox.maxY()));
4026 if (!hasLeftOverflow)
4027 overflowRect.shiftXEdgeTo(std::max(overflowRect.x(), clientBox.x()));
4029 overflowRect.shiftMaxXEdgeTo(std::min(overflowRect.maxX(), clientBox.maxX()));
4031 // Now re-test with the adjusted rectangle and see if it has become unreachable or fully
4033 if (clientBox.contains(overflowRect) || overflowRect.isEmpty())
4038 m_overflow = adoptPtr(new RenderOverflow(clientBox, borderBoxRect()));
4040 m_overflow->addLayoutOverflow(overflowRect);
4043 void RenderBox::addVisualOverflow(const LayoutRect& rect)
4045 LayoutRect borderBox = borderBoxRect();
4046 if (borderBox.contains(rect) || rect.isEmpty())
4050 m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBox));
4052 m_overflow->addVisualOverflow(rect);
4055 void RenderBox::addContentsVisualOverflow(const LayoutRect& rect)
4057 if (!hasOverflowClip()) {
4058 addVisualOverflow(rect);
4063 m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBoxRect()));
4064 m_overflow->addContentsVisualOverflow(rect);
4067 void RenderBox::clearLayoutOverflow()
4072 if (!hasVisualOverflow() && contentsVisualOverflowRect().isEmpty()) {
4073 clearAllOverflows();
4077 m_overflow->setLayoutOverflow(noOverflowRect());
4080 inline static bool percentageLogicalHeightIsResolvable(const RenderBox* box)
4082 return RenderBox::percentageLogicalHeightIsResolvableFromBlock(box->containingBlock(), box->isOutOfFlowPositioned());
4085 bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock* containingBlock, bool isOutOfFlowPositioned)
4087 // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
4088 // block that may have a specified height and then use it. In strict mode, this violates the
4089 // specification, which states that percentage heights just revert to auto if the containing
4090 // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
4091 // only at explicit containers.
4092 const RenderBlock* cb = containingBlock;
4093 bool inQuirksMode = cb->document().inQuirksMode();
4094 while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style()->logicalHeight().isAuto()) {
4095 if (!inQuirksMode && !cb->isAnonymousBlock())
4097 cb = cb->containingBlock();
4100 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
4101 // explicitly specified that can be used for any percentage computations.
4102 // FIXME: We can't just check top/bottom here.
4103 // https://bugs.webkit.org/show_bug.cgi?id=46500
4104 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
4106 // Table cells violate what the CSS spec says to do with heights. Basically we
4107 // don't care if the cell specified a height or not. We just always make ourselves
4108 // be a percentage of the cell's current content height.
4109 if (cb->isTableCell())
4112 // Otherwise we only use our percentage height if our containing block had a specified
4114 if (cb->style()->logicalHeight().isFixed())
4116 if (cb->style()->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight)
4117 return percentageLogicalHeightIsResolvableFromBlock(cb->containingBlock(), cb->isOutOfFlowPositioned());
4118 if (cb->isRenderView() || inQuirksMode || isOutOfFlowPositionedWithSpecifiedHeight)
4120 if (cb->isDocumentElement() && isOutOfFlowPositioned) {
4121 // Match the positioned objects behavior, which is that positioned objects will fill their viewport
4122 // always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
4129 bool RenderBox::hasUnsplittableScrollingOverflow() const
4131 // We will paginate as long as we don't scroll overflow in the pagination direction.
4132 bool isHorizontal = isHorizontalWritingMode();
4133 if ((isHorizontal && !scrollsOverflowY()) || (!isHorizontal && !scrollsOverflowX()))
4136 // We do have overflow. We'll still be willing to paginate as long as the block
4137 // has auto logical height, auto or undefined max-logical-height and a zero or auto min-logical-height.
4138 // Note this is just a heuristic, and it's still possible to have overflow under these
4139 // conditions, but it should work out to be good enough for common cases. Paginating overflow
4140 // with scrollbars present is not the end of the world and is what we used to do in the old model anyway.
4141 return !style()->logicalHeight().isIntrinsicOrAuto()
4142 || (!style()->logicalMaxHeight().isIntrinsicOrAuto() && !style()->logicalMaxHeight().isMaxSizeNone() && (!style()->logicalMaxHeight().isPercent() || percentageLogicalHeightIsResolvable(this)))
4143 || (!style()->logicalMinHeight().isIntrinsicOrAuto() && style()->logicalMinHeight().isPositive() && (!style()->logicalMinHeight().isPercent() || percentageLogicalHeightIsResolvable(this)));
4146 bool RenderBox::isUnsplittableForPagination() const
4148 return isReplaced() || hasUnsplittableScrollingOverflow() || (parent() && isWritingModeRoot());
4151 LayoutUnit RenderBox::lineHeight(bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
4154 return direction == HorizontalLine ? m_marginBox.top() + height() + m_marginBox.bottom() : m_marginBox.right() + width() + m_marginBox.left();
4158 int RenderBox::baselinePosition(FontBaseline baselineType, bool /*firstLine*/, LineDirectionMode direction, LinePositionMode linePositionMode) const
4160 ASSERT(linePositionMode == PositionOnContainingLine);
4162 int result = direction == HorizontalLine ? m_marginBox.top() + height() + m_marginBox.bottom() : m_marginBox.right() + width() + m_marginBox.left();
4163 if (baselineType == AlphabeticBaseline)
4165 return result - result / 2;
4171 RenderLayer* RenderBox::enclosingFloatPaintingLayer() const
4173 const RenderObject* curr = this;
4175 RenderLayer* layer = curr->hasLayer() && curr->isBox() ? toRenderBox(curr)->layer() : 0;
4176 if (layer && layer->isSelfPaintingLayer())
4178 curr = curr->parent();
4183 LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* parentStyle) const
4185 LayoutRect rect = visualOverflowRectForPropagation(parentStyle);
4186 if (!parentStyle->isHorizontalWritingMode())
4187 return rect.transposedRect();
4191 LayoutRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) const
4193 // If the writing modes of the child and parent match, then we don't have to
4194 // do anything fancy. Just return the result.
4195 LayoutRect rect = visualOverflowRect();
4196 if (parentStyle->writingMode() == style()->writingMode())
4199 // We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
4200 // in a particular axis, then we have to flip the rect along that axis.
4201 if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
4202 rect.setX(width() - rect.maxX());
4203 else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
4204 rect.setY(height() - rect.maxY());
4209 LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* parentStyle) const
4211 LayoutRect rect = layoutOverflowRectForPropagation(parentStyle);
4212 if (!parentStyle->isHorizontalWritingMode())
4213 return rect.transposedRect();
4217 LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) const
4219 // Only propagate interior layout overflow if we don't clip it.
4220 LayoutRect rect = borderBoxRect();
4221 // We want to include the margin, but only when it adds height. Quirky margins don't contribute height
4222 // nor do the margins of self-collapsing blocks.
4223 if (!style()->hasMarginAfterQuirk() && !isSelfCollapsingBlock())
4224 rect.expand(isHorizontalWritingMode() ? LayoutSize(LayoutUnit(), marginAfter()) : LayoutSize(marginAfter(), LayoutUnit()));
4226 if (!hasOverflowClip())
4227 rect.unite(layoutOverflowRect());
4229 bool hasTransform = hasLayer() && layer()->transform();
4230 if (isRelPositioned() || hasTransform) {
4231 // If we are relatively positioned or if we have a transform, then we have to convert
4232 // this rectangle into physical coordinates, apply relative positioning and transforms
4233 // to it, and then convert it back.
4234 flipForWritingMode(rect);
4237 rect = layer()->currentTransform().mapRect(rect);
4239 if (isRelPositioned())
4240 rect.move(offsetForInFlowPosition());
4242 // Now we need to flip back.
4243 flipForWritingMode(rect);
4246 // If the writing modes of the child and parent match, then we don't have to
4247 // do anything fancy. Just return the result.
4248 if (parentStyle->writingMode() == style()->writingMode())
4251 // We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
4252 // in a particular axis, then we have to flip the rect along that axis.
4253 if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
4254 rect.setX(width() - rect.maxX());
4255 else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
4256 rect.setY(height() - rect.maxY());
4261 LayoutRect RenderBox::noOverflowRect() const
4263 // Because of the special coordinate system used for overflow rectangles and many other
4264 // rectangles (not quite logical, not quite physical), we need to flip the block progression
4265 // coordinate in vertical-rl and horizontal-bt writing modes. In other words, the rectangle
4266 // returned is physical, except for the block direction progression coordinate (y in horizontal
4267 // writing modes, x in vertical writing modes), which is always "logical top". Apart from the
4268 // flipping, this method does the same as clientBoxRect().
4270 const int scrollBarWidth = verticalScrollbarWidth();
4271 const int scrollBarHeight = horizontalScrollbarHeight();
4272 LayoutUnit left = borderLeft() + (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? scrollBarWidth : 0);
4273 LayoutUnit top = borderTop();
4274 LayoutUnit right = borderRight();
4275 LayoutUnit bottom = borderBottom();
4276 LayoutRect rect(left, top, width() - left - right, height() - top - bottom);
4277 flipForWritingMode(rect);
4278 // Subtract space occupied by scrollbars. Order is important here: first flip, then subtract
4279 // scrollbars. This may seem backwards and weird, since one would think that a horizontal
4280 // scrollbar at the physical bottom in horizontal-bt ought to be at the logical top (physical
4281 // bottom), between the logical top (physical bottom) border and the logical top (physical
4282 // bottom) padding. But this is how the rest of the code expects us to behave. This is highly
4283 // related to https://bugs.webkit.org/show_bug.cgi?id=76129
4284 // FIXME: when the above mentioned bug is fixed, it should hopefully be possible to call
4285 // clientBoxRect() or paddingBoxRect() in this method, rather than fiddling with the edges on
4287 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
4288 rect.contract(0, scrollBarHeight);
4290 rect.contract(scrollBarWidth, scrollBarHeight);
4294 LayoutUnit RenderBox::offsetLeft() const
4296 return adjustedPositionRelativeToOffsetParent(topLeftLocation()).x();
4299 LayoutUnit RenderBox::offsetTop() const
4301 return adjustedPositionRelativeToOffsetParent(topLeftLocation()).y();
4304 LayoutPoint RenderBox::flipForWritingModeForChild(const RenderBox* child, const LayoutPoint& point) const
4306 if (!UNLIKELY(document().containsAnyRareWritingMode()))
4308 if (!style()->slowIsFlippedBlocksWritingMode())
4311 // The child is going to add in its x() and y(), so we have to make sure it ends up in
4313 if (isHorizontalWritingMode())
4314 return LayoutPoint(point.x(), point.y() + height() - child->height() - (2 * child->y()));
4315 return LayoutPoint(point.x() + width() - child->width() - (2 * child->x()), point.y());
4318 LayoutPoint RenderBox::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
4320 if (!UNLIKELY(document().containsAnyRareWritingMode()))
4322 if (!hasColumns() || !style()->slowIsFlippedBlocksWritingMode())
4323 return flipForWritingMode(point);
4324 return toRenderBlock(this)->flipForWritingModeIncludingColumns(point);
4327 LayoutPoint RenderBox::topLeftLocation() const
4329 RenderBlock* containerBlock = containingBlock();
4330 if (!containerBlock || containerBlock == this)
4332 return containerBlock->flipForWritingModeForChild(this, location());
4335 LayoutSize RenderBox::topLeftLocationOffset() const
4337 RenderBlock* containerBlock = containingBlock();
4338 if (!containerBlock || containerBlock == this)
4339 return locationOffset();
4341 LayoutRect rect(frameRect());
4342 containerBlock->flipForWritingMode(rect); // FIXME: This is wrong if we are an absolutely positioned object enclosed by a relative-positioned inline.
4343 return LayoutSize(rect.x(), rect.y());
4346 bool RenderBox::hasRelativeLogicalHeight() const
4348 return style()->logicalHeight().isPercent()
4349 || style()->logicalMinHeight().isPercent()
4350 || style()->logicalMaxHeight().isPercent();
4353 static void markBoxForRelayoutAfterSplit(RenderBox* box)
4355 // FIXME: The table code should handle that automatically. If not,
4356 // we should fix it and remove the table part checks.
4357 if (box->isTable()) {
4358 // Because we may have added some sections with already computed column structures, we need to
4359 // sync the table structure with them now. This avoids crashes when adding new cells to the table.
4360 toRenderTable(box)->forceSectionsRecalc();
4361 } else if (box->isTableSection())
4362 toRenderTableSection(box)->setNeedsCellRecalc();
4364 box->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
4367 RenderObject* RenderBox::splitAnonymousBoxesAroundChild(RenderObject* beforeChild)
4369 bool didSplitParentAnonymousBoxes = false;
4371 while (beforeChild->parent() != this) {
4372 RenderBox* boxToSplit = toRenderBox(beforeChild->parent());
4373 if (boxToSplit->slowFirstChild() != beforeChild && boxToSplit->isAnonymous()) {
4374 didSplitParentAnonymousBoxes = true;
4376 // We have to split the parent box into two boxes and move children
4377 // from |beforeChild| to end into the new post box.
4378 RenderBox* postBox = boxToSplit->createAnonymousBoxWithSameTypeAs(this);
4379 postBox->setChildrenInline(boxToSplit->childrenInline());
4380 RenderBox* parentBox = toRenderBox(boxToSplit->parent());
4381 // We need to invalidate the |parentBox| before inserting the new node
4382 // so that the table paint invalidation logic knows the structure is dirty.
4383 // See for example RenderTableCell:clippedOverflowRectForPaintInvalidation.
4384 markBoxForRelayoutAfterSplit(parentBox);
4385 parentBox->virtualChildren()->insertChildNode(parentBox, postBox, boxToSplit->nextSibling());
4386 boxToSplit->moveChildrenTo(postBox, beforeChild, 0, true);
4388 markBoxForRelayoutAfterSplit(boxToSplit);
4389 markBoxForRelayoutAfterSplit(postBox);
4391 beforeChild = postBox;
4393 beforeChild = boxToSplit;
4396 if (didSplitParentAnonymousBoxes)
4397 markBoxForRelayoutAfterSplit(this);
4399 ASSERT(beforeChild->parent() == this);
4403 LayoutUnit RenderBox::offsetFromLogicalTopOfFirstPage() const
4405 LayoutState* layoutState = view()->layoutState();
4406 if (layoutState && !layoutState->isPaginated())
4409 if (!layoutState && !flowThreadContainingBlock())
4412 RenderBlock* containerBlock = containingBlock();
4413 return containerBlock->offsetFromLogicalTopOfFirstPage() + logicalTop();
4416 void RenderBox::savePreviousBorderBoxSizeIfNeeded()
4418 // If m_rareData is already created, always save.
4420 LayoutSize paintInvalidationSize = previousPaintInvalidationRect().size();
4422 // Don't save old border box size if the paint rect is empty because we'll
4423 // full invalidate once the paint rect becomes non-empty.
4424 if (paintInvalidationSize.isEmpty())
4427 // Don't save old border box size if we can use size of the old paint rect
4428 // as the old border box size in the next invalidation.
4429 if (paintInvalidationSize == size())
4432 // We need the old border box size only when the box has background or box decorations.
4433 if (!style()->hasBackground() && !style()->hasBoxDecorations())
4437 ensureRareData().m_previousBorderBoxSize = size();
4440 LayoutSize RenderBox::computePreviousBorderBoxSize(const LayoutSize& previousBoundsSize) const
4442 // PreviousBorderBoxSize is only valid when there is background or box decorations.
4443 ASSERT(style()->hasBackground() || style()->hasBoxDecorations());
4445 if (m_rareData && m_rareData->m_previousBorderBoxSize.width() != -1)
4446 return m_rareData->m_previousBorderBoxSize;
4448 // We didn't save the old border box size because it was the same as the size of oldBounds.
4449 return previousBoundsSize;
4452 LayoutRect RenderBox::borderBoxAfterUpdatingLogicalWidth(const LayoutUnit& newLogicalTop)
4454 // FIXME: None of this is right for perpendicular writing-mode children.
4455 LayoutUnit oldLogicalWidth = logicalWidth();
4456 LayoutUnit oldMarginLeft = marginLeft();
4457 LayoutUnit oldMarginRight = marginRight();
4458 LayoutUnit oldLogicalTop = logicalTop();
4460 setLogicalTop(newLogicalTop);
4461 updateLogicalWidth();
4462 LayoutRect borderBox = borderBoxRect();
4464 setLogicalTop(oldLogicalTop);
4465 setLogicalWidth(oldLogicalWidth);
4466 setMarginLeft(oldMarginLeft);
4467 setMarginRight(oldMarginRight);
4472 } // namespace blink