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.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
26 #include "RenderBox.h"
29 #include "ChromeClient.h"
31 #include "FloatQuad.h"
33 #include "FrameView.h"
34 #include "GraphicsContext.h"
35 #include "HTMLElement.h"
36 #include "HTMLFrameOwnerElement.h"
37 #include "HTMLInputElement.h"
38 #include "HTMLNames.h"
39 #include "HTMLTextAreaElement.h"
40 #include "HitTestResult.h"
42 #include "PaintInfo.h"
43 #include "RenderArena.h"
44 #include "RenderBoxRegionInfo.h"
45 #include "RenderFlexibleBox.h"
46 #include "RenderFlowThread.h"
47 #include "RenderGeometryMap.h"
48 #include "RenderInline.h"
49 #include "RenderLayer.h"
50 #include "RenderRegion.h"
51 #include "RenderTableCell.h"
52 #include "RenderTheme.h"
53 #include "RenderView.h"
54 #include "TransformState.h"
55 #include "htmlediting.h"
58 #include <wtf/StackStats.h>
60 #if USE(ACCELERATED_COMPOSITING)
61 #include "RenderLayerCompositor.h"
68 using namespace HTMLNames;
70 // Used by flexible boxes when flexing this element and by table cells.
71 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
72 static OverrideSizeMap* gOverrideHeightMap = 0;
73 static OverrideSizeMap* gOverrideWidthMap = 0;
75 // Used by grid elements to properly size their grid items.
76 static OverrideSizeMap* gOverrideContainingBlockLogicalHeightMap = 0;
77 static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0;
80 // Size of border belt for autoscroll. When mouse pointer in border belt,
81 // autoscroll is started.
82 static const int autoscrollBeltSize = 20;
83 static const unsigned backgroundObscurationTestMaxDepth = 4;
85 bool RenderBox::s_hadOverflowClip = false;
87 static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
89 ASSERT(bodyElementRenderer->isBody());
90 // The <body> only paints its background if the root element has defined a background independent of the body,
91 // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
92 RenderObject* documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
93 return documentElementRenderer
94 && !documentElementRenderer->hasBackground()
95 && (documentElementRenderer == bodyElementRenderer->parent());
98 RenderBox::RenderBox(Element* element, unsigned baseTypeFlags)
99 : RenderBoxModelObject(element, baseTypeFlags)
100 , m_minPreferredLogicalWidth(-1)
101 , m_maxPreferredLogicalWidth(-1)
102 , m_inlineBoxWrapper(0)
107 RenderBox::~RenderBox()
111 RenderRegion* RenderBox::clampToStartAndEndRegions(RenderRegion* region) const
113 RenderFlowThread* flowThread = flowThreadContainingBlock();
115 ASSERT(isRenderView() || (region && flowThread));
119 // We need to clamp to the block, since we want any lines or blocks that overflow out of the
120 // logical top or logical bottom of the block to size as though the border box in the first and
121 // last regions extended infinitely. Otherwise the lines are going to size according to the regions
122 // they overflow into, which makes no sense when this block doesn't exist in |region| at all.
123 RenderRegion* startRegion = 0;
124 RenderRegion* endRegion = 0;
125 flowThread->getRegionRangeForBox(this, startRegion, endRegion);
127 if (startRegion && region->logicalTopForFlowThreadContent() < startRegion->logicalTopForFlowThreadContent())
129 if (endRegion && region->logicalTopForFlowThreadContent() > endRegion->logicalTopForFlowThreadContent())
135 LayoutRect RenderBox::clientBoxRectInRegion(RenderRegion* region) const
138 return clientBoxRect();
140 LayoutRect clientBox = borderBoxRectInRegion(region);
141 clientBox.setLocation(clientBox.location() + LayoutSize(borderLeft(), borderTop()));
142 clientBox.setSize(clientBox.size() - LayoutSize(borderLeft() + borderRight() + verticalScrollbarWidth(), borderTop() + borderBottom() + horizontalScrollbarHeight()));
147 LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
150 return borderBoxRect();
152 RenderFlowThread* flowThread = flowThreadContainingBlock();
154 return borderBoxRect();
156 RenderRegion* startRegion = 0;
157 RenderRegion* endRegion = 0;
158 flowThread->getRegionRangeForBox(this, startRegion, endRegion);
160 // FIXME: In a perfect world this condition should never happen.
161 if (!startRegion || !endRegion)
162 return borderBoxRect();
164 // FIXME: Once overflow is implemented this assertion needs to be enabled. Right now the overflow content is painted
165 // in regions outside the box range so the assert is disabled.
166 // ASSERT(clampToStartAndEndRegions(region) == region);
168 // FIXME: Remove once boxes are painted inside their region range.
169 region = clampToStartAndEndRegions(region);
171 // Compute the logical width and placement in this region.
172 RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
174 return borderBoxRect();
176 // We have cached insets.
177 LayoutUnit logicalWidth = boxInfo->logicalWidth();
178 LayoutUnit logicalLeft = boxInfo->logicalLeft();
180 // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
181 // FIXME: Doesn't work right with perpendicular writing modes.
182 const RenderBlock* currentBox = containingBlock();
183 RenderBoxRegionInfo* currentBoxInfo = currentBox->renderBoxRegionInfo(region);
184 while (currentBoxInfo && currentBoxInfo->isShifted()) {
185 if (currentBox->style()->direction() == LTR)
186 logicalLeft += currentBoxInfo->logicalLeft();
188 logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
189 currentBox = currentBox->containingBlock();
190 region = currentBox->clampToStartAndEndRegions(region);
191 currentBoxInfo = currentBox->renderBoxRegionInfo(region);
194 if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
197 if (isHorizontalWritingMode())
198 return LayoutRect(logicalLeft, 0, logicalWidth, height());
199 return LayoutRect(0, logicalLeft, width(), logicalWidth);
202 void RenderBox::clearRenderBoxRegionInfo()
204 if (isRenderFlowThread())
207 RenderFlowThread* flowThread = flowThreadContainingBlock();
209 flowThread->removeRenderBoxRegionInfo(this);
212 void RenderBox::willBeDestroyed()
215 clearContainingBlockOverrideSize();
217 RenderBlock::removePercentHeightDescendantIfNeeded(this);
219 #if ENABLE(CSS_SHAPES)
220 ShapeOutsideInfo::removeInfo(this);
223 RenderBoxModelObject::willBeDestroyed();
226 RenderBlockFlow* RenderBox::outermostBlockContainingFloatingObject()
228 ASSERT(isFloating());
229 RenderBlockFlow* parentBlock = 0;
230 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
231 if (curr->isRenderBlockFlow()) {
232 RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
233 if (!parentBlock || currBlock->containsFloat(this))
234 parentBlock = currBlock;
240 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
242 ASSERT(isFloatingOrOutOfFlowPositioned());
244 if (documentBeingDestroyed())
248 if (RenderBlockFlow* parentBlock = outermostBlockContainingFloatingObject()) {
249 parentBlock->markSiblingsWithFloatsForLayout(this);
250 parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
254 if (isOutOfFlowPositioned())
255 RenderBlock::removePositionedObject(this);
258 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
260 s_hadOverflowClip = hasOverflowClip();
262 RenderStyle* oldStyle = style();
264 // The background of the root element or the body element could propagate up to
265 // the canvas. Issue full repaint, when our style changes substantially.
266 if (diff >= StyleDifferenceRepaint && (isRoot() || isBody())) {
267 view().repaintRootContents();
268 #if USE(ACCELERATED_COMPOSITING)
269 if (oldStyle->hasEntirelyFixedBackground() != newStyle->hasEntirelyFixedBackground())
270 view().compositor().rootFixedBackgroundsChanged();
274 // When a layout hint happens and an object's position style changes, we have to do a layout
275 // to dirty the render tree using the old position value now.
276 if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle->position()) {
277 markContainingBlocksForLayout();
278 if (oldStyle->position() == StaticPosition)
280 else if (newStyle->hasOutOfFlowPosition())
281 parent()->setChildNeedsLayout();
282 if (isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
283 removeFloatingOrPositionedChildFromBlockLists();
285 } else if (newStyle && isBody())
286 view().repaintRootContents();
288 RenderBoxModelObject::styleWillChange(diff, newStyle);
291 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
293 // Horizontal writing mode definition is updated in RenderBoxModelObject::updateFromStyle,
294 // (as part of the RenderBoxModelObject::styleDidChange call below). So, we can safely cache the horizontal
295 // writing mode value before style change here.
296 bool oldHorizontalWritingMode = isHorizontalWritingMode();
298 RenderBoxModelObject::styleDidChange(diff, oldStyle);
300 RenderStyle* newStyle = style();
301 if (needsLayout() && oldStyle) {
302 RenderBlock::removePercentHeightDescendantIfNeeded(this);
304 // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
305 // when the positioned object's margin-before is changed. In this case the parent has to get a layout in order to run margin collapsing
306 // to determine the new static position.
307 if (isOutOfFlowPositioned() && newStyle->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle->marginBefore()
308 && parent() && !parent()->normalChildNeedsLayout())
309 parent()->setChildNeedsLayout();
312 if (RenderBlock::hasPercentHeightContainerMap() && firstChild()
313 && oldHorizontalWritingMode != isHorizontalWritingMode())
314 RenderBlock::clearPercentHeightDescendantsFrom(this);
316 // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
317 // new zoomed coordinate space.
318 if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom()) {
319 if (int left = layer()->scrollXOffset()) {
320 left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
321 layer()->scrollToXOffset(left);
323 if (int top = layer()->scrollYOffset()) {
324 top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
325 layer()->scrollToYOffset(top);
329 // Our opaqueness might have changed without triggering layout.
330 if (diff >= StyleDifferenceRepaint && diff <= StyleDifferenceRepaintLayer) {
331 RenderObject* parentToInvalidate = parent();
332 for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
333 parentToInvalidate->invalidateBackgroundObscurationStatus();
334 parentToInvalidate = parentToInvalidate->parent();
338 bool isBodyRenderer = isBody();
339 bool isRootRenderer = isRoot();
341 // Set the text color if we're the body.
343 document().setTextColor(newStyle->visitedDependentColor(CSSPropertyColor));
345 if (isRootRenderer || isBodyRenderer) {
346 // Propagate the new writing mode and direction up to the RenderView.
347 RenderStyle* viewStyle = view().style();
348 bool viewChangedWritingMode = false;
349 if (viewStyle->direction() != newStyle->direction() && (isRootRenderer || !document().directionSetOnDocumentElement())) {
350 viewStyle->setDirection(newStyle->direction());
352 document().documentElement()->renderer()->style()->setDirection(newStyle->direction());
353 setNeedsLayoutAndPrefWidthsRecalc();
356 if (viewStyle->writingMode() != newStyle->writingMode() && (isRootRenderer || !document().writingModeSetOnDocumentElement())) {
357 viewStyle->setWritingMode(newStyle->writingMode());
358 viewChangedWritingMode = true;
359 view().setHorizontalWritingMode(newStyle->isHorizontalWritingMode());
360 view().markAllDescendantsWithFloatsForLayout();
361 if (isBodyRenderer) {
362 document().documentElement()->renderer()->style()->setWritingMode(newStyle->writingMode());
363 document().documentElement()->renderer()->setHorizontalWritingMode(newStyle->isHorizontalWritingMode());
365 setNeedsLayoutAndPrefWidthsRecalc();
368 view().frameView().recalculateScrollbarOverlayStyle();
370 const Pagination& pagination = view().frameView().pagination();
371 if (viewChangedWritingMode && pagination.mode != Pagination::Unpaginated) {
372 viewStyle->setColumnStylesFromPaginationMode(pagination.mode);
373 if (view().hasColumns())
374 view().updateColumnInfoFromStyle(viewStyle);
378 #if ENABLE(CSS_SHAPES)
379 updateShapeOutsideInfoAfterStyleChange(style()->shapeOutside(), oldStyle ? oldStyle->shapeOutside() : 0);
383 #if ENABLE(CSS_SHAPES)
384 void RenderBox::updateShapeOutsideInfoAfterStyleChange(const ShapeValue* shapeOutside, const ShapeValue* oldShapeOutside)
386 // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
387 if (shapeOutside == oldShapeOutside)
391 ShapeOutsideInfo* shapeOutsideInfo = ShapeOutsideInfo::ensureInfo(this);
392 shapeOutsideInfo->dirtyShapeSize();
394 ShapeOutsideInfo::removeInfo(this);
395 markShapeOutsideDependentsForLayout();
399 void RenderBox::updateFromStyle()
401 RenderBoxModelObject::updateFromStyle();
403 RenderStyle* styleToUse = style();
404 bool isRootObject = isRoot();
405 bool isViewObject = isRenderView();
407 // The root and the RenderView always paint their backgrounds/borders.
408 if (isRootObject || isViewObject)
409 setHasBoxDecorations(true);
411 setFloating(!isOutOfFlowPositioned() && styleToUse->isFloating());
413 // We also handle <body> and <html>, whose overflow applies to the viewport.
414 if (styleToUse->overflowX() != OVISIBLE && !isRootObject && isRenderBlock()) {
415 bool boxHasOverflowClip = true;
417 // Overflow on the body can propagate to the viewport under the following conditions.
418 // (1) The root element is <html>.
419 // (2) We are the primary <body> (can be checked by looking at document.body).
420 // (3) The root element has visible overflow.
421 if (document().documentElement()->hasTagName(htmlTag)
422 && document().body() == element()
423 && document().documentElement()->renderer()->style()->overflowX() == OVISIBLE) {
424 boxHasOverflowClip = false;
428 // Check for overflow clip.
429 // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
430 if (boxHasOverflowClip) {
431 if (!s_hadOverflowClip)
432 // Erase the overflow
434 setHasOverflowClip();
438 setHasTransform(styleToUse->hasTransformRelatedProperty());
439 setHasReflection(styleToUse->boxReflect());
442 void RenderBox::layout()
444 StackStats::LayoutCheckPoint layoutCheckPoint;
445 ASSERT(needsLayout());
447 RenderObject* child = firstChild();
453 LayoutStateMaintainer statePusher(&view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
455 child->layoutIfNeeded();
456 ASSERT(!child->needsLayout());
457 child = child->nextSibling();
460 invalidateBackgroundObscurationStatus();
464 // More IE extensions. clientWidth and clientHeight represent the interior of an object
465 // excluding border and scrollbar.
466 LayoutUnit RenderBox::clientWidth() const
468 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
471 LayoutUnit RenderBox::clientHeight() const
473 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
476 int RenderBox::pixelSnappedClientWidth() const
478 return snapSizeToPixel(clientWidth(), x() + clientLeft());
481 int RenderBox::pixelSnappedClientHeight() const
483 return snapSizeToPixel(clientHeight(), y() + clientTop());
486 int RenderBox::pixelSnappedOffsetWidth() const
488 return snapSizeToPixel(offsetWidth(), x() + clientLeft());
491 int RenderBox::pixelSnappedOffsetHeight() const
493 return snapSizeToPixel(offsetHeight(), y() + clientTop());
496 int RenderBox::scrollWidth() const
498 if (hasOverflowClip())
499 return layer()->scrollWidth();
500 // For objects with visible overflow, this matches IE.
501 // FIXME: Need to work right with writing modes.
502 if (style()->isLeftToRightDirection())
503 return snapSizeToPixel(max(clientWidth(), layoutOverflowRect().maxX() - borderLeft()), x() + clientLeft());
504 return clientWidth() - min<LayoutUnit>(0, layoutOverflowRect().x() - borderLeft());
507 int RenderBox::scrollHeight() const
509 if (hasOverflowClip())
510 return layer()->scrollHeight();
511 // For objects with visible overflow, this matches IE.
512 // FIXME: Need to work right with writing modes.
513 return snapSizeToPixel(max(clientHeight(), layoutOverflowRect().maxY() - borderTop()), y() + clientTop());
516 int RenderBox::scrollLeft() const
518 return hasOverflowClip() ? layer()->scrollXOffset() : 0;
521 int RenderBox::scrollTop() const
523 return hasOverflowClip() ? layer()->scrollYOffset() : 0;
526 void RenderBox::setScrollLeft(int newLeft)
528 if (hasOverflowClip())
529 layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
532 void RenderBox::setScrollTop(int newTop)
534 if (hasOverflowClip())
535 layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
538 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
540 rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
543 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
545 quads.append(localToAbsoluteQuad(FloatRect(0, 0, width(), height()), 0 /* mode */, wasFixed));
548 void RenderBox::updateLayerTransform()
550 // Transform-origin depends on box size, so we need to update the layer transform after layout.
552 layer()->updateTransform();
555 LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region) const
557 RenderStyle* styleToUse = style();
558 if (!styleToUse->logicalMaxWidth().isUndefined())
559 logicalWidth = min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb, region));
560 return max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb, region));
563 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight) const
565 RenderStyle* styleToUse = style();
566 if (!styleToUse->logicalMaxHeight().isUndefined()) {
567 LayoutUnit maxH = computeLogicalHeightUsing(styleToUse->logicalMaxHeight());
569 logicalHeight = min(logicalHeight, maxH);
571 return max(logicalHeight, computeLogicalHeightUsing(styleToUse->logicalMinHeight()));
574 LayoutUnit RenderBox::constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight) const
576 RenderStyle* styleToUse = style();
577 if (!styleToUse->logicalMaxHeight().isUndefined()) {
578 LayoutUnit maxH = computeContentLogicalHeight(styleToUse->logicalMaxHeight());
580 logicalHeight = min(logicalHeight, maxH);
582 return max(logicalHeight, computeContentLogicalHeight(styleToUse->logicalMinHeight()));
585 IntRect RenderBox::absoluteContentBox() const
587 // This is wrong with transforms and flipped writing modes.
588 IntRect rect = pixelSnappedIntRect(contentBoxRect());
589 FloatPoint absPos = localToAbsolute();
590 rect.move(absPos.x(), absPos.y());
594 FloatQuad RenderBox::absoluteContentQuad() const
596 LayoutRect rect = contentBoxRect();
597 return localToAbsoluteQuad(FloatRect(rect));
600 LayoutRect RenderBox::outlineBoundsForRepaint(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap) const
602 LayoutRect box = borderBoundingBox();
603 adjustRectForOutlineAndShadow(box);
605 if (repaintContainer != this) {
606 FloatQuad containerRelativeQuad;
608 containerRelativeQuad = geometryMap->mapToContainer(box, repaintContainer);
610 containerRelativeQuad = localToContainerQuad(FloatRect(box), repaintContainer);
612 box = containerRelativeQuad.enclosingBoundingBox();
615 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
616 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
617 box.move(view().layoutDelta());
622 void RenderBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
624 if (!size().isEmpty())
625 rects.append(pixelSnappedIntRect(additionalOffset, size()));
628 LayoutRect RenderBox::reflectionBox() const
631 if (!style()->boxReflect())
633 LayoutRect box = borderBoxRect();
635 switch (style()->boxReflect()->direction()) {
636 case ReflectionBelow:
637 result.move(0, box.height() + reflectionOffset());
639 case ReflectionAbove:
640 result.move(0, -box.height() - reflectionOffset());
643 result.move(-box.width() - reflectionOffset(), 0);
645 case ReflectionRight:
646 result.move(box.width() + reflectionOffset(), 0);
652 int RenderBox::reflectionOffset() const
654 if (!style()->boxReflect())
656 if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
657 return valueForLength(style()->boxReflect()->offset(), borderBoxRect().width());
658 return valueForLength(style()->boxReflect()->offset(), borderBoxRect().height());
661 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
663 if (!style()->boxReflect())
666 LayoutRect box = borderBoxRect();
667 LayoutRect result = r;
668 switch (style()->boxReflect()->direction()) {
669 case ReflectionBelow:
670 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
672 case ReflectionAbove:
673 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
676 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
678 case ReflectionRight:
679 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
685 bool RenderBox::fixedElementLaysOutRelativeToFrame(const FrameView& frameView) const
687 return style() && style()->position() == FixedPosition && container()->isRenderView() && frameView.fixedElementsLayoutRelativeToFrame();
690 bool RenderBox::includeVerticalScrollbarSize() const
692 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
693 && (style()->overflowY() == OSCROLL || style()->overflowY() == OAUTO);
696 bool RenderBox::includeHorizontalScrollbarSize() const
698 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
699 && (style()->overflowX() == OSCROLL || style()->overflowX() == OAUTO);
702 int RenderBox::verticalScrollbarWidth() const
704 return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
707 int RenderBox::horizontalScrollbarHeight() const
709 return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
712 int RenderBox::instrinsicScrollbarLogicalWidth() const
714 if (!hasOverflowClip())
717 if (isHorizontalWritingMode() && style()->overflowY() == OSCROLL) {
718 ASSERT(layer()->hasVerticalScrollbar());
719 return verticalScrollbarWidth();
722 if (!isHorizontalWritingMode() && style()->overflowX() == OSCROLL) {
723 ASSERT(layer()->hasHorizontalScrollbar());
724 return horizontalScrollbarHeight();
730 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
732 RenderLayer* l = layer();
733 if (l && l->scroll(direction, granularity, multiplier)) {
735 *stopElement = element();
739 if (stopElement && *stopElement && *stopElement == element())
742 RenderBlock* b = containingBlock();
743 if (b && !b->isRenderView())
744 return b->scroll(direction, granularity, multiplier, stopElement);
748 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Element** stopElement)
750 bool scrolled = false;
752 RenderLayer* l = layer();
755 // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
756 if (granularity == ScrollByDocument)
757 scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
759 if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), granularity, multiplier))
764 *stopElement = element();
769 if (stopElement && *stopElement && *stopElement == element())
772 RenderBlock* b = containingBlock();
773 if (b && !b->isRenderView())
774 return b->logicalScroll(direction, granularity, multiplier, stopElement);
778 bool RenderBox::canBeScrolledAndHasScrollableArea() const
780 return canBeProgramaticallyScrolled() && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth());
783 bool RenderBox::canBeProgramaticallyScrolled() const
788 if (!hasOverflowClip())
791 bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
792 if (scrollsOverflow() && hasScrollableOverflow)
795 return element() && element()->rendererIsEditable();
798 bool RenderBox::usesCompositedScrolling() const
800 return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
803 void RenderBox::autoscroll(const IntPoint& position)
806 layer()->autoscroll(position);
809 // There are two kinds of renderer that can autoscroll.
810 bool RenderBox::canAutoscroll() const
813 return view().frameView().isScrollable();
815 // Check for a box that can be scrolled in its own right.
816 if (canBeScrolledAndHasScrollableArea())
822 // If specified point is in border belt, returned offset denotes direction of
824 IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) const
826 IntRect box(absoluteBoundingBoxRect());
827 box.move(view().frameView().scrollOffset());
828 IntRect windowBox = view().frameView().contentsToWindow(box);
830 IntPoint windowAutoscrollPoint = windowPoint;
832 if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
833 windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
834 else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
835 windowAutoscrollPoint.move(autoscrollBeltSize, 0);
837 if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
838 windowAutoscrollPoint.move(0, -autoscrollBeltSize);
839 else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
840 windowAutoscrollPoint.move(0, autoscrollBeltSize);
842 return windowAutoscrollPoint - windowPoint;
845 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
847 while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
848 if (renderer->isRenderView() && renderer->document().ownerElement())
849 renderer = renderer->document().ownerElement()->renderer();
851 renderer = renderer->parent();
854 return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
857 void RenderBox::panScroll(const IntPoint& source)
860 layer()->panScrollFromPoint(source);
863 bool RenderBox::needsPreferredWidthsRecalculation() const
865 return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent();
868 IntSize RenderBox::scrolledContentOffset() const
870 ASSERT(hasOverflowClip());
872 return layer()->scrolledContentOffset();
875 LayoutSize RenderBox::cachedSizeForOverflowClip() const
877 ASSERT(hasOverflowClip());
879 return layer()->size();
882 void RenderBox::applyCachedClipAndScrollOffsetForRepaint(LayoutRect& paintRect) const
884 flipForWritingMode(paintRect);
885 paintRect.move(-scrolledContentOffset()); // For overflow:auto/scroll/hidden.
887 // Do not clip scroll layer contents to reduce the number of repaints while scrolling.
888 if (usesCompositedScrolling()) {
889 flipForWritingMode(paintRect);
893 // height() is inaccurate if we're in the middle of a layout of this RenderBox, so use the
894 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
895 // anyway if its size does change.
896 LayoutRect clipRect(LayoutPoint(), cachedSizeForOverflowClip());
897 paintRect = intersection(paintRect, clipRect);
898 flipForWritingMode(paintRect);
901 void RenderBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
903 minLogicalWidth = minPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
904 maxLogicalWidth = maxPreferredLogicalWidth() - borderAndPaddingLogicalWidth();
907 LayoutUnit RenderBox::minPreferredLogicalWidth() const
909 if (preferredLogicalWidthsDirty()) {
911 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
913 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
916 return m_minPreferredLogicalWidth;
919 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
921 if (preferredLogicalWidthsDirty()) {
923 SetLayoutNeededForbiddenScope layoutForbiddenScope(const_cast<RenderBox*>(this));
925 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
928 return m_maxPreferredLogicalWidth;
931 bool RenderBox::hasOverrideHeight() const
933 return gOverrideHeightMap && gOverrideHeightMap->contains(this);
936 bool RenderBox::hasOverrideWidth() const
938 return gOverrideWidthMap && gOverrideWidthMap->contains(this);
941 void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
943 if (!gOverrideHeightMap)
944 gOverrideHeightMap = new OverrideSizeMap();
945 gOverrideHeightMap->set(this, height);
948 void RenderBox::setOverrideLogicalContentWidth(LayoutUnit width)
950 if (!gOverrideWidthMap)
951 gOverrideWidthMap = new OverrideSizeMap();
952 gOverrideWidthMap->set(this, width);
955 void RenderBox::clearOverrideLogicalContentHeight()
957 if (gOverrideHeightMap)
958 gOverrideHeightMap->remove(this);
961 void RenderBox::clearOverrideLogicalContentWidth()
963 if (gOverrideWidthMap)
964 gOverrideWidthMap->remove(this);
967 void RenderBox::clearOverrideSize()
969 clearOverrideLogicalContentHeight();
970 clearOverrideLogicalContentWidth();
973 LayoutUnit RenderBox::overrideLogicalContentWidth() const
975 ASSERT(hasOverrideWidth());
976 return gOverrideWidthMap->get(this);
979 LayoutUnit RenderBox::overrideLogicalContentHeight() const
981 ASSERT(hasOverrideHeight());
982 return gOverrideHeightMap->get(this);
985 LayoutUnit RenderBox::overrideContainingBlockContentLogicalWidth() const
987 ASSERT(hasOverrideContainingBlockLogicalWidth());
988 return gOverrideContainingBlockLogicalWidthMap->get(this);
991 LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
993 ASSERT(hasOverrideContainingBlockLogicalHeight());
994 return gOverrideContainingBlockLogicalHeightMap->get(this);
997 bool RenderBox::hasOverrideContainingBlockLogicalWidth() const
999 return gOverrideContainingBlockLogicalWidthMap && gOverrideContainingBlockLogicalWidthMap->contains(this);
1002 bool RenderBox::hasOverrideContainingBlockLogicalHeight() const
1004 return gOverrideContainingBlockLogicalHeightMap && gOverrideContainingBlockLogicalHeightMap->contains(this);
1007 void RenderBox::setOverrideContainingBlockContentLogicalWidth(LayoutUnit logicalWidth)
1009 if (!gOverrideContainingBlockLogicalWidthMap)
1010 gOverrideContainingBlockLogicalWidthMap = new OverrideSizeMap;
1011 gOverrideContainingBlockLogicalWidthMap->set(this, logicalWidth);
1014 void RenderBox::setOverrideContainingBlockContentLogicalHeight(LayoutUnit logicalHeight)
1016 if (!gOverrideContainingBlockLogicalHeightMap)
1017 gOverrideContainingBlockLogicalHeightMap = new OverrideSizeMap;
1018 gOverrideContainingBlockLogicalHeightMap->set(this, logicalHeight);
1021 void RenderBox::clearContainingBlockOverrideSize()
1023 if (gOverrideContainingBlockLogicalWidthMap)
1024 gOverrideContainingBlockLogicalWidthMap->remove(this);
1025 clearOverrideContainingBlockContentLogicalHeight();
1028 void RenderBox::clearOverrideContainingBlockContentLogicalHeight()
1030 if (gOverrideContainingBlockLogicalHeightMap)
1031 gOverrideContainingBlockLogicalHeightMap->remove(this);
1034 LayoutUnit RenderBox::adjustBorderBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1036 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
1037 if (style()->boxSizing() == CONTENT_BOX)
1038 return width + bordersPlusPadding;
1039 return max(width, bordersPlusPadding);
1042 LayoutUnit RenderBox::adjustBorderBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1044 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
1045 if (style()->boxSizing() == CONTENT_BOX)
1046 return height + bordersPlusPadding;
1047 return max(height, bordersPlusPadding);
1050 LayoutUnit RenderBox::adjustContentBoxLogicalWidthForBoxSizing(LayoutUnit width) const
1052 if (style()->boxSizing() == BORDER_BOX)
1053 width -= borderAndPaddingLogicalWidth();
1054 return max<LayoutUnit>(0, width);
1057 LayoutUnit RenderBox::adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const
1059 if (style()->boxSizing() == BORDER_BOX)
1060 height -= borderAndPaddingLogicalHeight();
1061 return max<LayoutUnit>(0, height);
1065 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1067 LayoutPoint adjustedLocation = accumulatedOffset + location();
1069 // Check kids first.
1070 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1071 if (!child->hasLayer() && child->nodeAtPoint(request, result, locationInContainer, adjustedLocation, action)) {
1072 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1077 // Check our bounds next. For this purpose always assume that we can only be hit in the
1078 // foreground phase (which is true for replaced elements like images).
1079 LayoutRect boundsRect = borderBoxRectInRegion(locationInContainer.region());
1080 boundsRect.moveBy(adjustedLocation);
1081 if (visibleToHitTesting() && action == HitTestForeground && locationInContainer.intersects(boundsRect)) {
1082 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
1083 if (!result.addNodeToRectBasedTestResult(element(), request, locationInContainer, boundsRect))
1090 // --------------------- painting stuff -------------------------------
1092 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
1094 if (paintInfo.skipRootBackground())
1097 RenderElement* rootBackgroundRenderer = rendererForRootBackground();
1099 const FillLayer* bgLayer = rootBackgroundRenderer->style()->backgroundLayers();
1100 Color bgColor = rootBackgroundRenderer->style()->visitedDependentColor(CSSPropertyBackgroundColor);
1102 paintFillLayers(paintInfo, bgColor, bgLayer, view().backgroundRect(this), BackgroundBleedNone, CompositeSourceOver, rootBackgroundRenderer);
1105 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
1107 if (context->paintingDisabled())
1108 return BackgroundBleedNone;
1110 const RenderStyle* style = this->style();
1112 if (!style->hasBackground() || !style->hasBorder() || !style->hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
1113 return BackgroundBleedNone;
1115 AffineTransform ctm = context->getCTM();
1116 FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
1118 // Because RoundedRect uses IntRect internally the inset applied by the
1119 // BackgroundBleedShrinkBackground strategy cannot be less than one integer
1120 // layout coordinate, even with subpixel layout enabled. To take that into
1121 // account, we clamp the contextScaling to 1.0 for the following test so
1122 // that borderObscuresBackgroundEdge can only return true if the border
1123 // widths are greater than 2 in both layout coordinates and screen
1125 // This precaution will become obsolete if RoundedRect is ever promoted to
1126 // a sub-pixel representation.
1127 if (contextScaling.width() > 1)
1128 contextScaling.setWidth(1);
1129 if (contextScaling.height() > 1)
1130 contextScaling.setHeight(1);
1132 if (borderObscuresBackgroundEdge(contextScaling))
1133 return BackgroundBleedShrinkBackground;
1134 if (!style->hasAppearance() && borderObscuresBackground() && backgroundHasOpaqueTopLayer())
1135 return BackgroundBleedBackgroundOverBorder;
1137 return BackgroundBleedUseTransparencyLayer;
1140 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1142 if (!paintInfo.shouldPaintWithinRoot(*this))
1145 LayoutRect paintRect = borderBoxRectInRegion(paintInfo.renderRegion);
1146 paintRect.moveBy(paintOffset);
1148 BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
1150 // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
1151 // custom shadows of their own.
1152 if (!boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1153 paintBoxShadow(paintInfo, paintRect, style(), Normal);
1155 GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
1156 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1157 // To avoid the background color bleeding out behind the border, we'll render background and border
1158 // into a transparency layer, and then clip that in one go (which requires setting up the clip before
1159 // beginning the layer).
1160 RoundedRect border = style()->getRoundedBorderFor(paintRect, &view());
1162 paintInfo.context->clipRoundedRect(border);
1163 paintInfo.context->beginTransparencyLayer(1);
1166 // If we have a native theme appearance, paint that before painting our background.
1167 // The theme will tell us whether or not we should also paint the CSS background.
1168 IntRect snappedPaintRect(pixelSnappedIntRect(paintRect));
1169 bool themePainted = style()->hasAppearance() && !theme()->paint(this, paintInfo, snappedPaintRect);
1170 if (!themePainted) {
1171 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
1172 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1174 paintBackground(paintInfo, paintRect, bleedAvoidance);
1176 if (style()->hasAppearance())
1177 theme()->paintDecorations(this, paintInfo, snappedPaintRect);
1179 paintBoxShadow(paintInfo, paintRect, style(), Inset);
1181 // The theme will tell us whether or not we should also paint the CSS border.
1182 if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style()->hasAppearance() || (!themePainted && theme()->paintBorderOnly(this, paintInfo, snappedPaintRect))) && style()->hasBorder())
1183 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
1185 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
1186 paintInfo.context->endTransparencyLayer();
1189 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
1192 paintRootBoxFillLayers(paintInfo);
1195 if (isBody() && skipBodyBackground(this))
1197 if (backgroundIsKnownToBeObscured() && !boxShadowShouldBeAppliedToBackground(bleedAvoidance))
1199 paintFillLayers(paintInfo, style()->visitedDependentColor(CSSPropertyBackgroundColor), style()->backgroundLayers(), paintRect, bleedAvoidance);
1202 bool RenderBox::getBackgroundPaintedExtent(LayoutRect& paintedExtent) const
1204 ASSERT(hasBackground());
1205 LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect());
1207 Color backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
1208 if (backgroundColor.isValid() && backgroundColor.alpha()) {
1209 paintedExtent = backgroundRect;
1213 if (!style()->backgroundLayers()->image() || style()->backgroundLayers()->next()) {
1214 paintedExtent = backgroundRect;
1218 BackgroundImageGeometry geometry;
1219 calculateBackgroundImageGeometry(0, style()->backgroundLayers(), backgroundRect, geometry);
1220 paintedExtent = geometry.destRect();
1221 return !geometry.hasNonLocalGeometry();
1224 bool RenderBox::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
1226 if (isBody() && skipBodyBackground(this))
1229 Color backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
1230 if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
1233 // If the element has appearance, it might be painted by theme.
1234 // We cannot be sure if theme paints the background opaque.
1235 // In this case it is safe to not assume opaqueness.
1236 // FIXME: May be ask theme if it paints opaque.
1237 if (style()->hasAppearance())
1239 // FIXME: Check the opaqueness of background images.
1241 // FIXME: Use rounded rect if border radius is present.
1242 if (style()->hasBorderRadius())
1244 // FIXME: The background color clip is defined by the last layer.
1245 if (style()->backgroundLayers()->next())
1247 LayoutRect backgroundRect;
1248 switch (style()->backgroundClip()) {
1250 backgroundRect = borderBoxRect();
1252 case PaddingFillBox:
1253 backgroundRect = paddingBoxRect();
1255 case ContentFillBox:
1256 backgroundRect = contentBoxRect();
1261 return backgroundRect.contains(localRect);
1264 static bool isCandidateForOpaquenessTest(RenderBox* childBox)
1266 RenderStyle* childStyle = childBox->style();
1267 if (childStyle->position() != StaticPosition && childBox->containingBlock() != childBox->parent())
1269 if (childStyle->visibility() != VISIBLE)
1271 #if ENABLE(CSS_SHAPES)
1272 if (childStyle->shapeOutside())
1275 if (!childBox->width() || !childBox->height())
1277 if (RenderLayer* childLayer = childBox->layer()) {
1278 #if USE(ACCELERATED_COMPOSITING)
1279 if (childLayer->isComposited())
1282 // FIXME: Deal with z-index.
1283 if (!childStyle->hasAutoZIndex())
1285 if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
1291 bool RenderBox::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
1293 if (!maxDepthToTest)
1295 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1296 if (!child->isBox())
1298 RenderBox* childBox = toRenderBox(child);
1299 if (!isCandidateForOpaquenessTest(childBox))
1301 LayoutPoint childLocation = childBox->location();
1302 if (childBox->isRelPositioned())
1303 childLocation.move(childBox->relativePositionOffset());
1304 LayoutRect childLocalRect = localRect;
1305 childLocalRect.moveBy(-childLocation);
1306 if (childLocalRect.y() < 0 || childLocalRect.x() < 0) {
1307 // If there is unobscured area above/left of a static positioned box then the rect is probably not covered.
1308 if (childBox->style()->position() == StaticPosition)
1312 if (childLocalRect.maxY() > childBox->height() || childLocalRect.maxX() > childBox->width())
1314 if (childBox->backgroundIsKnownToBeOpaqueInRect(childLocalRect))
1316 if (childBox->foregroundIsKnownToBeOpaqueInRect(childLocalRect, maxDepthToTest - 1))
1322 bool RenderBox::computeBackgroundIsKnownToBeObscured()
1324 // Test to see if the children trivially obscure the background.
1325 // FIXME: This test can be much more comprehensive.
1326 if (!hasBackground())
1328 // Table and root background painting is special.
1329 if (isTable() || isRoot())
1332 LayoutRect backgroundRect;
1333 if (!getBackgroundPaintedExtent(backgroundRect))
1335 return foregroundIsKnownToBeOpaqueInRect(backgroundRect, backgroundObscurationTestMaxDepth);
1338 bool RenderBox::backgroundHasOpaqueTopLayer() const
1340 const FillLayer* fillLayer = style()->backgroundLayers();
1341 if (!fillLayer || fillLayer->clip() != BorderFillBox)
1344 // Clipped with local scrolling
1345 if (hasOverflowClip() && fillLayer->attachment() == LocalBackgroundAttachment)
1348 if (fillLayer->hasOpaqueImage(this) && fillLayer->hasRepeatXY() && fillLayer->image()->canRender(this, style()->effectiveZoom()))
1351 // If there is only one layer and no image, check whether the background color is opaque
1352 if (!fillLayer->next() && !fillLayer->hasImage()) {
1353 Color bgColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
1354 if (bgColor.isValid() && bgColor.alpha() == 255)
1361 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1363 if (!paintInfo.shouldPaintWithinRoot(*this) || style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
1366 LayoutRect paintRect = LayoutRect(paintOffset, size());
1367 paintMaskImages(paintInfo, paintRect);
1370 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
1372 // Figure out if we need to push a transparency layer to render our mask.
1373 bool pushTransparencyLayer = false;
1374 bool compositedMask = hasLayer() && layer()->hasCompositedMask();
1375 bool flattenCompositingLayers = view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers;
1376 CompositeOperator compositeOp = CompositeSourceOver;
1378 bool allMaskImagesLoaded = true;
1380 if (!compositedMask || flattenCompositingLayers) {
1381 pushTransparencyLayer = true;
1382 StyleImage* maskBoxImage = style()->maskBoxImage().image();
1383 const FillLayer* maskLayers = style()->maskLayers();
1385 // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
1387 allMaskImagesLoaded &= maskBoxImage->isLoaded();
1390 allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1392 paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1393 paintInfo.context->beginTransparencyLayer(1);
1394 compositeOp = CompositeSourceOver;
1397 if (allMaskImagesLoaded) {
1398 paintFillLayers(paintInfo, Color(), style()->maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1399 paintNinePieceImage(paintInfo.context, paintRect, style(), style()->maskBoxImage(), compositeOp);
1402 if (pushTransparencyLayer)
1403 paintInfo.context->endTransparencyLayer();
1406 LayoutRect RenderBox::maskClipRect()
1408 const NinePieceImage& maskBoxImage = style()->maskBoxImage();
1409 if (maskBoxImage.image()) {
1410 LayoutRect borderImageRect = borderBoxRect();
1412 // Apply outsets to the border box.
1413 borderImageRect.expand(style()->maskBoxImageOutsets());
1414 return borderImageRect;
1418 LayoutRect borderBox = borderBoxRect();
1419 for (const FillLayer* maskLayer = style()->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1420 if (maskLayer->image()) {
1421 BackgroundImageGeometry geometry;
1422 // Masks should never have fixed attachment, so it's OK for paintContainer to be null.
1423 calculateBackgroundImageGeometry(0, maskLayer, borderBox, geometry);
1424 result.unite(geometry.destRect());
1430 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1431 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1433 Vector<const FillLayer*, 8> layers;
1434 const FillLayer* curLayer = fillLayer;
1435 bool shouldDrawBackgroundInSeparateBuffer = false;
1437 layers.append(curLayer);
1438 // Stop traversal when an opaque layer is encountered.
1439 // FIXME : It would be possible for the following occlusion culling test to be more aggressive
1440 // on layers with no repeat by testing whether the image covers the layout rect.
1441 // Testing that here would imply duplicating a lot of calculations that are currently done in
1442 // RenderBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move
1443 // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
1444 // and pass it down.
1446 if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal)
1447 shouldDrawBackgroundInSeparateBuffer = true;
1449 // The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
1450 if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(this) && curLayer->image()->canRender(this, style()->effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal)
1452 curLayer = curLayer->next();
1455 GraphicsContext* context = paintInfo.context;
1457 shouldDrawBackgroundInSeparateBuffer = false;
1458 if (shouldDrawBackgroundInSeparateBuffer)
1459 context->beginTransparencyLayer(1);
1461 Vector<const FillLayer*>::const_reverse_iterator topLayer = layers.rend();
1462 for (Vector<const FillLayer*>::const_reverse_iterator it = layers.rbegin(); it != topLayer; ++it)
1463 paintFillLayer(paintInfo, c, *it, rect, bleedAvoidance, op, backgroundObject);
1465 if (shouldDrawBackgroundInSeparateBuffer)
1466 context->endTransparencyLayer();
1469 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1470 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderElement* backgroundObject)
1472 paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, 0, LayoutSize(), op, backgroundObject);
1475 #if USE(ACCELERATED_COMPOSITING)
1476 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1478 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1479 if (curLayer->image() && image == curLayer->image()->data())
1487 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1492 if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1493 (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1498 bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
1499 if (!didFullRepaint)
1500 repaintLayerRectsForImage(image, style()->maskLayers(), false);
1503 #if USE(ACCELERATED_COMPOSITING)
1504 if (!isComposited())
1507 if (layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
1508 layer()->contentChanged(MaskImageChanged);
1509 if (layersUseImage(image, style()->backgroundLayers()))
1510 layer()->contentChanged(BackgroundImageChanged);
1514 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1516 LayoutRect rendererRect;
1517 RenderBox* layerRenderer = 0;
1519 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1520 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style()->effectiveZoom())) {
1521 // Now that we know this image is being used, compute the renderer and the rect if we haven't already.
1522 if (!layerRenderer) {
1523 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
1524 if (drawingRootBackground) {
1525 layerRenderer = &view();
1527 LayoutUnit rw = toRenderView(*layerRenderer).frameView().contentsWidth();
1528 LayoutUnit rh = toRenderView(*layerRenderer).frameView().contentsHeight();
1530 rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1531 -layerRenderer->marginTop(),
1532 max(layerRenderer->width() + layerRenderer->marginWidth() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1533 max(layerRenderer->height() + layerRenderer->marginHeight() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1535 layerRenderer = this;
1536 rendererRect = borderBoxRect();
1540 BackgroundImageGeometry geometry;
1541 layerRenderer->calculateBackgroundImageGeometry(0, curLayer, rendererRect, geometry);
1542 if (geometry.hasNonLocalGeometry()) {
1543 // Rather than incur the costs of computing the paintContainer for renderers with fixed backgrounds
1544 // in order to get the right destRect, just repaint the entire renderer.
1545 layerRenderer->repaint();
1549 layerRenderer->repaintRectangle(geometry.destRect());
1550 if (geometry.destRect() == rendererRect)
1559 void RenderBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type, bool behindText)
1561 Page* page = frame().page();
1565 InlineBox* boxWrap = inlineBoxWrapper();
1566 RootInlineBox* r = boxWrap ? &boxWrap->root() : 0;
1568 FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + r->selectionTop(), r->logicalWidth(), r->selectionHeight());
1569 FloatRect imageRect(paintOffset.x() + x(), rootRect.y(), width(), rootRect.height());
1570 page->chrome().client().paintCustomHighlight(element(), type, imageRect, rootRect, behindText, false);
1572 FloatRect imageRect(paintOffset.x() + x(), paintOffset.y() + y(), width(), height());
1573 page->chrome().client().paintCustomHighlight(element(), type, imageRect, imageRect, behindText, false);
1579 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1581 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1584 bool isControlClip = hasControlClip();
1585 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1587 if (!isControlClip && !isOverflowClip)
1590 if (paintInfo.phase == PaintPhaseOutline)
1591 paintInfo.phase = PaintPhaseChildOutlines;
1592 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1593 paintInfo.phase = PaintPhaseBlockBackground;
1594 paintObject(paintInfo, accumulatedOffset);
1595 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1597 IntRect clipRect = pixelSnappedIntRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion, IgnoreOverlayScrollbarSize, paintInfo.phase));
1598 paintInfo.context->save();
1599 if (style()->hasBorderRadius())
1600 paintInfo.context->clipRoundedRect(style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())));
1601 paintInfo.context->clip(clipRect);
1605 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1607 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1609 paintInfo.context->restore();
1610 if (originalPhase == PaintPhaseOutline) {
1611 paintInfo.phase = PaintPhaseSelfOutline;
1612 paintObject(paintInfo, accumulatedOffset);
1613 paintInfo.phase = originalPhase;
1614 } else if (originalPhase == PaintPhaseChildBlockBackground)
1615 paintInfo.phase = originalPhase;
1618 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy, PaintPhase)
1620 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1622 LayoutRect clipRect = borderBoxRectInRegion(region);
1623 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1624 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1626 // Subtract out scrollbars if we have them.
1628 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1629 clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
1630 clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1636 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1638 LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1639 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1641 if (!style()->clipLeft().isAuto()) {
1642 LayoutUnit c = valueForLength(style()->clipLeft(), borderBoxRect.width());
1643 clipRect.move(c, 0);
1644 clipRect.contract(c, 0);
1647 // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1648 // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1650 if (!style()->clipRight().isAuto())
1651 clipRect.contract(width() - valueForLength(style()->clipRight(), width()), 0);
1653 if (!style()->clipTop().isAuto()) {
1654 LayoutUnit c = valueForLength(style()->clipTop(), borderBoxRect.height());
1655 clipRect.move(0, c);
1656 clipRect.contract(0, c);
1659 if (!style()->clipBottom().isAuto())
1660 clipRect.contract(0, height() - valueForLength(style()->clipBottom(), height()));
1665 LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
1667 RenderRegion* containingBlockRegion = 0;
1668 LayoutUnit logicalTopPosition = logicalTop();
1670 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1671 logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1672 containingBlockRegion = cb->clampToStartAndEndRegions(region);
1675 LayoutUnit result = cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
1677 // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
1678 // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
1679 // offset at all, but can instead push all the way to the content edge of the containing block. In the case where the float
1680 // 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
1681 // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
1682 if (childMarginStart > 0) {
1683 LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
1684 LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
1685 LayoutUnit startOffset = cb->startOffsetForLine(logicalTopPosition, false, containingBlockRegion);
1686 if (startOffset > startContentSideWithMargin)
1687 result += childMarginStart;
1689 result += startOffset - startContentSide;
1692 if (childMarginEnd > 0) {
1693 LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
1694 LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
1695 LayoutUnit endOffset = cb->endOffsetForLine(logicalTopPosition, false, containingBlockRegion);
1696 if (endOffset > endContentSideWithMargin)
1697 result += childMarginEnd;
1699 result += endOffset - endContentSide;
1705 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1707 if (hasOverrideContainingBlockLogicalWidth())
1708 return overrideContainingBlockContentLogicalWidth();
1710 RenderBlock* cb = containingBlock();
1711 return cb->availableLogicalWidth();
1714 LayoutUnit RenderBox::containingBlockLogicalHeightForContent(AvailableLogicalHeightType heightType) const
1716 if (hasOverrideContainingBlockLogicalHeight())
1717 return overrideContainingBlockContentLogicalHeight();
1719 RenderBlock* cb = containingBlock();
1720 return cb->availableLogicalHeight(heightType);
1723 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
1726 return containingBlockLogicalWidthForContent();
1728 RenderBlock* cb = containingBlock();
1729 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1730 // FIXME: It's unclear if a region's content should use the containing block's override logical width.
1731 // If it should, the following line should call containingBlockLogicalWidthForContent.
1732 LayoutUnit result = cb->availableLogicalWidth();
1733 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
1736 return max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1739 LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
1741 RenderBlock* cb = containingBlock();
1742 RenderRegion* containingBlockRegion = 0;
1743 LayoutUnit logicalTopPosition = logicalTop();
1745 LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
1746 logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
1747 containingBlockRegion = cb->clampToStartAndEndRegions(region);
1749 return cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
1752 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1754 if (hasOverrideContainingBlockLogicalHeight())
1755 return overrideContainingBlockContentLogicalHeight();
1757 RenderBlock* cb = containingBlock();
1758 if (cb->hasOverrideHeight())
1759 return cb->overrideLogicalContentHeight();
1761 RenderStyle* containingBlockStyle = cb->style();
1762 Length logicalHeightLength = containingBlockStyle->logicalHeight();
1764 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1765 if (!logicalHeightLength.isFixed()) {
1766 LayoutUnit fillFallbackExtent = containingBlockStyle->isHorizontalWritingMode() ? view().frameView().visibleHeight() : view().frameView().visibleWidth();
1767 LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
1768 return min(fillAvailableExtent, fillFallbackExtent);
1771 // Use the content box logical height as specified by the style.
1772 return cb->adjustContentBoxLogicalHeightForBoxSizing(logicalHeightLength.value());
1775 void RenderBox::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
1777 if (repaintContainer == this)
1780 if (view().layoutStateEnabled() && !repaintContainer) {
1781 LayoutState* layoutState = view().layoutState();
1782 LayoutSize offset = layoutState->m_paintOffset + locationOffset();
1783 if (style()->hasInFlowPosition() && layer())
1784 offset += layer()->offsetForInFlowPosition();
1785 transformState.move(offset);
1789 bool containerSkipped;
1790 RenderElement* o = container(repaintContainer, &containerSkipped);
1794 bool isFixedPos = style()->position() == FixedPosition;
1795 bool hasTransform = hasLayer() && layer()->transform();
1796 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1797 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1798 if (hasTransform && !isFixedPos)
1800 else if (isFixedPos)
1804 *wasFixed = mode & IsFixed;
1806 LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1808 bool preserve3D = mode & UseTransforms && (o->style()->preserves3D() || style()->preserves3D());
1809 if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
1810 TransformationMatrix t;
1811 getTransformFromContainer(o, containerOffset, t);
1812 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1814 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1816 if (containerSkipped) {
1817 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1818 // to just subtract the delta between the repaintContainer and o.
1819 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1820 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1824 mode &= ~ApplyContainerFlip;
1826 // For fixed positioned elements inside out-of-flow named flows, we do not want to
1827 // map their position further to regions based on their coordinates inside the named flows.
1828 if (!o->isOutOfFlowRenderFlowThread() || !fixedPositionedWithNamedFlowContainingBlock())
1829 o->mapLocalToContainer(repaintContainer, transformState, mode, wasFixed);
1831 o->mapLocalToContainer(toRenderLayerModelObject(o), transformState, mode, wasFixed);
1834 const RenderObject* RenderBox::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
1836 ASSERT(ancestorToStopAt != this);
1838 bool ancestorSkipped;
1839 RenderElement* container = this->container(ancestorToStopAt, &ancestorSkipped);
1843 bool isFixedPos = style()->position() == FixedPosition;
1844 bool hasTransform = hasLayer() && layer()->transform();
1846 LayoutSize adjustmentForSkippedAncestor;
1847 if (ancestorSkipped) {
1848 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1849 // to just subtract the delta between the ancestor and o.
1850 adjustmentForSkippedAncestor = -ancestorToStopAt->offsetFromAncestorContainer(container);
1853 bool offsetDependsOnPoint = false;
1854 LayoutSize containerOffset = offsetFromContainer(container, LayoutPoint(), &offsetDependsOnPoint);
1856 bool preserve3D = container->style()->preserves3D() || style()->preserves3D();
1857 if (shouldUseTransformFromContainer(container)) {
1858 TransformationMatrix t;
1859 getTransformFromContainer(container, containerOffset, t);
1860 t.translateRight(adjustmentForSkippedAncestor.width(), adjustmentForSkippedAncestor.height());
1862 geometryMap.push(this, t, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform);
1864 containerOffset += adjustmentForSkippedAncestor;
1865 geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform);
1868 return ancestorSkipped ? ancestorToStopAt : container;
1871 void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
1873 bool isFixedPos = style()->position() == FixedPosition;
1874 bool hasTransform = hasLayer() && layer()->transform();
1875 if (hasTransform && !isFixedPos) {
1876 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1877 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1879 } else if (isFixedPos)
1882 RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
1885 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
1887 // A region "has" boxes inside it without being their container.
1888 ASSERT(o == container() || o->isRenderRegion());
1891 if (isInFlowPositioned())
1892 offset += offsetForInFlowPosition();
1894 if (!isInline() || isReplaced()) {
1895 if (!style()->hasOutOfFlowPosition() && o->hasColumns()) {
1896 RenderBlock* block = toRenderBlock(o);
1897 LayoutRect columnRect(frameRect());
1898 block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1899 offset += toSize(columnRect.location());
1900 LayoutPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
1901 offset = toLayoutSize(block->flipForWritingModeIncludingColumns(toLayoutPoint(offset)));
1902 o->adjustForColumns(offset, columnPoint);
1903 offset = block->flipForWritingMode(offset);
1905 if (offsetDependsOnPoint)
1906 *offsetDependsOnPoint = true;
1908 offset += topLeftLocationOffset();
1911 if (o->hasOverflowClip())
1912 offset -= toRenderBox(o)->scrolledContentOffset();
1914 if (style()->position() == AbsolutePosition && o->isInFlowPositioned() && o->isRenderInline())
1915 offset += toRenderInline(o)->offsetForInFlowPositionedInline(this);
1917 if (offsetDependsOnPoint)
1918 *offsetDependsOnPoint |= o->isRenderFlowThread();
1923 InlineBox* RenderBox::createInlineBox()
1925 return new (renderArena()) InlineBox(*this);
1928 void RenderBox::dirtyLineBoxes(bool fullLayout)
1930 if (m_inlineBoxWrapper) {
1932 m_inlineBoxWrapper->destroy(renderArena());
1933 m_inlineBoxWrapper = 0;
1935 m_inlineBoxWrapper->dirtyLineBoxes();
1939 void RenderBox::positionLineBox(InlineBox* box)
1941 if (isOutOfFlowPositioned()) {
1942 // Cache the x position only if we were an INLINE type originally.
1943 bool wasInline = style()->isOriginalDisplayInlineType();
1945 // The value is cached in the xPos of the box. We only need this value if
1946 // our object was inline originally, since otherwise it would have ended up underneath
1948 RootInlineBox& rootBox = box->root();
1949 rootBox.block().setStaticInlinePositionForChild(this, rootBox.lineTopWithLeading(), roundedLayoutUnit(box->logicalLeft()));
1950 if (style()->hasStaticInlinePosition(box->isHorizontal()))
1951 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1953 // Our object was a block originally, so we make our normal flow position be
1954 // just below the line box (as though all the inlines that came before us got
1955 // wrapped in an anonymous block, which is what would have happened had we been
1956 // in flow). This value was cached in the y() of the box.
1957 layer()->setStaticBlockPosition(box->logicalTop());
1958 if (style()->hasStaticBlockPosition(box->isHorizontal()))
1959 setChildNeedsLayout(MarkOnlyThis); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1964 box->destroy(renderArena());
1965 } else if (isReplaced()) {
1966 setLocation(roundedLayoutPoint(box->topLeft()));
1967 // m_inlineBoxWrapper should already be 0. Deleting it is a safeguard against security issues.
1968 ASSERT(!m_inlineBoxWrapper);
1969 if (m_inlineBoxWrapper)
1970 deleteLineBoxWrapper();
1971 m_inlineBoxWrapper = box;
1975 void RenderBox::deleteLineBoxWrapper()
1977 if (m_inlineBoxWrapper) {
1978 if (!documentBeingDestroyed())
1979 m_inlineBoxWrapper->remove();
1980 m_inlineBoxWrapper->destroy(renderArena());
1981 m_inlineBoxWrapper = 0;
1985 LayoutRect RenderBox::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
1987 if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
1988 return LayoutRect();
1990 LayoutRect r = visualOverflowRect();
1992 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1993 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1994 r.move(view().layoutDelta());
1997 // We have to use maximalOutlineSize() because a child might have an outline
1998 // that projects outside of our overflowRect.
1999 ASSERT(style()->outlineSize() <= view().maximalOutlineSize());
2000 r.inflate(view().maximalOutlineSize());
2003 computeRectForRepaint(repaintContainer, r);
2007 void RenderBox::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
2009 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
2010 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
2011 // offset corner for the enclosing container). This allows for a fully RL or BT document to repaint
2012 // properly even during layout, since the rect remains flipped all the way until the end.
2014 // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to
2015 // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the
2016 // physical coordinate space of the repaintContainer.
2017 RenderStyle* styleToUse = style();
2018 // LayoutState is only valid for root-relative, non-fixed position repainting
2019 if (view().layoutStateEnabled() && !repaintContainer && styleToUse->position() != FixedPosition) {
2020 LayoutState* layoutState = view().layoutState();
2022 if (layer() && layer()->transform())
2023 rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
2025 // We can't trust the bits on RenderObject, because this might be called while re-resolving style.
2026 if (styleToUse->hasInFlowPosition() && layer())
2027 rect.move(layer()->offsetForInFlowPosition());
2029 rect.moveBy(location());
2030 rect.move(layoutState->m_paintOffset);
2031 if (layoutState->m_clipped)
2032 rect.intersect(layoutState->m_clipRect);
2036 if (hasReflection())
2037 rect.unite(reflectedRect(rect));
2039 if (repaintContainer == this) {
2040 if (repaintContainer->style()->isFlippedBlocksWritingMode())
2041 flipForWritingMode(rect);
2045 bool containerSkipped;
2046 RenderElement* o = container(repaintContainer, &containerSkipped);
2050 if (isWritingModeRoot() && !isOutOfFlowPositioned())
2051 flipForWritingMode(rect);
2053 LayoutPoint topLeft = rect.location();
2054 topLeft.move(locationOffset());
2056 EPosition position = styleToUse->position();
2058 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
2059 // in the parent's coordinate space that encloses us.
2060 if (hasLayer() && layer()->transform()) {
2061 fixed = position == FixedPosition;
2062 rect = layer()->transform()->mapRect(pixelSnappedIntRect(rect));
2063 topLeft = rect.location();
2064 topLeft.move(locationOffset());
2065 } else if (position == FixedPosition)
2068 if (position == AbsolutePosition && o->isInFlowPositioned() && o->isRenderInline())
2069 topLeft += toRenderInline(o)->offsetForInFlowPositionedInline(this);
2070 else if (styleToUse->hasInFlowPosition() && layer()) {
2071 // Apply the relative position offset when invalidating a rectangle. The layer
2072 // is translated, but the render box isn't, so we need to do this to get the
2073 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
2074 // flag on the RenderObject has been cleared, so use the one on the style().
2075 topLeft += layer()->offsetForInFlowPosition();
2078 if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isRenderBlockFlow()) {
2079 LayoutRect repaintRect(topLeft, rect.size());
2080 toRenderBlock(o)->adjustRectForColumns(repaintRect);
2081 topLeft = repaintRect.location();
2085 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
2086 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
2087 rect.setLocation(topLeft);
2088 if (o->hasOverflowClip()) {
2089 RenderBox* containerBox = toRenderBox(o);
2090 containerBox->applyCachedClipAndScrollOffsetForRepaint(rect);
2095 if (containerSkipped) {
2096 // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
2097 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
2098 rect.move(-containerOffset);
2102 o->computeRectForRepaint(repaintContainer, rect, fixed);
2105 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& oldRect)
2107 if (oldRect.location() != m_frameRect.location()) {
2108 LayoutRect newRect = m_frameRect;
2109 // The child moved. Invalidate the object's old and new positions. We have to do this
2110 // since the object may not have gotten a layout.
2111 m_frameRect = oldRect;
2113 repaintOverhangingFloats(true);
2114 m_frameRect = newRect;
2116 repaintOverhangingFloats(true);
2120 void RenderBox::repaintOverhangingFloats(bool)
2124 void RenderBox::updateLogicalWidth()
2126 LogicalExtentComputedValues computedValues;
2127 computeLogicalWidthInRegion(computedValues);
2129 setLogicalWidth(computedValues.m_extent);
2130 setLogicalLeft(computedValues.m_position);
2131 setMarginStart(computedValues.m_margins.m_start);
2132 setMarginEnd(computedValues.m_margins.m_end);
2135 void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
2137 computedValues.m_extent = logicalWidth();
2138 computedValues.m_position = logicalLeft();
2139 computedValues.m_margins.m_start = marginStart();
2140 computedValues.m_margins.m_end = marginEnd();
2142 if (isOutOfFlowPositioned()) {
2143 // FIXME: This calculation is not patched for block-flow yet.
2144 // https://bugs.webkit.org/show_bug.cgi?id=46500
2145 computePositionedLogicalWidth(computedValues, region);
2149 // If layout is limited to a subtree, the subtree root's logical width does not change.
2150 if (element() && view().frameView().layoutRoot(true) == this)
2153 // The parent box is flexing us, so it has increased or decreased our
2154 // width. Use the width from the style context.
2155 // FIXME: Account for block-flow in flexible boxes.
2156 // https://bugs.webkit.org/show_bug.cgi?id=46418
2157 if (hasOverrideWidth() && (style()->borderFit() == BorderFitLines || parent()->isFlexibleBoxIncludingDeprecated())) {
2158 computedValues.m_extent = overrideLogicalContentWidth() + borderAndPaddingLogicalWidth();
2162 // FIXME: Account for block-flow in flexible boxes.
2163 // https://bugs.webkit.org/show_bug.cgi?id=46418
2164 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
2165 bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
2166 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
2168 RenderStyle* styleToUse = style();
2169 Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse->logicalWidth();
2171 RenderBlock* cb = containingBlock();
2172 LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
2173 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2175 if (isInline() && !isInlineBlockOrInlineTable()) {
2176 // just calculate margins
2177 computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
2178 computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
2179 if (treatAsReplaced)
2180 computedValues.m_extent = max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
2184 // Width calculations
2185 if (treatAsReplaced)
2186 computedValues.m_extent = logicalWidthLength.value() + borderAndPaddingLogicalWidth();
2188 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
2189 if (hasPerpendicularContainingBlock)
2190 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
2191 LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb, region);
2192 computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
2195 // Margin calculations.
2196 if (hasPerpendicularContainingBlock || isFloating() || isInline()) {
2197 computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth);
2198 computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth);
2200 LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
2201 if (avoidsFloats() && cb->containsFloats())
2202 containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
2203 bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
2204 computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
2205 hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
2206 hasInvertedDirection ? computedValues.m_margins.m_start : computedValues.m_margins.m_end);
2209 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (computedValues.m_extent + computedValues.m_margins.m_start + computedValues.m_margins.m_end)
2210 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated() && !cb->isRenderGrid()) {
2211 LayoutUnit newMargin = containerLogicalWidth - computedValues.m_extent - cb->marginStartForChild(this);
2212 bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
2213 if (hasInvertedDirection)
2214 computedValues.m_margins.m_start = newMargin;
2216 computedValues.m_margins.m_end = newMargin;
2220 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth) const
2222 LayoutUnit marginStart = 0;
2223 LayoutUnit marginEnd = 0;
2224 return fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2227 LayoutUnit RenderBox::fillAvailableMeasure(LayoutUnit availableLogicalWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2229 marginStart = minimumValueForLength(style()->marginStart(), availableLogicalWidth);
2230 marginEnd = minimumValueForLength(style()->marginEnd(), availableLogicalWidth);
2231 return availableLogicalWidth - marginStart - marginEnd;
2234 LayoutUnit RenderBox::computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const
2236 if (logicalWidthLength.type() == FillAvailable)
2237 return fillAvailableMeasure(availableLogicalWidth);
2239 LayoutUnit minLogicalWidth = 0;
2240 LayoutUnit maxLogicalWidth = 0;
2241 computeIntrinsicLogicalWidths(minLogicalWidth, maxLogicalWidth);
2243 if (logicalWidthLength.type() == MinContent)
2244 return minLogicalWidth + borderAndPadding;
2246 if (logicalWidthLength.type() == MaxContent)
2247 return maxLogicalWidth + borderAndPadding;
2249 if (logicalWidthLength.type() == FitContent) {
2250 minLogicalWidth += borderAndPadding;
2251 maxLogicalWidth += borderAndPadding;
2252 return max(minLogicalWidth, min(maxLogicalWidth, fillAvailableMeasure(availableLogicalWidth)));
2255 ASSERT_NOT_REACHED();
2259 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
2260 const RenderBlock* cb, RenderRegion* region) const
2262 if (!logicalWidth.isIntrinsicOrAuto()) {
2263 // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
2264 return adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, availableLogicalWidth));
2267 if (logicalWidth.isIntrinsic())
2268 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth());
2270 LayoutUnit marginStart = 0;
2271 LayoutUnit marginEnd = 0;
2272 LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
2274 if (shrinkToAvoidFloats() && cb->containsFloats())
2275 logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
2277 if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
2278 return max(minPreferredLogicalWidth(), min(maxPreferredLogicalWidth(), logicalWidthResult));
2279 return logicalWidthResult;
2282 static bool flexItemHasStretchAlignment(const RenderObject* flexitem)
2284 RenderObject* parent = flexitem->parent();
2285 return flexitem->style()->alignSelf() == AlignStretch || (flexitem->style()->alignSelf() == AlignAuto && parent->style()->alignItems() == AlignStretch);
2288 static bool isStretchingColumnFlexItem(const RenderObject* flexitem)
2290 RenderObject* parent = flexitem->parent();
2291 if (parent->isDeprecatedFlexibleBox() && parent->style()->boxOrient() == VERTICAL && parent->style()->boxAlign() == BSTRETCH)
2294 // We don't stretch multiline flexboxes because they need to apply line spacing (align-content) first.
2295 if (parent->isFlexibleBox() && parent->style()->flexWrap() == FlexNoWrap && parent->style()->isColumnFlexDirection() && flexItemHasStretchAlignment(flexitem))
2300 bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
2302 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
2303 // but they allow text to sit on the same line as the marquee.
2304 if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
2307 // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both
2308 // min-width and width. max-width is only clamped if it is also intrinsic.
2309 Length logicalWidth = (widthType == MaxSize) ? style()->logicalMaxWidth() : style()->logicalWidth();
2310 if (logicalWidth.type() == Intrinsic)
2313 // Children of a horizontal marquee do not fill the container by default.
2314 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
2315 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
2316 // block-flow (as well as how marquee overflow should relate to block flow).
2317 // https://bugs.webkit.org/show_bug.cgi?id=46472
2318 if (parent()->style()->overflowX() == OMARQUEE) {
2319 EMarqueeDirection dir = parent()->style()->marqueeDirection();
2320 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
2324 // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
2325 // In the case of columns that have a stretch alignment, we go ahead and layout at the
2326 // stretched size to avoid an extra layout when applying alignment.
2327 if (parent()->isFlexibleBox()) {
2328 // For multiline columns, we need to apply align-content first, so we can't stretch now.
2329 if (!parent()->style()->isColumnFlexDirection() || parent()->style()->flexWrap() != FlexNoWrap)
2331 if (!flexItemHasStretchAlignment(this))
2335 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
2336 // that don't stretch their kids lay out their children at their intrinsic widths.
2337 // FIXME: Think about block-flow here.
2338 // https://bugs.webkit.org/show_bug.cgi?id=46473
2339 if (parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
2342 // Button, input, select, textarea, and legend treat width value of 'auto' as 'intrinsic' unless it's in a
2343 // stretching column flexbox.
2344 // FIXME: Think about block-flow here.
2345 // https://bugs.webkit.org/show_bug.cgi?id=46473
2346 if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(this) && element() && (isHTMLInputElement(element()) || element()->hasTagName(selectTag) || element()->hasTagName(buttonTag) || isHTMLTextAreaElement(element()) || element()->hasTagName(legendTag)))
2349 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
2355 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
2357 const RenderStyle* containingBlockStyle = containingBlock->style();
2358 Length marginStartLength = style()->marginStartUsing(containingBlockStyle);
2359 Length marginEndLength = style()->marginEndUsing(containingBlockStyle);
2361 if (isFloating() || isInline()) {
2362 // Inline blocks/tables and floats don't have their margins increased.
2363 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2364 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2368 // Case One: The object is being centered in the containing block's available logical width.
2369 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
2370 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
2371 // Other browsers center the margin box for align=center elements so we match them here.
2372 LayoutUnit marginStartWidth = minimumValueForLength(marginStartLength, containerWidth);
2373 LayoutUnit marginEndWidth = minimumValueForLength(marginEndLength, containerWidth);
2374 LayoutUnit centeredMarginBoxStart = max<LayoutUnit>(0, (containerWidth - childWidth - marginStartWidth - marginEndWidth) / 2);
2375 marginStart = centeredMarginBoxStart + marginStartWidth;
2376 marginEnd = containerWidth - childWidth - marginStart + marginEndWidth;
2380 // Case Two: The object is being pushed to the start of the containing block's available logical width.
2381 if (marginEndLength.isAuto() && childWidth < containerWidth) {
2382 marginStart = valueForLength(marginStartLength, containerWidth);
2383 marginEnd = containerWidth - childWidth - marginStart;
2387 // Case Three: The object is being pushed to the end of the containing block's available logical width.
2388 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
2389 || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
2390 if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
2391 marginEnd = valueForLength(marginEndLength, containerWidth);
2392 marginStart = containerWidth - childWidth - marginEnd;
2396 // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3). In that case
2397 // auto margins will just turn into 0.
2398 marginStart = minimumValueForLength(marginStartLength, containerWidth);
2399 marginEnd = minimumValueForLength(marginEndLength, containerWidth);
2402 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
2404 // Make sure nobody is trying to call this with a null region.
2408 // If we have computed our width in this region already, it will be cached, and we can
2410 RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
2411 if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
2414 // No cached value was found, so we have to compute our insets in this region.
2415 // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
2416 // support to cover all boxes.
2417 RenderFlowThread* flowThread = flowThreadContainingBlock();
2418 if (isRenderFlowThread() || !flowThread || !canHaveBoxInfoInRegion() || flowThread->style()->writingMode() != style()->writingMode())
2421 LogicalExtentComputedValues computedValues;
2422 computeLogicalWidthInRegion(computedValues, region);
2424 // Now determine the insets based off where this object is supposed to be positioned.
2425 RenderBlock* cb = containingBlock();
2426 RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
2427 RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
2428 LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
2429 LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
2431 LayoutUnit marginStartInRegion = computedValues.m_margins.m_start;
2432 LayoutUnit startMarginDelta = marginStartInRegion - marginStart();
2433 LayoutUnit logicalWidthInRegion = computedValues.m_extent;
2434 LayoutUnit logicalLeftInRegion = computedValues.m_position;
2435 LayoutUnit widthDelta = logicalWidthInRegion - logicalWidth();
2436 LayoutUnit logicalLeftDelta = isOutOfFlowPositioned() ? logicalLeftInRegion - logicalLeft() : startMarginDelta;
2437 LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
2438 LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (logicalLeft() + logicalWidth());
2439 LayoutUnit logicalRightDelta = isOutOfFlowPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
2441 LayoutUnit logicalLeftOffset = 0;
2443 if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
2444 LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(this, marginStartInRegion, region);
2445 if (cb->style()->isLeftToRightDirection())
2446 logicalLeftDelta += startPositionDelta;
2448 logicalRightDelta += startPositionDelta;
2451 if (cb->style()->isLeftToRightDirection())
2452 logicalLeftOffset += logicalLeftDelta;
2454 logicalLeftOffset -= (widthDelta + logicalRightDelta);
2456 LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
2457 bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
2458 || (style()->isLeftToRightDirection() && logicalLeftOffset)
2459 || (!style()->isLeftToRightDirection() && logicalRightOffset);
2461 // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
2462 if (cacheFlag == CacheRenderBoxRegionInfo)
2463 return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
2464 return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
2467 static bool shouldFlipBeforeAfterMargins(const RenderStyle* containingBlockStyle, const RenderStyle* childStyle)
2469 ASSERT(containingBlockStyle->isHorizontalWritingMode() != childStyle->isHorizontalWritingMode());
2470 WritingMode childWritingMode = childStyle->writingMode();
2471 bool shouldFlip = false;
2472 switch (containingBlockStyle->writingMode()) {
2473 case TopToBottomWritingMode:
2474 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2476 case BottomToTopWritingMode:
2477 shouldFlip = (childWritingMode == RightToLeftWritingMode);
2479 case RightToLeftWritingMode:
2480 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2482 case LeftToRightWritingMode:
2483 shouldFlip = (childWritingMode == BottomToTopWritingMode);
2487 if (!containingBlockStyle->isLeftToRightDirection())
2488 shouldFlip = !shouldFlip;
2493 void RenderBox::updateLogicalHeight()
2495 LogicalExtentComputedValues computedValues;
2496 computeLogicalHeight(logicalHeight(), logicalTop(), computedValues);
2498 setLogicalHeight(computedValues.m_extent);
2499 setLogicalTop(computedValues.m_position);
2500 setMarginBefore(computedValues.m_margins.m_before);
2501 setMarginAfter(computedValues.m_margins.m_after);
2504 void RenderBox::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
2506 computedValues.m_extent = logicalHeight;
2507 computedValues.m_position = logicalTop;
2509 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
2510 if (isTableCell() || (isInline() && !isReplaced()))
2514 if (isOutOfFlowPositioned())
2515 computePositionedLogicalHeight(computedValues);
2517 RenderBlock* cb = containingBlock();
2518 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
2520 if (!hasPerpendicularContainingBlock) {
2521 bool shouldFlipBeforeAfter = cb->style()->writingMode() != style()->writingMode();
2522 computeBlockDirectionMargins(cb,
2523 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2524 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2527 // For tables, calculate margins only.
2529 if (hasPerpendicularContainingBlock) {
2530 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), style());
2531 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), computedValues.m_extent,
2532 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2533 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2538 // FIXME: Account for block-flow in flexible boxes.
2539 // https://bugs.webkit.org/show_bug.cgi?id=46418
2540 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
2541 bool stretching = parent()->style()->boxAlign() == BSTRETCH;
2542 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2543 bool checkMinMaxHeight = false;
2545 // The parent box is flexing us, so it has increased or decreased our height. We have to
2546 // grab our cached flexible height.
2547 // FIXME: Account for block-flow in flexible boxes.
2548 // https://bugs.webkit.org/show_bug.cgi?id=46418
2549 if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
2550 h = Length(overrideLogicalContentHeight(), Fixed);
2551 else if (treatAsReplaced)
2552 h = Length(computeReplacedLogicalHeight(), Fixed);
2554 h = style()->logicalHeight();
2555 checkMinMaxHeight = true;
2558 // Block children of horizontal flexible boxes fill the height of the box.
2559 // FIXME: Account for block-flow in flexible boxes.
2560 // https://bugs.webkit.org/show_bug.cgi?id=46418
2561 if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
2562 && parent()->isStretchingChildren()) {
2563 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2564 checkMinMaxHeight = false;
2567 LayoutUnit heightResult;
2568 if (checkMinMaxHeight) {
2569 heightResult = computeLogicalHeightUsing(style()->logicalHeight());
2570 if (heightResult == -1)
2571 heightResult = computedValues.m_extent;
2572 heightResult = constrainLogicalHeightByMinMax(heightResult);
2574 // The only times we don't check min/max height are when a fixed length has
2575 // been given as an override. Just use that. The value has already been adjusted
2577 heightResult = h.value() + borderAndPaddingLogicalHeight();
2580 computedValues.m_extent = heightResult;
2582 if (hasPerpendicularContainingBlock) {
2583 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), style());
2584 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2585 shouldFlipBeforeAfter ? computedValues.m_margins.m_after : computedValues.m_margins.m_before,
2586 shouldFlipBeforeAfter ? computedValues.m_margins.m_before : computedValues.m_margins.m_after);
2590 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2591 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2592 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2593 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2594 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2595 bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
2596 && (isRoot() || (isBody() && document().documentElement()->renderer()->style()->logicalHeight().isPercent())) && !isInline();
2597 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2598 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2599 LayoutUnit visibleHeight = view().pageOrViewLogicalHeight();
2601 computedValues.m_extent = max(computedValues.m_extent, visibleHeight - margins);
2603 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2604 computedValues.m_extent = max(computedValues.m_extent, visibleHeight - marginsBordersPadding);
2609 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& height) const
2611 LayoutUnit logicalHeight = computeContentAndScrollbarLogicalHeightUsing(height);
2612 if (logicalHeight != -1)
2613 logicalHeight = adjustBorderBoxLogicalHeightForBoxSizing(logicalHeight);
2614 return logicalHeight;
2617 LayoutUnit RenderBox::computeContentLogicalHeight(const Length& height) const
2619 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(height);
2620 if (heightIncludingScrollbar == -1)
2622 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2625 LayoutUnit RenderBox::computeContentAndScrollbarLogicalHeightUsing(const Length& height) const
2627 if (height.isFixed())
2628 return height.value();
2629 if (height.isPercent())
2630 return computePercentageLogicalHeight(height);
2631 if (height.isViewportPercentage())
2632 return valueForLength(height, 0);
2636 bool RenderBox::skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const
2638 // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
2639 // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
2640 if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
2642 return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style()->logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
2645 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height) const
2647 LayoutUnit availableHeight = -1;
2649 bool skippedAutoHeightContainingBlock = false;
2650 RenderBlock* cb = containingBlock();
2651 const RenderBox* containingBlockChild = this;
2652 LayoutUnit rootMarginBorderPaddingHeight = 0;
2653 while (!cb->isRenderView() && skipContainingBlockForPercentHeightCalculation(cb)) {
2654 if (cb->isBody() || cb->isRoot())
2655 rootMarginBorderPaddingHeight += cb->marginBefore() + cb->marginAfter() + cb->borderAndPaddingLogicalHeight();
2656 skippedAutoHeightContainingBlock = true;
2657 containingBlockChild = cb;
2658 cb = cb->containingBlock();
2659 cb->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2662 RenderStyle* cbstyle = cb->style();
2664 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2665 // explicitly specified that can be used for any percentage computations.
2666 bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle->logicalHeight().isAuto() || (!cbstyle->logicalTop().isAuto() && !cbstyle->logicalBottom().isAuto()));
2668 bool includeBorderPadding = isTable();
2670 if (isHorizontalWritingMode() != cb->isHorizontalWritingMode())
2671 availableHeight = containingBlockChild->containingBlockLogicalWidthForContent();
2672 else if (hasOverrideContainingBlockLogicalHeight())
2673 availableHeight = overrideContainingBlockContentLogicalHeight();
2674 else if (cb->isTableCell()) {
2675 if (!skippedAutoHeightContainingBlock) {
2676 // Table cells violate what the CSS spec says to do with heights. Basically we
2677 // don't care if the cell specified a height or not. We just always make ourselves
2678 // be a percentage of the cell's current content height.
2679 if (!cb->hasOverrideHeight()) {
2680 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2681 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2682 // While we can't get all cases right, we can at least detect when the cell has a specified
2683 // height or when the table has a specified height. In these cases we want to initially have
2684 // no size and allow the flexing of the table or the cell to its specified height to cause us
2685 // to grow to fill the space. This could end up being wrong in some cases, but it is
2686 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2687 RenderTableCell* cell = toRenderTableCell(cb);
2688 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2692 availableHeight = cb->overrideLogicalContentHeight();
2693 includeBorderPadding = true;
2695 } else if (cbstyle->logicalHeight().isFixed()) {
2696 LayoutUnit contentBoxHeight = cb->adjustContentBoxLogicalHeightForBoxSizing(cbstyle->logicalHeight().value());
2697 availableHeight = max<LayoutUnit>(0, cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeight - cb->scrollbarLogicalHeight()));
2698 } else if (cbstyle->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2699 // We need to recur and compute the percentage height for our containing block.
2700 LayoutUnit heightWithScrollbar = cb->computePercentageLogicalHeight(cbstyle->logicalHeight());
2701 if (heightWithScrollbar != -1) {
2702 LayoutUnit contentBoxHeightWithScrollbar = cb->adjustContentBoxLogicalHeightForBoxSizing(heightWithScrollbar);
2703 // We need to adjust for min/max height because this method does not
2704 // handle the min/max of the current block, its caller does. So the
2705 // return value from the recursive call will not have been adjusted
2707 LayoutUnit contentBoxHeight = cb->constrainContentBoxLogicalHeightByMinMax(contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight());
2708 availableHeight = max<LayoutUnit>(0, contentBoxHeight);
2710 } else if (isOutOfFlowPositionedWithSpecifiedHeight) {
2711 // Don't allow this to affect the block' height() member variable, since this
2712 // can get called while the block is still laying out its kids.
2713 LogicalExtentComputedValues computedValues;
2714 cb->computeLogicalHeight(cb->logicalHeight(), 0, computedValues);
2715 availableHeight = computedValues.m_extent - cb->borderAndPaddingLogicalHeight() - cb->scrollbarLogicalHeight();
2716 } else if (cb->isRenderView())
2717 availableHeight = view().pageOrViewLogicalHeight();
2719 if (availableHeight == -1)
2720 return availableHeight;
2722 availableHeight -= rootMarginBorderPaddingHeight;
2724 LayoutUnit result = valueForLength(height, availableHeight);
2725 if (includeBorderPadding) {
2726 // FIXME: Table cells should default to box-sizing: border-box so we can avoid this hack.
2727 // It is necessary to use the border-box to match WinIE's broken
2728 // box model. This is essential for sizing inside
2729 // table cells using percentage heights.
2730 result -= borderAndPaddingLogicalHeight();
2731 return max<LayoutUnit>(0, result);
2736 LayoutUnit RenderBox::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
2738 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), shouldComputePreferred);
2741 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, ShouldComputePreferred shouldComputePreferred) const
2743 LayoutUnit minLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMinWidth().isPercent()) || style()->logicalMinWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2744 LayoutUnit maxLogicalWidth = (shouldComputePreferred == ComputePreferred && style()->logicalMaxWidth().isPercent()) || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2745 return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
2748 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2750 switch (logicalWidth.type()) {
2752 return adjustContentBoxLogicalWidthForBoxSizing(logicalWidth.value());
2755 // MinContent/MaxContent don't need the availableLogicalWidth argument.
2756 LayoutUnit availableLogicalWidth = 0;
2757 return computeIntrinsicLogicalWidthUsing(logicalWidth, availableLogicalWidth, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2759 case ViewportPercentageWidth:
2760 case ViewportPercentageHeight:
2761 case ViewportPercentageMin:
2762 case ViewportPercentageMax:
2763 return adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, 0));
2768 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2769 // containing block's block-flow.
2770 // https://bugs.webkit.org/show_bug.cgi?id=46496
2771 const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2772 Length containerLogicalWidth = containingBlock()->style()->logicalWidth();
2773 // FIXME: Handle cases when containing block width is calculated or viewport percent.
2774 // https://bugs.webkit.org/show_bug.cgi?id=91071
2775 if (logicalWidth.isIntrinsic())
2776 return computeIntrinsicLogicalWidthUsing(logicalWidth, cw, borderAndPaddingLogicalWidth()) - borderAndPaddingLogicalWidth();
2777 if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2778 return adjustContentBoxLogicalWidthForBoxSizing(minimumValueForLength(logicalWidth, cw));
2786 return intrinsicLogicalWidth();
2789 ASSERT_NOT_REACHED();
2793 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2795 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2798 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2800 LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2801 LayoutUnit maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2802 return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
2805 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2807 switch (logicalHeight.type()) {
2809 return adjustContentBoxLogicalHeightForBoxSizing(logicalHeight.value());
2813 RenderObject* cb = isOutOfFlowPositioned() ? container() : containingBlock();
2814 while (cb->isAnonymous() && !cb->isRenderView()) {
2815 cb = cb->containingBlock();
2816 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2819 // FIXME: This calculation is not patched for block-flow yet.
2820 // https://bugs.webkit.org/show_bug.cgi?id=46500
2821 if (cb->isOutOfFlowPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2822 ASSERT_WITH_SECURITY_IMPLICATION(cb->isRenderBlock());
2823 RenderBlock* block = toRenderBlock(cb);
2824 LogicalExtentComputedValues computedValues;
2825 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2826 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2827 LayoutUnit newHeight = block->adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2828 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, newHeight));
2831 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2832 // containing block's block-flow.
2833 // https://bugs.webkit.org/show_bug.cgi?id=46496
2834 LayoutUnit availableHeight;
2835 if (isOutOfFlowPositioned())
2836 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2838 availableHeight = containingBlockLogicalHeightForContent(IncludeMarginBorderPadding);
2839 // It is necessary to use the border-box to match WinIE's broken
2840 // box model. This is essential for sizing inside
2841 // table cells using percentage heights.
2842 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
2843 // https://bugs.webkit.org/show_bug.cgi?id=46997
2844 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2845 if (cb->isTableCell()) {
2846 // Don't let table cells squeeze percent-height replaced elements
2847 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2848 availableHeight = max(availableHeight, intrinsicLogicalHeight());
2849 return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
2851 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2852 cb = cb->containingBlock();
2855 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, availableHeight));
2857 case ViewportPercentageWidth:
2858 case ViewportPercentageHeight:
2859 case ViewportPercentageMin:
2860 case ViewportPercentageMax:
2861 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeight, 0));
2863 return intrinsicLogicalHeight();
2867 LayoutUnit RenderBox::availableLogicalHeight(AvailableLogicalHeightType heightType) const
2869 return constrainLogicalHeightByMinMax(availableLogicalHeightUsing(style()->logicalHeight(), heightType));
2872 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
2874 // We need to stop here, since we don't want to increase the height of the table
2875 // artificially. We're going to rely on this cell getting expanded to some new
2876 // height, and then when we lay out again we'll use the calculation below.
2877 if (isTableCell() && (h.isAuto() || h.isPercent())) {
2878 if (hasOverrideHeight())
2879 return overrideLogicalContentHeight();
2880 return logicalHeight() - borderAndPaddingLogicalHeight();
2883 if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
2884 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2885 LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2886 return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
2889 LayoutUnit heightIncludingScrollbar = computeContentAndScrollbarLogicalHeightUsing(h);
2890 if (heightIncludingScrollbar != -1)
2891 return std::max<LayoutUnit>(0, adjustContentBoxLogicalHeightForBoxSizing(heightIncludingScrollbar) - scrollbarLogicalHeight());
2893 // FIXME: Check logicalTop/logicalBottom here to correctly handle vertical writing-mode.
2894 // https://bugs.webkit.org/show_bug.cgi?id=46500
2895 if (isRenderBlock() && isOutOfFlowPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2896 RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2897 LogicalExtentComputedValues computedValues;
2898 block->computeLogicalHeight(block->logicalHeight(), 0, computedValues);
2899 LayoutUnit newContentHeight = computedValues.m_extent - block->borderAndPaddingLogicalHeight() - block->scrollbarLogicalHeight();
2900 return adjustContentBoxLogicalHeightForBoxSizing(newContentHeight);
2903 // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
2904 LayoutUnit availableHeight = containingBlockLogicalHeightForContent(heightType);
2905 if (heightType == ExcludeMarginBorderPadding) {
2906 // FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes collapsed margins.
2907 availableHeight -= marginBefore() + marginAfter() + borderAndPaddingLogicalHeight();
2909 return availableHeight;
2912 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
2914 if (isTableCell()) {
2915 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
2916 // we may just do it with an extra anonymous block inside the cell.
2922 // Margins are calculated with respect to the logical width of
2923 // the containing block (8.3)
2924 LayoutUnit cw = containingBlockLogicalWidthForContent();
2925 RenderStyle* containingBlockStyle = containingBlock->style();
2926 marginBefore = minimumValueForLength(style()->marginBeforeUsing(containingBlockStyle), cw);
2927 marginAfter = minimumValueForLength(style()->marginAfterUsing(containingBlockStyle), cw);
2930 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
2932 LayoutUnit marginBefore;
2933 LayoutUnit marginAfter;
2934 computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
2935 containingBlock->setMarginBeforeForChild(this, marginBefore);
2936 containingBlock->setMarginAfterForChild(this, marginAfter);
2939 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
2941 // Container for position:fixed is the frame.
2942 const FrameView& frameView = view().frameView();
2943 if (fixedElementLaysOutRelativeToFrame(frameView))
2944 return (view().isHorizontalWritingMode() ? frameView.visibleWidth() : frameView.visibleHeight()) / frameView.frame().frameScaleFactor();
2946 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2947 return containingBlockLogicalHeightForPositioned(containingBlock, false);
2949 if (containingBlock->isBox()) {
2950 RenderFlowThread* flowThread = flowThreadContainingBlock();
2952 return toRenderBox(containingBlock)->clientLogicalWidth();
2954 if (containingBlock->isRenderNamedFlowThread() && style()->position() == FixedPosition)
2955 return containingBlock->view().clientLogicalWidth();
2957 const RenderBlock* cb = toRenderBlock(containingBlock);
2958 RenderBoxRegionInfo* boxInfo = 0;
2960 if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
2961 return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
2962 if (isWritingModeRoot()) {
2963 LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
2964 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2966 boxInfo = cb->renderBoxRegionInfo(cbRegion);
2968 } else if (region && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
2969 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
2970 boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
2972 return (boxInfo) ? max<LayoutUnit>(0, cb->clientLogicalWidth() - (cb->logicalWidth() - boxInfo->logicalWidth())) : cb->clientLogicalWidth();
2975 ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
2977 const RenderInline* flow = toRenderInline(containingBlock);
2978 InlineFlowBox* first = flow->firstLineBox();
2979 InlineFlowBox* last = flow->lastLineBox();
2981 // If the containing block is empty, return a width of 0.
2982 if (!first || !last)
2985 LayoutUnit fromLeft;
2986 LayoutUnit fromRight;
2987 if (containingBlock->style()->isLeftToRightDirection()) {
2988 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2989 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2991 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2992 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2995 return max<LayoutUnit>(0, fromRight - fromLeft);
2998 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
3000 const FrameView& frameView = view().frameView();
3001 if (fixedElementLaysOutRelativeToFrame(frameView))
3002 return (view().isHorizontalWritingMode() ? frameView.visibleHeight() : frameView.visibleWidth()) / frameView.frame().frameScaleFactor();
3004 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
3005 return containingBlockLogicalWidthForPositioned(containingBlock, 0, false);
3007 if (containingBlock->isBox()) {
3008 const RenderBlock* cb = toRenderBlock(containingBlock);
3009 LayoutUnit result = cb->clientLogicalHeight();
3010 RenderFlowThread* flowThread = flowThreadContainingBlock();
3011 if (flowThread && containingBlock->isRenderFlowThread() && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
3012 if (containingBlock->isRenderNamedFlowThread() && style()->position() == FixedPosition)
3013 return containingBlock->view().clientLogicalHeight();
3014 return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion();
3019 ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
3021 const RenderInline* flow = toRenderInline(containingBlock);
3022 InlineFlowBox* first = flow->firstLineBox();
3023 InlineFlowBox* last = flow->lastLineBox();
3025 // If the containing block is empty, return a height of 0.
3026 if (!first || !last)
3029 LayoutUnit heightResult;
3030 LayoutRect boundingBox = flow->linesBoundingBox();
3031 if (containingBlock->isHorizontalWritingMode())
3032 heightResult = boundingBox.height();
3034 heightResult = boundingBox.width();
3035 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
3036 return heightResult;
3039 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
3041 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
3044 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
3045 if (child->parent()->style()->direction() == LTR) {
3046 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
3047 for (RenderElement* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
3048 if (curr->isBox()) {
3049 staticPosition += toRenderBox(curr)->logicalLeft();
3050 if (region && curr->isRenderBlock()) {
3051 const RenderBlock* cb = toRenderBlock(curr);
3052 region = cb->clampToStartAndEndRegions(region);
3053 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
3055 staticPosition += boxInfo->logicalLeft();
3059 logicalLeft.setValue(Fixed, staticPosition);
3061 RenderBox* enclosingBox = child->parent()->enclosingBox();
3062 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
3063 for (RenderElement* curr = enclosingBox; curr; curr = curr->container()) {
3064 if (curr->isBox()) {
3065 if (curr != containerBlock)
3066 staticPosition -= toRenderBox(curr)->logicalLeft();
3067 if (curr == enclosingBox)
3068 staticPosition -= enclosingBox->logicalWidth();
3069 if (region && curr->isRenderBlock()) {
3070 const RenderBlock* cb = toRenderBlock(curr);
3071 region = cb->clampToStartAndEndRegions(region);
3072 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
3074 if (curr != containerBlock)
3075 staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
3076 if (curr == enclosingBox)
3077 staticPosition += enclosingBox->logicalWidth() - boxInfo->logicalWidth();
3081 if (curr == containerBlock)
3084 logicalRight.setValue(Fixed, staticPosition);
3088 void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
3091 // FIXME: Positioned replaced elements inside a flow thread are not working properly
3092 // with variable width regions (see https://bugs.webkit.org/show_bug.cgi?id=69896 ).
3093 computePositionedLogicalWidthReplaced(computedValues);
3098 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
3099 // the type 'static' in determining whether to calculate the static distance?
3100 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
3102 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
3103 // than or less than the computed width(). Be careful of box-sizing and
3104 // percentage issues.
3106 // The following is based off of the W3C Working Draft from April 11, 2006 of
3107 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
3108 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
3109 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
3110 // correspond to text from the spec)
3113 // We don't use containingBlock(), since we may be positioned by an enclosing
3114 // relative positioned inline.
3115 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3117 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
3119 // Use the container block's direction except when calculating the static distance
3120 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
3121 // of the CSS 2.1 test suite
3122 TextDirection containerDirection = containerBlock->style()->direction();
3124 bool isHorizontal = isHorizontalWritingMode();
3125 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
3126 const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3127 const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3129 Length logicalLeftLength = style()->logicalLeft();
3130 Length logicalRightLength = style()->logicalRight();
3132 /*---------------------------------------------------------------------------*\
3133 * For the purposes of this section and the next, the term "static position"
3134 * (of an element) refers, roughly, to the position an element would have had
3135 * in the normal flow. More precisely:
3137 * * The static position for 'left' is the distance from the left edge of the
3138 * containing block to the left margin edge of a hypothetical box that would
3139 * have been the first box of the element if its 'position' property had
3140 * been 'static' and 'float' had been 'none'. The value is negative if the
3141 * hypothetical box is to the left of the containing block.
3142 * * The static position for 'right' is the distance from the right edge of the
3143 * containing block to the right margin edge of the same hypothetical box as
3144 * above. The value is positive if the hypothetical box is to the left of the
3145 * containing block's edge.
3147 * But rather than actually calculating the dimensions of that hypothetical box,
3148 * user agents are free to make a guess at its probable position.
3150 * For the purposes of calculating the static position, the containing block of
3151 * fixed positioned elements is the initial containing block instead of the
3152 * viewport, and all scrollable boxes should be assumed to be scrolled to their
3154 \*---------------------------------------------------------------------------*/
3157 // Calculate the static distance if needed.
3158 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
3160 // Calculate constraint equation values for 'width' case.
3161 computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
3162 containerLogicalWidth, bordersPlusPadding,
3163 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3166 // Calculate constraint equation values for 'max-width' case.
3167 if (!style()->logicalMaxWidth().isUndefined()) {
3168 LogicalExtentComputedValues maxValues;
3170 computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
3171 containerLogicalWidth, bordersPlusPadding,
3172 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3175 if (computedValues.m_extent > maxValues.m_extent) {
3176 computedValues.m_extent = maxValues.m_extent;
3177 computedValues.m_position = maxValues.m_position;
3178 computedValues.m_margins.m_start = maxValues.m_margins.m_start;
3179 computedValues.m_margins.m_end = maxValues.m_margins.m_end;
3183 // Calculate constraint equation values for 'min-width' case.
3184 if (!style()->logicalMinWidth().isZero() || style()->logicalMinWidth().isIntrinsic()) {
3185 LogicalExtentComputedValues minValues;
3187 computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
3188 containerLogicalWidth, bordersPlusPadding,
3189 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
3192 if (computedValues.m_extent < minValues.m_extent) {
3193 computedValues.m_extent = minValues.m_extent;
3194 computedValues.m_position = minValues.m_position;
3195 computedValues.m_margins.m_start = minValues.m_margins.m_start;
3196 computedValues.m_margins.m_end = minValues.m_margins.m_end;
3200 computedValues.m_extent += bordersPlusPadding;
3202 // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
3203 // FIXME: Add support for other types of objects as containerBlock, not only RenderBlock.
3204 RenderFlowThread* flowThread = flowThreadContainingBlock();
3205 if (flowThread && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode() && containerBlock->isRenderBlock()) {
3206 ASSERT(containerBlock->canHaveBoxInfoInRegion());
3207 LayoutUnit logicalLeftPos = computedValues.m_position;
3208 const RenderBlock* cb = toRenderBlock(containerBlock);
3209 LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
3210 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
3212 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion);
3214 logicalLeftPos += boxInfo->logicalLeft();
3215 computedValues.m_position = logicalLeftPos;
3221 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
3223 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3224 // 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.
3225 if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
3226 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
3227 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
3229 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
3232 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
3233 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
3234 Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
3235 LogicalExtentComputedValues& computedValues) const
3237 if (logicalWidth.isIntrinsic())
3238 logicalWidth = Length(computeIntrinsicLogicalWidthUsing(logicalWidth, containerLogicalWidth, bordersPlusPadding) - bordersPlusPadding, Fixed);
3240 // 'left' and 'right' cannot both be 'auto' because one would of been
3241 // converted to the static position already
3242 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3244 LayoutUnit logicalLeftValue = 0;
3246 const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
3248 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
3249 bool logicalLeftIsAuto = logicalLeft.isAuto();
3250 bool logicalRightIsAuto = logicalRight.isAuto();
3251 LayoutUnit& marginLogicalLeftValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
3252 LayoutUnit& marginLogicalRightValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
3254 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
3255 /*-----------------------------------------------------------------------*\
3256 * If none of the three is 'auto': If both 'margin-left' and 'margin-
3257 * right' are 'auto', solve the equation under the extra constraint that
3258 * the two margins get equal values, unless this would make them negative,
3259 * in which case when direction of the containing block is 'ltr' ('rtl'),
3260 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
3261 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
3262 * solve the equation for that value. If the values are over-constrained,
3263 * ignore the value for 'left' (in case the 'direction' property of the
3264 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
3265 * and solve for that value.
3266 \*-----------------------------------------------------------------------*/
3267 // NOTE: It is not necessary to solve for 'right' in the over constrained
3268 // case because the value is not used for any further calculations.
3270 logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth);
3271 computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth));
3273 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + computedValues.m_extent + valueForLength(logicalRight, containerLogicalWidth) + bordersPlusPadding);
3275 // Margins are now the only unknown
3276 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3277 // Both margins auto, solve for equality
3278 if (availableSpace >= 0) {
3279 marginLogicalLeftValue = availableSpace / 2; // split the difference
3280 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
3282 // Use the containing block's direction rather than the parent block's
3283 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3284 if (containerDirection == LTR) {
3285 marginLogicalLeftValue = 0;
3286 marginLogicalRightValue = availableSpace; // will be negative
3288 marginLogicalLeftValue = availableSpace; // will be negative
3289 marginLogicalRightValue = 0;
3292 } else if (marginLogicalLeft.isAuto()) {
3293 // Solve for left margin
3294 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3295 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
3296 } else if (marginLogicalRight.isAuto()) {
3297 // Solve for right margin
3298 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3299 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
3301 // Over-constrained, solve for left if direction is RTL
3302 marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerRelativeLogicalWidth);
3303 marginLogicalRightValue = valueForLength(marginLogicalRight, containerRelativeLogicalWidth);
3305 // Use the containing block's direction rather than the parent block's
3306 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
3307 if (containerDirection == RTL)
3308 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
3311 /*--------------------------------------------------------------------*\