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"
28 #include "CachedImage.h"
30 #include "ChromeClient.h"
32 #include "FrameView.h"
33 #include "GraphicsContext.h"
34 #include "HitTestResult.h"
35 #include "htmlediting.h"
36 #include "HTMLElement.h"
37 #include "HTMLNames.h"
38 #include "ImageBuffer.h"
39 #include "FloatQuad.h"
42 #include "PaintInfo.h"
43 #include "RenderArena.h"
44 #include "RenderBoxRegionInfo.h"
45 #include "RenderFlowThread.h"
46 #include "RenderInline.h"
47 #include "RenderLayer.h"
48 #include "RenderPart.h"
49 #include "RenderRegion.h"
50 #include "RenderTableCell.h"
51 #include "RenderTheme.h"
52 #include "RenderView.h"
53 #include "ScrollbarTheme.h"
54 #include "TransformState.h"
62 using namespace HTMLNames;
64 // Used by flexible boxes when flexing this element and by table cells.
65 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
66 static OverrideSizeMap* gOverrideHeightMap = 0;
67 static OverrideSizeMap* gOverrideWidthMap = 0;
69 bool RenderBox::s_hadOverflowClip = false;
71 RenderBox::RenderBox(Node* node)
72 : RenderBoxModelObject(node)
77 , m_minPreferredLogicalWidth(-1)
78 , m_maxPreferredLogicalWidth(-1)
79 , m_inlineBoxWrapper(0)
84 RenderBox::~RenderBox()
88 LayoutUnit RenderBox::marginBefore() const
90 switch (style()->writingMode()) {
91 case TopToBottomWritingMode:
93 case BottomToTopWritingMode:
94 return m_marginBottom;
95 case LeftToRightWritingMode:
97 case RightToLeftWritingMode:
100 ASSERT_NOT_REACHED();
104 LayoutUnit RenderBox::marginAfter() const
106 switch (style()->writingMode()) {
107 case TopToBottomWritingMode:
108 return m_marginBottom;
109 case BottomToTopWritingMode:
111 case LeftToRightWritingMode:
112 return m_marginRight;
113 case RightToLeftWritingMode:
116 ASSERT_NOT_REACHED();
117 return m_marginBottom;
120 LayoutUnit RenderBox::marginStart() const
122 if (isHorizontalWritingMode())
123 return style()->isLeftToRightDirection() ? m_marginLeft : m_marginRight;
124 return style()->isLeftToRightDirection() ? m_marginTop : m_marginBottom;
127 LayoutUnit RenderBox::marginEnd() const
129 if (isHorizontalWritingMode())
130 return style()->isLeftToRightDirection() ? m_marginRight : m_marginLeft;
131 return style()->isLeftToRightDirection() ? m_marginBottom : m_marginTop;
134 void RenderBox::setMarginStart(LayoutUnit margin)
136 if (isHorizontalWritingMode()) {
137 if (style()->isLeftToRightDirection())
138 m_marginLeft = margin;
140 m_marginRight = margin;
142 if (style()->isLeftToRightDirection())
143 m_marginTop = margin;
145 m_marginBottom = margin;
149 void RenderBox::setMarginEnd(LayoutUnit margin)
151 if (isHorizontalWritingMode()) {
152 if (style()->isLeftToRightDirection())
153 m_marginRight = margin;
155 m_marginLeft = margin;
157 if (style()->isLeftToRightDirection())
158 m_marginBottom = margin;
160 m_marginTop = margin;
164 void RenderBox::setMarginBefore(LayoutUnit margin)
166 switch (style()->writingMode()) {
167 case TopToBottomWritingMode:
168 m_marginTop = margin;
170 case BottomToTopWritingMode:
171 m_marginBottom = margin;
173 case LeftToRightWritingMode:
174 m_marginLeft = margin;
176 case RightToLeftWritingMode:
177 m_marginRight = margin;
182 void RenderBox::setMarginAfter(LayoutUnit margin)
184 switch (style()->writingMode()) {
185 case TopToBottomWritingMode:
186 m_marginBottom = margin;
188 case BottomToTopWritingMode:
189 m_marginTop = margin;
191 case LeftToRightWritingMode:
192 m_marginRight = margin;
194 case RightToLeftWritingMode:
195 m_marginLeft = margin;
200 LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, LayoutUnit offsetFromTopOfFirstPage, RenderBoxRegionInfoFlags cacheFlag) const
203 return borderBoxRect();
205 // Compute the logical width and placement in this region.
206 RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, offsetFromTopOfFirstPage, cacheFlag);
208 return borderBoxRect();
210 // We have cached insets.
211 LayoutUnit logicalWidth = boxInfo->logicalWidth();
212 LayoutUnit logicalLeft = boxInfo->logicalLeft();
214 // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
215 // FIXME: Doesn't work right with perpendicular writing modes.
216 const RenderBlock* currentBox = containingBlock();
217 offsetFromTopOfFirstPage -= logicalTop();
218 RenderBoxRegionInfo* currentBoxInfo = currentBox->renderBoxRegionInfo(region, offsetFromTopOfFirstPage);
219 while (currentBoxInfo && currentBoxInfo->isShifted()) {
220 if (currentBox->style()->direction() == LTR)
221 logicalLeft += currentBoxInfo->logicalLeft();
223 logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
224 offsetFromTopOfFirstPage -= logicalTop();
225 currentBox = currentBox->containingBlock();
226 region = currentBox->clampToStartAndEndRegions(region);
227 currentBoxInfo = currentBox->renderBoxRegionInfo(region, offsetFromTopOfFirstPage);
230 if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
233 if (isHorizontalWritingMode())
234 return LayoutRect(logicalLeft, 0, logicalWidth, height());
235 return LayoutRect(0, logicalLeft, width(), logicalWidth);
238 void RenderBox::clearRenderBoxRegionInfo()
240 if (!inRenderFlowThread() || isRenderFlowThread())
243 RenderFlowThread* flowThread = enclosingRenderFlowThread();
244 if (!flowThread->hasValidRegions())
247 flowThread->removeRenderBoxRegionInfo(this);
250 void RenderBox::willBeDestroyed()
254 if (style() && (style()->logicalHeight().isPercent() || style()->logicalMinHeight().isPercent() || style()->logicalMaxHeight().isPercent()))
255 RenderBlock::removePercentHeightDescendant(this);
257 // If this renderer is owning renderer for the frameview's custom scrollbars,
258 // we need to clear it from the scrollbar. See webkit bug 64737.
259 if (style() && style()->hasPseudoStyle(SCROLLBAR) && frame() && frame()->view())
260 frame()->view()->clearOwningRendererForCustomScrollbars(this);
262 // If the following assertion fails, logicalHeight()/logicalMinHeight()/
263 // logicalMaxHeight() values are changed from a percent value to a non-percent
264 // value during laying out. It causes a use-after-free bug.
265 ASSERT(!RenderBlock::hasPercentHeightDescendant(this));
267 RenderBoxModelObject::willBeDestroyed();
270 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
272 ASSERT(isFloatingOrPositioned());
274 if (documentBeingDestroyed())
278 RenderBlock* parentBlock = 0;
279 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
280 if (curr->isRenderBlock()) {
281 RenderBlock* currBlock = toRenderBlock(curr);
282 if (!parentBlock || currBlock->containsFloat(this))
283 parentBlock = currBlock;
288 RenderObject* parent = parentBlock->parent();
289 if (parent && parent->isDeprecatedFlexibleBox())
290 parentBlock = toRenderBlock(parent);
292 parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
296 if (isPositioned()) {
297 for (RenderObject* curr = parent(); curr; curr = curr->parent()) {
298 if (curr->isRenderBlock())
299 toRenderBlock(curr)->removePositionedObject(this);
304 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
306 s_hadOverflowClip = hasOverflowClip();
309 // The background of the root element or the body element could propagate up to
310 // the canvas. Just dirty the entire canvas when our style changes substantially.
311 if (diff >= StyleDifferenceRepaint && node() &&
312 (node()->hasTagName(htmlTag) || node()->hasTagName(bodyTag)))
315 // When a layout hint happens and an object's position style changes, we have to do a layout
316 // to dirty the render tree using the old position value now.
317 if (diff == StyleDifferenceLayout && parent() && style()->position() != newStyle->position()) {
318 markContainingBlocksForLayout();
319 if (style()->position() == StaticPosition)
321 else if (newStyle->position() == AbsolutePosition || newStyle->position() == FixedPosition)
322 parent()->setChildNeedsLayout(true);
323 if (isFloating() && !isPositioned() && (newStyle->position() == AbsolutePosition || newStyle->position() == FixedPosition))
324 removeFloatingOrPositionedChildFromBlockLists();
326 } else if (newStyle && isBody())
329 if (FrameView *frameView = view()->frameView()) {
330 bool newStyleIsFixed = newStyle && newStyle->position() == FixedPosition;
331 bool oldStyleIsFixed = style() && style()->position() == FixedPosition;
332 if (newStyleIsFixed != oldStyleIsFixed) {
334 frameView->addFixedObject();
336 frameView->removeFixedObject();
340 RenderBoxModelObject::styleWillChange(diff, newStyle);
343 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
345 RenderBoxModelObject::styleDidChange(diff, oldStyle);
347 if (needsLayout() && oldStyle) {
348 if (oldStyle && (oldStyle->logicalHeight().isPercent() || oldStyle->logicalMinHeight().isPercent() || oldStyle->logicalMaxHeight().isPercent()))
349 RenderBlock::removePercentHeightDescendant(this);
351 // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
352 // 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
353 // to determine the new static position.
354 if (isPositioned() && style()->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != style()->marginBefore()
355 && parent() && !parent()->normalChildNeedsLayout())
356 parent()->setChildNeedsLayout(true);
359 // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
360 // new zoomed coordinate space.
361 if (hasOverflowClip() && oldStyle && style() && oldStyle->effectiveZoom() != style()->effectiveZoom()) {
362 if (int left = layer()->scrollXOffset()) {
363 left = (left / oldStyle->effectiveZoom()) * style()->effectiveZoom();
364 layer()->scrollToXOffset(left);
366 if (int top = layer()->scrollYOffset()) {
367 top = (top / oldStyle->effectiveZoom()) * style()->effectiveZoom();
368 layer()->scrollToYOffset(top);
372 bool isBodyRenderer = isBody();
373 bool isRootRenderer = isRoot();
375 // Set the text color if we're the body.
377 document()->setTextColor(style()->visitedDependentColor(CSSPropertyColor));
379 if (isRootRenderer || isBodyRenderer) {
380 // Propagate the new writing mode and direction up to the RenderView.
381 RenderView* viewRenderer = view();
382 RenderStyle* viewStyle = viewRenderer->style();
383 if (viewStyle->direction() != style()->direction() && (isRootRenderer || !document()->directionSetOnDocumentElement())) {
384 viewStyle->setDirection(style()->direction());
386 document()->documentElement()->renderer()->style()->setDirection(style()->direction());
387 setNeedsLayoutAndPrefWidthsRecalc();
390 if (viewStyle->writingMode() != style()->writingMode() && (isRootRenderer || !document()->writingModeSetOnDocumentElement())) {
391 viewStyle->setWritingMode(style()->writingMode());
392 viewRenderer->setHorizontalWritingMode(style()->isHorizontalWritingMode());
393 if (isBodyRenderer) {
394 document()->documentElement()->renderer()->style()->setWritingMode(style()->writingMode());
395 document()->documentElement()->renderer()->setHorizontalWritingMode(style()->isHorizontalWritingMode());
397 setNeedsLayoutAndPrefWidthsRecalc();
400 frame()->view()->recalculateScrollbarOverlayStyle();
404 void RenderBox::updateBoxModelInfoFromStyle()
406 RenderBoxModelObject::updateBoxModelInfoFromStyle();
408 bool isRootObject = isRoot();
409 bool isViewObject = isRenderView();
411 // The root and the RenderView always paint their backgrounds/borders.
412 if (isRootObject || isViewObject)
413 setHasBoxDecorations(true);
415 setPositioned(style()->position() == AbsolutePosition || style()->position() == FixedPosition);
416 setFloating(style()->isFloating() && (!isPositioned() || style()->floating() == PositionedFloat));
418 // We also handle <body> and <html>, whose overflow applies to the viewport.
419 if (style()->overflowX() != OVISIBLE && !isRootObject && (isRenderBlock() || isTableRow() || isTableSection())) {
420 bool boxHasOverflowClip = true;
422 // Overflow on the body can propagate to the viewport under the following conditions.
423 // (1) The root element is <html>.
424 // (2) We are the primary <body> (can be checked by looking at document.body).
425 // (3) The root element has visible overflow.
426 if (document()->documentElement()->hasTagName(htmlTag) &&
427 document()->body() == node() &&
428 document()->documentElement()->renderer()->style()->overflowX() == OVISIBLE)
429 boxHasOverflowClip = false;
432 // Check for overflow clip.
433 // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
434 if (boxHasOverflowClip) {
435 if (!s_hadOverflowClip)
436 // Erase the overflow
438 setHasOverflowClip();
442 setHasTransform(style()->hasTransformRelatedProperty());
443 setHasReflection(style()->boxReflect());
446 void RenderBox::layout()
448 ASSERT(needsLayout());
450 RenderObject* child = firstChild();
452 setNeedsLayout(false);
456 LayoutStateMaintainer statePusher(view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
458 child->layoutIfNeeded();
459 ASSERT(!child->needsLayout());
460 child = child->nextSibling();
463 setNeedsLayout(false);
466 // More IE extensions. clientWidth and clientHeight represent the interior of an object
467 // excluding border and scrollbar.
468 LayoutUnit RenderBox::clientWidth() const
470 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
473 LayoutUnit RenderBox::clientHeight() const
475 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
478 LayoutUnit RenderBox::scrollWidth() const
480 if (hasOverflowClip())
481 return layer()->scrollWidth();
482 // For objects with visible overflow, this matches IE.
483 // FIXME: Need to work right with writing modes.
484 if (style()->isLeftToRightDirection())
485 return max(clientWidth(), maxXLayoutOverflow() - borderLeft());
486 return clientWidth() - min<LayoutUnit>(0, minXLayoutOverflow() - borderLeft());
489 LayoutUnit RenderBox::scrollHeight() const
491 if (hasOverflowClip())
492 return layer()->scrollHeight();
493 // For objects with visible overflow, this matches IE.
494 // FIXME: Need to work right with writing modes.
495 return max(clientHeight(), maxYLayoutOverflow() - borderTop());
498 LayoutUnit RenderBox::scrollLeft() const
500 return hasOverflowClip() ? layer()->scrollXOffset() : 0;
503 LayoutUnit RenderBox::scrollTop() const
505 return hasOverflowClip() ? layer()->scrollYOffset() : 0;
508 void RenderBox::setScrollLeft(LayoutUnit newLeft)
510 if (hasOverflowClip())
511 layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
514 void RenderBox::setScrollTop(LayoutUnit newTop)
516 if (hasOverflowClip())
517 layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
520 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
522 rects.append(LayoutRect(accumulatedOffset, size()));
525 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
527 quads.append(localToAbsoluteQuad(FloatRect(0, 0, width(), height()), false, wasFixed));
530 void RenderBox::updateLayerTransform()
532 // Transform-origin depends on box size, so we need to update the layer transform after layout.
534 layer()->updateTransform();
537 LayoutRect RenderBox::absoluteContentBox() const
539 LayoutRect rect = contentBoxRect();
540 FloatPoint absPos = localToAbsolute(FloatPoint());
541 rect.move(absPos.x(), absPos.y());
545 FloatQuad RenderBox::absoluteContentQuad() const
547 LayoutRect rect = contentBoxRect();
548 return localToAbsoluteQuad(FloatRect(rect));
551 LayoutRect RenderBox::outlineBoundsForRepaint(RenderBoxModelObject* repaintContainer, LayoutPoint* cachedOffsetToRepaintContainer) const
553 LayoutRect box = borderBoundingBox();
554 adjustRectForOutlineAndShadow(box);
556 FloatQuad containerRelativeQuad = FloatRect(box);
557 if (cachedOffsetToRepaintContainer)
558 containerRelativeQuad.move(cachedOffsetToRepaintContainer->x(), cachedOffsetToRepaintContainer->y());
560 containerRelativeQuad = localToContainerQuad(containerRelativeQuad, repaintContainer);
562 box = containerRelativeQuad.enclosingBoundingBox();
564 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
565 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
566 box.move(view()->layoutDelta());
571 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset)
573 if (!size().isEmpty())
574 rects.append(LayoutRect(additionalOffset, size()));
577 LayoutRect RenderBox::reflectionBox() const
580 if (!style()->boxReflect())
582 LayoutRect box = borderBoxRect();
584 switch (style()->boxReflect()->direction()) {
585 case ReflectionBelow:
586 result.move(0, box.height() + reflectionOffset());
588 case ReflectionAbove:
589 result.move(0, -box.height() - reflectionOffset());
592 result.move(-box.width() - reflectionOffset(), 0);
594 case ReflectionRight:
595 result.move(box.width() + reflectionOffset(), 0);
601 int RenderBox::reflectionOffset() const
603 if (!style()->boxReflect())
605 if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
606 return style()->boxReflect()->offset().calcValue(borderBoxRect().width());
607 return style()->boxReflect()->offset().calcValue(borderBoxRect().height());
610 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
612 if (!style()->boxReflect())
615 LayoutRect box = borderBoxRect();
616 LayoutRect result = r;
617 switch (style()->boxReflect()->direction()) {
618 case ReflectionBelow:
619 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
621 case ReflectionAbove:
622 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
625 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
627 case ReflectionRight:
628 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
634 bool RenderBox::includeVerticalScrollbarSize() const
636 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
637 && (style()->overflowY() == OSCROLL || style()->overflowY() == OAUTO);
640 bool RenderBox::includeHorizontalScrollbarSize() const
642 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
643 && (style()->overflowX() == OSCROLL || style()->overflowX() == OAUTO);
646 LayoutUnit RenderBox::verticalScrollbarWidth() const
648 return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
651 LayoutUnit RenderBox::horizontalScrollbarHeight() const
653 return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
656 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
658 RenderLayer* l = layer();
659 if (l && l->scroll(direction, granularity, multiplier)) {
665 if (stopNode && *stopNode && *stopNode == node())
668 RenderBlock* b = containingBlock();
669 if (b && !b->isRenderView())
670 return b->scroll(direction, granularity, multiplier, stopNode);
674 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
676 bool scrolled = false;
678 RenderLayer* l = layer();
681 // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
682 if (granularity == ScrollByDocument)
683 scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
685 if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), granularity, multiplier))
695 if (stopNode && *stopNode && *stopNode == node())
698 RenderBlock* b = containingBlock();
699 if (b && !b->isRenderView())
700 return b->logicalScroll(direction, granularity, multiplier, stopNode);
704 bool RenderBox::canBeScrolledAndHasScrollableArea() const
706 return canBeProgramaticallyScrolled() && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth());
709 bool RenderBox::canBeProgramaticallyScrolled() const
711 return (hasOverflowClip() && (scrollsOverflow() || (node() && node()->rendererIsEditable()))) || (node() && node()->isDocumentNode());
714 void RenderBox::autoscroll()
717 layer()->autoscroll();
720 void RenderBox::panScroll(const IntPoint& source)
723 layer()->panScrollFromPoint(source);
726 bool RenderBox::needsPreferredWidthsRecalculation() const
728 return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent();
731 LayoutUnit RenderBox::minPreferredLogicalWidth() const
733 if (preferredLogicalWidthsDirty())
734 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
736 return m_minPreferredLogicalWidth;
739 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
741 if (preferredLogicalWidthsDirty())
742 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
744 return m_maxPreferredLogicalWidth;
747 bool RenderBox::hasOverrideHeight() const
749 return gOverrideHeightMap && gOverrideHeightMap->contains(this);
752 bool RenderBox::hasOverrideWidth() const
754 return gOverrideWidthMap && gOverrideWidthMap->contains(this);
757 void RenderBox::setOverrideHeight(LayoutUnit height)
759 if (!gOverrideHeightMap)
760 gOverrideHeightMap = new OverrideSizeMap();
761 gOverrideHeightMap->set(this, height);
764 void RenderBox::setOverrideWidth(LayoutUnit width)
766 if (!gOverrideWidthMap)
767 gOverrideWidthMap = new OverrideSizeMap();
768 gOverrideWidthMap->set(this, width);
771 void RenderBox::clearOverrideSize()
773 if (hasOverrideHeight())
774 gOverrideHeightMap->remove(this);
775 if (hasOverrideWidth())
776 gOverrideWidthMap->remove(this);
779 LayoutUnit RenderBox::overrideWidth() const
781 return hasOverrideWidth() ? gOverrideWidthMap->get(this) : width();
784 LayoutUnit RenderBox::overrideHeight() const
786 return hasOverrideHeight() ? gOverrideHeightMap->get(this) : height();
789 LayoutUnit RenderBox::computeBorderBoxLogicalWidth(LayoutUnit width) const
791 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
792 if (style()->boxSizing() == CONTENT_BOX)
793 return width + bordersPlusPadding;
794 return max(width, bordersPlusPadding);
797 LayoutUnit RenderBox::computeBorderBoxLogicalHeight(LayoutUnit height) const
799 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
800 if (style()->boxSizing() == CONTENT_BOX)
801 return height + bordersPlusPadding;
802 return max(height, bordersPlusPadding);
805 LayoutUnit RenderBox::computeContentBoxLogicalWidth(LayoutUnit width) const
807 if (style()->boxSizing() == BORDER_BOX)
808 width -= borderAndPaddingLogicalWidth();
809 return max<LayoutUnit>(0, width);
812 LayoutUnit RenderBox::computeContentBoxLogicalHeight(LayoutUnit height) const
814 if (style()->boxSizing() == BORDER_BOX)
815 height -= borderAndPaddingLogicalHeight();
816 return max<LayoutUnit>(0, height);
820 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
822 LayoutPoint adjustedLocation = accumulatedOffset + location();
825 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
826 if (!child->hasLayer() && child->nodeAtPoint(request, result, pointInContainer, adjustedLocation, action)) {
827 updateHitTestResult(result, pointInContainer - toLayoutSize(adjustedLocation));
832 // Check our bounds next. For this purpose always assume that we can only be hit in the
833 // foreground phase (which is true for replaced elements like images).
834 LayoutRect boundsRect = borderBoxRectInRegion(result.region());
835 boundsRect.moveBy(adjustedLocation);
836 if (visibleToHitTesting() && action == HitTestForeground && boundsRect.intersects(result.rectForPoint(pointInContainer))) {
837 updateHitTestResult(result, pointInContainer - toLayoutSize(adjustedLocation));
838 if (!result.addNodeToRectBasedTestResult(node(), pointInContainer, boundsRect))
845 // --------------------- painting stuff -------------------------------
847 void RenderBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
849 LayoutPoint adjustedPaintOffset = paintOffset + location();
850 // default implementation. Just pass paint through to the children
851 PaintInfo childInfo(paintInfo);
852 childInfo.updatePaintingRootForChildren(this);
853 for (RenderObject* child = firstChild(); child; child = child->nextSibling())
854 child->paint(childInfo, adjustedPaintOffset);
857 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
859 const FillLayer* bgLayer = style()->backgroundLayers();
860 Color bgColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
861 RenderObject* bodyObject = 0;
862 if (!hasBackground() && node() && node()->hasTagName(HTMLNames::htmlTag)) {
863 // Locate the <body> element using the DOM. This is easier than trying
864 // to crawl around a render tree with potential :before/:after content and
865 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
866 // render object very easily via the DOM.
867 HTMLElement* body = document()->body();
868 bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
870 bgLayer = bodyObject->style()->backgroundLayers();
871 bgColor = bodyObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
875 RenderView* view = this->view();
876 LayoutRect backgroundRect = view->backgroundRect();
877 flipForWritingMode(backgroundRect);
878 paintFillLayers(paintInfo, bgColor, bgLayer, backgroundRect, BackgroundBleedNone, CompositeSourceOver, bodyObject);
881 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
883 if (context->paintingDisabled())
884 return BackgroundBleedNone;
886 const RenderStyle* style = this->style();
888 if (!style->hasBackground() || !style->hasBorder() || !style->hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
889 return BackgroundBleedNone;
891 AffineTransform ctm = context->getCTM();
892 FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
893 if (borderObscuresBackgroundEdge(contextScaling))
894 return BackgroundBleedShrinkBackground;
896 // FIXME: there is one more strategy possible, for opaque backgrounds and
897 // translucent borders. In that case we could avoid using a transparency layer,
898 // and paint the border first, and then paint the background clipped to the
899 // inside of the border.
901 return BackgroundBleedUseTransparencyLayer;
904 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
906 if (!paintInfo.shouldPaintWithinRoot(this))
909 LayoutRect paintRect = borderBoxRectInRegion(paintInfo.renderRegion);
910 paintRect.moveBy(paintOffset);
912 // border-fit can adjust where we paint our border and background. If set, we snugly fit our line box descendants. (The iChat
913 // balloon layout is an example of this).
914 borderFitAdjust(paintRect);
916 // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
917 // custom shadows of their own.
918 paintBoxShadow(paintInfo, paintRect, style(), Normal);
920 BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
922 GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
923 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
924 // To avoid the background color bleeding out behind the border, we'll render background and border
925 // into a transparency layer, and then clip that in one go (which requires setting up the clip before
926 // beginning the layer).
927 RoundedRect border = style()->getRoundedBorderFor(paintRect);
929 paintInfo.context->addRoundedRectClip(border);
930 paintInfo.context->beginTransparencyLayer(1);
933 // If we have a native theme appearance, paint that before painting our background.
934 // The theme will tell us whether or not we should also paint the CSS background.
935 bool themePainted = style()->hasAppearance() && !theme()->paint(this, paintInfo, paintRect);
937 paintBackground(paintInfo, paintRect, bleedAvoidance);
939 if (style()->hasAppearance())
940 theme()->paintDecorations(this, paintInfo, paintRect);
942 paintBoxShadow(paintInfo, paintRect, style(), Inset);
944 // The theme will tell us whether or not we should also paint the CSS border.
945 if ((!style()->hasAppearance() || (!themePainted && theme()->paintBorderOnly(this, paintInfo, paintRect))) && style()->hasBorder())
946 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
948 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
949 paintInfo.context->endTransparencyLayer();
952 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
955 paintRootBoxFillLayers(paintInfo);
956 else if (!isBody() || document()->documentElement()->renderer()->hasBackground()) {
957 // The <body> only paints its background if the root element has defined a background
958 // independent of the body.
959 if (!backgroundIsObscured())
960 paintFillLayers(paintInfo, style()->visitedDependentColor(CSSPropertyBackgroundColor), style()->backgroundLayers(), paintRect, bleedAvoidance);
964 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
966 if (!paintInfo.shouldPaintWithinRoot(this) || style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
969 LayoutRect paintRect = LayoutRect(paintOffset, size());
971 // border-fit can adjust where we paint our border and background. If set, we snugly fit our line box descendants. (The iChat
972 // balloon layout is an example of this).
973 borderFitAdjust(paintRect);
975 paintMaskImages(paintInfo, paintRect);
978 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
980 // Figure out if we need to push a transparency layer to render our mask.
981 bool pushTransparencyLayer = false;
982 bool compositedMask = hasLayer() && layer()->hasCompositedMask();
983 CompositeOperator compositeOp = CompositeSourceOver;
985 bool allMaskImagesLoaded = true;
987 if (!compositedMask) {
988 // If the context has a rotation, scale or skew, then use a transparency layer to avoid
989 // pixel cruft around the edge of the mask.
990 const AffineTransform& currentCTM = paintInfo.context->getCTM();
991 pushTransparencyLayer = !currentCTM.isIdentityOrTranslationOrFlipped();
993 StyleImage* maskBoxImage = style()->maskBoxImage().image();
994 const FillLayer* maskLayers = style()->maskLayers();
996 // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
998 allMaskImagesLoaded &= maskBoxImage->isLoaded();
1001 allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1003 // Before all images have loaded, just use an empty transparency layer as the mask.
1004 if (!allMaskImagesLoaded)
1005 pushTransparencyLayer = true;
1007 bool hasMaskLayerWithImage = maskLayers->hasImage();
1008 if (maskBoxImage && hasMaskLayerWithImage) {
1009 // We have a mask-box-image and mask-image, so need to composite them together before using the result as a mask.
1010 pushTransparencyLayer = true;
1011 } else if (hasMaskLayerWithImage) {
1012 // We have to use an extra image buffer to hold the mask. Multiple mask images need
1013 // to composite together using source-over so that they can then combine into a single unified mask that
1014 // can be composited with the content using destination-in. SVG images need to be able to set compositing modes
1015 // as they draw images contained inside their sub-document, so we paint all our images into a separate buffer
1016 // and composite that buffer as the mask.
1017 // We have to check that the mask images to be rendered contain at least one image that can be actually used in rendering
1018 // before pushing the transparency layer.
1019 for (const FillLayer* fillLayer = maskLayers->next(); fillLayer; fillLayer = fillLayer->next()) {
1020 if (fillLayer->image() && fillLayer->image()->canRender(this, style()->effectiveZoom())) {
1021 pushTransparencyLayer = true;
1022 // We found one image that can be used in rendering, exit the loop
1028 compositeOp = CompositeDestinationIn;
1029 if (pushTransparencyLayer) {
1030 paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1031 paintInfo.context->beginTransparencyLayer(1.0f);
1032 compositeOp = CompositeSourceOver;
1036 if (allMaskImagesLoaded) {
1037 paintFillLayers(paintInfo, Color(), style()->maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1038 paintNinePieceImage(paintInfo.context, paintRect, style(), style()->maskBoxImage(), compositeOp);
1041 if (pushTransparencyLayer)
1042 paintInfo.context->endTransparencyLayer();
1045 LayoutRect RenderBox::maskClipRect()
1047 const NinePieceImage& maskBoxImage = style()->maskBoxImage();
1048 if (maskBoxImage.image()) {
1049 LayoutRect borderImageRect = borderBoxRect();
1051 // Apply outsets to the border box.
1052 LayoutUnit topOutset;
1053 LayoutUnit rightOutset;
1054 LayoutUnit bottomOutset;
1055 LayoutUnit leftOutset;
1056 style()->getMaskBoxImageOutsets(topOutset, rightOutset, bottomOutset, leftOutset);
1058 borderImageRect.setX(borderImageRect.x() - leftOutset);
1059 borderImageRect.setY(borderImageRect.y() - topOutset);
1060 borderImageRect.setWidth(borderImageRect.width() + leftOutset + rightOutset);
1061 borderImageRect.setHeight(borderImageRect.height() + topOutset + bottomOutset);
1063 return borderImageRect;
1067 LayoutRect borderBox = borderBoxRect();
1068 for (const FillLayer* maskLayer = style()->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1069 if (maskLayer->image()) {
1070 BackgroundImageGeometry geometry;
1071 calculateBackgroundImageGeometry(maskLayer, borderBox, geometry);
1072 result.unite(geometry.destRect());
1078 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1079 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1084 paintFillLayers(paintInfo, c, fillLayer->next(), rect, bleedAvoidance, op, backgroundObject);
1085 paintFillLayer(paintInfo, c, fillLayer, rect, bleedAvoidance, op, backgroundObject);
1088 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1089 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1091 paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, 0, IntSize(), op, backgroundObject);
1094 #if USE(ACCELERATED_COMPOSITING)
1095 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1097 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1098 if (curLayer->image() && image == curLayer->image()->data())
1106 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1111 if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1112 (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1117 bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
1118 if (!didFullRepaint)
1119 repaintLayerRectsForImage(image, style()->maskLayers(), false);
1122 #if USE(ACCELERATED_COMPOSITING)
1123 if (hasLayer() && layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
1124 layer()->contentChanged(RenderLayer::MaskImageChanged);
1128 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1130 LayoutRect rendererRect;
1131 RenderBox* layerRenderer = 0;
1133 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1134 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style()->effectiveZoom())) {
1135 // Now that we know this image is being used, compute the renderer and the rect
1136 // if we haven't already
1137 if (!layerRenderer) {
1138 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document()->documentElement()->renderer()->hasBackground()));
1139 if (drawingRootBackground) {
1140 layerRenderer = view();
1145 if (FrameView* frameView = toRenderView(layerRenderer)->frameView()) {
1146 rw = frameView->contentsWidth();
1147 rh = frameView->contentsHeight();
1149 rw = layerRenderer->width();
1150 rh = layerRenderer->height();
1152 rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1153 -layerRenderer->marginTop(),
1154 max(layerRenderer->width() + layerRenderer->marginLeft() + layerRenderer->marginRight() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1155 max(layerRenderer->height() + layerRenderer->marginTop() + layerRenderer->marginBottom() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1157 layerRenderer = this;
1158 rendererRect = borderBoxRect();
1162 BackgroundImageGeometry geometry;
1163 layerRenderer->calculateBackgroundImageGeometry(curLayer, rendererRect, geometry);
1164 layerRenderer->repaintRectangle(geometry.destRect());
1165 if (geometry.destRect() == rendererRect)
1174 void RenderBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type, bool behindText)
1176 Frame* frame = this->frame();
1179 Page* page = frame->page();
1183 InlineBox* boxWrap = inlineBoxWrapper();
1184 RootInlineBox* r = boxWrap ? boxWrap->root() : 0;
1186 FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + r->selectionTop(), r->logicalWidth(), r->selectionHeight());
1187 FloatRect imageRect(paintOffset.x() + x(), rootRect.y(), width(), rootRect.height());
1188 page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, rootRect, behindText, false);
1190 FloatRect imageRect(paintOffset.x() + x(), paintOffset.y() + y(), width(), height());
1191 page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, imageRect, behindText, false);
1197 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1199 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1202 bool isControlClip = hasControlClip();
1203 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1205 if (!isControlClip && !isOverflowClip)
1208 if (paintInfo.phase == PaintPhaseOutline)
1209 paintInfo.phase = PaintPhaseChildOutlines;
1210 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1211 paintInfo.phase = PaintPhaseBlockBackground;
1212 paintObject(paintInfo, accumulatedOffset);
1213 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1215 IntRect clipRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion));
1216 paintInfo.context->save();
1217 if (style()->hasBorderRadius())
1218 paintInfo.context->addRoundedRectClip(style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())));
1219 paintInfo.context->clip(clipRect);
1223 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1225 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1227 paintInfo.context->restore();
1228 if (originalPhase == PaintPhaseOutline) {
1229 paintInfo.phase = PaintPhaseSelfOutline;
1230 paintObject(paintInfo, accumulatedOffset);
1231 paintInfo.phase = originalPhase;
1232 } else if (originalPhase == PaintPhaseChildBlockBackground)
1233 paintInfo.phase = originalPhase;
1236 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy)
1238 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1240 LayoutRect clipRect = borderBoxRectInRegion(region);
1241 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1242 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1244 // Subtract out scrollbars if we have them.
1246 clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1251 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1253 LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1254 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1256 if (!style()->clipLeft().isAuto()) {
1257 LayoutUnit c = style()->clipLeft().calcValue(borderBoxRect.width());
1258 clipRect.move(c, 0);
1259 clipRect.contract(c, 0);
1262 // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1263 // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1265 if (!style()->clipRight().isAuto())
1266 clipRect.contract(width() - style()->clipRight().calcValue(width()), 0);
1268 if (!style()->clipTop().isAuto()) {
1269 LayoutUnit c = style()->clipTop().calcValue(borderBoxRect.height());
1270 clipRect.move(0, c);
1271 clipRect.contract(0, c);
1274 if (!style()->clipBottom().isAuto())
1275 clipRect.contract(0, height() - style()->clipBottom().calcValue(height()));
1280 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1282 RenderBlock* cb = containingBlock();
1283 if (shrinkToAvoidFloats() && !inRenderFlowThread())
1284 return cb->availableLogicalWidthForLine(logicalTop(), false);
1285 return cb->availableLogicalWidth();
1288 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
1291 return containingBlockLogicalWidthForContent();
1293 RenderBlock* cb = containingBlock();
1294 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1295 if (shrinkToAvoidFloats()) {
1296 LayoutUnit offsetFromLogicalTopOfRegion = region->offsetFromLogicalTopOfFirstPage() - offsetFromLogicalTopOfFirstPage;
1297 return cb->availableLogicalWidthForLine(max(logicalTop(), logicalTop() + offsetFromLogicalTopOfRegion), false, containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
1299 LayoutUnit result = cb->availableLogicalWidth();
1300 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
1303 return max(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1306 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1308 RenderBlock* cb = containingBlock();
1309 RenderStyle* containingBlockStyle = cb->style();
1310 Length logicalHeightLength = containingBlockStyle->logicalHeight();
1312 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1313 if (!logicalHeightLength.isFixed()) {
1314 // Rather than making the child be completely unconstrained, WinIE uses the viewport width and height
1315 // as a constraint. We do that for now as well even though it's likely being unconstrained is what the spec
1317 return containingBlockStyle->isHorizontalWritingMode() ? view()->frameView()->visibleHeight() : view()->frameView()->visibleWidth();
1320 // Use the content box logical height as specified by the style.
1321 return cb->computeContentBoxLogicalHeight(logicalHeightLength.value());
1324 void RenderBox::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
1326 if (repaintContainer == this)
1329 if (RenderView* v = view()) {
1330 if (v->layoutStateEnabled() && !repaintContainer) {
1331 LayoutState* layoutState = v->layoutState();
1332 LayoutSize offset = layoutState->m_paintOffset;
1333 offset.expand(x(), y());
1334 if (style()->position() == RelativePosition && layer())
1335 offset += layer()->relativePositionOffset();
1336 transformState.move(offset);
1341 bool containerSkipped;
1342 RenderObject* o = container(repaintContainer, &containerSkipped);
1346 bool isFixedPos = style()->position() == FixedPosition;
1347 bool hasTransform = hasLayer() && layer()->transform();
1349 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1350 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1351 fixed &= isFixedPos;
1353 fixed |= isFixedPos;
1357 LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1359 bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1360 if (useTransforms && shouldUseTransformFromContainer(o)) {
1361 TransformationMatrix t;
1362 getTransformFromContainer(o, containerOffset, t);
1363 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1365 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1367 if (containerSkipped) {
1368 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1369 // to just subtract the delta between the repaintContainer and o.
1370 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1371 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1375 if (o->isRenderFlowThread()) {
1376 // Transform from render flow coordinates into region coordinates.
1377 RenderRegion* region = toRenderFlowThread(o)->mapFromFlowToRegion(transformState);
1379 region->mapLocalToContainer(region->containerForRepaint(), fixed, useTransforms, transformState, wasFixed);
1383 o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
1386 void RenderBox::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1388 // We don't expect absoluteToLocal() to be called during layout (yet)
1389 ASSERT(!view() || !view()->layoutStateEnabled());
1391 bool isFixedPos = style()->position() == FixedPosition;
1392 bool hasTransform = hasLayer() && layer()->transform();
1394 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1395 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1396 fixed &= isFixedPos;
1398 fixed |= isFixedPos;
1400 RenderObject* o = container();
1404 o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1406 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
1408 bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1409 if (useTransforms && shouldUseTransformFromContainer(o)) {
1410 TransformationMatrix t;
1411 getTransformFromContainer(o, containerOffset, t);
1412 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1414 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1417 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point) const
1419 ASSERT(o == container());
1422 if (isRelPositioned())
1423 offset += relativePositionOffset();
1425 if (!isInline() || isReplaced()) {
1426 if (style()->position() != AbsolutePosition && style()->position() != FixedPosition && o->hasColumns()) {
1427 RenderBlock* block = toRenderBlock(o);
1428 LayoutRect columnRect(frameRect());
1429 block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1430 offset += toSize(columnRect.location());
1431 IntPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
1432 offset = toSize(block->flipForWritingModeIncludingColumns(LayoutPoint(offset)));
1433 o->adjustForColumns(offset, columnPoint);
1434 offset = block->flipForWritingMode(offset);
1436 offset += topLeftLocationOffset();
1439 if (o->hasOverflowClip())
1440 offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1442 if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1443 offset += toRenderInline(o)->relativePositionedInlineOffset(this);
1448 InlineBox* RenderBox::createInlineBox()
1450 return new (renderArena()) InlineBox(this);
1453 void RenderBox::dirtyLineBoxes(bool fullLayout)
1455 if (m_inlineBoxWrapper) {
1457 m_inlineBoxWrapper->destroy(renderArena());
1458 m_inlineBoxWrapper = 0;
1460 m_inlineBoxWrapper->dirtyLineBoxes();
1464 void RenderBox::positionLineBox(InlineBox* box)
1466 if (isPositioned()) {
1467 // Cache the x position only if we were an INLINE type originally.
1468 bool wasInline = style()->isOriginalDisplayInlineType();
1470 // The value is cached in the xPos of the box. We only need this value if
1471 // our object was inline originally, since otherwise it would have ended up underneath
1473 RootInlineBox* root = box->root();
1474 root->block()->setStaticInlinePositionForChild(this, root->lineTopWithLeading(), lroundf(box->logicalLeft()));
1475 if (style()->hasStaticInlinePosition(box->isHorizontal()))
1476 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1478 // Our object was a block originally, so we make our normal flow position be
1479 // just below the line box (as though all the inlines that came before us got
1480 // wrapped in an anonymous block, which is what would have happened had we been
1481 // in flow). This value was cached in the y() of the box.
1482 layer()->setStaticBlockPosition(box->logicalTop());
1483 if (style()->hasStaticBlockPosition(box->isHorizontal()))
1484 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1489 box->destroy(renderArena());
1490 } else if (isReplaced()) {
1491 setLocation(roundedLayoutPoint(FloatPoint(box->x(), box->y())));
1492 ASSERT(!m_inlineBoxWrapper);
1493 m_inlineBoxWrapper = box;
1497 void RenderBox::deleteLineBoxWrapper()
1499 if (m_inlineBoxWrapper) {
1500 if (!documentBeingDestroyed())
1501 m_inlineBoxWrapper->remove();
1502 m_inlineBoxWrapper->destroy(renderArena());
1503 m_inlineBoxWrapper = 0;
1507 LayoutRect RenderBox::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
1509 if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
1510 return LayoutRect();
1512 LayoutRect r = visualOverflowRect();
1514 RenderView* v = view();
1516 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1517 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1518 r.move(v->layoutDelta());
1522 if (style()->hasAppearance())
1523 // The theme may wish to inflate the rect used when repainting.
1524 theme()->adjustRepaintRect(this, r);
1526 // We have to use maximalOutlineSize() because a child might have an outline
1527 // that projects outside of our overflowRect.
1529 ASSERT(style()->outlineSize() <= v->maximalOutlineSize());
1530 r.inflate(v->maximalOutlineSize());
1534 computeRectForRepaint(repaintContainer, r);
1538 void RenderBox::computeRectForRepaint(RenderBoxModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1540 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1541 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1542 // offset corner for the enclosing container). This allows for a fully RL or BT document to repaint
1543 // properly even during layout, since the rect remains flipped all the way until the end.
1545 // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to
1546 // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the
1547 // physical coordinate space of the repaintContainer.
1548 if (RenderView* v = view()) {
1549 // LayoutState is only valid for root-relative, non-fixed position repainting
1550 if (v->layoutStateEnabled() && !repaintContainer && style()->position() != FixedPosition) {
1551 LayoutState* layoutState = v->layoutState();
1553 if (layer() && layer()->transform())
1554 rect = layer()->transform()->mapRect(rect);
1556 if (style()->position() == RelativePosition && layer())
1557 rect.move(layer()->relativePositionOffset());
1559 rect.moveBy(location());
1560 rect.move(layoutState->m_paintOffset);
1561 if (layoutState->m_clipped)
1562 rect.intersect(layoutState->m_clipRect);
1567 if (hasReflection())
1568 rect.unite(reflectedRect(rect));
1570 if (repaintContainer == this) {
1571 if (repaintContainer->style()->isFlippedBlocksWritingMode())
1572 flipForWritingMode(rect);
1576 bool containerSkipped;
1577 RenderObject* o = container(repaintContainer, &containerSkipped);
1581 if (isWritingModeRoot() && !isPositioned())
1582 flipForWritingMode(rect);
1583 LayoutPoint topLeft = rect.location();
1584 topLeft.move(x(), y());
1586 EPosition position = style()->position();
1588 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
1589 // in the parent's coordinate space that encloses us.
1590 if (layer() && layer()->transform()) {
1591 fixed = position == FixedPosition;
1592 rect = layer()->transform()->mapRect(rect);
1593 topLeft = rect.location();
1594 topLeft.move(x(), y());
1595 } else if (position == FixedPosition)
1598 if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1599 topLeft += toRenderInline(o)->relativePositionedInlineOffset(this);
1600 else if (position == RelativePosition && layer()) {
1601 // Apply the relative position offset when invalidating a rectangle. The layer
1602 // is translated, but the render box isn't, so we need to do this to get the
1603 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
1604 // flag on the RenderObject has been cleared, so use the one on the style().
1605 topLeft += layer()->relativePositionOffset();
1608 if (o->isBlockFlow() && position != AbsolutePosition && position != FixedPosition) {
1609 RenderBlock* cb = toRenderBlock(o);
1610 if (cb->hasColumns()) {
1611 LayoutRect repaintRect(topLeft, rect.size());
1612 cb->adjustRectForColumns(repaintRect);
1613 topLeft = repaintRect.location();
1618 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1619 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1620 if (o->hasOverflowClip()) {
1621 RenderBox* containerBox = toRenderBox(o);
1623 // o->height() is inaccurate if we're in the middle of a layout of |o|, so use the
1624 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
1625 // anyway if its size does change.
1626 topLeft -= containerBox->layer()->scrolledContentOffset(); // For overflow:auto/scroll/hidden.
1628 LayoutRect repaintRect(topLeft, rect.size());
1629 LayoutRect boxRect(LayoutPoint(), containerBox->layer()->size());
1630 rect = intersection(repaintRect, boxRect);
1634 rect.setLocation(topLeft);
1636 if (containerSkipped) {
1637 // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
1638 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1639 rect.move(-containerOffset);
1643 o->computeRectForRepaint(repaintContainer, rect, fixed);
1646 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& rect)
1648 LayoutUnit newX = x();
1649 LayoutUnit newY = y();
1650 LayoutUnit newWidth = width();
1651 LayoutUnit newHeight = height();
1652 if (rect.x() != newX || rect.y() != newY) {
1653 // The child moved. Invalidate the object's old and new positions. We have to do this
1654 // since the object may not have gotten a layout.
1657 repaintOverhangingFloats(true);
1658 m_frameRect = LayoutRect(newX, newY, newWidth, newHeight);
1660 repaintOverhangingFloats(true);
1664 void RenderBox::computeLogicalWidth()
1666 computeLogicalWidthInRegion();
1669 void RenderBox::computeLogicalWidthInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
1671 if (isPositioned()) {
1672 // FIXME: This calculation is not patched for block-flow yet.
1673 // https://bugs.webkit.org/show_bug.cgi?id=46500
1674 computePositionedLogicalWidth(region, offsetFromLogicalTopOfFirstPage);
1678 // If layout is limited to a subtree, the subtree root's logical width does not change.
1679 if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1682 // The parent box is flexing us, so it has increased or decreased our
1683 // width. Use the width from the style context.
1684 // FIXME: Account for block-flow in flexible boxes.
1685 // https://bugs.webkit.org/show_bug.cgi?id=46418
1686 if (hasOverrideWidth() && parent()->isFlexibleBoxIncludingDeprecated()) {
1687 setLogicalWidth(overrideWidth());
1691 // FIXME: Account for block-flow in flexible boxes.
1692 // https://bugs.webkit.org/show_bug.cgi?id=46418
1693 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1694 bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1695 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1697 Length logicalWidthLength = (treatAsReplaced) ? Length(computeReplacedLogicalWidth(), Fixed) : style()->logicalWidth();
1699 RenderBlock* cb = containingBlock();
1700 LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region, offsetFromLogicalTopOfFirstPage));
1701 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1702 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
1703 if (hasPerpendicularContainingBlock)
1704 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1706 if (isInline() && !isInlineBlockOrInlineTable()) {
1707 // just calculate margins
1708 setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1709 setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1710 if (treatAsReplaced)
1711 setLogicalWidth(max<LayoutUnit>(logicalWidthLength.calcFloatValue(0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth()));
1715 // Width calculations
1716 if (treatAsReplaced)
1717 setLogicalWidth(logicalWidthLength.value() + borderAndPaddingLogicalWidth());
1719 // Calculate LogicalWidth
1720 setLogicalWidth(computeLogicalWidthUsing(LogicalWidth, containerWidthInInlineDirection));
1722 // Calculate MaxLogicalWidth
1723 if (!style()->logicalMaxWidth().isUndefined()) {
1724 LayoutUnit maxLogicalWidth = computeLogicalWidthUsing(MaxLogicalWidth, containerWidthInInlineDirection);
1725 if (logicalWidth() > maxLogicalWidth) {
1726 setLogicalWidth(maxLogicalWidth);
1727 logicalWidthLength = style()->logicalMaxWidth();
1731 // Calculate MinLogicalWidth
1732 LayoutUnit minLogicalWidth = computeLogicalWidthUsing(MinLogicalWidth, containerWidthInInlineDirection);
1733 if (logicalWidth() < minLogicalWidth) {
1734 setLogicalWidth(minLogicalWidth);
1735 logicalWidthLength = style()->logicalMinWidth();
1739 // Fieldsets are currently the only objects that stretch to their minimum width.
1740 if (stretchesToMinIntrinsicLogicalWidth()) {
1741 setLogicalWidth(max(logicalWidth(), minPreferredLogicalWidth()));
1742 logicalWidthLength = Length(logicalWidth(), Fixed);
1745 // Margin calculations.
1746 if (logicalWidthLength.isAuto() || hasPerpendicularContainingBlock) {
1747 setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1748 setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1750 computeInlineDirectionMargins(cb, containerLogicalWidth, logicalWidth());
1752 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (logicalWidth() + marginStart() + marginEnd())
1753 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated())
1754 cb->setMarginEndForChild(this, containerLogicalWidth - logicalWidth() - cb->marginStartForChild(this));
1757 LayoutUnit RenderBox::computeLogicalWidthUsing(LogicalWidthType widthType, LayoutUnit availableLogicalWidth)
1759 LayoutUnit logicalWidthResult = logicalWidth();
1760 Length logicalWidth;
1761 if (widthType == LogicalWidth)
1762 logicalWidth = style()->logicalWidth();
1763 else if (widthType == MinLogicalWidth)
1764 logicalWidth = style()->logicalMinWidth();
1766 logicalWidth = style()->logicalMaxWidth();
1768 if (logicalWidth.isIntrinsicOrAuto()) {
1769 LayoutUnit marginStart = style()->marginStart().calcMinValue(availableLogicalWidth);
1770 LayoutUnit marginEnd = style()->marginEnd().calcMinValue(availableLogicalWidth);
1771 logicalWidthResult = availableLogicalWidth - marginStart - marginEnd;
1773 if (sizesToIntrinsicLogicalWidth(widthType)) {
1774 logicalWidthResult = max(logicalWidthResult, minPreferredLogicalWidth());
1775 logicalWidthResult = min(logicalWidthResult, maxPreferredLogicalWidth());
1777 } else // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
1778 logicalWidthResult = computeBorderBoxLogicalWidth(logicalWidth.calcValue(availableLogicalWidth));
1780 return logicalWidthResult;
1783 bool RenderBox::sizesToIntrinsicLogicalWidth(LogicalWidthType widthType) const
1785 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
1786 // but they allow text to sit on the same line as the marquee.
1787 if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
1790 // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both
1791 // min-width and width. max-width is only clamped if it is also intrinsic.
1792 Length logicalWidth = (widthType == MaxLogicalWidth) ? style()->logicalMaxWidth() : style()->logicalWidth();
1793 if (logicalWidth.type() == Intrinsic)
1796 // Children of a horizontal marquee do not fill the container by default.
1797 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
1798 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
1799 // block-flow (as well as how marquee overflow should relate to block flow).
1800 // https://bugs.webkit.org/show_bug.cgi?id=46472
1801 if (parent()->style()->overflowX() == OMARQUEE) {
1802 EMarqueeDirection dir = parent()->style()->marqueeDirection();
1803 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
1807 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
1808 // that don't stretch their kids lay out their children at their intrinsic widths.
1809 // FIXME: Think about block-flow here.
1810 // https://bugs.webkit.org/show_bug.cgi?id=46473
1811 if (parent()->isDeprecatedFlexibleBox()
1812 && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
1815 // Button, input, select, textarea, and legend treat
1816 // width value of 'auto' as 'intrinsic' unless it's in a
1817 // stretching vertical flexbox.
1818 // FIXME: Think about block-flow here.
1819 // https://bugs.webkit.org/show_bug.cgi?id=46473
1820 if (logicalWidth.type() == Auto && !(parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == VERTICAL && parent()->style()->boxAlign() == BSTRETCH) && node() && (node()->hasTagName(inputTag) || node()->hasTagName(selectTag) || node()->hasTagName(buttonTag) || node()->hasTagName(textareaTag) || node()->hasTagName(legendTag)))
1823 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
1829 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, int containerWidth, int childWidth)
1831 const RenderStyle* containingBlockStyle = containingBlock->style();
1832 Length marginStartLength = style()->marginStartUsing(containingBlockStyle);
1833 Length marginEndLength = style()->marginEndUsing(containingBlockStyle);
1835 if (isFloating() || isInline()) {
1836 // Inline blocks/tables and floats don't have their margins increased.
1837 containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1838 containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1842 // Case One: The object is being centered in the containing block's available logical width.
1843 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
1844 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
1845 containingBlock->setMarginStartForChild(this, max<LayoutUnit>(0, (containerWidth - childWidth) / 2));
1846 containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1850 // Case Two: The object is being pushed to the start of the containing block's available logical width.
1851 if (marginEndLength.isAuto() && childWidth < containerWidth) {
1852 containingBlock->setMarginStartForChild(this, marginStartLength.calcValue(containerWidth));
1853 containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1857 // Case Three: The object is being pushed to the end of the containing block's available logical width.
1858 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
1859 || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
1860 if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
1861 containingBlock->setMarginEndForChild(this, marginEndLength.calcValue(containerWidth));
1862 containingBlock->setMarginStartForChild(this, containerWidth - childWidth - containingBlock->marginEndForChild(this));
1866 // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3). In that case
1867 // auto margins will just turn into 0.
1868 containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1869 containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1872 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, RenderBoxRegionInfoFlags cacheFlag) const
1874 // Make sure nobody is trying to call this with a null region.
1878 // If we have computed our width in this region already, it will be cached, and we can
1880 RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
1881 if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
1884 // No cached value was found, so we have to compute our insets in this region.
1885 // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
1886 // support to cover all boxes.
1887 if (!inRenderFlowThread() || isFloating() || isReplaced() || isInline() || hasColumns()
1888 || isTableCell() || !isBlockFlow() || isRenderFlowThread())
1891 // FIXME: It's gross to cast away the const, but it would be a huge refactoring to
1892 // change all width computation to avoid updating any member variables, and it would be pretty lame to
1893 // make all the variables mutable as well.
1894 RenderFlowThread* flowThread = enclosingRenderFlowThread();
1895 if (flowThread->style()->writingMode() != style()->writingMode())
1898 LayoutUnit oldLogicalWidth = logicalWidth();
1899 LayoutUnit oldLogicalLeft = logicalLeft();
1900 LayoutUnit oldMarginStart = marginStart();
1901 LayoutUnit oldMarginEnd = marginEnd();
1903 RenderBox* mutableBox = const_cast<RenderBox*>(this);
1905 mutableBox->computeLogicalWidthInRegion(region, offsetFromLogicalTopOfFirstPage);
1907 // Now determine the insets based off where this object is supposed to be positioned.
1908 RenderBlock* cb = containingBlock();
1909 RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
1910 RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion,
1911 offsetFromLogicalTopOfFirstPage - logicalTop());
1912 LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
1913 LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
1915 LayoutUnit marginStartInRegion = marginStart();
1916 LayoutUnit startMarginDelta = marginStartInRegion - oldMarginStart;
1917 LayoutUnit logicalWidthInRegion = logicalWidth();
1918 LayoutUnit logicalLeftInRegion = logicalLeft();
1919 LayoutUnit widthDelta = logicalWidthInRegion - oldLogicalWidth;
1920 LayoutUnit logicalLeftDelta = isPositioned() ? logicalLeftInRegion - oldLogicalLeft : startMarginDelta;
1921 LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
1922 LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (oldLogicalLeft + oldLogicalWidth);
1923 LayoutUnit logicalRightDelta = isPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
1925 // Set our values back.
1926 mutableBox->setLogicalWidth(oldLogicalWidth);
1927 mutableBox->setLogicalLeft(oldLogicalLeft);
1928 mutableBox->setMarginStart(oldMarginStart);
1929 mutableBox->setMarginEnd(oldMarginEnd);
1931 LayoutUnit logicalLeftOffset = 0;
1933 if (!isPositioned() && avoidsFloats() && cb->containsFloats()) {
1934 LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(this, marginStartInRegion, logicalWidthInRegion,
1935 region, offsetFromLogicalTopOfFirstPage);
1936 if (cb->style()->isLeftToRightDirection())
1937 logicalLeftDelta += startPositionDelta;
1939 logicalRightDelta += startPositionDelta;
1942 if (cb->style()->isLeftToRightDirection())
1943 logicalLeftOffset += logicalLeftDelta;
1945 logicalLeftOffset -= (widthDelta + logicalRightDelta);
1947 LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
1948 bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
1949 || (style()->isLeftToRightDirection() && logicalLeftOffset)
1950 || (!style()->isLeftToRightDirection() && logicalRightOffset);
1952 // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
1953 if (cacheFlag == CacheRenderBoxRegionInfo)
1954 return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
1955 return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
1958 void RenderBox::computeLogicalHeight()
1960 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
1961 if (isTableCell() || (isInline() && !isReplaced()))
1966 computePositionedLogicalHeight();
1968 RenderBlock* cb = containingBlock();
1969 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1971 if (!hasPerpendicularContainingBlock)
1972 computeBlockDirectionMargins(cb);
1974 // For tables, calculate margins only.
1976 if (hasPerpendicularContainingBlock)
1977 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), logicalHeight());
1981 // FIXME: Account for block-flow in flexible boxes.
1982 // https://bugs.webkit.org/show_bug.cgi?id=46418
1983 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
1984 bool stretching = parent()->style()->boxAlign() == BSTRETCH;
1985 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
1986 bool checkMinMaxHeight = false;
1988 // The parent box is flexing us, so it has increased or decreased our height. We have to
1989 // grab our cached flexible height.
1990 // FIXME: Account for block-flow in flexible boxes.
1991 // https://bugs.webkit.org/show_bug.cgi?id=46418
1992 if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
1993 h = Length(overrideHeight() - borderAndPaddingLogicalHeight(), Fixed);
1994 else if (treatAsReplaced)
1995 h = Length(computeReplacedLogicalHeight(), Fixed);
1997 h = style()->logicalHeight();
1998 checkMinMaxHeight = true;
2001 // Block children of horizontal flexible boxes fill the height of the box.
2002 // FIXME: Account for block-flow in flexible boxes.
2003 // https://bugs.webkit.org/show_bug.cgi?id=46418
2004 if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
2005 && parent()->isStretchingChildren()) {
2006 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2007 checkMinMaxHeight = false;
2010 LayoutUnit heightResult;
2011 if (checkMinMaxHeight) {
2012 heightResult = computeLogicalHeightUsing(style()->logicalHeight());
2013 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2014 if (heightResult == -1)
2015 heightResult = logicalHeight();
2016 LayoutUnit minH = computeLogicalHeightUsing(style()->logicalMinHeight()); // Leave as -1 if unset.
2017 LayoutUnit maxH = style()->logicalMaxHeight().isUndefined() ? heightResult : computeLogicalHeightUsing(style()->logicalMaxHeight());
2019 maxH = heightResult;
2020 heightResult = min(maxH, heightResult);
2021 heightResult = max(minH, heightResult);
2023 // The only times we don't check min/max height are when a fixed length has
2024 // been given as an override. Just use that. The value has already been adjusted
2026 heightResult = h.value() + borderAndPaddingLogicalHeight();
2029 setLogicalHeight(heightResult);
2031 if (hasPerpendicularContainingBlock)
2032 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult);
2035 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2036 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2037 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2038 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2039 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2040 bool paginatedContentNeedsBaseHeight = document()->printing() && h.isPercent()
2041 && (isRoot() || (isBody() && document()->documentElement()->renderer()->style()->logicalHeight().isPercent()));
2042 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2043 // FIXME: Finish accounting for block flow here.
2044 // https://bugs.webkit.org/show_bug.cgi?id=46603
2045 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2046 LayoutUnit visHeight;
2047 if (document()->printing())
2048 visHeight = static_cast<LayoutUnit>(view()->pageLogicalHeight());
2050 if (isHorizontalWritingMode())
2051 visHeight = view()->viewHeight();
2053 visHeight = view()->viewWidth();
2056 setLogicalHeight(max(logicalHeight(), visHeight - margins));
2058 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2059 setLogicalHeight(max(logicalHeight(), visHeight - marginsBordersPadding));
2064 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& h)
2066 LayoutUnit logicalHeight = -1;
2069 logicalHeight = h.value();
2070 else if (h.isPercent())
2071 logicalHeight = computePercentageLogicalHeight(h);
2072 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2073 if (logicalHeight != -1) {
2074 logicalHeight = computeBorderBoxLogicalHeight(logicalHeight);
2075 return logicalHeight;
2078 return logicalHeight;
2081 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height)
2083 LayoutUnit result = -1;
2085 // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
2086 // block that may have a specified height and then use it. In strict mode, this violates the
2087 // specification, which states that percentage heights just revert to auto if the containing
2088 // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
2089 // only at explicit containers.
2090 bool skippedAutoHeightContainingBlock = false;
2091 RenderBlock* cb = containingBlock();
2092 while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isPositioned() && cb->style()->logicalHeight().isAuto()) {
2093 if (!document()->inQuirksMode() && !cb->isAnonymousBlock())
2095 skippedAutoHeightContainingBlock = true;
2096 cb = cb->containingBlock();
2097 cb->addPercentHeightDescendant(this);
2100 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2101 // explicitly specified that can be used for any percentage computations.
2102 // FIXME: We can't just check top/bottom here.
2103 // https://bugs.webkit.org/show_bug.cgi?id=46500
2104 bool isPositionedWithSpecifiedHeight = cb->isPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
2106 bool includeBorderPadding = isTable();
2108 // Table cells violate what the CSS spec says to do with heights. Basically we
2109 // don't care if the cell specified a height or not. We just always make ourselves
2110 // be a percentage of the cell's current content height.
2111 if (cb->isTableCell()) {
2112 if (!skippedAutoHeightContainingBlock) {
2113 if (!cb->hasOverrideHeight()) {
2114 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2115 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2116 // While we can't get all cases right, we can at least detect when the cell has a specified
2117 // height or when the table has a specified height. In these cases we want to initially have
2118 // no size and allow the flexing of the table or the cell to its specified height to cause us
2119 // to grow to fill the space. This could end up being wrong in some cases, but it is
2120 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2121 RenderTableCell* cell = toRenderTableCell(cb);
2122 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2126 result = cb->overrideHeight();
2127 includeBorderPadding = true;
2130 // Otherwise we only use our percentage height if our containing block had a specified
2132 else if (cb->style()->logicalHeight().isFixed())
2133 result = cb->computeContentBoxLogicalHeight(cb->style()->logicalHeight().value());
2134 else if (cb->style()->logicalHeight().isPercent() && !isPositionedWithSpecifiedHeight) {
2135 // We need to recur and compute the percentage height for our containing block.
2136 result = cb->computePercentageLogicalHeight(cb->style()->logicalHeight());
2137 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2139 result = cb->computeContentBoxLogicalHeight(result);
2140 } else if (cb->isRenderView() || (cb->isBody() && document()->inQuirksMode()) || isPositionedWithSpecifiedHeight) {
2141 // Don't allow this to affect the block' height() member variable, since this
2142 // can get called while the block is still laying out its kids.
2143 LayoutUnit oldHeight = cb->logicalHeight();
2144 cb->computeLogicalHeight();
2145 result = cb->contentLogicalHeight();
2146 cb->setLogicalHeight(oldHeight);
2147 } else if (cb->isRoot() && isPositioned())
2148 // Match the positioned objects behavior, which is that positioned objects will fill their viewport
2149 // always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
2150 result = cb->computeContentBoxLogicalHeight(cb->availableLogicalHeight());
2152 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2154 result = height.calcValue(result);
2155 if (includeBorderPadding) {
2156 // It is necessary to use the border-box to match WinIE's broken
2157 // box model. This is essential for sizing inside
2158 // table cells using percentage heights.
2159 result -= borderAndPaddingLogicalHeight();
2160 result = max<LayoutUnit>(0, result);
2166 LayoutUnit RenderBox::computeReplacedLogicalWidth(bool includeMaxWidth) const
2168 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), includeMaxWidth);
2171 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, bool includeMaxWidth) const
2173 LayoutUnit minLogicalWidth = computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2174 LayoutUnit maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2175 return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
2178 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2180 switch (logicalWidth.type()) {
2182 return computeContentBoxLogicalWidth(logicalWidth.value());
2184 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2185 // containing block's block-flow.
2186 // https://bugs.webkit.org/show_bug.cgi?id=46496
2187 const LayoutUnit cw = isPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2189 return computeContentBoxLogicalWidth(logicalWidth.calcMinValue(cw));
2193 return intrinsicLogicalWidth();
2197 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2199 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2202 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2204 LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2205 LayoutUnit maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2206 return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
2209 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2211 switch (logicalHeight.type()) {
2213 return computeContentBoxLogicalHeight(logicalHeight.value());
2216 RenderObject* cb = isPositioned() ? container() : containingBlock();
2217 while (cb->isAnonymous()) {
2218 cb = cb->containingBlock();
2219 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2222 // FIXME: This calculation is not patched for block-flow yet.
2223 // https://bugs.webkit.org/show_bug.cgi?id=46500
2224 if (cb->isPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2225 ASSERT(cb->isRenderBlock());
2226 RenderBlock* block = toRenderBlock(cb);
2227 LayoutUnit oldHeight = block->height();
2228 block->computeLogicalHeight();
2229 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentHeight());
2230 block->setHeight(oldHeight);
2231 return computeContentBoxLogicalHeight(logicalHeight.calcValue(newHeight));
2234 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2235 // containing block's block-flow.
2236 // https://bugs.webkit.org/show_bug.cgi?id=46496
2237 LayoutUnit availableHeight;
2239 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2241 availableHeight = toRenderBox(cb)->availableLogicalHeight();
2242 // It is necessary to use the border-box to match WinIE's broken
2243 // box model. This is essential for sizing inside
2244 // table cells using percentage heights.
2245 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
2246 // https://bugs.webkit.org/show_bug.cgi?id=46997
2247 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2248 if (cb->isTableCell()) {
2249 // Don't let table cells squeeze percent-height replaced elements
2250 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2251 availableHeight = max(availableHeight, intrinsicLogicalHeight());
2252 return logicalHeight.calcValue(availableHeight - borderAndPaddingLogicalHeight());
2254 cb = cb->containingBlock();
2257 return computeContentBoxLogicalHeight(logicalHeight.calcValue(availableHeight));
2260 return intrinsicLogicalHeight();
2264 LayoutUnit RenderBox::availableLogicalHeight() const
2266 return availableLogicalHeightUsing(style()->logicalHeight());
2269 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const
2272 return computeContentBoxLogicalHeight(h.value());
2275 return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
2277 // We need to stop here, since we don't want to increase the height of the table
2278 // artificially. We're going to rely on this cell getting expanded to some new
2279 // height, and then when we lay out again we'll use the calculation below.
2280 if (isTableCell() && (h.isAuto() || h.isPercent()))
2281 return overrideHeight() - borderAndPaddingLogicalWidth();
2283 if (h.isPercent()) {
2284 LayoutUnit availableHeight;
2285 // https://bugs.webkit.org/show_bug.cgi?id=64046
2286 // For absolutely positioned elements whose containing block is based on a block-level element,
2287 // the percentage is calculated with respect to the height of the padding box of that element
2289 availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2291 availableHeight = containingBlock()->availableLogicalHeight();
2292 return computeContentBoxLogicalHeight(h.calcValue(availableHeight));
2295 // FIXME: We can't just check top/bottom here.
2296 // https://bugs.webkit.org/show_bug.cgi?id=46500
2297 if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2298 RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2299 LayoutUnit oldHeight = block->logicalHeight();
2300 block->computeLogicalHeight();
2301 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
2302 block->setLogicalHeight(oldHeight);
2303 return computeContentBoxLogicalHeight(newHeight);
2306 return containingBlock()->availableLogicalHeight();
2309 void RenderBox::computeBlockDirectionMargins(RenderBlock* containingBlock)
2311 if (isTableCell()) {
2312 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
2313 // we may just do it with an extra anonymous block inside the cell.
2319 // Margins are calculated with respect to the logical width of
2320 // the containing block (8.3)
2321 LayoutUnit cw = containingBlockLogicalWidthForContent();
2323 RenderStyle* containingBlockStyle = containingBlock->style();
2324 containingBlock->setMarginBeforeForChild(this, style()->marginBeforeUsing(containingBlockStyle).calcMinValue(cw));
2325 containingBlock->setMarginAfterForChild(this, style()->marginAfterUsing(containingBlockStyle).calcMinValue(cw));
2328 int RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region,
2329 LayoutUnit offsetFromLogicalTopOfFirstPage, bool checkForPerpendicularWritingMode) const
2331 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2332 return containingBlockLogicalHeightForPositioned(containingBlock, false);
2334 if (containingBlock->isBox()) {
2335 const RenderBlock* cb = toRenderBlock(containingBlock);
2336 LayoutUnit result = cb->clientLogicalWidth();
2337 if (inRenderFlowThread()) {
2338 RenderBoxRegionInfo* boxInfo = 0;
2340 if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
2341 return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
2342 if (isWritingModeRoot()) {
2343 LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2344 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2345 cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2346 boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2348 } else if (region && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
2349 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
2350 boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
2353 return max(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
2358 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2360 const RenderInline* flow = toRenderInline(containingBlock);
2361 InlineFlowBox* first = flow->firstLineBox();
2362 InlineFlowBox* last = flow->lastLineBox();
2364 // If the containing block is empty, return a width of 0.
2365 if (!first || !last)
2368 LayoutUnit fromLeft;
2369 LayoutUnit fromRight;
2370 if (containingBlock->style()->isLeftToRightDirection()) {
2371 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2372 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2374 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2375 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2378 return max<LayoutUnit>(0, fromRight - fromLeft);
2381 int RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2383 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2384 return containingBlockLogicalWidthForPositioned(containingBlock, 0, 0, false);
2386 if (containingBlock->isBox()) {
2387 const RenderBlock* cb = toRenderBlock(containingBlock);
2388 LayoutUnit result = cb->clientLogicalHeight();
2389 if (inRenderFlowThread() && containingBlock->isRenderFlowThread() && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode())
2390 return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion();
2394 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2396 const RenderInline* flow = toRenderInline(containingBlock);
2397 InlineFlowBox* first = flow->firstLineBox();
2398 InlineFlowBox* last = flow->lastLineBox();
2400 // If the containing block is empty, return a height of 0.
2401 if (!first || !last)
2404 LayoutUnit heightResult;
2405 LayoutRect boundingBox = flow->linesBoundingBox();
2406 if (containingBlock->isHorizontalWritingMode())
2407 heightResult = boundingBox.height();
2409 heightResult = boundingBox.width();
2410 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2411 return heightResult;
2414 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
2416 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2419 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2420 if (child->parent()->style()->direction() == LTR) {
2421 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2422 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2423 if (curr->isBox()) {
2424 staticPosition += toRenderBox(curr)->logicalLeft();
2425 if (region && curr->isRenderBlock()) {
2426 const RenderBlock* cb = toRenderBlock(curr);
2427 region = cb->clampToStartAndEndRegions(region);
2428 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2430 staticPosition += boxInfo->logicalLeft();
2434 logicalLeft.setValue(Fixed, staticPosition);
2436 RenderBox* enclosingBox = child->parent()->enclosingBox();
2437 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
2438 for (RenderObject* curr = enclosingBox; curr; curr = curr->container()) {
2439 if (curr->isBox()) {
2440 if (curr != containerBlock)
2441 staticPosition -= toRenderBox(curr)->logicalLeft();
2442 if (curr == enclosingBox)
2443 staticPosition -= enclosingBox->logicalWidth();
2444 if (region && curr->isRenderBlock()) {
2445 const RenderBlock* cb = toRenderBlock(curr);
2446 region = cb->clampToStartAndEndRegions(region);
2447 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2449 if (curr != containerBlock)
2450 staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
2451 if (curr == enclosingBox)
2452 staticPosition += enclosingBox->logicalWidth() - boxInfo->logicalWidth();
2456 if (curr == containerBlock)
2459 logicalRight.setValue(Fixed, staticPosition);
2463 void RenderBox::computePositionedLogicalWidth(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
2466 computePositionedLogicalWidthReplaced(); // FIXME: Patch for regions when we add replaced element support.
2471 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
2472 // the type 'static' in determining whether to calculate the static distance?
2473 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2475 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
2476 // than or less than the computed width(). Be careful of box-sizing and
2477 // percentage issues.
2479 // The following is based off of the W3C Working Draft from April 11, 2006 of
2480 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2481 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2482 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2483 // correspond to text from the spec)
2486 // We don't use containingBlock(), since we may be positioned by an enclosing
2487 // relative positioned inline.
2488 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2490 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region, offsetFromLogicalTopOfFirstPage);
2492 // Use the container block's direction except when calculating the static distance
2493 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
2494 // of the CSS 2.1 test suite
2495 TextDirection containerDirection = containerBlock->style()->direction();
2497 bool isHorizontal = isHorizontalWritingMode();
2498 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2499 const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2500 const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2501 LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
2502 LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
2504 Length logicalLeftLength = style()->logicalLeft();
2505 Length logicalRightLength = style()->logicalRight();
2507 /*---------------------------------------------------------------------------*\
2508 * For the purposes of this section and the next, the term "static position"
2509 * (of an element) refers, roughly, to the position an element would have had
2510 * in the normal flow. More precisely:
2512 * * The static position for 'left' is the distance from the left edge of the
2513 * containing block to the left margin edge of a hypothetical box that would
2514 * have been the first box of the element if its 'position' property had
2515 * been 'static' and 'float' had been 'none'. The value is negative if the
2516 * hypothetical box is to the left of the containing block.
2517 * * The static position for 'right' is the distance from the right edge of the
2518 * containing block to the right margin edge of the same hypothetical box as
2519 * above. The value is positive if the hypothetical box is to the left of the
2520 * containing block's edge.
2522 * But rather than actually calculating the dimensions of that hypothetical box,
2523 * user agents are free to make a guess at its probable position.
2525 * For the purposes of calculating the static position, the containing block of
2526 * fixed positioned elements is the initial containing block instead of the
2527 * viewport, and all scrollable boxes should be assumed to be scrolled to their
2529 \*---------------------------------------------------------------------------*/
2532 // Calculate the static distance if needed.
2533 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
2535 // Calculate constraint equation values for 'width' case.
2536 LayoutUnit logicalWidthResult;
2537 LayoutUnit logicalLeftResult;
2538 computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2539 containerLogicalWidth, bordersPlusPadding,
2540 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2541 logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2542 setLogicalWidth(logicalWidthResult);
2543 setLogicalLeft(logicalLeftResult);
2545 // Calculate constraint equation values for 'max-width' case.
2546 if (!style()->logicalMaxWidth().isUndefined()) {
2547 LayoutUnit maxLogicalWidth;
2548 LayoutUnit maxMarginLogicalLeft;
2549 LayoutUnit maxMarginLogicalRight;
2550 LayoutUnit maxLogicalLeftPos;
2552 computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2553 containerLogicalWidth, bordersPlusPadding,
2554 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2555 maxLogicalWidth, maxMarginLogicalLeft, maxMarginLogicalRight, maxLogicalLeftPos);
2557 if (logicalWidth() > maxLogicalWidth) {
2558 setLogicalWidth(maxLogicalWidth);
2559 marginLogicalLeftAlias = maxMarginLogicalLeft;
2560 marginLogicalRightAlias = maxMarginLogicalRight;
2561 setLogicalLeft(maxLogicalLeftPos);
2565 // Calculate constraint equation values for 'min-width' case.
2566 if (!style()->logicalMinWidth().isZero()) {
2567 LayoutUnit minLogicalWidth;
2568 LayoutUnit minMarginLogicalLeft;
2569 LayoutUnit minMarginLogicalRight;
2570 LayoutUnit minLogicalLeftPos;
2572 computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2573 containerLogicalWidth, bordersPlusPadding,
2574 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2575 minLogicalWidth, minMarginLogicalLeft, minMarginLogicalRight, minLogicalLeftPos);
2577 if (logicalWidth() < minLogicalWidth) {
2578 setLogicalWidth(minLogicalWidth);
2579 marginLogicalLeftAlias = minMarginLogicalLeft;
2580 marginLogicalRightAlias = minMarginLogicalRight;
2581 setLogicalLeft(minLogicalLeftPos);
2585 if (stretchesToMinIntrinsicLogicalWidth() && logicalWidth() < minPreferredLogicalWidth() - bordersPlusPadding) {
2586 computePositionedLogicalWidthUsing(Length(minPreferredLogicalWidth() - bordersPlusPadding, Fixed), containerBlock, containerDirection,
2587 containerLogicalWidth, bordersPlusPadding,
2588 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2589 logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2590 setLogicalWidth(logicalWidthResult);
2591 setLogicalLeft(logicalLeftResult);
2594 // Put logicalWidth() into correct form.
2595 setLogicalWidth(logicalWidth() + bordersPlusPadding);
2597 // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
2598 if (inRenderFlowThread() && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2599 LayoutUnit logicalLeftPos = logicalLeft();
2600 const RenderBlock* cb = toRenderBlock(containerBlock);
2601 LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2602 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2603 cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2604 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2606 logicalLeftPos += boxInfo->logicalLeft();
2607 setLogicalLeft(logicalLeftPos);
2612 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2614 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2615 // 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.
2616 if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2617 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2618 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2620 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2623 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2624 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2625 Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
2626 LayoutUnit& logicalWidthValue, LayoutUnit& marginLogicalLeftValue, LayoutUnit& marginLogicalRightValue, LayoutUnit& logicalLeftPos)
2628 // 'left' and 'right' cannot both be 'auto' because one would of been
2629 // converted to the static position already
2630 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2632 LayoutUnit logicalLeftValue = 0;
2634 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2635 bool logicalLeftIsAuto = logicalLeft.isAuto();
2636 bool logicalRightIsAuto = logicalRight.isAuto();
2638 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2639 /*-----------------------------------------------------------------------*\
2640 * If none of the three is 'auto': If both 'margin-left' and 'margin-
2641 * right' are 'auto', solve the equation under the extra constraint that
2642 * the two margins get equal values, unless this would make them negative,
2643 * in which case when direction of the containing block is 'ltr' ('rtl'),
2644 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2645 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2646 * solve the equation for that value. If the values are over-constrained,
2647 * ignore the value for 'left' (in case the 'direction' property of the
2648 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2649 * and solve for that value.
2650 \*-----------------------------------------------------------------------*/
2651 // NOTE: It is not necessary to solve for 'right' in the over constrained
2652 // case because the value is not used for any further calculations.
2654 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2655 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2657 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + logicalWidthValue + logicalRight.calcValue(containerLogicalWidth) + bordersPlusPadding);
2659 // Margins are now the only unknown
2660 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2661 // Both margins auto, solve for equality
2662 if (availableSpace >= 0) {
2663 marginLogicalLeftValue = availableSpace / 2; // split the difference
2664 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2666 // Use the containing block's direction rather than the parent block's
2667 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2668 if (containerDirection == LTR) {
2669 marginLogicalLeftValue = 0;
2670 marginLogicalRightValue = availableSpace; // will be negative
2672 marginLogicalLeftValue = availableSpace; // will be negative
2673 marginLogicalRightValue = 0;
2676 } else if (marginLogicalLeft.isAuto()) {
2677 // Solve for left margin
2678 marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2679 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
2680 } else if (marginLogicalRight.isAuto()) {
2681 // Solve for right margin
2682 marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2683 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
2685 // Over-constrained, solve for left if direction is RTL
2686 marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2687 marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2689 // Use the containing block's direction rather than the parent block's
2690 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2691 if (containerDirection == RTL)
2692 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
2695 /*--------------------------------------------------------------------*\
2696 * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
2697 * to 0, and pick the one of the following six rules that applies.
2699 * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
2700 * width is shrink-to-fit. Then solve for 'left'
2702 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2703 * ------------------------------------------------------------------
2704 * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
2705 * the 'direction' property of the containing block is 'ltr' set
2706 * 'left' to the static position, otherwise set 'right' to the
2707 * static position. Then solve for 'left' (if 'direction is 'rtl')
2708 * or 'right' (if 'direction' is 'ltr').
2709 * ------------------------------------------------------------------
2711 * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
2712 * width is shrink-to-fit . Then solve for 'right'
2713 * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
2715 * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
2717 * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
2720 * Calculation of the shrink-to-fit width is similar to calculating the
2721 * width of a table cell using the automatic table layout algorithm.
2722 * Roughly: calculate the preferred width by formatting the content
2723 * without breaking lines other than where explicit line breaks occur,
2724 * and also calculate the preferred minimum width, e.g., by trying all
2725 * possible line breaks. CSS 2.1 does not define the exact algorithm.
2726 * Thirdly, calculate the available width: this is found by solving
2727 * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
2730 * Then the shrink-to-fit width is:
2731 * min(max(preferred minimum width, available width), preferred width).
2732 \*--------------------------------------------------------------------*/
2733 // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
2734 // because the value is not used for any further calculations.
2736 // Calculate margins, 'auto' margins are ignored.
2737 marginLogicalLeftValue = marginLogicalLeft.calcMinValue(containerLogicalWidth);
2738 marginLogicalRightValue = marginLogicalRight.calcMinValue(containerLogicalWidth);
2740 const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
2742 // FIXME: Is there a faster way to find the correct case?
2743 // Use rule/case that applies.
2744 if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2745 // RULE 1: (use shrink-to-fit for width, and solve of left)
2746 LayoutUnit logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2748 // FIXME: would it be better to have shrink-to-fit in one step?
2749 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2750 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2751 LayoutUnit availableWidth = availableSpace - logicalRightValue;
2752 logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2753 logicalLeftValue = availableSpace - (logicalWidthValue + logicalRightValue);
2754 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
2755 // RULE 3: (use shrink-to-fit for width, and no need solve of right)
2756 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2758 // FIXME: would it be better to have shrink-to-fit in one step?
2759 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2760 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2761 LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2762 logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2763 } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2764 // RULE 4: (solve for left)
2765 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2766 logicalLeftValue = availableSpace - (logicalWidthValue + logicalRight.calcValue(containerLogicalWidth));
2767 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2768 // RULE 5: (solve for width)
2769 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2770 logicalWidthValue = availableSpace - (logicalLeftValue + logicalRight.calcValue(containerLogicalWidth));
2771 } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
2772 // RULE 6: (no need solve for right)
2773 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2774 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2778 // Use computed values to calculate the horizontal position.
2780 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
2781 // positioned, inline because right now, it is using the logical left position
2782 // of the first line box when really it should use the last line box. When
2783 // this is fixed elsewhere, this block should be removed.
2784 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2785 const RenderInline* flow = toRenderInline(containerBlock);
2786 InlineFlowBox* firstLine = flow->firstLineBox();
2787 InlineFlowBox* lastLine = flow->lastLineBox();
2788 if (firstLine && lastLine && firstLine != lastLine) {
2789 logicalLeftPos = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
2794 logicalLeftPos = logicalLeftValue + marginLogicalLeftValue;
2795 computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidthValue, containerBlock, containerLogicalWidth);
2798 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
2800 if (!logicalTop.isAuto() || !logicalBottom.isAuto())
2803 // FIXME: The static distance computation has not been patched for mixed writing modes.
2804 LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
2805 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2806 if (curr->isBox() && !curr->isTableRow())
2807 staticLogicalTop += toRenderBox(curr)->logicalTop();
2809 logicalTop.setValue(Fixed, staticLogicalTop);
2812 void RenderBox::computePositionedLogicalHeight()
2815 computePositionedLogicalHeightReplaced();
2819 // The following is based off of the W3C Working Draft from April 11, 2006 of
2820 // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
2821 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
2822 // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
2823 // correspond to text from the spec)
2826 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
2827 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2829 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
2831 bool isHorizontal = isHorizontalWritingMode();
2832 bool isFlipped = style()->isFlippedBlocksWritingMode();
2833 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
2834 const Length marginBefore = style()->marginBefore();
2835 const Length marginAfter = style()->marginAfter();
2836 LayoutUnit& marginBeforeAlias = isHorizontal ? (isFlipped ? m_marginBottom : m_marginTop) : (isFlipped ? m_marginRight: m_marginLeft);
2837 LayoutUnit& marginAfterAlias = isHorizontal ? (isFlipped ? m_marginTop : m_marginBottom) : (isFlipped ? m_marginLeft: m_marginRight);
2839 Length logicalTopLength = style()->logicalTop();
2840 Length logicalBottomLength = style()->logicalBottom();
2842 /*---------------------------------------------------------------------------*\
2843 * For the purposes of this section and the next, the term "static position"
2844 * (of an element) refers, roughly, to the position an element would have had
2845 * in the normal flow. More precisely, the static position for 'top' is the
2846 * distance from the top edge of the containing block to the top margin edge
2847 * of a hypothetical box that would have been the first box of the element if
2848 * its 'position' property had been 'static' and 'float' had been 'none'. The
2849 * value is negative if the hypothetical box is above the containing block.
2851 * But rather than actually calculating the dimensions of that hypothetical
2852 * box, user agents are free to make a guess at its probable position.
2854 * For the purposes of calculating the static position, the containing block
2855 * of fixed positioned elements is the initial containing block instead of
2857 \*---------------------------------------------------------------------------*/
2860 // Calculate the static distance if needed.
2861 computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
2863 LayoutUnit logicalHeightResult; // Needed to compute overflow.
2864 LayoutUnit logicalTopPos;
2866 // Calculate constraint equation values for 'height' case.
2867 computePositionedLogicalHeightUsing(style()->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2868 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2869 logicalHeightResult, marginBeforeAlias, marginAfterAlias, logicalTopPos);
2870 setLogicalTop(logicalTopPos);
2872 // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
2875 // Calculate constraint equation values for 'max-height' case.
2876 if (!style()->logicalMaxHeight().isUndefined()) {
2877 LayoutUnit maxLogicalHeight;
2878 LayoutUnit maxMarginBefore;
2879 LayoutUnit maxMarginAfter;
2880 LayoutUnit maxLogicalTopPos;
2882 computePositionedLogicalHeightUsing(style()->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2883 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2884 maxLogicalHeight, maxMarginBefore, maxMarginAfter, maxLogicalTopPos);
2886 if (logicalHeightResult > maxLogicalHeight) {
2887 logicalHeightResult = maxLogicalHeight;
2888 marginBeforeAlias = maxMarginBefore;
2889 marginAfterAlias = maxMarginAfter;
2890 setLogicalTop(maxLogicalTopPos);
2894 // Calculate constraint equation values for 'min-height' case.
2895 if (!style()->logicalMinHeight().isZero()) {
2896 LayoutUnit minLogicalHeight;
2897 LayoutUnit minMarginBefore;
2898 LayoutUnit minMarginAfter;
2899 LayoutUnit minLogicalTopPos;
2901 computePositionedLogicalHeightUsing(style()->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2902 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2903 minLogicalHeight, minMarginBefore, minMarginAfter, minLogicalTopPos);
2905 if (logicalHeightResult < minLogicalHeight) {
2906 logicalHeightResult = minLogicalHeight;
2907 marginBeforeAlias = minMarginBefore;
2908 marginAfterAlias = minMarginAfter;
2909 setLogicalTop(minLogicalTopPos);
2913 // Set final height value.
2914 setLogicalHeight(logicalHeightResult + bordersPlusPadding);
2916 // Adjust logicalTop if we need to for perpendicular writing modes in regions.
2917 if (inRenderFlowThread() && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode()) {
2918 LayoutUnit logicalTopPos = logicalTop();
2919 const RenderBlock* cb = toRenderBlock(containerBlock);
2920 LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage() - logicalLeft();
2921 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2922 cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2923 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2925 logicalTopPos += boxInfo->logicalLeft();
2926 setLogicalTop(logicalTopPos);
2931 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
2933 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2934 // 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.
2935 if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
2936 || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
2937 logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
2939 // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
2940 if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2941 if (child->isHorizontalWritingMode())
2942 logicalTopPos += containerBlock->borderBottom();
2944 logicalTopPos += containerBlock->borderRight();
2946 if (child->isHorizontalWritingMode())
2947 logicalTopPos += containerBlock->borderTop();
2949 logicalTopPos += containerBlock->borderLeft();
2953 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
2954 LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding,
2955 Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
2956 LayoutUnit& logicalHeightValue, LayoutUnit& marginBeforeValue, LayoutUnit& marginAfterValue, LayoutUnit& logicalTopPos)
2958 // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
2959 // converted to the static position in computePositionedLogicalHeight()
2960 ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
2962 LayoutUnit contentLogicalHeight = logicalHeight() - bordersPlusPadding;
2964 LayoutUnit logicalTopValue = 0;
2966 bool logicalHeightIsAuto = logicalHeightLength.isAuto();
2967 bool logicalTopIsAuto = logicalTop.isAuto();
2968 bool logicalBottomIsAuto = logicalBottom.isAuto();
2970 // Height is never unsolved for tables.
2972 logicalHeightLength.setValue(Fixed, contentLogicalHeight);
2973 logicalHeightIsAuto = false;
2976 if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
2977 /*-----------------------------------------------------------------------*\
2978 * If none of the three are 'auto': If both 'margin-top' and 'margin-
2979 * bottom' are 'auto', solve the equation under the extra constraint that
2980 * the two margins get equal values. If one of 'margin-top' or 'margin-
2981 * bottom' is 'auto', solve the equation for that value. If the values
2982 * are over-constrained, ignore the value for 'bottom' and solve for that
2984 \*-----------------------------------------------------------------------*/
2985 // NOTE: It is not necessary to solve for 'bottom' in the over constrained
2986 // case because the value is not used for any further calculations.
2988 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2989 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2991 const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight) + bordersPlusPadding);
2993 // Margins are now the only unknown
2994 if (marginBefore.isAuto() && marginAfter.isAuto()) {
2995 // Both margins auto, solve for equality
2996 // NOTE: This may result in negative values.
2997 marginBeforeValue = availableSpace / 2; // split the difference
2998 marginAfterValue = availableSpace - marginBeforeValue; // account for odd valued differences
2999 } else if (marginBefore.isAuto()) {
3000 // Solve for top margin
3001 marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
3002 marginBeforeValue = availableSpace - marginAfterValue;
3003 } else if (marginAfter.isAuto()) {
3004 // Solve for bottom margin
3005 marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
3006 marginAfterValue = availableSpace - marginBeforeValue;
3008 // Over-constrained, (no need solve for bottom)
3009 marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
3010 marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
3013 /*--------------------------------------------------------------------*\
3014 * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3015 * to 0, and pick the one of the following six rules that applies.
3017 * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3018 * the height is based on the content, and solve for 'top'.
3020 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3021 * ------------------------------------------------------------------
3022 * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3023 * set 'top' to the static position, and solve for 'bottom'.
3024 * ------------------------------------------------------------------
3026 * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3027 * the height is based on the content, and solve for 'bottom'.
3028 * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3030 * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3031 * solve for 'height'.
3032 * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3033 * solve for 'bottom'.
3034 \*--------------------------------------------------------------------*/
3035 // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3036 // because the value is not used for any further calculations.
3038 // Calculate margins, 'auto' margins are ignored.
3039 marginBeforeValue = marginBefore.calcMinValue(containerLogicalHeight);
3040 marginAfterValue = marginAfter.calcMinValue(containerLogicalHeight);
3042 const LayoutUnit availableSpace = containerLogicalHeight - (marginBeforeValue + marginAfterValue + bordersPlusPadding);
3044 // Use rule/case that applies.
3045 if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3046 // RULE 1: (height is content based, solve of top)
3047 logicalHeightValue = contentLogicalHeight;
3048 logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
3049 } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
3050 // RULE 3: (height is content based, no need solve of bottom)
3051 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3052 logicalHeightValue = contentLogicalHeight;
3053 } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3054 // RULE 4: (solve of top)
3055 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
3056 logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
3057 } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3058 // RULE 5: (solve of height)
3059 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3060 logicalHeightValue = max<LayoutUnit>(0, availableSpace - (logicalTopValue + logicalBottom.calcValue(containerLogicalHeight)));
3061 } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
3062 // RULE 6: (no need solve of bottom)
3063 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
3064 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3068 // Use computed values to calculate the vertical position.
3069 logicalTopPos = logicalTopValue + marginBeforeValue;
3070 computeLogicalTopPositionedOffset(logicalTopPos, this, logicalHeightValue, containerBlock, containerLogicalHeight);
3073 void RenderBox::computePositionedLogicalWidthReplaced()
3075 // The following is based off of the W3C Working Draft from April 11, 2006 of
3076 // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
3077 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
3078 // (block-style-comments in this function correspond to text from the spec and
3079 // the numbers correspond to numbers in spec)
3081 // We don't use containingBlock(), since we may be positioned by an enclosing
3082 // relative positioned inline.
3083 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3085 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
3087 // To match WinIE, in quirks mode use the parent's 'direction' property
3088 // instead of the the container block's.
3089 TextDirection containerDirection = containerBlock->style()->direction();
3091 // Variables to solve.
3092 bool isHorizontal = isHorizontalWritingMode();
3093 Length logicalLeft = style()->logicalLeft();
3094 Length logicalRight = style()->logicalRight();
3095 Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3096 Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3097 LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
3098 LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
3100 /*-----------------------------------------------------------------------*\
3101 * 1. The used value of 'width' is determined as for inline replaced
3103 \*-----------------------------------------------------------------------*/
3104 // NOTE: This value of width is FINAL in that the min/max width calculations
3105 // are dealt with in computeReplacedWidth(). This means that the steps to produce
3106 // correct max/min in the non-replaced version, are not necessary.
3107 setLogicalWidth(computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth());
3109 const LayoutUnit availableSpace = containerLogicalWidth - logicalWidth();
3111 /*-----------------------------------------------------------------------*\
3112 * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
3113 * of the containing block is 'ltr', set 'left' to the static position;
3114 * else if 'direction' is 'rtl', set 'right' to the static position.
3115 \*-----------------------------------------------------------------------*/
3117 computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, 0); // FIXME: Pass the region.
3119 /*-----------------------------------------------------------------------*\
3120 * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
3121 * or 'margin-right' with '0'.
3122 \*-----------------------------------------------------------------------*/
3123 if (logicalLeft.isAuto() || logicalRight.isAuto()) {
3124 if (marginLogicalLeft.isAuto())
3125 marginLogicalLeft.setValue(Fixed, 0);
3126 if (marginLogicalRight.isAuto())
3127 marginLogicalRight.setValue(Fixed, 0);
3130 /*-----------------------------------------------------------------------*\
3131 * 4. If at this point both 'margin-left' and 'margin-right' are still
3132 * 'auto', solve the equation under the extra constraint that the two
3133 * margins must get equal values, unless this would make them negative,
3134 * in which case when the direction of the containing block is 'ltr'
3135 * ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
3136 * 'margin-right' ('margin-left').
3137 \*-----------------------------------------------------------------------*/
3138 LayoutUnit logicalLeftValue = 0;
3139 LayoutUnit logicalRightValue = 0;
3141 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3142 // 'left' and 'right' cannot be 'auto' due to step 3
3143 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3145 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3146 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3148 LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
3149 if (difference > 0) {
3150 marginLogicalLeftAlias = difference / 2; // split the difference
3151 marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
3153 // Use the containing block's direction rather than the parent block's
3154 // per CSS 2.1 reference test abspos-replaced-width-margin-000.
3155 if (containerDirection == LTR) {
3156 marginLogicalLeftAlias = 0;
3157 marginLogicalRightAlias = difference; // will be negative
3159 marginLogicalLeftAlias = difference; // will be negative
3160 marginLogicalRightAlias = 0;
3164 /*-----------------------------------------------------------------------*\
3165 * 5. If at this point there is an 'auto' left, solve the equation for
3167 \*-----------------------------------------------------------------------*/
3168 } else if (logicalLeft.isAuto()) {
3169 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3170 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3171 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3174 logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3175 } else if (logicalRight.isAuto()) {
3176 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3177 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3178 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3180 // Solve for 'right'
3181 logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3182 } else if (marginLogicalLeft.isAuto()) {
3183 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3184 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3185 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3187 // Solve for 'margin-left'
3188 marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
3189 } else if (marginLogicalRight.isAuto()) {
3190 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3191 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3192 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3194 // Solve for 'margin-right'
3195 marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
3197 // Nothing is 'auto', just calculate the values.
3198 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3199 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3200 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3201 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3202 // If the containing block is right-to-left, then push the left position as far to the right as possible
3203 if (containerDirection == RTL) {
3204 int totalLogicalWidth = logicalWidth() + logicalLeftValue + logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias;
3205 logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
3209 /*-----------------------------------------------------------------------*\
3210 * 6. If at this point the values are over-constrained, ignore the value
3211 * for either 'left' (in case the 'direction' property of the
3212 * containing block is 'rtl') or 'right' (in case 'direction' is
3213 * 'ltr') and solve for that value.
3214 \*-----------------------------------------------------------------------*/
3215 // NOTE: Constraints imposed by the width of the containing block and its content have already been accounted for above.
3217 // FIXME: Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space, so that
3218 // can make the result here rather complicated to compute.
3220 // Use computed values to calculate the horizontal position.
3222 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3223 // positioned, inline containing block because right now, it is using the logical left position
3224 // of the first line box when really it should use the last line box. When