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(true);
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(true);
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(true);
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();
217 updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle);
218 updateGridPositionAfterStyleChange(oldStyle);
221 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
223 const ShapeValue* shapeOutside = style.shapeOutside();
224 const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : RenderStyle::initialShapeOutside();
226 Length shapeMargin = style.shapeMargin();
227 Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
229 float shapeImageThreshold = style.shapeImageThreshold();
230 float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
232 // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
233 if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
237 ShapeOutsideInfo::removeInfo(*this);
239 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
241 if (shapeOutside || shapeOutside != oldShapeOutside)
242 markShapeOutsideDependentsForLayout();
245 void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle* oldStyle)
247 if (!oldStyle || !parent() || !parent()->isRenderGrid())
250 if (oldStyle->gridColumnStart() == style()->gridColumnStart()
251 && oldStyle->gridColumnEnd() == style()->gridColumnEnd()
252 && oldStyle->gridRowStart() == style()->gridRowStart()
253 && oldStyle->gridRowEnd() == style()->gridRowEnd()
254 && oldStyle->order() == style()->order()
255 && oldStyle->hasOutOfFlowPosition() == style()->hasOutOfFlowPosition())
258 // It should be possible to not dirty the grid in some cases (like moving an explicitly placed grid item).
259 // For now, it's more simple to just always recompute the grid.
260 toRenderGrid(parent())->dirtyGrid();
263 void RenderBox::updateFromStyle()
265 RenderBoxModelObject::updateFromStyle();
267 RenderStyle* styleToUse = style();
268 bool isRootObject = isDocumentElement();
269 bool isViewObject = isRenderView();
271 // The root and the RenderView always paint their backgrounds/borders.
272 if (isRootObject || isViewObject)
273 setHasBoxDecorationBackground(true);
275 setFloating(!isOutOfFlowPositioned() && styleToUse->isFloating());
277 bool boxHasOverflowClip = false;
278 if (!styleToUse->isOverflowVisible() && isRenderBlock() && !isViewObject) {
279 // If overflow has been propagated to the viewport, it has no effect here.
280 if (node() != document().viewportDefiningElement())
281 boxHasOverflowClip = true;
284 if (boxHasOverflowClip != hasOverflowClip()) {
285 // FIXME: This shouldn't be required if we tracked the visual overflow
286 // generated by positioned children or self painting layers. crbug.com/345403
287 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling())
288 child->setShouldDoFullPaintInvalidationIfSelfPaintingLayer(true);
291 setHasOverflowClip(boxHasOverflowClip);
293 setHasTransform(styleToUse->hasTransformRelatedProperty());
294 setHasReflection(styleToUse->boxReflect());
297 void RenderBox::layout()
299 ASSERT(needsLayout());
301 RenderObject* child = slowFirstChild();
307 LayoutState state(*this, locationOffset());
309 child->layoutIfNeeded();
310 ASSERT(!child->needsLayout());
311 child = child->nextSibling();
313 invalidateBackgroundObscurationStatus();
317 // More IE extensions. clientWidth and clientHeight represent the interior of an object
318 // excluding border and scrollbar.
319 LayoutUnit RenderBox::clientWidth() const
321 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
324 LayoutUnit RenderBox::clientHeight() const
326 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
329 int RenderBox::pixelSnappedClientWidth() const
331 return snapSizeToPixel(clientWidth(), x() + clientLeft());
334 int RenderBox::pixelSnappedClientHeight() const
336 return snapSizeToPixel(clientHeight(), y() + clientTop());
339 int RenderBox::pixelSnappedOffsetWidth() const
341 return snapSizeToPixel(offsetWidth(), x() + clientLeft());
344 int RenderBox::pixelSnappedOffsetHeight() const
346 return snapSizeToPixel(offsetHeight(), y() + clientTop());
349 LayoutUnit RenderBox::scrollWidth() const
351 if (hasOverflowClip())
352 return layer()->scrollableArea()->scrollWidth();
353 // For objects with visible overflow, this matches IE.
354 // FIXME: Need to work right with writing modes.
355 if (style()->isLeftToRightDirection())
356 return std::max(clientWidth(), layoutOverflowRect().maxX() - borderLeft());
357 return clientWidth() - std::min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
360 LayoutUnit RenderBox::scrollHeight() const
362 if (hasOverflowClip())
363 return layer()->scrollableArea()->scrollHeight();
364 // For objects with visible overflow, this matches IE.
365 // FIXME: Need to work right with writing modes.
366 return std::max(clientHeight(), layoutOverflowRect().maxY() - borderTop());
369 LayoutUnit RenderBox::scrollLeft() const
371 return hasOverflowClip() ? layer()->scrollableArea()->scrollXOffset() : 0;
374 LayoutUnit RenderBox::scrollTop() const
376 return hasOverflowClip() ? layer()->scrollableArea()->scrollYOffset() : 0;
379 int RenderBox::pixelSnappedScrollWidth() const
381 return snapSizeToPixel(scrollWidth(), x() + clientLeft());
384 int RenderBox::pixelSnappedScrollHeight() const
386 if (hasOverflowClip())
387 return layer()->scrollableArea()->scrollHeight();
388 // For objects with visible overflow, this matches IE.
389 // FIXME: Need to work right with writing modes.
390 return snapSizeToPixel(scrollHeight(), y() + clientTop());
393 void RenderBox::setScrollLeft(LayoutUnit newLeft)
395 // This doesn't hit in any tests, but since the equivalent code in setScrollTop
396 // does, presumably this code does as well.
397 DisableCompositingQueryAsserts disabler;
399 if (hasOverflowClip())
400 layer()->scrollableArea()->scrollToXOffset(newLeft, ScrollOffsetClamped);
403 void RenderBox::setScrollTop(LayoutUnit newTop)
405 // Hits in compositing/overflow/do-not-assert-on-invisible-composited-layers.html
406 DisableCompositingQueryAsserts disabler;
408 if (hasOverflowClip())
409 layer()->scrollableArea()->scrollToYOffset(newTop, ScrollOffsetClamped);
412 void RenderBox::scrollToOffset(const IntSize& offset)
414 ASSERT(hasOverflowClip());
416 // This doesn't hit in any tests, but since the equivalent code in setScrollTop
417 // does, presumably this code does as well.
418 DisableCompositingQueryAsserts disabler;
419 layer()->scrollableArea()->scrollToOffset(offset, ScrollOffsetClamped);
422 static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
424 // If scrollbars aren't explicitly forbidden, permit scrolling.
425 if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
428 // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
429 if (frameView->wasScrolledByUser())
432 // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
433 // like navigation to an anchor.
434 Page* page = frameView->frame().page();
437 return !page->autoscrollController().autoscrollInProgress();
440 void RenderBox::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
442 // Presumably the same issue as in setScrollTop. See crbug.com/343132.
443 DisableCompositingQueryAsserts disabler;
445 RenderBox* parentBox = 0;
446 LayoutRect newRect = rect;
448 bool restrictedByLineClamp = false;
450 parentBox = parent()->enclosingBox();
451 restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
454 if (hasOverflowClip() && !restrictedByLineClamp) {
455 // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
456 // This will prevent us from revealing text hidden by the slider in Safari RSS.
457 newRect = layer()->scrollableArea()->exposeRect(rect, alignX, alignY);
458 } else if (!parentBox && canBeProgramaticallyScrolled()) {
459 if (FrameView* frameView = this->frameView()) {
460 HTMLFrameOwnerElement* ownerElement = document().ownerElement();
462 if (ownerElement && ownerElement->renderer()) {
463 HTMLFrameElementBase* frameElementBase = isHTMLFrameElementBase(*ownerElement) ? toHTMLFrameElementBase(ownerElement) : 0;
464 if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
465 LayoutRect viewRect = frameView->visibleContentRect();
466 LayoutRect exposeRect = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
468 int xOffset = roundToInt(exposeRect.x());
469 int yOffset = roundToInt(exposeRect.y());
470 // Adjust offsets if they're outside of the allowable range.
471 xOffset = std::max(0, std::min(frameView->contentsWidth(), xOffset));
472 yOffset = std::max(0, std::min(frameView->contentsHeight(), yOffset));
474 frameView->setScrollPosition(IntPoint(xOffset, yOffset));
475 if (frameView->safeToPropagateScrollToParent()) {
476 parentBox = ownerElement->renderer()->enclosingBox();
477 // FIXME: This doesn't correctly convert the rect to
478 // absolute coordinates in the parent.
479 newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
480 newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
486 if (frame()->settings()->pinchVirtualViewportEnabled()) {
487 PinchViewport& pinchViewport = frame()->page()->frameHost().pinchViewport();
488 LayoutRect r = ScrollAlignment::getRectToExpose(LayoutRect(pinchViewport.visibleRectInDocument()), rect, alignX, alignY);
489 pinchViewport.scrollIntoView(r);
491 LayoutRect viewRect = frameView->visibleContentRect();
492 LayoutRect r = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
493 frameView->setScrollPosition(roundedIntPoint(r.location()));
499 if (frame()->page()->autoscrollController().autoscrollInProgress())
500 parentBox = enclosingScrollableBox();
503 parentBox->scrollRectToVisible(newRect, alignX, alignY);
506 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
508 rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
511 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
513 quads.append(localToAbsoluteQuad(FloatRect(0, 0, width().toFloat(), height().toFloat()), 0 /* mode */, wasFixed));
516 void RenderBox::updateLayerTransformAfterLayout()
518 // Transform-origin depends on box size, so we need to update the layer transform after layout.
520 layer()->updateTransformationMatrix();
523 LayoutUnit RenderBox::constrainLogicalWidthByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb) const
525 RenderStyle* styleToUse = style();
526 if (!styleToUse->logicalMaxWidth().isMaxSizeNone())
527 logicalWidth = std::min(logicalWidth, computeLogicalWidthUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb));
528 return std::max(logicalWidth, computeLogicalWidthUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb));
531 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
533 RenderStyle* styleToUse = style();
534 if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
535 LayoutUnit maxH = computeLogicalHeightUsing(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
537 logicalHeight = std::min(logicalHeight, maxH);
539 return std::max(logicalHeight, computeLogicalHeightUsing(styleToUse->logicalMinHeight(), intrinsicContentHeight));
542 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
544 RenderStyle* styleToUse = style();
545 if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
546 LayoutUnit maxH = computeContentLogicalHeight(styleToUse->logicalMaxHeight(), intrinsicContentHeight);
548 logicalHeight = std::min(logicalHeight, maxH);
550 return std::max(logicalHeight, computeContentLogicalHeight(styleToUse->logicalMinHeight(), intrinsicContentHeight));
553 IntRect RenderBox::absoluteContentBox() const
555 // This is wrong with transforms and flipped writing modes.
556 IntRect rect = pixelSnappedIntRect(contentBoxRect());
557 FloatPoint absPos = localToAbsolute();
558 rect.move(absPos.x(), absPos.y());
562 FloatQuad RenderBox::absoluteContentQuad() const
564 LayoutRect rect = contentBoxRect();
565 return localToAbsoluteQuad(FloatRect(rect));
568 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*) const
570 if (!size().isEmpty())
571 rects.append(LayoutRect(additionalOffset, size()));
574 bool RenderBox::canResize() const
576 // We need a special case for <iframe> because they never have
577 // hasOverflowClip(). However, they do "implicitly" clip their contents, so
578 // we want to allow resizing them also.
579 return (hasOverflowClip() || isRenderIFrame()) && style()->resize() != RESIZE_NONE;
582 void RenderBox::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
584 LayoutPoint adjustedLayerOffset = layerOffset + locationOffset();
585 RenderBoxModelObject::addLayerHitTestRects(layerRects, currentLayer, adjustedLayerOffset, containerRect);
588 void RenderBox::computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint& layerOffset) const
590 if (!size().isEmpty())
591 rects.append(LayoutRect(layerOffset, size()));
594 int RenderBox::reflectionOffset() const
596 if (!style()->boxReflect())
598 if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
599 return valueForLength(style()->boxReflect()->offset(), borderBoxRect().width());
600 return valueForLength(style()->boxReflect()->offset(), borderBoxRect().height());
603 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
605 if (!style()->boxReflect())
608 LayoutRect box = borderBoxRect();
609 LayoutRect result = r;
610 switch (style()->boxReflect()->direction()) {
611 case ReflectionBelow:
612 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
614 case ReflectionAbove:
615 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
618 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
620 case ReflectionRight:
621 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
627 int RenderBox::verticalScrollbarWidth() const
629 if (!hasOverflowClip() || style()->overflowY() == OOVERLAY)
632 return layer()->scrollableArea()->verticalScrollbarWidth();
635 int RenderBox::horizontalScrollbarHeight() const
637 if (!hasOverflowClip() || style()->overflowX() == OOVERLAY)
640 return layer()->scrollableArea()->horizontalScrollbarHeight();
643 int RenderBox::instrinsicScrollbarLogicalWidth() const
645 if (!hasOverflowClip())
648 if (isHorizontalWritingMode() && style()->overflowY() == OSCROLL) {
649 ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasVerticalScrollbar());
650 return verticalScrollbarWidth();
653 if (!isHorizontalWritingMode() && style()->overflowX() == OSCROLL) {
654 ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasHorizontalScrollbar());
655 return horizontalScrollbarHeight();
661 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float delta)
663 // Presumably the same issue as in setScrollTop. See crbug.com/343132.
664 DisableCompositingQueryAsserts disabler;
666 // Logical scroll is a higher level concept, all directions by here must be physical
667 ASSERT(!isLogical(direction));
669 if (!layer() || !layer()->scrollableArea())
672 return layer()->scrollableArea()->scroll(direction, granularity, delta);
675 bool RenderBox::canBeScrolledAndHasScrollableArea() const
677 return canBeProgramaticallyScrolled() && (pixelSnappedScrollHeight() != pixelSnappedClientHeight() || pixelSnappedScrollWidth() != pixelSnappedClientWidth());
680 bool RenderBox::canBeProgramaticallyScrolled() const
682 Node* node = this->node();
683 if (node && node->isDocumentNode())
686 if (!hasOverflowClip())
689 bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
690 if (scrollsOverflow() && hasScrollableOverflow)
693 return node && node->hasEditableStyle();
696 bool RenderBox::usesCompositedScrolling() const
698 return hasOverflowClip() && hasLayer() && layer()->scrollableArea()->usesCompositedScrolling();
701 void RenderBox::autoscroll(const IntPoint& position)
703 LocalFrame* frame = this->frame();
707 FrameView* frameView = frame->view();
711 IntPoint currentDocumentPosition = frameView->windowToContents(position);
712 scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
715 bool RenderBox::autoscrollInProgress() const
717 return frame() && frame()->page() && frame()->page()->autoscrollController().autoscrollInProgress(this);
720 // There are two kinds of renderer that can autoscroll.
721 bool RenderBox::canAutoscroll() const
723 if (node() && node()->isDocumentNode())
724 return view()->frameView()->isScrollable();
726 // Check for a box that can be scrolled in its own right.
727 return canBeScrolledAndHasScrollableArea();
730 // If specified point is in border belt, returned offset denotes direction of
732 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
737 FrameView* frameView = frame()->view();
741 IntRect box(absoluteBoundingBoxRect());
742 box.move(view()->frameView()->scrollOffset());
743 IntRect windowBox = view()->frameView()->contentsToWindow(box);
745 IntPoint windowAutoscrollPoint = windowPoint;
747 if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
748 windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
749 else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
750 windowAutoscrollPoint.move(autoscrollBeltSize, 0);
752 if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
753 windowAutoscrollPoint.move(0, -autoscrollBeltSize);
754 else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
755 windowAutoscrollPoint.move(0, autoscrollBeltSize);
757 return windowAutoscrollPoint - windowPoint;
760 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
762 while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
763 if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document().ownerElement())
764 renderer = renderer->document().ownerElement()->renderer();
766 renderer = renderer->parent();
769 return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
772 static inline int adjustedScrollDelta(int beginningDelta)
774 // This implemention matches Firefox's.
775 // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
776 const int speedReducer = 12;
778 int adjustedDelta = beginningDelta / speedReducer;
779 if (adjustedDelta > 1)
780 adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
781 else if (adjustedDelta < -1)
782 adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
784 return adjustedDelta;
787 static inline IntSize adjustedScrollDelta(const IntSize& delta)
789 return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
792 void RenderBox::panScroll(const IntPoint& sourcePoint)
794 LocalFrame* frame = this->frame();
798 IntPoint lastKnownMousePosition = frame->eventHandler().lastKnownMousePosition();
800 // 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
801 static IntPoint previousMousePosition;
802 if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
803 lastKnownMousePosition = previousMousePosition;
805 previousMousePosition = lastKnownMousePosition;
807 IntSize delta = lastKnownMousePosition - sourcePoint;
809 if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
811 if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
814 scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
817 void RenderBox::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp)
822 bool restrictedByLineClamp = false;
824 restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
826 if (hasOverflowClip() && !restrictedByLineClamp) {
827 IntSize newScrollOffset = layer()->scrollableArea()->adjustedScrollOffset() + delta;
828 layer()->scrollableArea()->scrollToOffset(newScrollOffset, clamp);
830 // If this layer can't do the scroll we ask the next layer up that can scroll to try
831 IntSize remainingScrollOffset = newScrollOffset - layer()->scrollableArea()->adjustedScrollOffset();
832 if (!remainingScrollOffset.isZero() && parent()) {
833 if (RenderBox* scrollableBox = enclosingScrollableBox())
834 scrollableBox->scrollByRecursively(remainingScrollOffset, clamp);
836 LocalFrame* frame = this->frame();
837 if (frame && frame->page())
838 frame->page()->autoscrollController().updateAutoscrollRenderer();
840 } else if (view()->frameView()) {
841 // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
842 // have an overflow clip. Which means that it is a document node that can be scrolled.
843 view()->frameView()->scrollBy(delta);
845 // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement?
846 // https://bugs.webkit.org/show_bug.cgi?id=28237
850 bool RenderBox::needsPreferredWidthsRecalculation() const
852 return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent();
855 IntSize RenderBox::scrolledContentOffset() const
857 ASSERT(hasOverflowClip());
859 return layer()->scrollableArea()->scrollOffset();
862 void RenderBox::applyCachedClipAndScrollOffsetForPaintInvalidation(LayoutRect& paintRect) const
865 ASSERT(hasOverflowClip());
867 flipForWritingMode(paintRect);
868 paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
870 // Do not clip scroll layer contents because the compositor expects the whole layer
871 // to be always invalidated in-time.
872 if (usesCompositedScrolling()) {
873 flipForWritingMode(paintRect);
877 // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
878 // layer's size instead. Even if the layer's size is wrong, the layer itself will issue paint invalidations
879 // anyway if its size does change.
880 LayoutRect clipRect(LayoutPoint(), layer()->size());
881 paintRect = intersection(paintRect, clipRect);
882 flipForWritingMode(paintRect);
885 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
887 minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
888 maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
891 LayoutUnit RenderBox::minPreferredLogicalWidth() const
893 if (preferredLogicalWidthsDirty()) {
895 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
897 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
900 return m_minPreferredLogicalWidth;
903 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
905 if (preferredLogicalWidthsDirty()) {
907 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox&>(*this));
909 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
912 return m_maxPreferredLogicalWidth;
915 bool RenderBox::hasOverrideHeight() const
917 return m_rareData && m_rareData->m_overrideLogicalContentHeight != -1;
920 bool RenderBox::hasOverrideWidth() const
922 return m_rareData && m_rareData->m_overrideLogicalContentWidth != -1;
925 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
928 ensureRareData().m_overrideLogicalContentHeight = height;
931 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
934 ensureRareData().m_overrideLogicalContentWidth = width;
937 void RenderBox::clearOverrideLogicalContentHeight()
940 m_rareData->m_overrideLogicalContentHeight = -1;
943 void RenderBox::clearOverrideLogicalContentWidth()
946 m_rareData->m_overrideLogicalContentWidth = -1;
949 void RenderBox::clearOverrideSize()
951 clearOverrideLogicalContentHeight();
952 clearOverrideLogicalContentWidth();
955 LayoutUnit RenderBox::overrideLogicalContentWidth() const
957 ASSERT(hasOverrideWidth());
958 return m_rareData->m_overrideLogicalContentWidth;
961 LayoutUnit RenderBox::overrideLogicalContentHeight() const
963 ASSERT(hasOverrideHeight());
964 return m_rareData->m_overrideLogicalContentHeight;
967 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
969 ASSERT(hasOverrideContainingBlockLogicalWidth());
970 return gOverrideContainingBlockLogicalWidthMap->get(this);
973 LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
975 ASSERT(hasOverrideContainingBlockLogicalHeight());
976 return gOverrideContainingBlockLogicalHeightMap->get(this);
979 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
981 return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
984 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
986 return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
989 void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
991 if (!gOverrideContainingBlockLogicalWidthMap)
992 gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
993 gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
996 void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
998 if (!gOverrideContainingBlockLogicalHeightMap)
999 gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
1000 gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1003 void RenderBox::clearContainingBlockOverrideSize()
1005 if (gOverrideContainingBlockLogicalWidthMap)
1006 gOverrideContainingBlockLogicalWidthMap->remove(this);
1007 clearOverrideContainingBlockContentLogicalHeight();
1010 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1012 if (gOverrideContainingBlockLogicalHeightMap)
1013 gOverrideContainingBlockLogicalHeightMap->remove(this);
1016 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1018 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1019 if (style()->boxSizing() == CONTENT_BOX)
1020 return width + bordersPlusPadding;
1021 return std::max(width, bordersPlusPadding);
1024 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1026 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1027 if (style()->boxSizing() == CONTENT_BOX)
1028 return height + bordersPlusPadding;
1029 return std::max(height, bordersPlusPadding);
1032 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1034 if (style()->boxSizing() == BORDER_BOX)
1035 width -= borderAndPaddingLogicalWidth();
1036 return std::max<LayoutUnit>(0, width);
1039 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1041 if (style()->boxSizing() == BORDER_BOX)
1042 height -= borderAndPaddingLogicalHeight();
1043 return std::max<LayoutUnit>(0, height);
1047 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1049 LayoutPoint adjustedLocation = accumulatedOffset + location();
1051 // Check kids first.
1052 for (RenderObject* child = slowLastChild(); child; child = child->previousSibling()) {
1053 if ((!child->hasLayer() || !toRenderLayerModelObject(child)->layer()->isSelfPaintingLayer()) && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1054 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1059 // Check our bounds next. For this purpose always assume that we can only be hit in the
1060 // foreground phase (which is true for replaced elements like images).
1061 LayoutRect boundsRect = borderBoxRect();
1062 boundsRect.moveBy(adjustedLocation);
1063 if (visibleToHitTestRequest(request) && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1064 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1065 if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
1072 void RenderBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1074 BoxPainter(*this).paint(paintInfo, paintOffset);
1078 void RenderBox::paintBoxDecorationBackground(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1080 BoxPainter(*this).paintBoxDecorationBackground(paintInfo, paintOffset);
1084 bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent)
1086 ASSERT(hasBackground());
1087 LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect());
1089 Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
1090 if (backgroundColor.alpha()) {
1091 paintedExtent = backgroundRect;
1095 if (!style()->backgroundLayers().image() || style()->backgroundLayers().next()) {
1096 paintedExtent = backgroundRect;
1100 BackgroundImageGeometry geometry;
1101 BoxPainter::calculateBackgroundImageGeometry(*this, 0, style()->backgroundLayers(), backgroundRect, geometry);
1102 if (geometry.hasNonLocalGeometry())
1104 paintedExtent = geometry.destRect();
1108 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1110 if (isBody() && skipBodyBackground(this))
1113 Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
1114 if (backgroundColor.hasAlpha())
1117 // If the element has appearance, it might be painted by theme.
1118 // We cannot be sure if theme paints the background opaque.
1119 // In this case it is safe to not assume opaqueness.
1120 // FIXME: May be ask theme if it paints opaque.
1121 if (style()->hasAppearance())
1123 // FIXME: Check the opaqueness of background images.
1125 // FIXME: Use rounded rect if border radius is present.
1126 if (style()->hasBorderRadius())
1128 // FIXME: The background color clip is defined by the last layer.
1129 if (style()->backgroundLayers().next())
1131 LayoutRect backgroundRect;
1132 switch (style()->backgroundClip()) {
1134 backgroundRect = borderBoxRect();
1136 case PaddingFillBox:
1137 backgroundRect = paddingBoxRect();
1139 case ContentFillBox:
1140 backgroundRect = contentBoxRect();
1145 return backgroundRect.contains(localRect);
1148 static bool isCandidateForOpaquenessTest(RenderBox* childBox)
1150 RenderStyle* childStyle = childBox->style();
1151 if (childStyle->position() != StaticPosition && childBox->containingBlock() != childBox->parent())
1153 if (childStyle->visibility() != VISIBLE || childStyle->shapeOutside())
1155 if (!childBox->width() || !childBox->height())
1157 if (RenderLayer* childLayer = childBox->layer()) {
1158 // FIXME: perhaps this could be less conservative?
1159 if (childLayer->compositingState() != NotComposited)
1161 // FIXME: Deal with z-index.
1162 if (!childStyle->hasAutoZIndex())
1164 if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1166 if (childBox->hasOverflowClip() && childStyle->hasBorderRadius())
1172 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1174 if (!maxDepthToTest)
1176 for (RenderObject* child = slowFirstChild(); child; child = child->nextSibling()) {
1177 if (!child->isBox())
1179 RenderBox* childBox = toRenderBox(child);
1180 if (!isCandidateForOpaquenessTest(childBox))
1182 LayoutPoint childLocation = childBox->location();
1183 if (childBox->isRelPositioned())
1184 childLocation.move(childBox->relativePositionOffset());
1185 LayoutRect childLocalRect = localRect;
1186 childLocalRect.moveBy(-childLocation);
1187 if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1188 // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1189 if (childBox->style()->position() == StaticPosition)
1193 if (childLocalRect.maxY() > childBox->height() || childLocalRect.maxX() > childBox->width())
1195 if (childBox->backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1197 if (childBox->foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1203 bool RenderBox::computeBackgroundIsKnownToBeObscured()
1205 // Test to see if the children trivially obscure the background.
1206 // FIXME: This test can be much more comprehensive.
1207 if (!hasBackground())
1209 // Table and root background painting is special.
1210 if (isTable() || isDocumentElement())
1212 // FIXME: box-shadow is painted while background painting.
1213 if (style()->boxShadow())
1215 LayoutRect backgroundRect;
1216 if (!getBackgroundPaintedExtent(backgroundRect))
1218 return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1221 bool RenderBox::backgroundHasOpaqueTopLayer() const
1223 const FillLayer& fillLayer = style()->backgroundLayers();
1224 if (fillLayer.clip() != BorderFillBox)
1227 // Clipped with local scrolling
1228 if (hasOverflowClip() && fillLayer.attachment() == LocalBackgroundAttachment)
1231 if (fillLayer.hasOpaqueImage(this) && fillLayer.hasRepeatXY() && fillLayer.image()->canRender(*this, style()->effectiveZoom()))
1234 // If there is only one layer and no image, check whether the background color is opaque
1235 if (!fillLayer.next() && !fillLayer.hasImage()) {
1236 Color bgColor = resolveColor(CSSPropertyBackgroundColor);
1237 if (bgColor.alpha() == 255)
1244 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1246 BoxPainter(*this).paintMask(paintInfo, paintOffset);
1249 void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1251 BoxPainter(*this).paintClippingMask(paintInfo, paintOffset);
1254 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1259 AllowPaintInvalidationScope scoper(frameView());
1261 if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1262 (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1263 setShouldDoFullPaintInvalidation(true);
1267 ShapeValue* shapeOutsideValue = style()->shapeOutside();
1268 if (!frameView()->isInPerformLayout() && isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image) {
1269 ShapeOutsideInfo::ensureInfo(*this).markShapeAsDirty();
1270 markShapeOutsideDependentsForLayout();
1273 if (!paintInvalidationLayerRectsForImage(image, style()->backgroundLayers(), true))
1274 paintInvalidationLayerRectsForImage(image, style()->maskLayers(), false);
1277 bool RenderBox::paintInvalidationLayerRectsForImage(WrappedImagePtr image, const FillLayer& layers, bool drawingBackground)
1279 for (const FillLayer* curLayer = &layers; curLayer; curLayer = curLayer->next()) {
1280 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(*this, style()->effectiveZoom())) {
1281 setShouldDoFullPaintInvalidation(true);
1288 InvalidationReason RenderBox::invalidatePaintIfNeeded(const PaintInvalidationState& paintInvalidationState, const RenderLayerModelObject& newPaintInvalidationContainer)
1290 // If we are set to do a full paint invalidation that means the RenderView will be
1291 // issue paint invalidations. We can then skip issuing of paint invalidations for the child
1292 // renderers as they'll be covered by the RenderView.
1293 if (!view()->doingFullPaintInvalidation()) {
1294 if ((onlyNeededPositionedMovementLayout() && compositingState() != PaintsIntoOwnBacking)
1295 || (shouldDoFullPaintInvalidationIfSelfPaintingLayer()
1297 && layer()->isSelfPaintingLayer())) {
1298 setShouldDoFullPaintInvalidation(true, MarkOnlyThis);
1302 InvalidationReason reason = RenderBoxModelObject::invalidatePaintIfNeeded(paintInvalidationState, newPaintInvalidationContainer);
1304 if (!view()->doingFullPaintInvalidation()) {
1305 if (reason == InvalidationNone || reason == InvalidationIncremental)
1306 invalidatePaintForOverflowIfNeeded();
1308 // Issue paint invalidations for any scrollbars if there is a scrollable area for this renderer.
1309 if (ScrollableArea* area = scrollableArea()) {
1310 if (area->hasVerticalBarDamage())
1311 invalidatePaintRectangle(area->verticalBarDamage());
1312 if (area->hasHorizontalBarDamage())
1313 invalidatePaintRectangle(area->horizontalBarDamage());
1317 // This is for the next invalidatePaintIfNeeded so must be at the end.
1318 savePreviousBorderBoxSizeIfNeeded();
1322 void RenderBox::clearPaintInvalidationState(const PaintInvalidationState& paintInvalidationState)
1324 RenderBoxModelObject::clearPaintInvalidationState(paintInvalidationState);
1326 if (ScrollableArea* area = scrollableArea())
1327 area->resetScrollbarDamage();
1331 bool RenderBox::paintInvalidationStateIsDirty() const
1333 if (ScrollableArea* area = scrollableArea()) {
1334 if (area->hasVerticalBarDamage() || area->hasHorizontalBarDamage())
1337 return RenderBoxModelObject::paintInvalidationStateIsDirty();
1341 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset, ContentsClipBehavior contentsClipBehavior)
1343 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1346 bool isControlClip = hasControlClip();
1347 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1349 if (!isControlClip && !isOverflowClip)
1352 LayoutRect clipRect = isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset);
1353 RoundedRect clipRoundedRect(0, 0, 0, 0);
1354 bool hasBorderRadius = style()->hasBorderRadius();
1355 if (hasBorderRadius)
1356 clipRoundedRect = style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size()));
1358 if (contentsClipBehavior == SkipContentsClipIfPossible) {
1359 LayoutRect contentsVisualOverflow = contentsVisualOverflowRect();
1360 if (contentsVisualOverflow.isEmpty())
1363 LayoutRect conservativeClipRect = clipRect;
1364 if (hasBorderRadius)
1365 conservativeClipRect.intersect(clipRoundedRect.radiusCenterRect());
1366 conservativeClipRect.moveBy(-accumulatedOffset);
1368 conservativeClipRect.move(scrolledContentOffset());
1369 if (conservativeClipRect.contains(contentsVisualOverflow))
1373 if (paintInfo.phase == PaintPhaseOutline)
1374 paintInfo.phase = PaintPhaseChildOutlines;
1375 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1376 paintInfo.phase = PaintPhaseBlockBackground;
1377 paintObject(paintInfo, accumulatedOffset);
1378 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1380 paintInfo.context->save();
1381 if (hasBorderRadius)
1382 paintInfo.context->clipRoundedRect(clipRoundedRect);
1383 paintInfo.context->clip(pixelSnappedIntRect(clipRect));
1387 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1389 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1391 paintInfo.context->restore();
1392 if (originalPhase == PaintPhaseOutline) {
1393 paintInfo.phase = PaintPhaseSelfOutline;
1394 paintObject(paintInfo, accumulatedOffset);
1395 paintInfo.phase = originalPhase;
1396 } else if (originalPhase == PaintPhaseChildBlockBackground)
1397 paintInfo.phase = originalPhase;
1400 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy relevancy)
1402 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1404 LayoutRect clipRect = borderBoxRect();
1405 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1406 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1408 if (!hasOverflowClip())
1411 // Subtract out scrollbars if we have them.
1412 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1413 clipRect.move(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), 0);
1414 clipRect.contract(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), layer()->scrollableArea()->horizontalScrollbarHeight(relevancy));
1419 LayoutRect RenderBox::clipRect(const LayoutPoint& location)
1421 LayoutRect borderBoxRect = this->borderBoxRect();
1422 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1424 if (!style()->clipLeft().isAuto()) {
1425 LayoutUnit c = valueForLength(style()->clipLeft(), borderBoxRect.width());
1426 clipRect.move(c, 0);
1427 clipRect.contract(c, 0);
1430 if (!style()->clipRight().isAuto())
1431 clipRect.contract(width() - valueForLength(style()->clipRight(), width()), 0);
1433 if (!style()->clipTop().isAuto()) {
1434 LayoutUnit c = valueForLength(style()->clipTop(), borderBoxRect.height());
1435 clipRect.move(0, c);
1436 clipRect.contract(0, c);
1439 if (!style()->clipBottom().isAuto())
1440 clipRect.contract(0, height() - valueForLength(style()->clipBottom(), height()));
1445 static LayoutUnit portionOfMarginNotConsumedByFloat(LayoutUnit childMargin, LayoutUnit contentSide, LayoutUnit offset)
1447 if (childMargin <= 0)
1449 LayoutUnit contentSideWithMargin = contentSide + childMargin;
1450 if (offset > contentSideWithMargin)
1452 return offset - contentSide;
1455 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb) const
1457 LayoutUnit logicalTopPosition = logicalTop();
1458 LayoutUnit startOffsetForContent = cb->startOffsetForContent();
1459 LayoutUnit endOffsetForContent = cb->endOffsetForContent();
1460 LayoutUnit startOffsetForLine = cb->startOffsetForLine(logicalTopPosition, false);
1461 LayoutUnit endOffsetForLine = cb->endOffsetForLine(logicalTopPosition, false);
1463 // If there aren't any floats constraining us then allow the margins to shrink/expand the width as much as they want.
1464 if (startOffsetForContent == startOffsetForLine && endOffsetForContent == endOffsetForLine)
1465 return cb->availableLogicalWidthForLine(logicalTopPosition, false) - childMarginStart - childMarginEnd;
1467 LayoutUnit width = cb->availableLogicalWidthForLine(logicalTopPosition, false) - std::max<LayoutUnit>(0, childMarginStart) - std::max<LayoutUnit>(0, childMarginEnd);
1468 // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1469 // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1470 // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1471 // 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
1472 // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1473 width += portionOfMarginNotConsumedByFloat(childMarginStart, startOffsetForContent, startOffsetForLine);
1474 width += portionOfMarginNotConsumedByFloat(childMarginEnd, endOffsetForContent, endOffsetForLine);
1478 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1480 if (hasOverrideContainingBlockLogicalWidth())
1481 return overrideContainingBlockContentLogicalWidth();
1483 RenderBlock* cb = containingBlock();
1484 return cb->availableLogicalWidth();
1487 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1489 if (hasOverrideContainingBlockLogicalHeight())
1490 return overrideContainingBlockContentLogicalHeight();
1492 RenderBlock* cb = containingBlock();
1493 return cb->availableLogicalHeight(heightType);
1496 LayoutUnit RenderBox::containingBlockAvailableLineWidth() const
1498 RenderBlock* cb = containingBlock();
1499 if (cb->isRenderBlockFlow())
1500 return toRenderBlockFlow(cb)->availableLogicalWidthForLine(logicalTop(), false, availableLogicalHeight(IncludeMarginBorderPadding));
1504 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1506 if (hasOverrideContainingBlockLogicalHeight())
1507 return overrideContainingBlockContentLogicalHeight();
1509 RenderBlock* cb = containingBlock();
1510 if (cb->hasOverrideHeight())
1511 return cb->overrideLogicalContentHeight();
1513 RenderStyle* containingBlockStyle = cb->style();
1514 Length logicalHeightLength = containingBlockStyle->logicalHeight();
1516 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1517 if (!logicalHeightLength.isFixed()) {
1518 LayoutUnit fillFallbackExtent = containingBlockStyle->isHorizontalWritingMode()
1519 ? view()->frameView()->unscaledVisibleContentSize().height()
1520 : view()->frameView()->unscaledVisibleContentSize().width();
1521 LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1522 return std::min(fillAvailableExtent, fillFallbackExtent);
1525 // Use the content box logical height as specified by the style.
1526 return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
1529 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
1531 if (paintInvalidationContainer == this)
1534 if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer)) {
1535 LayoutSize offset = paintInvalidationState->paintOffset() + locationOffset();
1536 if (style()->hasInFlowPosition() && layer())
1537 offset += layer()->offsetForInFlowPosition();
1538 transformState.move(offset);
1542 bool containerSkipped;
1543 RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
1547 bool isFixedPos = style()->position() == FixedPosition;
1548 bool hasTransform = hasLayer() && layer()->transform();
1549 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1550 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1551 if (hasTransform && !isFixedPos)
1553 else if (isFixedPos)
1557 *wasFixed = mode & IsFixed;
1559 LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1561 bool preserve3D = mode & UseTransforms && (o->style()->preserves3D() || style()->preserves3D());
1562 if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
1563 TransformationMatrix t;
1564 getTransformFromContainer(o, containerOffset, t);
1565 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1567 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1569 if (containerSkipped) {
1570 // There can't be a transform between paintInvalidationContainer and o, because transforms create containers, so it should be safe
1571 // to just subtract the delta between the paintInvalidationContainer and o.
1572 LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
1573 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1577 mode &= ~ApplyContainerFlip;
1579 o->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed);
1582 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1584 bool isFixedPos = style()->position() == FixedPosition;
1585 bool hasTransform = hasLayer() && layer()->transform();
1586 if (hasTransform && !isFixedPos) {
1587 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1588 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1590 } else if (isFixedPos)
1593 RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
1596 LayoutSize RenderBox::offsetFromContainer(const RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
1598 ASSERT(o == container());
1601 if (isRelPositioned())
1602 offset += offsetForInFlowPosition();
1604 if (!isInline() || isReplaced()) {
1605 if (!style()->hasOutOfFlowPosition() && o->hasColumns()) {
1606 const RenderBlock* block = toRenderBlock(o);
1607 LayoutRect columnRect(frameRect());
1608 block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1609 offset += toSize(columnRect.location());
1610 LayoutPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
1611 offset = toLayoutSize(block->flipForWritingModeIncludingColumns(toLayoutPoint(offset)));
1612 offset += o->columnOffset(columnPoint);
1613 offset = block->flipForWritingMode(offset);
1615 if (offsetDependsOnPoint)
1616 *offsetDependsOnPoint = true;
1618 offset += topLeftLocationOffset();
1619 if (o->isRenderFlowThread()) {
1620 // So far the point has been in flow thread coordinates (i.e. as if everything in
1621 // the fragmentation context lived in one tall single column). Convert it to a
1622 // visual point now.
1623 LayoutPoint pointInContainer = point + offset;
1624 offset += o->columnOffset(pointInContainer);
1625 if (offsetDependsOnPoint)
1626 *offsetDependsOnPoint = true;
1631 if (o->hasOverflowClip())
1632 offset -= toRenderBox(o)->scrolledContentOffset();
1634 if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1635 offset += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
1640 InlineBox* RenderBox::createInlineBox()
1642 return new InlineBox(*this);
1645 void RenderBox::dirtyLineBoxes(bool fullLayout)
1647 if (inlineBoxWrapper()) {
1649 inlineBoxWrapper()->destroy();
1651 m_rareData->m_inlineBoxWrapper = 0;
1653 inlineBoxWrapper()->dirtyLineBoxes();
1658 void RenderBox::positionLineBox(InlineBox* box)
1660 if (isOutOfFlowPositioned()) {
1661 // Cache the x position only if we were an INLINE type originally.
1662 bool wasInline = style()->isOriginalDisplayInlineType();
1664 // The value is cached in the xPos of the box. We only need this value if
1665 // our object was inline originally, since otherwise it would have ended up underneath
1667 RootInlineBox& root = box->root();
1668 root.block().setStaticInlinePositionForChild(this, LayoutUnit::fromFloatRound(box->logicalLeft()));
1669 if (style()->hasStaticInlinePosition(box->isHorizontal()))
1670 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1672 // Our object was a block originally, so we make our normal flow position be
1673 // just below the line box (as though all the inlines that came before us got
1674 // wrapped in an anonymous block, which is what would have happened had we been
1675 // in flow). This value was cached in the y() of the box.
1676 layer()->setStaticBlockPosition(box->logicalTop());
1677 if (style()->hasStaticBlockPosition(box->isHorizontal()))
1678 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1681 if (container()->isRenderInline())
1682 moveWithEdgeOfInlineContainerIfNecessary(box->isHorizontal());
1685 box->remove(DontMarkLineBoxes);
1687 } else if (isReplaced()) {
1688 setLocation(roundedLayoutPoint(box->topLeft()));
1689 setInlineBoxWrapper(box);
1693 void RenderBox::moveWithEdgeOfInlineContainerIfNecessary(bool isHorizontal)
1695 ASSERT(isOutOfFlowPositioned() && container()->isRenderInline() && container()->isRelPositioned());
1696 // If this object is inside a relative positioned inline and its inline position is an explicit offset from the edge of its container
1697 // then it will need to move if its inline container has changed width. We do not track if the width has changed
1698 // 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
1699 // move to the new offset created by the new width.
1700 if (!normalChildNeedsLayout() && !style()->hasStaticInlinePosition(isHorizontal))
1701 setChildNeedsLayout(MarkOnlyThis);
1704 void RenderBox::deleteLineBoxWrapper()
1706 if (inlineBoxWrapper()) {
1707 if (!documentBeingDestroyed())
1708 inlineBoxWrapper()->remove();
1709 inlineBoxWrapper()->destroy();
1711 m_rareData->m_inlineBoxWrapper = 0;
1715 LayoutRect RenderBox::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
1717 if (style()->visibility() != VISIBLE) {
1718 RenderLayer* layer = enclosingLayer();
1719 layer->updateDescendantDependentFlags();
1720 if (layer->subtreeIsInvisible())
1721 return LayoutRect();
1724 LayoutRect r = visualOverflowRect();
1725 mapRectToPaintInvalidationBacking(paintInvalidationContainer, r, paintInvalidationState);
1729 void RenderBox::mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect& rect, const PaintInvalidationState* paintInvalidationState) const
1731 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1732 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1733 // offset corner for the enclosing container). This allows for a fully RL or BT document to issue paint invalidations
1734 // properly even during layout, since the rect remains flipped all the way until the end.
1736 // RenderView::computeRectForPaintInvalidation then converts the rect to physical coordinates. We also convert to
1737 // physical when we hit a paintInvalidationContainer boundary. Therefore the final rect returned is always in the
1738 // physical coordinate space of the paintInvalidationContainer.
1739 RenderStyle* styleToUse = style();
1741 EPosition position = styleToUse->position();
1743 // We need to inflate the paint invalidation rect before we use paintInvalidationState,
1744 // else we would forget to inflate it for the current renderer. FIXME: If these were
1745 // included into the visual overflow for repaint, we wouldn't have this issue.
1746 inflatePaintInvalidationRectForReflectionAndFilter(rect);
1748 if (paintInvalidationState && paintInvalidationState->canMapToContainer(paintInvalidationContainer) && position != FixedPosition) {
1749 if (layer() && layer()->transform())
1750 rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
1752 // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
1753 if (styleToUse->hasInFlowPosition() && layer())
1754 rect.move(layer()->offsetForInFlowPosition());
1756 rect.moveBy(location());
1757 rect.move(paintInvalidationState->paintOffset());
1758 if (paintInvalidationState->isClipped())
1759 rect.intersect(paintInvalidationState->clipRect());
1763 if (paintInvalidationContainer == this) {
1764 if (paintInvalidationContainer->style()->isFlippedBlocksWritingMode())
1765 flipForWritingMode(rect);
1769 bool containerSkipped;
1770 RenderObject* o = container(paintInvalidationContainer, &containerSkipped);
1774 if (isWritingModeRoot())
1775 flipForWritingMode(rect);
1777 LayoutPoint topLeft = rect.location();
1778 topLeft.move(locationOffset());
1780 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
1781 // in the parent's coordinate space that encloses us.
1782 if (hasLayer() && layer()->transform()) {
1783 rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
1784 topLeft = rect.location();
1785 topLeft.move(locationOffset());
1788 if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline()) {
1789 topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(*this);
1790 } else if (styleToUse->hasInFlowPosition() && layer()) {
1791 // Apply the relative position offset when invalidating a rectangle. The layer
1792 // is translated, but the render box isn't, so we need to do this to get the
1793 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
1794 // flag on the RenderObject has been cleared, so use the one on the style().
1795 topLeft += layer()->offsetForInFlowPosition();
1798 if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isRenderBlockFlow()) {
1799 LayoutRect paintInvalidationRect(topLeft, rect.size());
1800 toRenderBlock(o)->adjustRectForColumns(paintInvalidationRect);
1801 topLeft = paintInvalidationRect.location();
1802 rect = paintInvalidationRect;
1805 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1806 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1807 rect.setLocation(topLeft);
1808 if (o->hasOverflowClip()) {
1809 RenderBox* containerBox = toRenderBox(o);
1810 containerBox->applyCachedClipAndScrollOffsetForPaintInvalidation(rect);
1815 if (containerSkipped) {
1816 // If the paintInvalidationContainer is below o, then we need to map the rect into paintInvalidationContainer's coordinates.
1817 LayoutSize containerOffset = paintInvalidationContainer->offsetFromAncestorContainer(o);
1818 rect.move(-containerOffset);
1822 if (o->isRenderView())
1823 toRenderView(o)->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, position == FixedPosition ? RenderView::IsFixedPosition : RenderView::IsNotFixedPosition, paintInvalidationState);
1825 o->mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
1828 void RenderBox::inflatePaintInvalidationRectForReflectionAndFilter(LayoutRect& paintInvalidationRect) const
1830 if (hasReflection())
1831 paintInvalidationRect.unite(reflectedRect(paintInvalidationRect));
1833 if (style()->hasFilter())
1834 style()->filterOutsets().expandRect(paintInvalidationRect);
1837 void RenderBox::invalidatePaintForOverhangingFloats(bool)
1841 void RenderBox::updateLogicalWidth()
1843 LogicalExtentComputedValues computedValues;
1844 computeLogicalWidth(computedValues);
1846 setLogicalWidth(computedValues.m_extent);
1847 setLogicalLeft(computedValues.m_position);
1848 setMarginStart(computedValues.m_margins.m_start);
1849 setMarginEnd(computedValues.m_margins.m_end);
1852 static float getMaxWidthListMarker(const RenderBox* renderer)
1856 Node* parentNode = renderer->generatingNode();
1858 ASSERT(isHTMLOListElement(parentNode) || isHTMLUListElement(parentNode));
1859 ASSERT(renderer->style()->textAutosizingMultiplier() != 1);
1862 for (RenderObject* child = renderer->slowFirstChild(); child; child = child->nextSibling()) {
1863 if (!child->isListItem())
1866 RenderBox* listItem = toRenderBox(child);
1867 for (RenderObject* itemChild = listItem->slowFirstChild(); itemChild; itemChild = itemChild->nextSibling()) {
1868 if (!itemChild->isListMarker())
1870 RenderBox* itemMarker = toRenderBox(itemChild);
1871 // Make sure to compute the autosized width.
1872 if (itemMarker->needsLayout())
1873 itemMarker->layout();
1874 maxWidth = std::max<float>(maxWidth, toRenderListMarker(itemMarker)->logicalWidth().toFloat());
1881 void RenderBox::computeLogicalWidth(LogicalExtentComputedValues& computedValues) const
1883 computedValues.m_extent = logicalWidth();
1884 computedValues.m_position = logicalLeft();
1885 computedValues.m_margins.m_start = marginStart();
1886 computedValues.m_margins.m_end = marginEnd();
1888 if (isOutOfFlowPositioned()) {
1889 // FIXME: This calculation is not patched for block-flow yet.
1890 // https://bugs.webkit.org/show_bug.cgi?id=46500
1891 computePositionedLogicalWidth(computedValues);
1895 // If layout is limited to a subtree, the subtree root's logical width does not change.
1896 if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1899 // The parent box is flexing us, so it has increased or decreased our
1900 // width. Use the width from the style context.
1901 // FIXME: Account for block-flow in flexible boxes.
1902 // https://bugs.webkit.org/show_bug.cgi?id=46418
1903 if (hasOverrideWidth() && (style()->borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) {
1904 computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
1908 // FIXME: Account for block-flow in flexible boxes.
1909 // https://bugs.webkit.org/show_bug.cgi?id=46418
1910 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1911 bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1912 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1914 RenderStyle* styleToUse = style();
1915 Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse->logicalWidth();
1917 RenderBlock* cb = containingBlock();
1918 LayoutUnit containerLogicalWidth = std::max<LayoutUnit>(0, containingBlockLogicalWidthForContent());
1919 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1921 if (isInline() && !isInlineBlockOrInlineTable()) {
1922 // just calculate margins
1923 computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
1924 computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
1925 if (treatAsReplaced)
1926 computedValues.m_extent = std::max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
1930 // Width calculations
1931 if (treatAsReplaced)
1932 computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
1934 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
1935 if (hasPerpendicularContainingBlock)
1936 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1937 LayoutUnit preferredWidth = computeLogicalWidthUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb);
1938 computedValues.m_extent = constrainLogicalWidthByMinMax(preferredWidth, containerWidthInInlineDirection, cb);
1941 // Margin calculations.
1942 computeMarginsForDirection(InlineDirection, cb, containerLogicalWidth, computedValues.m_extent, computedValues.m_margins.m_start,
1943 computedValues.m_margins.m_end, style()->marginStart(), style()->marginEnd());
1945 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
1946 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated() && !cb->isRenderGrid()) {
1947 LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(this);
1948 bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
1949 if (hasInvertedDirection)
1950 computedValues.m_margins.m_start = newMargin;
1952 computedValues.m_margins.m_end = newMargin;
1955 if (styleToUse->textAutosizingMultiplier() != 1 && styleToUse->marginStart().type() == Fixed) {
1956 Node* parentNode = generatingNode();
1957 if (parentNode && (isHTMLOListElement(*parentNode) || isHTMLUListElement(*parentNode))) {
1958 // Make sure the markers in a list are properly positioned (i.e. not chopped off) when autosized.
1959 const float adjustedMargin = (1 - 1.0 / styleToUse->textAutosizingMultiplier()) * getMaxWidthListMarker(this);
1960 bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
1961 if (hasInvertedDirection)
1962 computedValues.m_margins.m_end += adjustedMargin;
1964 computedValues.m_margins.m_start += adjustedMargin;
1969 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
1971 LayoutUnit marginStart = 0;
1972 LayoutUnit marginEnd = 0;
1973 return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
1976 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
1978 marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth);
1979 marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth);
1980 return availableLogicalWidth - marginStart - marginEnd;
1983 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(const Length& logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
1985 if (logicalWidthLength.type() == FillAvailable)
1986 return fillAvailableMeasure(availableLogicalWidth);
1988 LayoutUnit minLogicalWidth = 0;
1989 LayoutUnit maxLogicalWidth = 0;
1990 computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
1992 if (logicalWidthLength.type() == MinContent)
1993 return minLogicalWidth + borderAndPadding;
1995 if (logicalWidthLength.type() == MaxContent)
1996 return maxLogicalWidth + borderAndPadding;
1998 if (logicalWidthLength.type() == FitContent) {
1999 minLogicalWidth += borderAndPadding;
2000 maxLogicalWidth += borderAndPadding;
2001 return std::max(minLogicalWidth, std::min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2004 ASSERT_NOT_REACHED();
2008 LayoutUnit RenderBox::computeLogicalWidthUsing(SizeType widthType, const Length& logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* cb) const
2010 if (!logicalWidth.isIntrinsicOrAuto()) {
2011 // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2012 return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2015 if (logicalWidth.isIntrinsic())
2016 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2018 LayoutUnit marginStart = 0;
2019 LayoutUnit marginEnd = 0;
2020 LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2022 if (shrinkToAvoidFloats() && cb->isRenderBlockFlow() && toRenderBlockFlow(cb)->containsFloats())
2023 logicalWidthResult = std::min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb)));
2025 if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(logicalWidth))
2026 return std::max(minPreferredLogicalWidth(), std::min(maxPreferredLogicalWidth(), logicalWidthResult));
2027 return logicalWidthResult;
2030 static bool flexItemHasStretchAlignment(const RenderObject* flexitem)
2032 RenderObject* parent = flexitem->parent();
2033 // auto margins mean we don't stretch.
2034 if (parent->style()->isColumnFlexDirection()) {
2035 if (flexitem->style()->marginStart().isAuto() || flexitem->style()->marginEnd().isAuto())
2038 if (flexitem->style()->marginBefore().isAuto() || flexitem->style()->marginAfter().isAuto())
2041 return flexitem->style()->alignSelf() == ItemPositionStretch || (flexitem->style()->alignSelf() == ItemPositionAuto && parent->style()->alignItems() == ItemPositionStretch);
2044 static bool isStretchingColumnFlexItem(const RenderObject* flexitem)
2046 RenderObject* parent = flexitem->parent();
2047 if (parent->isDeprecatedFlexibleBox() && parent->style()->boxOrient() == VERTICAL && parent->style()->boxAlign() == BSTRETCH)
2050 // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2051 if (parent->isFlexibleBox() && parent->style()->flexWrap() == FlexNoWrap && parent->style()->isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2056 bool RenderBox::sizesLogicalWidthToFitContent(const Length& logicalWidth) const
2058 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
2059 // but they allow text to sit on the same line as the marquee.
2060 if (isFloating() || (isInlineBlockOrInlineTable() && !isMarquee()))
2063 if (logicalWidth.type() == Intrinsic)
2066 // Children of a horizontal marquee do not fill the container by default.
2067 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
2068 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
2069 // block-flow (as well as how marquee overflow should relate to block flow).
2070 // https://bugs.webkit.org/show_bug.cgi?id=46472
2071 if (parent()->isMarquee()) {
2072 EMarqueeDirection dir = parent()->style()->marqueeDirection();
2073 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2077 // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2078 // In the case of columns that have a stretch alignment, we go ahead and layout at the
2079 // stretched size to avoid an extra layout when applying alignment.
2080 if (parent()->isFlexibleBox()) {
2081 // For multiline columns, we need to apply align-content first, so we can't stretch now.
2082 if (!parent()->style()->isColumnFlexDirection() || parent()->style()->flexWrap() != FlexNoWrap)
2084 if (!flexItemHasStretchAlignment(this))
2088 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
2089 // that don't stretch their kids lay out their children at their intrinsic widths.
2090 // FIXME: Think about block-flow here.
2091 // https://bugs.webkit.org/show_bug.cgi?id=46473
2092 if (parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
2095 // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2096 // stretching column flexbox.
2097 // FIXME: Think about block-flow here.
2098 // https://bugs.webkit.org/show_bug.cgi?id=46473
2099 if (logicalWidth.isAuto() && !isStretchingColumnFlexItem(this) && autoWidthShouldFitContent())
2102 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2108 bool RenderBox::autoWidthShouldFitContent() const
2110 return node() && (isHTMLInputElement(*node()) || isHTMLSelectElement(*node()) || isHTMLButtonElement(*node())
2111 || isHTMLTextAreaElement(*node()) || (isHTMLLegendElement(*node()) && !style()->hasOutOfFlowPosition()));
2114 void RenderBox::computeMarginsForDirection(MarginDirection flowDirection, const RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd, Length marginStartLength, Length marginEndLength) const
2116 if (flowDirection == BlockDirection || isFloating() || isInline()) {
2117 if (isTableCell() && flowDirection == BlockDirection) {
2118 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
2119 // we may just do it with an extra anonymous block inside the cell.
2125 // Margins are calculated with respect to the logical width of
2126 // the containing block (8.3)
2127 // Inline blocks/tables and floats don't have their margins increased.
2128 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2129 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2133 if (containingBlock->isFlexibleBox()) {
2134 // We need to let flexbox handle the margin adjustment - otherwise, flexbox
2135 // will think we're wider than we actually are and calculate line sizes wrong.
2136 // See also http://dev.w3.org/csswg/css-flexbox/#auto-margins
2137 if (marginStartLength.isAuto())
2138 marginStartLength.setValue(0);
2139 if (marginEndLength.isAuto())
2140 marginEndLength.setValue(0);
2143 LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2144 LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2146 LayoutUnit availableWidth = containerWidth;
2147 if (avoidsFloats() && containingBlock->isRenderBlockFlow() && toRenderBlockFlow(containingBlock)->containsFloats()) {
2148 availableWidth = containingBlockAvailableLineWidth();
2149 if (shrinkToAvoidFloats() && availableWidth < containerWidth) {
2150 marginStart = std::max<LayoutUnit>(0, marginStartWidth);
2151 marginEnd = std::max<LayoutUnit>(0, marginEndWidth);
2155 // CSS 2.1 (10.3.3): "If 'width' is not 'auto' and 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width'
2156 // (plus any of 'margin-left' or 'margin-right' that are not 'auto') is larger than the width of the containing block, then any 'auto'
2157 // values for 'margin-left' or 'margin-right' are, for the following rules, treated as zero.
2158 LayoutUnit marginBoxWidth = childWidth + (!style()->width().isAuto() ? marginStartWidth + marginEndWidth : LayoutUnit());
2160 // CSS 2.1: "If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element
2161 // with respect to the edges of the containing block."
2162 const RenderStyle* containingBlockStyle = containingBlock->style();
2163 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && marginBoxWidth < availableWidth)
2164 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlockStyle->textAlign() == WEBKIT_CENTER)) {
2165 // Other browsers center the margin box for align=center elements so we match them here.
2166 LayoutUnit centeredMarginBoxStart = std::max<LayoutUnit>(0, (availableWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2167 marginStart = centeredMarginBoxStart + marginStartWidth;
2168 marginEnd = availableWidth - childWidth - marginStart + marginEndWidth;
2172 // CSS 2.1: "If there is exactly one value specified as 'auto', its used value follows from the equality."
2173 if (marginEndLength.isAuto() && marginBoxWidth < availableWidth) {
2174 marginStart = marginStartWidth;
2175 marginEnd = availableWidth - childWidth - marginStart;
2179 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
2180 || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
2181 if ((marginStartLength.isAuto() && marginBoxWidth < availableWidth) || pushToEndFromTextAlign) {
2182 marginEnd = marginEndWidth;
2183 marginStart = availableWidth - childWidth - marginEnd;
2187 // Either no auto margins, or our margin box width is >= the container width, auto margins will just turn into 0.
2188 marginStart = marginStartWidth;
2189 marginEnd = marginEndWidth;
2192 void RenderBox::updateLogicalHeight()
2194 m_intrinsicContentLogicalHeight = contentLogicalHeight();
2196 LogicalExtentComputedValues computedValues;
2197 computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2199 setLogicalHeight(computedValues.m_extent);
2200 setLogicalTop(computedValues.m_position);
2201 setMarginBefore(computedValues.m_margins.m_before);
2202 setMarginAfter(computedValues.m_margins.m_after);
2205 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2207 computedValues.m_extent = logicalHeight;
2208 computedValues.m_position = logicalTop;
2210 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2211 if (isTableCell() || (isInline() && !isReplaced()))
2215 if (isOutOfFlowPositioned())
2216 computePositionedLogicalHeight(computedValues);
2218 RenderBlock* cb = containingBlock();
2220 // If we are perpendicular to our containing block then we need to resolve our block-start and block-end margins so that if they
2221 // 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.
2222 // 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
2223 // writing mode when figuring out the block-direction margins for positioning in |computeAndSetBlockDirectionMargins| (i.e. margin collapsing etc.).
2224 // See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
2225 MarginDirection flowDirection = isHorizontalWritingMode() != cb->isHorizontalWritingMode() ? InlineDirection : BlockDirection;
2227 // For tables, calculate margins only.
2229 computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
2230 computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
2234 // FIXME: Account for block-flow in flexible boxes.
2235 // https://bugs.webkit.org/show_bug.cgi?id=46418
2236 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
2237 bool stretching = parent()->style()->boxAlign() == BSTRETCH;
2238 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2239 bool checkMinMaxHeight = false;
2241 // The parent box is flexing us, so it has increased or decreased our height. We have to
2242 // grab our cached flexible height.
2243 // FIXME: Account for block-flow in flexible boxes.
2244 // https://bugs.webkit.org/show_bug.cgi?id=46418
2245 if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
2246 h = Length(overrideLogicalContentHeight(), Fixed);
2247 else if (treatAsReplaced)
2248 h = Length(computeReplacedLogicalHeight(), Fixed);
2250 h = style()->logicalHeight();
2251 checkMinMaxHeight = true;
2254 // Block children of horizontal flexible boxes fill the height of the box.
2255 // FIXME: Account for block-flow in flexible boxes.
2256 // https://bugs.webkit.org/show_bug.cgi?id=46418
2257 if (h.isAuto() && inHorizontalBox && toRenderDeprecatedFlexibleBox(parent())->isStretchingChildren()) {
2258 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2259 checkMinMaxHeight = false;
2262 LayoutUnit heightResult;
2263 if (checkMinMaxHeight) {
2264 heightResult = computeLogicalHeightUsing(style()->logicalHeight(), computedValues.m_extent - borderAndPaddingLogicalHeight());
2265 if (heightResult == -1)
2266 heightResult = computedValues.m_extent;
2267 heightResult = constrainLogicalHeightByMinMax(heightResult, computedValues.m_extent - borderAndPaddingLogicalHeight());
2269 // The only times we don't check min/max height are when a fixed length has
2270 // been given as an override. Just use that. The value has already been adjusted
2272 ASSERT(h.isFixed());
2273 heightResult = h.value() + borderAndPaddingLogicalHeight();
2276 computedValues.m_extent = heightResult;
2277 computeMarginsForDirection(flowDirection, cb, containingBlockLogicalWidthForContent(), computedValues.m_extent, computedValues.m_margins.m_before,
2278 computedValues.m_margins.m_after, style()->marginBefore(), style()->marginAfter());
2281 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2282 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2283 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2284 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2285 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2286 bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
2287 && (isDocumentElement() || (isBody() && document().documentElement()->renderer()->style()->logicalHeight().isPercent())) && !isInline();
2288 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2289 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2290 LayoutUnit visibleHeight = view()->viewLogicalHeightForPercentages();
2291 if (isDocumentElement())
2292 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - margins);
2294 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2295 computedValues.m_extent = std::max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2300 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
2302 LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
2303 if (logicalHeight != -1)
2304 logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2305 return logicalHeight;
2308 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height, LayoutUnit intrinsicContentHeight) const
2310 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height, intrinsicContentHeight);
2311 if (heightIncludingScrollbar == -1)
2313 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2316 LayoutUnit RenderBox::computeIntrinsicLogicalContentHeightUsing(const Length& logicalHeightLength, LayoutUnit intrinsicContentHeight, LayoutUnit borderAndPadding) const
2318 // FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
2319 // If that happens, this code will have to change.
2320 if (logicalHeightLength.isMinContent() || logicalHeightLength.isMaxContent() || logicalHeightLength.isFitContent()) {
2322 return intrinsicSize().height();
2323 if (m_intrinsicContentLogicalHeight != -1)
2324 return m_intrinsicContentLogicalHeight;
2325 return intrinsicContentHeight;
2327 if (logicalHeightLength.isFillAvailable())
2328 return containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding) - borderAndPadding;
2329 ASSERT_NOT_REACHED();
2333 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const
2335 // FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
2336 // If that happens, this code will have to change.
2337 if (height.isIntrinsic()) {
2338 if (intrinsicContentHeight == -1)
2339 return -1; // Intrinsic height isn't available.
2340 return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
2342 if (height.isFixed())
2343 return height.value();
2344 if (height.isPercent())
2345 return computePercentageLogicalHeight(height);
2349 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const
2351 // Flow threads for multicol or paged overflow should be skipped. They are invisible to the DOM,
2352 // and percent heights of children should be resolved against the multicol or paged container.
2353 if (containingBlock->isRenderFlowThread())
2356 // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2357 // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2358 if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2360 return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style()->logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2363 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2365 LayoutUnit availableHeight = -1;
2367 bool skippedAutoHeightContainingBlock = false;
2368 RenderBlock* cb = containingBlock();
2369 const RenderBox* containingBlockChild = this;
2370 LayoutUnit rootMarginBorderPaddingHeight = 0;
2371 while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb)) {
2372 if (cb->isBody() || cb->isDocumentElement())
2373 rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2374 skippedAutoHeightContainingBlock = true;
2375 containingBlockChild = cb;
2376 cb = cb->containingBlock();
2378 cb->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2380 RenderStyle* cbstyle = cb->style();
2382 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2383 // explicitly specified that can be used for any percentage computations.
2384 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle->logicalHeight().isAuto() || (!cbstyle->logicalTop().isAuto() && !cbstyle->logicalBottom().isAuto()));
2386 bool includeBorderPadding = isTable();
2388 if (isHorizontalWritingMode() != cb->isHorizontalWritingMode()) {
2389 availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2390 } else if (hasOverrideContainingBlockLogicalHeight()) {
2391 availableHeight = overrideContainingBlockContentLogicalHeight();
2392 } else if (cb->isFlexItem() && flexItemHasStretchAlignment(cb) && cb->hasOverrideHeight()) {
2393 availableHeight = cb->overrideLogicalContentHeight();
2394 } else if (cb->isTableCell()) {
2395 if (!skippedAutoHeightContainingBlock) {
2396 // Table cells violate what the CSS spec says to do with heights. Basically we
2397 // don't care if the cell specified a height or not. We just always make ourselves
2398 // be a percentage of the cell's current content height.
2399 if (!cb->hasOverrideHeight()) {
2400 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2401 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2402 // While we can't get all cases right, we can at least detect when the cell has a specified
2403 // height or when the table has a specified height. In these cases we want to initially have
2404 // no size and allow the flexing of the table or the cell to its specified height to cause us
2405 // to grow to fill the space. This could end up being wrong in some cases, but it is
2406 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2407 RenderTableCell* cell = toRenderTableCell(cb);
2408 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2412 availableHeight = cb->overrideLogicalContentHeight();
2413 includeBorderPadding = true;
2415 } else if (cbstyle->logicalHeight().isFixed()) {
2416 LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle->logicalHeight().value());
2417 availableHeight = std::max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight(), -1));
2418 } else if (cbstyle->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2419 // We need to recur and compute the percentage height for our containing block.
2420 LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle->logicalHeight());
2421 if (heightWithScrollbar != -1) {
2422 LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2423 // We need to adjust for min/max height because this method does not
2424 // handle the min/max of the current block, its caller does. So the
2425 // return value from the recursive call will not have been adjusted
2427 LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight(), -1);
2428 availableHeight = std::max<LayoutUnit>(0, contentBoxHeight);
2430 } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2431 // Don't allow this to affect the block' height() member variable, since this
2432 // can get called while the block is still laying out its kids.
2433 LogicalExtentComputedValues computedValues;
2434 cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2435 availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2436 } else if (cb->isRenderView())
2437 availableHeight = view()->viewLogicalHeightForPercentages();
2439 if (availableHeight == -1)
2440 return availableHeight;
2442 availableHeight -= rootMarginBorderPaddingHeight;
2444 if (isTable() && isOutOfFlowPositioned())
2445 availableHeight += cb->paddingLogicalHeight();
2447 LayoutUnit result = valueForLength(height, availableHeight);
2448 if (includeBorderPadding) {
2449 // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2450 // It is necessary to use the border-box to match WinIE's broken
2451 // box model. This is essential for sizing inside
2452 // table cells using percentage heights.
2453 result -= borderAndPaddingLogicalHeight();
2454 return std::max<LayoutUnit>(0, result);
2459 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2461 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), shouldComputePreferred);
2464 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2466 LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMinWidth().isPercent()) || style()->logicalMinWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2467 LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMaxWidth().isPercent()) || style()->logicalMaxWidth().isMaxSizeNone() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2468 return std::max(minLogicalWidth, std::min(logicalWidth, maxLogicalWidth));
2471 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(const Length& logicalWidth) const
2473 switch (logicalWidth.type()) {
2475 return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2478 // MinContent/MaxContent don't need the availableLogicalWidth argument.
2479 LayoutUnit availableLogicalWidth = 0;
2480 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2486 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2487 // containing block's block-flow.
2488 // https://bugs.webkit.org/show_bug.cgi?id=46496
2489 const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2490 Length containerLogicalWidth = containingBlock()->style()->logicalWidth();
2491 // FIXME: Handle cases when containing block width is calculated or viewport percent.
2492 // https://bugs.webkit.org/show_bug.cgi?id=91071
2493 if (logicalWidth.isIntrinsic())
2494 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2495 if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2496 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2503 return intrinsicLogicalWidth();
2510 ASSERT_NOT_REACHED();
2514 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2516 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2519 bool RenderBox::logicalHeightComputesAsNone(SizeType sizeType) const
2521 ASSERT(sizeType == MinSize || sizeType == MaxSize);
2522 Length logicalHeight = sizeType == MinSize ? style()->logicalMinHeight() : style()->logicalMaxHeight();
2523 Length initialLogicalHeight = sizeType == MinSize ? RenderStyle::initialMinSize() : RenderStyle::initialMaxSize();
2525 if (logicalHeight == initialLogicalHeight)
2528 if (!logicalHeight.isPercent() || isOutOfFlowPositioned())
2531 // Anonymous block boxes are ignored when resolving percentage values that would refer to it:
2532 // the closest non-anonymous ancestor box is used instead.
2533 RenderBlock* containingBlock = this->containingBlock();
2534 while (containingBlock->isAnonymous())
2535 containingBlock = containingBlock->containingBlock();
2537 return containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight();
2540 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2542 // 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,
2543 // the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').
2544 LayoutUnit minLogicalHeight;
2545 if (!logicalHeightComputesAsNone(MinSize))
2546 minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2547 LayoutUnit maxLogicalHeight = logicalHeight;
2548 if (!logicalHeightComputesAsNone(MaxSize))
2549 maxLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2550 return std::max(minLogicalHeight, std::min(logicalHeight, maxLogicalHeight));
2553 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(const Length& logicalHeight) const
2555 switch (logicalHeight.type()) {
2557 return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
2561 RenderObject* cb = isOutOfFlowPositioned() ? container() : containingBlock();
2562 while (cb->isAnonymous())
2563 cb = cb->containingBlock();
2564 if (cb->isRenderBlock())
2565 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2567 // FIXME: This calculation is not patched for block-flow yet.
2568 // https://bugs.webkit.org/show_bug.cgi?id=46500
2569 if (cb->isOutOfFlowPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2570 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
2571 RenderBlock* block = toRenderBlock(cb);
2572 LogicalExtentComputedValues computedValues;
2573 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2574 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2575 LayoutUnit newHeight = block->adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2576 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
2579 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2580 // containing block's block-flow.
2581 // https://bugs.webkit.org/show_bug.cgi?id=46496
2582 LayoutUnit availableHeight;
2583 if (isOutOfFlowPositioned())
2584 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2586 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
2587 // It is necessary to use the border-box to match WinIE's broken
2588 // box model. This is essential for sizing inside
2589 // table cells using percentage heights.
2590 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
2591 // https://bugs.webkit.org/show_bug.cgi?id=46997
2592 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2593 if (cb->isTableCell()) {
2594 // Don't let table cells squeeze percent-height replaced elements
2595 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2596 availableHeight = std::max(availableHeight, intrinsicLogicalHeight());
2597 return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
2599 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2600 cb = cb->containingBlock();
2603 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
2609 return adjustContentBoxLogicalHeightForBoxSizing(computeIntrinsicLogicalContentHeightUsing(logicalHeight, intrinsicLogicalHeight(), borderAndPaddingHeight()));
2611 return intrinsicLogicalHeight();
2615 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
2617 // http://www.w3.org/TR/CSS2/visudet.html#propdef-height - We are interested in the content height.
2618 return constrainContentBoxLogicalHeightByMinMax(availableLogicalHeightUsing(style()->logicalHeight(), heightType), -1);
2621 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
2624 return isHorizontalWritingMode() ? toRenderView(this)->frameView()->unscaledVisibleContentSize().height() : toRenderView(this)->frameView()->unscaledVisibleContentSize().width();
2626 // We need to stop here, since we don't want to increase the height of the table
2627 // artificially. We're going to rely on this cell getting expanded to some new
2628 // height, and then when we lay out again we'll use the calculation below.
2629 if (isTableCell() && (h.isAuto() || h.isPercent())) {
2630 if (hasOverrideHeight())
2631 return overrideLogicalContentHeight();
2632 return logicalHeight() - borderAndPaddingLogicalHeight();
2635 if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
2636 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2637 LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2638 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
2641 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h, -1);
2642 if (heightIncludingScrollbar != -1)
2643 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2645 // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
2646 // https://bugs.webkit.org/show_bug.cgi?id=46500
2647 if (isRenderBlock() && isOutOfFlowPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2648 RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2649 LogicalExtentComputedValues computedValues;
2650 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2651 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2652 return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2655 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2656 LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
2657 if (heightType == ExcludeMarginBorderPadding) {
2658 // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
2659 availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
2661 return availableHeight;
2664 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
2666 LayoutUnit marginBefore;
2667 LayoutUnit marginAfter;
2668 computeMarginsForDirection(BlockDirection, containingBlock, containingBlockLogicalWidthForContent(), logicalHeight(), marginBefore, marginAfter,
2669 style()->marginBeforeUsing(containingBlock->style()),
2670 style()->marginAfterUsing(containingBlock->style()));
2671 // 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.
2672 // See http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
2673 containingBlock->setMarginBeforeForChild(this, marginBefore);
2674 containingBlock->setMarginAfterForChild(this, marginAfter);
2677 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2679 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2680 return containingBlockLogicalHeightForPositioned(containingBlock, false);
2682 // Use viewport as container for top-level fixed-position elements.
2683 if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
2684 const RenderView* view = toRenderView(containingBlock);
2685 if (FrameView* frameView = view->frameView()) {
2686 LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2687 return containingBlock->isHorizontalWritingMode() ? viewportRect.width() : viewportRect.height();
2691 if (containingBlock->isBox())
2692 return toRenderBox(containingBlock)->clientLogicalWidth();
2694 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2696 const RenderInline* flow = toRenderInline(containingBlock);
2697 InlineFlowBox* first = flow->firstLineBox();
2698 InlineFlowBox* last = flow->lastLineBox();
2700 // If the containing block is empty, return a width of 0.
2701 if (!first || !last)
2704 LayoutUnit fromLeft;
2705 LayoutUnit fromRight;
2706 if (containingBlock->style()->isLeftToRightDirection()) {
2707 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2708 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2710 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2711 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2714 return std::max<LayoutUnit>(0, fromRight - fromLeft);
2717 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2719 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2720 return containingBlockLogicalWidthForPositioned(containingBlock, false);
2722 // Use viewport as container for top-level fixed-position elements.
2723 if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
2724 const RenderView* view = toRenderView(containingBlock);
2725 if (FrameView* frameView = view->frameView()) {
2726 LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
2727 return containingBlock->isHorizontalWritingMode() ? viewportRect.height() : viewportRect.width();
2731 if (containingBlock->isBox()) {
2732 const RenderBlock* cb = containingBlock->isRenderBlock() ?
2733 toRenderBlock(containingBlock) : containingBlock->containingBlock();
2734 return cb->clientLogicalHeight();
2737 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2739 const RenderInline* flow = toRenderInline(containingBlock);
2740 InlineFlowBox* first = flow->firstLineBox();
2741 InlineFlowBox* last = flow->lastLineBox();
2743 // If the containing block is empty, return a height of 0.
2744 if (!first || !last)
2747 LayoutUnit heightResult;
2748 LayoutRect boundingBox = flow->linesBoundingBox();
2749 if (containingBlock->isHorizontalWritingMode())
2750 heightResult = boundingBox.height();
2752 heightResult = boundingBox.width();
2753 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2754 return heightResult;
2757 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2759 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2762 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2763 if (child->parent()->style()->direction() == LTR) {
2764 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2765 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2766 if (curr->isBox()) {
2767 staticPosition += toRenderBox(curr)->logicalLeft();
2768 if (toRenderBox(curr)->isRelPositioned())
2769 staticPosition += toRenderBox(curr)->relativePositionOffset().width();
2770 } else if (curr->isInline()) {
2771 if (curr->isRelPositioned()) {
2772 if (!curr->style()->logicalLeft().isAuto())
2773 staticPosition += curr->style()->logicalLeft().value();
2775 staticPosition -= curr->style()->logicalRight().value();
2779 logicalLeft.setValue(Fixed, staticPosition);
2781 RenderBox* enclosingBox = child->parent()->enclosingBox();
2782 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
2783 for (RenderObject* curr = child->parent(); curr; curr = curr->container()) {
2784 if (curr->isBox()) {
2785 if (curr != containerBlock) {
2786 staticPosition -= toRenderBox(curr)->logicalLeft();
2787 if (toRenderBox(curr)->isRelPositioned())
2788 staticPosition -= toRenderBox(curr)->relativePositionOffset().width();
2790 if (curr == enclosingBox)
2791 staticPosition -= enclosingBox->logicalWidth();
2792 } else if (curr->isInline()) {
2793 if (curr->isRelPositioned()) {
2794 if (!curr->style()->logicalLeft().isAuto())
2795 staticPosition -= curr->style()->logicalLeft().value();
2797 staticPosition += curr->style()->logicalRight().value();
2800 if (curr == containerBlock)
2803 logicalRight.setValue(Fixed, staticPosition);
2807 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues) const
2810 computePositionedLogicalWidthReplaced(computedValues);
2815 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
2816 // the type 'static' in determining whether to calculate the static distance?
2817 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2819 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
2820 // than or less than the computed width(). Be careful of box-sizing and
2821 // percentage issues.
2823 // The following is based off of the W3C Working Draft from April 11, 2006 of
2824 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2825 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2826 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2827 // correspond to text from the spec)
2830 // We don't use containingBlock(), since we may be positioned by an enclosing
2831 // relative positioned inline.
2832 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2834 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
2836 // Use the container block's direction except when calculating the static distance
2837 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
2838 // of the CSS 2.1 test suite
2839 TextDirection containerDirection = containerBlock->style()->direction();
2841 bool isHorizontal = isHorizontalWritingMode();
2842 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2843 const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2844 const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2846 Length logicalLeftLength = style()->logicalLeft();
2847 Length logicalRightLength = style()->logicalRight();
2849 /*---------------------------------------------------------------------------*\
2850 * For the purposes of this section and the next, the term "static position"
2851 * (of an element) refers, roughly, to the position an element would have had
2852 * in the normal flow. More precisely:
2854 * * The static position for 'left' is the distance from the left edge of the
2855 * containing block to the left margin edge of a hypothetical box that would
2856 * have been the first box of the element if its 'position' property had
2857 * been 'static' and 'float' had been 'none'. The value is negative if the
2858 * hypothetical box is to the left of the containing block.
2859 * * The static position for 'right' is the distance from the right edge of the
2860 * containing block to the right margin edge of the same hypothetical box as
2861 * above. The value is positive if the hypothetical box is to the left of the
2862 * containing block's edge.
2864 * But rather than actually calculating the dimensions of that hypothetical box,
2865 * user agents are free to make a guess at its probable position.
2867 * For the purposes of calculating the static position, the containing block of
2868 * fixed positioned elements is the initial containing block instead of the
2869 * viewport, and all scrollable boxes should be assumed to be scrolled to their
2871 \*---------------------------------------------------------------------------*/
2874 // Calculate the static distance if needed.
2875 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth);
2877 // Calculate constraint equation values for 'width' case.
2878 computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2879 containerLogicalWidth, bordersPlusPadding,
2880 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2883 // Calculate constraint equation values for 'max-width' case.
2884 if (!style()->logicalMaxWidth().isMaxSizeNone()) {
2885 LogicalExtentComputedValues maxValues;
2887 computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2888 containerLogicalWidth, bordersPlusPadding,
2889 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2892 if (computedValues.m_extent > maxValues.m_extent) {
2893 computedValues.m_extent = maxValues.m_extent;
2894 computedValues.m_position = maxValues.m_position;
2895 computedValues.m_margins.m_start = maxValues.m_margins.m_start;
2896 computedValues.m_margins.m_end = maxValues.m_margins.m_end;
2900 // Calculate constraint equation values for 'min-width' case.
2901 if (!style()->logicalMinWidth().isZero() || style()->logicalMinWidth().isIntrinsic()) {
2902 LogicalExtentComputedValues minValues;
2904 computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2905 containerLogicalWidth, bordersPlusPadding,
2906 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2909 if (computedValues.m_extent < minValues.m_extent) {
2910 computedValues.m_extent = minValues.m_extent;
2911 computedValues.m_position = minValues.m_position;
2912 computedValues.m_margins.m_start = minValues.m_margins.m_start;
2913 computedValues.m_margins.m_end = minValues.m_margins.m_end;
2917 computedValues.m_extent += bordersPlusPadding;
2920 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2922 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2923 // 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.
2924 if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2925 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2926 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2928 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2932 void RenderBox::shrinkToFitWidth(const LayoutUnit availableSpace, const LayoutUnit logicalLeftValue, const LayoutUnit bordersPlusPadding, LogicalExtentComputedValues& computedValues) const
2934 // FIXME: would it be better to have shrink-to-fit in one step?
2935 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2936 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2937 LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2938 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
2941 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2942 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2943 const Length& logicalLeft, const Length& logicalRight, const Length& marginLogicalLeft,
2944 const Length& marginLogicalRight, LogicalExtentComputedValues& computedValues) const
2946 if (logicalWidth.isIntrinsic())
2947 logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
2949 // 'left' and 'right' cannot both be 'auto' because one would of been
2950 // converted to the static position already
2951 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2953 LayoutUnit logicalLeftValue = 0;
2955 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
2957 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2958 bool logicalLeftIsAuto = logicalLeft.isAuto();
2959 bool logicalRightIsAuto = logicalRight.isAuto();
2960 LayoutUnit& marginLogicalLeftValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
2961 LayoutUnit& marginLogicalRightValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
2962 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2963 /*-----------------------------------------------------------------------*\
2964 * If none of the three is 'auto': If both 'margin-left' and 'margin-
2965 * right' are 'auto', solve the equation under the extra constraint that
2966 * the two margins get equal values, unless this would make them negative,
2967 * in which case when direction of the containing block is 'ltr' ('rtl'),
2968 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2969 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2970 * solve the equation for that value. If the values are over-constrained,
2971 * ignore the value for 'left' (in case the 'direction' property of the
2972 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2973 * and solve for that value.
2974 \*-----------------------------------------------------------------------*/
2975 // NOTE: It is not necessary to solve for 'right' in the over constrained
2976 // case because the value is not used for any further calculations.
2978 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
2979 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
2981 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
2983 // Margins are now the only unknown
2984 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2985 // Both margins auto, solve for equality
2986 if (availableSpace >= 0) {
2987 marginLogicalLeftValue = availableSpace / 2; // split the difference
2988 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2990 // Use the containing block's direction rather than the parent block's
2991 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2992 if (containerDirection == LTR) {
2993 marginLogicalLeftValue = 0;
2994 marginLogicalRightValue = availableSpace; // will be negative
2996 marginLogicalLeftValue = availableSpace; // will be negative
2997 marginLogicalRightValue = 0;
3000 } else if (marginLogicalLeft.isAuto()) {
3001 // Solve for left margin
3002 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3003 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3004 } else if (marginLogicalRight.isAuto()) {
3005 // Solve for right margin
3006 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3007 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3009 // Over-constrained, solve for left if direction is RTL
3010 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3011 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3013 // Use the containing block's direction rather than the parent block's
3014 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3015 if (containerDirection == RTL)
3016 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3019 /*--------------------------------------------------------------------*\
3020 * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
3021 * to 0, and pick the one of the following six rules that applies.
3023 * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
3024 * width is shrink-to-fit. Then solve for 'left'
3026 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3027 * ------------------------------------------------------------------
3028 * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
3029 * the 'direction' property of the containing block is 'ltr' set
3030 * 'left' to the static position, otherwise set 'right' to the
3031 * static position. Then solve for 'left' (if 'direction is 'rtl')
3032 * or 'right' (if 'direction' is 'ltr').
3033 * ------------------------------------------------------------------
3035 * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
3036 * width is shrink-to-fit . Then solve for 'right'
3037 * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
3039 * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
3041 * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
3044 * Calculation of the shrink-to-fit width is similar to calculating the
3045 * width of a table cell using the automatic table layout algorithm.
3046 * Roughly: calculate the preferred width by formatting the content
3047 * without breaking lines other than where explicit line breaks occur,
3048 * and also calculate the preferred minimum width, e.g., by trying all
3049 * possible line breaks. CSS 2.1 does not define the exact algorithm.
3050 * Thirdly, calculate the available width: this is found by solving
3051 * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
3054 * Then the shrink-to-fit width is:
3055 * min(max(preferred minimum width, available width), preferred width).
3056 \*--------------------------------------------------------------------*/
3057 // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
3058 // because the value is not used for any further calculations.
3060 // Calculate margins, 'auto' margins are ignored.
3061 marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3062 marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3064 const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
3066 // FIXME: Is there a faster way to find the correct case?
3067 // Use rule/case that applies.
3068 if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3069 // RULE 1: (use shrink-to-fit for width, and solve of left)
3070 LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3072 // FIXME: would it be better to have shrink-to-fit in one step?
3073 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
3074 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
3075 LayoutUnit availableWidth = availableSpace - logicalRightValue;
3076 computedValues.m_extent = std::min(std::max(preferredMinWidth, availableWidth), preferredWidth);
3077 logicalLeftValue = availableSpace - (computedValues.m_extent + logicalRightValue);
3078 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
3079 // RULE 3: (use shrink-to-fit for width, and no need solve of right)
3080 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3082 shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
3083 } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3084 // RULE 4: (solve for left)
3085 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3086 logicalLeftValue = availableSpace - (computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth));
3087 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
3088 // RULE 5: (solve for width)
3089 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3090 if (autoWidthShouldFitContent())
3091 shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
3093 computedValues.m_extent = std::max<LayoutUnit>(0, availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth)));
3094 } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
3095 // RULE 6: (no need solve for right)
3096 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3097 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3101 // Use computed values to calculate the horizontal position.
3103 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3104 // positioned, inline because right now, it is using the logical left position
3105 // of the first line box when really it should use the last line box. When
3106 // this is fixed elsewhere, this block should be removed.
3107 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3108 const RenderInline* flow = toRenderInline(containerBlock);
3109 InlineFlowBox* firstLine = flow->firstLineBox();
3110 InlineFlowBox* lastLine = flow->lastLineBox();
3111 if (firstLine && lastLine && firstLine != lastLine) {
3112 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3117 if (containerBlock->isBox() && toRenderBox(containerBlock)->scrollsOverflowY() && containerBlock->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
3118 logicalLeftValue = logicalLeftValue + toRenderBox(containerBlock)->verticalScrollbarWidth();
3121 computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
3122 computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3125 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
3127 if (!logicalTop.isAuto() || !logicalBottom.isAuto())
3130 // FIXME: The static distance computation has not been patched for mixed writing modes.
3131 LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
3132 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
3133 if (curr->isBox() && !curr->isTableRow())
3134 staticLogicalTop += toRenderBox(curr)->logicalTop();
3136 logicalTop.setValue(Fixed, staticLogicalTop);
3139 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
3142 computePositionedLogicalHeightReplaced(computedValues);
3146 // The following is based off of the W3C Working Draft from April 11, 2006 of
3147 // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
3148 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
3149 // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
3150 // correspond to text from the spec)
3153 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3154 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3156 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3158 RenderStyle* styleToUse = style();
3159 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
3160 const Length marginBefore = styleToUse->marginBefore();
3161 const Length marginAfter = styleToUse->marginAfter();
3162 Length logicalTopLength = styleToUse->logicalTop();
3163 Length logicalBottomLength = styleToUse->logicalBottom();
3165 /*---------------------------------------------------------------------------*\
3166 * For the purposes of this section and the next, the term "static position"
3167 * (of an element) refers, roughly, to the position an element would have had
3168 * in the normal flow. More precisely, the static position for 'top' is the
3169 * distance from the top edge of the containing block to the top margin edge
3170 * of a hypothetical box that would have been the first box of the element if
3171 * its 'position' property had been 'static' and 'float' had been 'none'. The
3172 * value is negative if the hypothetical box is above the containing block.
3174 * But rather than actually calculating the dimensions of that hypothetical
3175 * box, user agents are free to make a guess at its probable position.
3177 * For the purposes of calculating the static position, the containing block
3178 * of fixed positioned elements is the initial containing block instead of
3180 \*---------------------------------------------------------------------------*/
3183 // Calculate the static distance if needed.
3184 computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
3186 // Calculate constraint equation values for 'height' case.
3187 LayoutUnit logicalHeight = computedValues.m_extent;
3188 computePositionedLogicalHeightUsing(styleToUse->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3189 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3192 // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
3195 // Calculate constraint equation values for 'max-height' case.
3196 if (!styleToUse->logicalMaxHeight().isMaxSizeNone()) {
3197 LogicalExtentComputedValues maxValues;
3199 computePositionedLogicalHeightUsing(styleToUse->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3200 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3203 if (computedValues.m_extent > maxValues.m_extent) {
3204 computedValues.m_extent = maxValues.m_extent;
3205 computedValues.m_position = maxValues.m_position;
3206 computedValues.m_margins.m_before = maxValues.m_margins.m_before;
3207 computedValues.m_margins.m_after = maxValues.m_margins.m_after;
3211 // Calculate constraint equation values for 'min-height' case.
3212 if (!styleToUse->logicalMinHeight().isZero() || styleToUse->logicalMinHeight().isIntrinsic()) {
3213 LogicalExtentComputedValues minValues;
3215 computePositionedLogicalHeightUsing(styleToUse->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding, logicalHeight,
3216 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
3219 if (computedValues.m_extent < minValues.m_extent) {
3220 computedValues.m_extent = minValues.m_extent;
3221 computedValues.m_position = minValues.m_position;
3222 computedValues.m_margins.m_before = minValues.m_margins.m_before;
3223 computedValues.m_margins.m_after = minValues.m_margins.m_after;
3227 // Set final height value.
3228 computedValues.m_extent += bordersPlusPadding;
3231 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3233 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3234 // 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.
3235 if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3236 || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3237 logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3239 // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3240 if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3241 if (child->isHorizontalWritingMode())
3242 logicalTopPos += containerBlock->borderBottom();
3244 logicalTopPos += containerBlock->borderRight();
3246 if (child->isHorizontalWritingMode())
3247 logicalTopPos += containerBlock->borderTop();
3249 logicalTopPos += containerBlock->borderLeft();
3253 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3254 LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding, LayoutUnit logicalHeight,
3255 const Length& logicalTop, const Length& logicalBottom, const Length& marginBefore,
3256 const Length& marginAfter, LogicalExtentComputedValues& computedValues) const
3258 // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
3259 // converted to the static position in computePositionedLogicalHeight()
3260 ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
3262 LayoutUnit logicalHeightValue;
3263 LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
3265 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3267 LayoutUnit logicalTopValue = 0;
3269 bool logicalHeightIsAuto = logicalHeightLength.isAuto();
3270 bool logicalTopIsAuto = logicalTop.isAuto();
3271 bool logicalBottomIsAuto = logicalBottom.isAuto();
3273 LayoutUnit resolvedLogicalHeight;
3274 // Height is never unsolved for tables.
3276 resolvedLogicalHeight = contentLogicalHeight;
3277 logicalHeightIsAuto = false;
3279 if (logicalHeightLength.isIntrinsic())
3280 resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding);
3282 resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight));
3285 if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3286 /*-----------------------------------------------------------------------*\
3287 * If none of the three are 'auto': If both 'margin-top' and 'margin-
3288 * bottom' are 'auto', solve the equation under the extra constraint that
3289 * the two margins get equal values. If one of 'margin-top' or 'margin-
3290 * bottom' is 'auto', solve the equation for that value. If the values
3291 * are over-constrained, ignore the value for 'bottom' and solve for that
3293 \*-----------------------------------------------------------------------*/
3294 // NOTE: It is not necessary to solve for 'bottom' in the over constrained
3295 // case because the value is not used for any further calculations.
3297 logicalHeightValue = resolvedLogicalHeight;
3298 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3300 const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight) + bordersPlusPadding);
3302 // Margins are now the only unknown
3303 if (marginBefore.isAuto() && marginAfter.isAuto()) {
3304 // Both margins auto, solve for equality
3305 // NOTE: This may result in negative values.
3306 computedValues.m_margins.m_before = availableSpace / 2; // split the difference
3307 computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
3308 } else if (marginBefore.isAuto()) {
3309 // Solve for top margin
3310 computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3311 computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
3312 } else if (marginAfter.isAuto()) {
3313 // Solve for bottom margin
3314 computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3315 computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
3317 // Over-constrained, (no need solve for bottom)
3318 computedValues.m_margins.m_before = valueForLength(marginBefore, containerRelativeLogicalWidth);
3319 computedValues.m_margins.m_after = valueForLength(marginAfter, containerRelativeLogicalWidth);
3322 /*--------------------------------------------------------------------*\
3323 * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3324 * to 0, and pick the one of the following six rules that applies.
3326 * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3327 * the height is based on the content, and solve for 'top'.
3329 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3330 * ------------------------------------------------------------------
3331 * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3332 * set 'top' to the static position, and solve for 'bottom'.
3333 * ------------------------------------------------------------------
3335 * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3336 * the height is based on the content, and solve for 'bottom'.
3337 * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3339 * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3340 * solve for 'height'.
3341 * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3342 * solve for 'bottom'.
3343 \*--------------------------------------------------------------------*/
3344 // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3345 // because the value is not used for any further calculations.
3347 // Calculate margins, 'auto' margins are ignored.
3348 computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerRelativeLogicalWidth);
3349 computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerRelativeLogicalWidth);
3351 const LayoutUnit availableSpace = containerLogicalHeight - (computedValues.m_margins.m_before + computedValues.m_margins.m_after + bordersPlusPadding);
3353 // Use rule/case that applies.
3354 if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3355 // RULE 1: (height is content based, solve of top)
3356 logicalHeightValue = contentLogicalHeight;
3357 logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
3358 } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
3359 // RULE 3: (height is content based, no need solve of bottom)
3360 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3361 logicalHeightValue = contentLogicalHeight;
3362 } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3363 // RULE 4: (solve of top)
3364 logicalHeightValue = resolvedLogicalHeight;
3365 logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight));
3366 } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3367 // RULE 5: (solve of height)
3368 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3369 logicalHeightValue = std::max<LayoutUnit>(0, availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight)));
3370 } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
3371 // RULE 6: (no need solve of bottom)
3372 logicalHeightValue = resolvedLogicalHeight;
3373 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3376 computedValues.m_extent = logicalHeightValue;
3378 // Use computed values to calculate the vertical position.
3379 computedValues.m_position = logicalTopValue + computedValues.m_margins.m_before;
3380 computeLogicalTopPositionedOffset(computedValues.m_position, this, logicalHeightValue, containerBlock, containerLogicalHeight);
3383 void RenderBox::computePositionedLogicalWidthReplaced(LogicalExtentComputedValues& computedValues) const
3385 // The following is based off of the W3C Working Draft from April 11, 2006 of
3386 // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
3387 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
3388 // (block-style-comments in this function correspond to text from the spec and
3389 // the numbers correspond to numbers in spec)
3391 // We don't use containingBlock(), since we may be positioned by an enclosing
3392 // relative positioned inline.
3393 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3395 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
3396 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3398 // To match WinIE, in quirks mode use the parent's 'direction' property
3399 // instead of the the container block's.
3400 TextDirection containerDirection = containerBlock->style()->direction();
3402 // Variables to solve.
3403 bool isHorizontal = isHorizontalWritingMode();
3404 Length logicalLeft = style()->logicalLeft();
3405 Length logicalRight = style()->logicalRight();
3406 Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3407 Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3408 LayoutUnit& marginLogicalLeftAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3409 LayoutUnit& marginLogicalRightAlias = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3411 /*-----------------------------------------------------------------------*\
3412 * 1. The used value of 'width' is determined as for inline replaced
3414 \*-----------------------------------------------------------------------*/
3415 // NOTE: This value of width is FINAL in that the min/max width calculations
3416 // are dealt with in computeReplacedWidth(). This means that the steps to produce
3417 // correct max/min in the non-replaced version, are not necessary.
3418 computedValues.m_extent = computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth();
3420 const LayoutUnit availableSpace = containerLogicalWidth - computedValues.m_extent;
3422 /*-----------------------------------------------------------------------*\
3423 * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
3424 * of the containing block is 'ltr', set 'left' to the static position;
3425 * else if 'direction' is 'rtl', set 'right' to the static position.
3426 \*-----------------------------------------------------------------------*/
3428 computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth);
3430 /*-----------------------------------------------------------------------*\
3431 * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
3432 * or 'margin-right' with '0'.
3433 \*-----------------------------------------------------------------------*/
3434 if (logicalLeft.isAuto() || logicalRight.isAuto()) {
3435 if (marginLogicalLeft.isAuto())
3436 marginLogicalLeft.setValue(Fixed, 0);
3437 if (marginLogicalRight.isAuto())
3438 marginLogicalRight.setValue(Fixed, 0);
3441 /*-----------------------------------------------------------------------*\
3442 * 4. If at this point both 'margin-left' and 'margin-right' are still
3443 * 'auto', solve the equation under the extra constraint that the two
3444 * margins must get equal values, unless this would make them negative,
3445 * in which case when the direction of the containing block is 'ltr'
3446 * ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
3447 * 'margin-right' ('margin-left').
3448 \*-----------------------------------------------------------------------*/
3449 LayoutUnit logicalLeftValue = 0;
3450 LayoutUnit logicalRightValue = 0;
3452 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3453 // 'left' and 'right' cannot be 'auto' due to step 3
3454 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3456 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3457 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3459 LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
3460 if (difference > 0) {
3461 marginLogicalLeftAlias = difference / 2; // split the difference
3462 marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
3464 // Use the containing block's direction rather than the parent block's
3465 // per CSS 2.1 reference test abspos-replaced-width-margin-000.
3466 if (containerDirection == LTR) {
3467 marginLogicalLeftAlias = 0;
3468 marginLogicalRightAlias = difference; // will be negative
3470 marginLogicalLeftAlias = difference; // will be negative
3471 marginLogicalRightAlias = 0;
3475 /*-----------------------------------------------------------------------*\
3476 * 5. If at this point there is an 'auto' left, solve the equation for
3478 \*-----------------------------------------------------------------------*/
3479 } else if (logicalLeft.isAuto()) {
3480 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3481 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3482 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3485 logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3486 } else if (logicalRight.isAuto()) {
3487 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3488 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3489 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3491 // Solve for 'right'
3492 logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3493 } else if (marginLogicalLeft.isAuto()) {
3494 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3495 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3496 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3498 // Solve for 'margin-left'
3499 marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
3500 } else if (marginLogicalRight.isAuto()) {
3501 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3502 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3503 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3505 // Solve for 'margin-right'
3506 marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
3508 // Nothing is 'auto', just calculate the values.
3509 marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3510 marginLogicalRightAlias = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3511 logicalRightValue = valueForLength(logicalRight, containerLogicalWidth);
3512 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3513 // If the containing block is right-to-left, then push the left position as far to the right as possible
3514 if (containerDirection == RTL) {
3515 int totalLogicalWidth = computedValues.m_extent + logicalLeftValue + logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias;
3516 logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
3520 /*-----------------------------------------------------------------------*\
3521 * 6. If at this point the values are over-constrained, ignore the value
3522 * for either 'left' (in case the 'direction' property of the
3523 * containing block is 'rtl') or 'right' (in case 'direction' is
3524 * 'ltr') and solve for that value.
3525 \*-----------------------------------------------------------------------*/
3526 // NOTE: Constraints imposed by the width of the containing block and its content have already been accounted for above.
3528 // FIXME: Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space, so that
3529 // can make the result here rather complicated to compute.
3531 // Use computed values to calculate the horizontal position.
3533 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3534 // positioned, inline containing block because right now, it is using the logical left position
3535 // of the first line box when really it should use the last line box. When
3536 // this is fixed elsewhere, this block should be removed.
3537 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3538 const RenderInline* flow = toRenderInline(containerBlock);
3539 InlineFlowBox* firstLine = flow->firstLineBox();
3540 InlineFlowBox* lastLine = flow->lastLineBox();
3541 if (firstLine && lastLine && firstLine != lastLine) {
3542 computedValues.m_position = logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
3547 LayoutUnit logicalLeftPos = logicalLeftValue + marginLogicalLeftAlias;
3548 computeLogicalLeftPositionedOffset(logicalLeftPos, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
3549 computedValues.m_position = logicalLeftPos;
3552 void RenderBox::computePositionedLogicalHeightReplaced(LogicalExtentComputedValues& computedValues) const
3554 // The following is based off of the W3C Working Draft from April 11, 2006 of
3555 // CSS 2.1: Section 10.6.5 "Absolutely positioned, replaced elements"
3556 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-height>
3557 // (block-style-comments in this function correspond to text from the spec and
3558 // the numbers correspond to numbers in spec)
3560 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3561 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3563 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3564 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, false);
3566 // Variables to solve.
3567 Length marginBefore = style()->marginBefore();
3568 Length marginAfter = style()->marginAfter();
3569 LayoutUnit& marginBeforeAlias = computedValues.m_margins.m_before;
3570 LayoutUnit& marginAfterAlias = computedValues.m_margins.m_after;
3572 Length logicalTop = style()->logicalTop();
3573 Length logicalBottom = style()->logicalBottom();
3575 /*-----------------------------------------------------------------------*\
3576 * 1. The used value of 'height' is determined as for inline replaced
3578 \*-----------------------------------------------------------------------*/
3579 // NOTE: This value of height is FINAL in that the min/max height calculations
3580 // are dealt with in computeReplacedHeight(). This means that the steps to produce
3581 // correct max/min in the non-replaced version, are not necessary.
3582 computedValues.m_extent = computeReplacedLogicalHeight() + borderAndPaddingLogicalHeight();
3583 const LayoutUnit availableSpace = containerLogicalHeight - computedValues.m_extent;
3585 /*-----------------------------------------------------------------------*\
3586 * 2. If both 'top' and 'bottom' have the value 'auto', replace 'top'
3587 * with the element's static position.
3588 \*-----------------------------------------------------------------------*/
3590 computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
3592 /*-----------------------------------------------------------------------*\
3593 * 3. If 'bottom' is 'auto', replace any 'auto' on 'margin-top' or
3594 * 'margin-bottom' with '0'.
3595 \*-----------------------------------------------------------------------*/
3596 // FIXME: The spec. says that this step should only be taken when bottom is
3597 // auto, but if only top is auto, this makes step 4 impossible.
3598 if (logicalTop.isAuto() || logicalBottom.isAuto()) {
3599 if (marginBefore.isAuto())
3600 marginBefore.setValue(Fixed, 0);
3601 if (marginAfter.isAuto())
3602 marginAfter.setValue(Fixed, 0);
3605 /*-----------------------------------------------------------------------*\
3606 * 4. If at this point both 'margin-top' and 'margin-bottom' are still
3607 * 'auto', solve the equation under the extra constraint that the two
3608 * margins must get equal values.
3609 \*-----------------------------------------------------------------------*/
3610 LayoutUnit logicalTopValue = 0;
3611 LayoutUnit logicalBottomValue = 0;
3613 if (marginBefore.isAuto() && marginAfter.isAuto()) {
3614 // 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
3615 ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
3617 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3618 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3620 LayoutUnit difference = availableSpace - (logicalTopValue + logicalBottomValue);
3621 // NOTE: This may result in negative values.
3622 marginBeforeAlias = difference / 2; // split the difference
3623 marginAfterAlias = difference - marginBeforeAlias; // account for odd valued differences
3625 /*-----------------------------------------------------------------------*\
3626 * 5. If at this point there is only one 'auto' left, solve the equation
3628 \*-----------------------------------------------------------------------*/
3629 } else if (logicalTop.isAuto()) {
3630 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3631 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3632 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3635 logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
3636 } else if (logicalBottom.isAuto()) {
3637 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3638 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3639 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3641 // Solve for 'bottom'
3642 // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3644 } else if (marginBefore.isAuto()) {
3645 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3646 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3647 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3649 // Solve for 'margin-top'
3650 marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
3651 } else if (marginAfter.isAuto()) {
3652 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3653 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3654 logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight);
3656 // Solve for 'margin-bottom'
3657 marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
3659 // Nothing is 'auto', just calculate the values.
3660 marginBeforeAlias = valueForLength(marginBefore, containerRelativeLogicalWidth);
3661 marginAfterAlias = valueForLength(marginAfter, containerRelativeLogicalWidth);
3662 logicalTopValue = valueForLength(logicalTop, containerLogicalHeight);
3663 // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3667 /*-----------------------------------------------------------------------*\
3668 * 6. If at this point the values are over-constrained, ignore the value
3669 * for 'bottom' and solve for that value.
3670 \*-----------------------------------------------------------------------*/
3671 // NOTE: It is not necessary to do this step because we don't end up using
3672 // the value of 'bottom' regardless of whether the values are over-constrained
3675 // Use computed values to calculate the vertical position.
3676 LayoutUnit logicalTopPos = logicalTopValue + marginBeforeAlias;
3677 computeLogicalTopPositionedOffset(logicalTopPos, this, computedValues.m_extent, containerBlock, containerLogicalHeight);
3678 computedValues.m_position = logicalTopPos;
3681 LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
3683 // VisiblePositions at offsets inside containers either a) refer to the positions before/after
3684 // those containers (tables and select elements) or b) refer to the position inside an empty block.
3685 // They never refer to children.
3686 // FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.
3688 LayoutRect rect(location(), LayoutSize(caretWidth, height()));
3689 bool ltr = box ? box->isLeftToRightDirection() : style()->isLeftToRightDirection();
3691 if ((!caretOffset) ^ ltr)
3692 rect.move(LayoutSize(width() - caretWidth, 0));
3695 RootInlineBox& rootBox = box->root();
3696 LayoutUnit top = rootBox.lineTop();
3698 rect.setHeight(rootBox.lineBottom() - top);
3701 // If height of box is smaller than font height, use the latter one,
3702 // otherwise the caret might become invisible.
3704 // Also, if the box is not a replaced element, always use the font height.
3705 // This prevents the "big caret" bug described in:
3706 // <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
3708 // FIXME: ignoring :first-line, missing good reason to take care of
3709 LayoutUnit fontHeight = style()->fontMetrics().height();
3710 if (fontHeight > rect.height() || (!isReplaced() && !isTable()))
3711 rect.setHeight(fontHeight);
3713 if (extraWidthToEndOfLine)
3714 *extraWidthToEndOfLine = x() + width() - rect.maxX();
3716 // Move to local coords
3717 rect.moveBy(-location());
3719 // FIXME: Border/padding should be added for all elements but this workaround
3720 // is needed because we use offsets inside an "atomic" element to represent
3721 // positions before and after the element in deprecated editing offsets.
3722 if (node() && !(editingIgnoresContent(node()) || isRenderedTableElement(node()))) {
3723 rect.setX(rect.x() + borderLeft() + paddingLeft());
3724 rect.setY(rect.y() + paddingTop() + borderTop());
3727 if (!isHorizontalWritingMode())
3728 return rect.transposedRect();
3733 PositionWithAffinity RenderBox::positionForPoint(const LayoutPoint& point)
3735 // no children...return this render object's element, if there is one, and offset 0
3736 RenderObject* firstChild = slowFirstChild();
3738 return createPositionWithAffinity(nonPseudoNode() ? firstPositionInOrBeforeNode(nonPseudoNode()) : Position());
3740 if (isTable() && nonPseudoNode()) {
3741 LayoutUnit right = contentWidth() + borderAndPaddingWidth();
3742 LayoutUnit bottom = contentHeight() + borderAndPaddingHeight();
3744 if (point.x() < 0 || point.x() > right || point.y() < 0 || point.y() > bottom) {
3745 if (point.x() <= right / 2)
3746 return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
3747 return createPositionWithAffinity(lastPositionInOrAfterNode(nonPseudoNode()));
3751 // Pass off to the closest child.
3752 LayoutUnit minDist = LayoutUnit::max();
3753 RenderBox* closestRenderer = 0;
3754 LayoutPoint adjustedPoint = point;
3756 adjustedPoint.moveBy(location());
3758 for (RenderObject* renderObject = firstChild; renderObject; renderObject = renderObject->nextSibling()) {
3759 if ((!renderObject->slowFirstChild() && !renderObject->isInline() && !renderObject->isRenderBlockFlow() )
3760 || renderObject->style()->visibility() != VISIBLE)
3763 if (!renderObject->isBox())
3766 RenderBox* renderer = toRenderBox(renderObject);
3768 LayoutUnit top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? LayoutUnit() : renderer->y());
3769 LayoutUnit bottom = top + renderer->contentHeight();
3770 LayoutUnit left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? LayoutUnit() : renderer->x());
3771 LayoutUnit right = left + renderer->contentWidth();
3773 if (point.x() <= right && point.x() >= left && point.y() <= top && point.y() >= bottom) {
3774 if (renderer->isTableRow())
3775 return renderer->positionForPoint(point + adjustedPoint - renderer->locationOffset());
3776 return renderer->positionForPoint(point - renderer->locationOffset());
3779 // Find the distance from (x, y) to the box. Split the space around the box into 8 pieces
3780 // and use a different compare depending on which piece (x, y) is in.
3782 if (point.x() > right) {
3783 if (point.y() < top)
3784 cmp = LayoutPoint(right, top);
3785 else if (point.y() > bottom)
3786 cmp = LayoutPoint(right, bottom);
3788 cmp = LayoutPoint(right, point.y());
3789 } else if (point.x() < left) {
3790 if (point.y() < top)
3791 cmp = LayoutPoint(left, top);
3792 else if (point.y() > bottom)
3793 cmp = LayoutPoint(left, bottom);
3795 cmp = LayoutPoint(left, point.y());
3797 if (point.y() < top)
3798 cmp = LayoutPoint(point.x(), top);
3800 cmp = LayoutPoint(point.x(), bottom);
3803 LayoutSize difference = cmp - point;
3805 LayoutUnit dist = difference.width() * difference.width() + difference.height() * difference.height();
3806 if (dist < minDist) {
3807 closestRenderer = renderer;
3812 if (closestRenderer)
3813 return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset());
3814 return createPositionWithAffinity(firstPositionInOrBeforeNode(nonPseudoNode()));
3817 bool RenderBox::shrinkToAvoidFloats() const
3819 // Floating objects don't shrink. Objects that don't avoid floats don't shrink. Marquees don't shrink.
3820 if ((isInline() && !isMarquee()) || !avoidsFloats() || isFloating())
3823 // Only auto width objects can possibly shrink to avoid floats.
3824 return style()->width().isAuto();
3827 static bool isReplacedElement(Node* node)
3829 // Checkboxes and radioboxes are not isReplaced() nor do they have their own renderer in which to override avoidFloats().
3830 return node && node->isElementNode() && toElement(node)->isFormControlElement();
3833 bool RenderBox::avoidsFloats() const
3835 return isReplaced() || isReplacedElement(node()) || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isFlexItemIncludingDeprecated();
3838 InvalidationReason RenderBox::getPaintInvalidationReason(const RenderLayerModelObject& paintInvalidationContainer,
3839 const LayoutRect& oldBounds, const LayoutPoint& oldLocation, const LayoutRect& newBounds, const LayoutPoint& newLocation)
3841 InvalidationReason invalidationReason = RenderBoxModelObject::getPaintInvalidationReason(paintInvalidationContainer, oldBounds, oldLocation, newBounds, newLocation);
3842 if (invalidationReason != InvalidationNone && invalidationReason != InvalidationIncremental)
3843 return invalidationReason;
3845 if (!style()->hasBackground() && !style()->hasBoxDecorations())
3846 return invalidationReason;
3848 LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
3849 LayoutSize newBorderBoxSize = size();
3851 if (oldBorderBoxSize == newBorderBoxSize)
3852 return invalidationReason;
3854 // FIXME: Implement correct incremental invalidation for visual overflowing effects.
3855 if (style()->hasVisualOverflowingEffect() || style()->hasAppearance() || style()->hasFilter())
3856 return InvalidationBorderBoxChange;
3858 if (style()->hasBorderRadius()) {
3859 // If a border-radius exists and width/height is smaller than radius width/height,
3860 // we need to fully invalidate to cover the changed radius.
3861 RoundedRect oldRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), oldBorderBoxSize));
3862 RoundedRect newRoundedRect = style()->getRoundedBorderFor(LayoutRect(LayoutPoint(0, 0), newBorderBoxSize));
3863 if (oldRoundedRect.radii() != newRoundedRect.radii())
3864 return InvalidationBorderBoxChange;
3867 if (oldBorderBoxSize.width() != newBorderBoxSize.width() && mustInvalidateBackgroundOrBorderPaintOnWidthChange())
3868 return InvalidationBorderBoxChange;
3869 if (oldBorderBoxSize.height() != newBorderBoxSize.height() && mustInvalidateBackgroundOrBorderPaintOnHeightChange())
3870 return InvalidationBorderBoxChange;
3872 return InvalidationIncremental;
3875 void RenderBox::incrementallyInvalidatePaint(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& oldBounds, const LayoutRect& newBounds, const LayoutPoint& positionFromPaintInvalidationBacking)
3877 RenderObject::incrementallyInvalidatePaint(paintInvalidationContainer, oldBounds, newBounds, positionFromPaintInvalidationBacking);
3879 bool hasBoxDecorations = style()->hasBoxDecorations();
3880 if (!style()->hasBackground() && !hasBoxDecorations)
3883 LayoutSize oldBorderBoxSize = computePreviousBorderBoxSize(oldBounds.size());
3884 LayoutSize newBorderBoxSize = size();
3886 // If border box size didn't change, RenderObject's incrementallyInvalidatePaint() is good.
3887 if (oldBorderBoxSize == newBorderBoxSize)
3890 // If size of the paint invalidation rect equals to size of border box, RenderObject::incrementallyInvalidatePaint()
3891 // is good for boxes having background without box decorations.
3892 ASSERT(oldBounds.location() == newBounds.location()); // Otherwise we won't do incremental invalidation.
3893 if (!hasBoxDecorations
3894 && positionFromPaintInvalidationBacking == newBounds.location()
3895 && oldBorderBoxSize == oldBounds.size()
3896 && newBorderBoxSize == newBounds.size())
3899 // Invalidate the right delta part and the right border of the old or new box which has smaller width.
3900 LayoutUnit deltaWidth = absoluteValue(oldBorderBoxSize.width() - newBorderBoxSize.width());
3902 LayoutUnit smallerWidth = std::min(oldBorderBoxSize.width(), newBorderBoxSize.width());
3903 LayoutUnit borderTopRightRadiusWidth = valueForLength(style()->borderTopRightRadius().width(), smallerWidth);
3904 LayoutUnit borderBottomRightRadiusWidth = valueForLength(style()->borderBottomRightRadius().width(), smallerWidth);
3905 LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight(), std::max(borderTopRightRadiusWidth, borderBottomRightRadiusWidth));
3906 LayoutRect rightDeltaRect(positionFromPaintInvalidationBacking.x() + smallerWidth - borderWidth,
3907 positionFromPaintInvalidationBacking.y(),
3908 deltaWidth + borderWidth,
3909 std::max(oldBorderBoxSize.height(), newBorderBoxSize.height()));
3910 invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, rightDeltaRect, oldBounds, newBounds);
3913 // Invalidate the bottom delta part and the bottom border of the old or new box which has smaller height.
3914 LayoutUnit deltaHeight = absoluteValue(oldBorderBoxSize.height() - newBorderBoxSize.height());
3916 LayoutUnit smallerHeight = std::min(oldBorderBoxSize.height(), newBorderBoxSize.height());
3917 LayoutUnit borderBottomLeftRadiusHeight = valueForLength(style()->borderBottomLeftRadius().height(), smallerHeight);
3918 LayoutUnit borderBottomRightRadiusHeight = valueForLength(style()->borderBottomRightRadius().height(), smallerHeight);
3919 LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom(), std::max(borderBottomLeftRadiusHeight, borderBottomRightRadiusHeight));
3920 LayoutRect bottomDeltaRect(positionFromPaintInvalidationBacking.x(),
3921 positionFromPaintInvalidationBacking.y() + smallerHeight - borderHeight,
3922 std::max(oldBorderBoxSize.width(), newBorderBoxSize.width()),
3923 deltaHeight + borderHeight);
3924 invalidatePaintRectClippedByOldAndNewBounds(paintInvalidationContainer, bottomDeltaRect, oldBounds, newBounds);
3928 void RenderBox::invalidatePaintRectClippedByOldAndNewBounds(const RenderLayerModelObject& paintInvalidationContainer, const LayoutRect& rect, const LayoutRect& oldBounds, const LayoutRect& newBounds)
3932 LayoutRect rectClippedByOldBounds = intersection(rect, oldBounds);
3933 LayoutRect rectClippedByNewBounds = intersection(rect, newBounds);
3934 // Invalidate only once if the clipped rects equal.
3935 if (rectClippedByOldBounds == rectClippedByNewBounds) {
3936 invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, InvalidationIncremental);
3939 // Invalidate the bigger one if one contains another. Otherwise invalidate both.
3940 if (!rectClippedByNewBounds.contains(rectClippedByOldBounds))
3941 invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByOldBounds, InvalidationIncremental);
3942 if (!rectClippedByOldBounds.contains(rectClippedByNewBounds))
3943 invalidatePaintUsingContainer(&paintInvalidationContainer, rectClippedByNewBounds, InvalidationIncremental);
3946 void RenderBox::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutScope)
3948 ASSERT(!needsLayout());
3949 // If fragmentation height has changed, we need to lay out. No need to enter the renderer if it
3950 // is childless, though.
3951 if (view()->layoutState()->pageLogicalHeightChanged() && slowFirstChild())
3952 layoutScope.setChildNeedsLayout(this);
3955 void RenderBox::addVisualEffectOverflow()
3957 if (!style()->hasVisualOverflowingEffect())
3960 // Add in the final overflow with shadows, outsets and outline combined.
3961 LayoutRect visualEffectOverflow = borderBoxRect();
3962 visualEffectOverflow.expand(computeVisualEffectOverflowExtent());
3963 addVisualOverflow(visualEffectOverflow);
3966 LayoutBoxExtent RenderBox::computeVisualEffectOverflowExtent() const
3968 ASSERT(style()->hasVisualOverflowingEffect());
3975 if (style()->boxShadow()) {
3976 style()->getBoxShadowExtent(top, right, bottom, left);
3978 // Box shadow extent's top and left are negative when extend to left and top direction, respectively.
3979 // Negate to make them positive.
3984 if (style()->hasBorderImageOutsets()) {
3985 LayoutBoxExtent borderOutsets = style()->borderImageOutsets();
3986 top = std::max(top, borderOutsets.top());
3987 right = std::max(right, borderOutsets.right());
3988 bottom = std::max(bottom, borderOutsets.bottom());
3989 left = std::max(left, borderOutsets.left());
3992 if (style()->hasOutline()) {
3993 if (style()->outlineStyleIsAuto()) {
3994 // The result focus ring rects are in coordinates of this object's border box.
3995 Vector<LayoutRect> focusRingRects;
3996 addFocusRingRects(focusRingRects, LayoutPoint(), this);
3997 LayoutRect rect = unionRect(focusRingRects);
3999 int outlineSize = GraphicsContext::focusRingOutsetExtent(style()->outlineOffset(), style()->outlineWidth());
4000 top = std::max(top, -rect.y() + outlineSize);
4001 right = std::max(right, rect.maxX() - width() + outlineSize);
4002 bottom = std::max(bottom, rect.maxY() - height() + outlineSize);
4003 left = std::max(left, -rect.x() + outlineSize);
4005 LayoutUnit outlineSize = style()->outlineSize();
4006 top = std::max(top, outlineSize);
4007 right = std::max(right, outlineSize);
4008 bottom = std::max(bottom, outlineSize);
4009 left = std::max(left, outlineSize);
4013 return LayoutBoxExtent(top, right, bottom, left);
4016 void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta)
4018 // Never allow flow threads to propagate overflow up to a parent.
4019 if (child->isRenderFlowThread())
4022 // Only propagate layout overflow from the child if the child isn't clipping its overflow. If it is, then
4023 // its overflow is internal to it, and we don't care about it. layoutOverflowRectForPropagation takes care of this
4024 // and just propagates the border box rect instead.
4025 LayoutRect childLayoutOverflowRect = child->layoutOverflowRectForPropagation(style());
4026 childLayoutOverflowRect.move(delta);
4027 addLayoutOverflow(childLayoutOverflowRect);
4029 // Add in visual overflow from the child. Even if the child clips its overflow, it may still
4030 // have visual overflow of its own set from box shadows or reflections. It is unnecessary to propagate this
4031 // overflow if we are clipping our own overflow.
4032 if (child->hasSelfPaintingLayer())
4034 LayoutRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
4035 childVisualOverflowRect.move(delta);
4036 addContentsVisualOverflow(childVisualOverflowRect);
4039 void RenderBox::addLayoutOverflow(const LayoutRect& rect)
4041 LayoutRect clientBox = noOverflowRect();
4042 if (clientBox.contains(rect) || rect.isEmpty())
4045 // For overflow clip objects, we don't want to propagate overflow into unreachable areas.
4046 LayoutRect overflowRect(rect);
4047 if (hasOverflowClip() || isRenderView()) {
4048 // Overflow is in the block's coordinate space and thus is flipped for horizontal-bt and vertical-rl
4049 // writing modes. At this stage that is actually a simplification, since we can treat horizontal-tb/bt as the same
4050 // and vertical-lr/rl as the same.
4051 bool hasTopOverflow = !style()->isLeftToRightDirection() && !isHorizontalWritingMode();
4052 bool hasLeftOverflow = !style()->isLeftToRightDirection() && isHorizontalWritingMode();
4053 if (isFlexibleBox() && style()->isReverseFlexDirection()) {
4054 RenderFlexibleBox* flexibleBox = toRenderFlexibleBox(this);
4055 if (flexibleBox->isHorizontalFlow())
4056 hasLeftOverflow = true;
4058 hasTopOverflow = true;
4061 if (!hasTopOverflow)
4062 overflowRect.shiftYEdgeTo(std::max(overflowRect.y(), clientBox.y()));
4064 overflowRect.shiftMaxYEdgeTo(std::min(overflowRect.maxY(), clientBox.maxY()));
4065 if (!hasLeftOverflow)
4066 overflowRect.shiftXEdgeTo(std::max(overflowRect.x(), clientBox.x()));
4068 overflowRect.shiftMaxXEdgeTo(std::min(overflowRect.maxX(), clientBox.maxX()));
4070 // Now re-test with the adjusted rectangle and see if it has become unreachable or fully
4072 if (clientBox.contains(overflowRect) || overflowRect.isEmpty())
4077 m_overflow = adoptPtr(new RenderOverflow(clientBox, borderBoxRect()));
4079 m_overflow->addLayoutOverflow(overflowRect);
4082 void RenderBox::addVisualOverflow(const LayoutRect& rect)
4084 LayoutRect borderBox = borderBoxRect();
4085 if (borderBox.contains(rect) || rect.isEmpty())
4089 m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBox));
4091 m_overflow->addVisualOverflow(rect);
4094 void RenderBox::addContentsVisualOverflow(const LayoutRect& rect)
4096 if (!hasOverflowClip()) {
4097 addVisualOverflow(rect);
4102 m_overflow = adoptPtr(new RenderOverflow(noOverflowRect(), borderBoxRect()));
4103 m_overflow->addContentsVisualOverflow(rect);
4106 void RenderBox::clearLayoutOverflow()
4111 if (!hasVisualOverflow() && contentsVisualOverflowRect().isEmpty()) {
4112 clearAllOverflows();
4116 m_overflow->setLayoutOverflow(noOverflowRect());
4119 inline static bool percentageLogicalHeightIsResolvable(const RenderBox* box)
4121 return RenderBox::percentageLogicalHeightIsResolvableFromBlock(box->containingBlock(), box->isOutOfFlowPositioned());
4124 bool RenderBox::percentageLogicalHeightIsResolvableFromBlock(const RenderBlock* containingBlock, bool isOutOfFlowPositioned)
4126 // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
4127 // block that may have a specified height and then use it. In strict mode, this violates the
4128 // specification, which states that percentage heights just revert to auto if the containing
4129 // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
4130 // only at explicit containers.
4131 const RenderBlock* cb = containingBlock;
4132 bool inQuirksMode = cb->document().inQuirksMode();
4133 while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style()->logicalHeight().isAuto()) {
4134 if (!inQuirksMode && !cb->isAnonymousBlock())
4136 cb = cb->containingBlock();
4139 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
4140 // explicitly specified that can be used for any percentage computations.
4141 // FIXME: We can't just check top/bottom here.
4142 // https://bugs.webkit.org/show_bug.cgi?id=46500
4143 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
4145 // Table cells violate what the CSS spec says to do with heights. Basically we
4146 // don't care if the cell specified a height or not. We just always make ourselves
4147 // be a percentage of the cell's current content height.
4148 if (cb->isTableCell())
4151 // Otherwise we only use our percentage height if our containing block had a specified
4153 if (cb->style()->logicalHeight().isFixed())
4155 if (cb->style()->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight)
4156 return percentageLogicalHeightIsResolvableFromBlock(cb->containingBlock(), cb->isOutOfFlowPositioned());
4157 if (cb->isRenderView() || inQuirksMode || isOutOfFlowPositionedWithSpecifiedHeight)
4159 if (cb->isDocumentElement() && isOutOfFlowPositioned) {
4160 // Match the positioned objects behavior, which is that positioned objects will fill their viewport
4161 // always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
4168 bool RenderBox::hasUnsplittableScrollingOverflow() const
4170 // We will paginate as long as we don't scroll overflow in the pagination direction.
4171 bool isHorizontal = isHorizontalWritingMode();
4172 if ((isHorizontal && !scrollsOverflowY()) || (!isHorizontal && !scrollsOverflowX()))
4175 // We do have overflow. We'll still be willing to paginate as long as the block
4176 // has auto logical height, auto or undefined max-logical-height and a zero or auto min-logical-height.
4177 // Note this is just a heuristic, and it's still possible to have overflow under these
4178 // conditions, but it should work out to be good enough for common cases. Paginating overflow
4179 // with scrollbars present is not the end of the world and is what we used to do in the old model anyway.
4180 return !style()->logicalHeight().isIntrinsicOrAuto()
4181 || (!style()->logicalMaxHeight().isIntrinsicOrAuto() && !style()->logicalMaxHeight().isMaxSizeNone() && (!style()->logicalMaxHeight().isPercent() || percentageLogicalHeightIsResolvable(this)))
4182 || (!style()->logicalMinHeight().isIntrinsicOrAuto() && style()->logicalMinHeight().isPositive() && (!style()->logicalMinHeight().isPercent() || percentageLogicalHeightIsResolvable(this)));
4185 bool RenderBox::isUnsplittableForPagination() const
4187 return isReplaced() || hasUnsplittableScrollingOverflow() || (parent() && isWritingModeRoot());
4190 LayoutUnit RenderBox::lineHeight(bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
4193 return direction == HorizontalLine ? m_marginBox.top() + height() + m_marginBox.bottom() : m_marginBox.right() + width() + m_marginBox.left();
4197 int RenderBox::baselinePosition(FontBaseline baselineType, bool /*firstLine*/, LineDirectionMode direction, LinePositionMode linePositionMode) const
4199 ASSERT(linePositionMode == PositionOnContainingLine);
4201 int result = direction == HorizontalLine ? m_marginBox.top() + height() + m_marginBox.bottom() : m_marginBox.right() + width() + m_marginBox.left();
4202 if (baselineType == AlphabeticBaseline)
4204 return result - result / 2;
4210 RenderLayer* RenderBox::enclosingFloatPaintingLayer() const
4212 const RenderObject* curr = this;
4214 RenderLayer* layer = curr->hasLayer() && curr->isBox() ? toRenderBox(curr)->layer() : 0;
4215 if (layer && layer->isSelfPaintingLayer())
4217 curr = curr->parent();
4222 LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* parentStyle) const
4224 LayoutRect rect = visualOverflowRectForPropagation(parentStyle);
4225 if (!parentStyle->isHorizontalWritingMode())
4226 return rect.transposedRect();
4230 LayoutRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) const
4232 // If the writing modes of the child and parent match, then we don't have to
4233 // do anything fancy. Just return the result.
4234 LayoutRect rect = visualOverflowRect();
4235 if (parentStyle->writingMode() == style()->writingMode())
4238 // We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
4239 // in a particular axis, then we have to flip the rect along that axis.
4240 if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
4241 rect.setX(width() - rect.maxX());
4242 else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
4243 rect.setY(height() - rect.maxY());
4248 LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* parentStyle) const
4250 LayoutRect rect = layoutOverflowRectForPropagation(parentStyle);
4251 if (!parentStyle->isHorizontalWritingMode())
4252 return rect.transposedRect();
4256 LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) const
4258 // Only propagate interior layout overflow if we don't clip it.
4259 LayoutRect rect = borderBoxRect();
4260 // We want to include the margin, but only when it adds height. Quirky margins don't contribute height
4261 // nor do the margins of self-collapsing blocks.
4262 if (!style()->hasMarginAfterQuirk() && !isSelfCollapsingBlock())
4263 rect.expand(isHorizontalWritingMode() ? LayoutSize(LayoutUnit(), marginAfter()) : LayoutSize(marginAfter(), LayoutUnit()));
4265 if (!hasOverflowClip())
4266 rect.unite(layoutOverflowRect());
4268 bool hasTransform = hasLayer() && layer()->transform();
4269 if (isRelPositioned() || hasTransform) {
4270 // If we are relatively positioned or if we have a transform, then we have to convert
4271 // this rectangle into physical coordinates, apply relative positioning and transforms
4272 // to it, and then convert it back.
4273 flipForWritingMode(rect);
4276 rect = layer()->currentTransform().mapRect(rect);
4278 if (isRelPositioned())
4279 rect.move(offsetForInFlowPosition());
4281 // Now we need to flip back.
4282 flipForWritingMode(rect);
4285 // If the writing modes of the child and parent match, then we don't have to
4286 // do anything fancy. Just return the result.
4287 if (parentStyle->writingMode() == style()->writingMode())
4290 // We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
4291 // in a particular axis, then we have to flip the rect along that axis.
4292 if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
4293 rect.setX(width() - rect.maxX());
4294 else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
4295 rect.setY(height() - rect.maxY());
4300 LayoutRect RenderBox::noOverflowRect() const
4302 // Because of the special coordinate system used for overflow rectangles and many other
4303 // rectangles (not quite logical, not quite physical), we need to flip the block progression
4304 // coordinate in vertical-rl and horizontal-bt writing modes. In other words, the rectangle
4305 // returned is physical, except for the block direction progression coordinate (y in horizontal
4306 // writing modes, x in vertical writing modes), which is always "logical top". Apart from the
4307 // flipping, this method does the same as clientBoxRect().
4309 const int scrollBarWidth = verticalScrollbarWidth();
4310 const int scrollBarHeight = horizontalScrollbarHeight();
4311 LayoutUnit left = borderLeft() + (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? scrollBarWidth : 0);
4312 LayoutUnit top = borderTop();
4313 LayoutUnit right = borderRight();
4314 LayoutUnit bottom = borderBottom();
4315 LayoutRect rect(left, top, width() - left - right, height() - top - bottom);
4316 flipForWritingMode(rect);
4317 // Subtract space occupied by scrollbars. Order is important here: first flip, then subtract
4318 // scrollbars. This may seem backwards and weird, since one would think that a horizontal
4319 // scrollbar at the physical bottom in horizontal-bt ought to be at the logical top (physical
4320 // bottom), between the logical top (physical bottom) border and the logical top (physical
4321 // bottom) padding. But this is how the rest of the code expects us to behave. This is highly
4322 // related to https://bugs.webkit.org/show_bug.cgi?id=76129
4323 // FIXME: when the above mentioned bug is fixed, it should hopefully be possible to call
4324 // clientBoxRect() or paddingBoxRect() in this method, rather than fiddling with the edges on
4326 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
4327 rect.contract(0, scrollBarHeight);
4329 rect.contract(scrollBarWidth, scrollBarHeight);
4333 LayoutUnit RenderBox::offsetLeft() const
4335 return adjustedPositionRelativeToOffsetParent(topLeftLocation()).x();
4338 LayoutUnit RenderBox::offsetTop() const
4340 return adjustedPositionRelativeToOffsetParent(topLeftLocation()).y();
4343 LayoutPoint RenderBox::flipForWritingModeForChild(const RenderBox* child, const LayoutPoint& point) const
4345 if (!style()->isFlippedBlocksWritingMode())
4348 // The child is going to add in its x() and y(), so we have to make sure it ends up in
4350 if (isHorizontalWritingMode())
4351 return LayoutPoint(point.x(), point.y() + height() - child->height() - (2 * child->y()));
4352 return LayoutPoint(point.x() + width() - child->width() - (2 * child->x()), point.y());
4355 void RenderBox::flipForWritingMode(LayoutRect& rect) const
4357 if (!style()->isFlippedBlocksWritingMode())
4360 if (isHorizontalWritingMode())
4361 rect.setY(height() - rect.maxY());
4363 rect.setX(width() - rect.maxX());
4366 LayoutUnit RenderBox::flipForWritingMode(LayoutUnit position) const
4368 if (!style()->isFlippedBlocksWritingMode())
4370 return logicalHeight() - position;
4373 LayoutPoint RenderBox::flipForWritingMode(const LayoutPoint& position) const
4375 if (!style()->isFlippedBlocksWritingMode())
4377 return isHorizontalWritingMode() ? LayoutPoint(position.x(), height() - position.y()) : LayoutPoint(width() - position.x(), position.y());
4380 LayoutPoint RenderBox::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
4382 if (!hasColumns() || !style()->isFlippedBlocksWritingMode())
4383 return flipForWritingMode(point);
4384 return toRenderBlock(this)->flipForWritingModeIncludingColumns(point);
4387 LayoutSize RenderBox::flipForWritingMode(const LayoutSize& offset) const
4389 if (!style()->isFlippedBlocksWritingMode())
4391 return isHorizontalWritingMode() ? LayoutSize(offset.width(), height() - offset.height()) : LayoutSize(width() - offset.width(), offset.height());
4394 FloatPoint RenderBox::flipForWritingMode(const FloatPoint& position) const
4396 if (!style()->isFlippedBlocksWritingMode())
4398 return isHorizontalWritingMode() ? FloatPoint(position.x(), height() - position.y()) : FloatPoint(width() - position.x(), position.y());
4401 void RenderBox::flipForWritingMode(FloatRect& rect) const
4403 if (!style()->isFlippedBlocksWritingMode())
4406 if (isHorizontalWritingMode())
4407 rect.setY(height() - rect.maxY());
4409 rect.setX(width() - rect.maxX());
4412 LayoutPoint RenderBox::topLeftLocation() const
4414 RenderBlock* containerBlock = containingBlock();
4415 if (!containerBlock || containerBlock == this)
4417 return containerBlock->flipForWritingModeForChild(this, location());
4420 LayoutSize RenderBox::topLeftLocationOffset() const
4422 RenderBlock* containerBlock = containingBlock();
4423 if (!containerBlock || containerBlock == this)
4424 return locationOffset();
4426 LayoutRect rect(frameRect());
4427 containerBlock->flipForWritingMode(rect); // FIXME: This is wrong if we are an absolutely positioned object enclosed by a relative-positioned inline.
4428 return LayoutSize(rect.x(), rect.y());
4431 bool RenderBox::hasRelativeLogicalHeight() const
4433 return style()->logicalHeight().isPercent()
4434 || style()->logicalMinHeight().isPercent()
4435 || style()->logicalMaxHeight().isPercent();
4438 static void markBoxForRelayoutAfterSplit(RenderBox* box)
4440 // FIXME: The table code should handle that automatically. If not,
4441 // we should fix it and remove the table part checks.
4442 if (box->isTable()) {
4443 // Because we may have added some sections with already computed column structures, we need to
4444 // sync the table structure with them now. This avoids crashes when adding new cells to the table.
4445 toRenderTable(box)->forceSectionsRecalc();
4446 } else if (box->isTableSection())
4447 toRenderTableSection(box)->setNeedsCellRecalc();
4449 box->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
4452 RenderObject* RenderBox::splitAnonymousBoxesAroundChild(RenderObject* beforeChild)
4454 bool didSplitParentAnonymousBoxes = false;
4456 while (beforeChild->parent() != this) {
4457 RenderBox* boxToSplit = toRenderBox(beforeChild->parent());
4458 if (boxToSplit->slowFirstChild() != beforeChild && boxToSplit->isAnonymous()) {
4459 didSplitParentAnonymousBoxes = true;
4461 // We have to split the parent box into two boxes and move children
4462 // from |beforeChild| to end into the new post box.
4463 RenderBox* postBox = boxToSplit->createAnonymousBoxWithSameTypeAs(this);
4464 postBox->setChildrenInline(boxToSplit->childrenInline());
4465 RenderBox* parentBox = toRenderBox(boxToSplit->parent());
4466 // We need to invalidate the |parentBox| before inserting the new node
4467 // so that the table paint invalidation logic knows the structure is dirty.
4468 // See for example RenderTableCell:clippedOverflowRectForPaintInvalidation.
4469 markBoxForRelayoutAfterSplit(parentBox);
4470 parentBox->virtualChildren()->insertChildNode(parentBox, postBox, boxToSplit->nextSibling());
4471 boxToSplit->moveChildrenTo(postBox, beforeChild, 0, true);
4473 markBoxForRelayoutAfterSplit(boxToSplit);
4474 markBoxForRelayoutAfterSplit(postBox);
4476 beforeChild = postBox;
4478 beforeChild = boxToSplit;
4481 if (didSplitParentAnonymousBoxes)
4482 markBoxForRelayoutAfterSplit(this);
4484 ASSERT(beforeChild->parent() == this);
4488 LayoutUnit RenderBox::offsetFromLogicalTopOfFirstPage() const
4490 LayoutState* layoutState = view()->layoutState();
4491 if (layoutState && !layoutState->isPaginated())
4494 if (!layoutState && !flowThreadContainingBlock())
4497 RenderBlock* containerBlock = containingBlock();
4498 return containerBlock->offsetFromLogicalTopOfFirstPage() + logicalTop();
4501 void RenderBox::savePreviousBorderBoxSizeIfNeeded()
4503 // If m_rareData is already created, always save.
4505 LayoutSize paintInvalidationSize = previousPaintInvalidationRect().size();
4507 // Don't save old border box size if the paint rect is empty because we'll
4508 // full invalidate once the paint rect becomes non-empty.
4509 if (paintInvalidationSize.isEmpty())
4512 // Don't save old border box size if we can use size of the old paint rect
4513 // as the old border box size in the next invalidation.
4514 if (paintInvalidationSize == size())
4517 // We need the old border box size only when the box has background or box decorations.
4518 if (!style()->hasBackground() && !style()->hasBoxDecorations())
4522 ensureRareData().m_previousBorderBoxSize = size();
4525 LayoutSize RenderBox::computePreviousBorderBoxSize(const LayoutSize& previousBoundsSize) const
4527 // PreviousBorderBoxSize is only valid when there is background or box decorations.
4528 ASSERT(style()->hasBackground() || style()->hasBoxDecorations());
4530 if (m_rareData && m_rareData->m_previousBorderBoxSize.width() != -1)
4531 return m_rareData->m_previousBorderBoxSize;
4533 // We didn't save the old border box size because it was the same as the size of oldBounds.
4534 return previousBoundsSize;
4537 } // namespace blink