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 paintFillLayers(paintInfo, bgColor, bgLayer, view()->backgroundRect(this), BackgroundBleedNone, CompositeSourceOver, bodyObject);
878 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
880 if (context->paintingDisabled())
881 return BackgroundBleedNone;
883 const RenderStyle* style = this->style();
885 if (!style->hasBackground() || !style->hasBorder() || !style->hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
886 return BackgroundBleedNone;
888 AffineTransform ctm = context->getCTM();
889 FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
890 if (borderObscuresBackgroundEdge(contextScaling))
891 return BackgroundBleedShrinkBackground;
893 // FIXME: there is one more strategy possible, for opaque backgrounds and
894 // translucent borders. In that case we could avoid using a transparency layer,
895 // and paint the border first, and then paint the background clipped to the
896 // inside of the border.
898 return BackgroundBleedUseTransparencyLayer;
901 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
903 if (!paintInfo.shouldPaintWithinRoot(this))
906 LayoutRect paintRect = borderBoxRectInRegion(paintInfo.renderRegion);
907 paintRect.moveBy(paintOffset);
909 // border-fit can adjust where we paint our border and background. If set, we snugly fit our line box descendants. (The iChat
910 // balloon layout is an example of this).
911 borderFitAdjust(paintRect);
913 // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
914 // custom shadows of their own.
915 paintBoxShadow(paintInfo, paintRect, style(), Normal);
917 BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
919 GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
920 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
921 // To avoid the background color bleeding out behind the border, we'll render background and border
922 // into a transparency layer, and then clip that in one go (which requires setting up the clip before
923 // beginning the layer).
924 RoundedRect border = style()->getRoundedBorderFor(paintRect);
926 paintInfo.context->addRoundedRectClip(border);
927 paintInfo.context->beginTransparencyLayer(1);
930 // If we have a native theme appearance, paint that before painting our background.
931 // The theme will tell us whether or not we should also paint the CSS background.
932 bool themePainted = style()->hasAppearance() && !theme()->paint(this, paintInfo, paintRect);
934 paintBackground(paintInfo, paintRect, bleedAvoidance);
936 if (style()->hasAppearance())
937 theme()->paintDecorations(this, paintInfo, paintRect);
939 paintBoxShadow(paintInfo, paintRect, style(), Inset);
941 // The theme will tell us whether or not we should also paint the CSS border.
942 if ((!style()->hasAppearance() || (!themePainted && theme()->paintBorderOnly(this, paintInfo, paintRect))) && style()->hasBorder())
943 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
945 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
946 paintInfo.context->endTransparencyLayer();
949 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
952 paintRootBoxFillLayers(paintInfo);
953 else if (!isBody() || document()->documentElement()->renderer()->hasBackground()) {
954 // The <body> only paints its background if the root element has defined a background
955 // independent of the body.
956 if (!backgroundIsObscured())
957 paintFillLayers(paintInfo, style()->visitedDependentColor(CSSPropertyBackgroundColor), style()->backgroundLayers(), paintRect, bleedAvoidance);
961 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
963 if (!paintInfo.shouldPaintWithinRoot(this) || style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
966 LayoutRect paintRect = LayoutRect(paintOffset, size());
968 // border-fit can adjust where we paint our border and background. If set, we snugly fit our line box descendants. (The iChat
969 // balloon layout is an example of this).
970 borderFitAdjust(paintRect);
972 paintMaskImages(paintInfo, paintRect);
975 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
977 // Figure out if we need to push a transparency layer to render our mask.
978 bool pushTransparencyLayer = false;
979 bool compositedMask = hasLayer() && layer()->hasCompositedMask();
980 CompositeOperator compositeOp = CompositeSourceOver;
982 bool allMaskImagesLoaded = true;
984 if (!compositedMask) {
985 // If the context has a rotation, scale or skew, then use a transparency layer to avoid
986 // pixel cruft around the edge of the mask.
987 const AffineTransform& currentCTM = paintInfo.context->getCTM();
988 pushTransparencyLayer = !currentCTM.isIdentityOrTranslationOrFlipped();
990 StyleImage* maskBoxImage = style()->maskBoxImage().image();
991 const FillLayer* maskLayers = style()->maskLayers();
993 // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
995 allMaskImagesLoaded &= maskBoxImage->isLoaded();
998 allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1000 // Before all images have loaded, just use an empty transparency layer as the mask.
1001 if (!allMaskImagesLoaded)
1002 pushTransparencyLayer = true;
1004 bool hasMaskLayerWithImage = maskLayers->hasImage();
1005 if (maskBoxImage && hasMaskLayerWithImage) {
1006 // We have a mask-box-image and mask-image, so need to composite them together before using the result as a mask.
1007 pushTransparencyLayer = true;
1008 } else if (hasMaskLayerWithImage) {
1009 // We have to use an extra image buffer to hold the mask. Multiple mask images need
1010 // to composite together using source-over so that they can then combine into a single unified mask that
1011 // can be composited with the content using destination-in. SVG images need to be able to set compositing modes
1012 // as they draw images contained inside their sub-document, so we paint all our images into a separate buffer
1013 // and composite that buffer as the mask.
1014 // We have to check that the mask images to be rendered contain at least one image that can be actually used in rendering
1015 // before pushing the transparency layer.
1016 for (const FillLayer* fillLayer = maskLayers->next(); fillLayer; fillLayer = fillLayer->next()) {
1017 if (fillLayer->image() && fillLayer->image()->canRender(this, style()->effectiveZoom())) {
1018 pushTransparencyLayer = true;
1019 // We found one image that can be used in rendering, exit the loop
1025 compositeOp = CompositeDestinationIn;
1026 if (pushTransparencyLayer) {
1027 paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1028 paintInfo.context->beginTransparencyLayer(1.0f);
1029 compositeOp = CompositeSourceOver;
1033 if (allMaskImagesLoaded) {
1034 paintFillLayers(paintInfo, Color(), style()->maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1035 paintNinePieceImage(paintInfo.context, paintRect, style(), style()->maskBoxImage(), compositeOp);
1038 if (pushTransparencyLayer)
1039 paintInfo.context->endTransparencyLayer();
1042 LayoutRect RenderBox::maskClipRect()
1044 const NinePieceImage& maskBoxImage = style()->maskBoxImage();
1045 if (maskBoxImage.image()) {
1046 LayoutRect borderImageRect = borderBoxRect();
1048 // Apply outsets to the border box.
1049 LayoutUnit topOutset;
1050 LayoutUnit rightOutset;
1051 LayoutUnit bottomOutset;
1052 LayoutUnit leftOutset;
1053 style()->getMaskBoxImageOutsets(topOutset, rightOutset, bottomOutset, leftOutset);
1055 borderImageRect.setX(borderImageRect.x() - leftOutset);
1056 borderImageRect.setY(borderImageRect.y() - topOutset);
1057 borderImageRect.setWidth(borderImageRect.width() + leftOutset + rightOutset);
1058 borderImageRect.setHeight(borderImageRect.height() + topOutset + bottomOutset);
1060 return borderImageRect;
1064 LayoutRect borderBox = borderBoxRect();
1065 for (const FillLayer* maskLayer = style()->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1066 if (maskLayer->image()) {
1067 BackgroundImageGeometry geometry;
1068 calculateBackgroundImageGeometry(maskLayer, borderBox, geometry);
1069 result.unite(geometry.destRect());
1075 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1076 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1081 paintFillLayers(paintInfo, c, fillLayer->next(), rect, bleedAvoidance, op, backgroundObject);
1082 paintFillLayer(paintInfo, c, fillLayer, rect, bleedAvoidance, op, backgroundObject);
1085 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1086 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1088 paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, 0, IntSize(), op, backgroundObject);
1091 #if USE(ACCELERATED_COMPOSITING)
1092 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1094 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1095 if (curLayer->image() && image == curLayer->image()->data())
1103 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1108 if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1109 (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1114 bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
1115 if (!didFullRepaint)
1116 repaintLayerRectsForImage(image, style()->maskLayers(), false);
1119 #if USE(ACCELERATED_COMPOSITING)
1120 if (hasLayer() && layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
1121 layer()->contentChanged(RenderLayer::MaskImageChanged);
1125 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1127 LayoutRect rendererRect;
1128 RenderBox* layerRenderer = 0;
1130 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1131 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style()->effectiveZoom())) {
1132 // Now that we know this image is being used, compute the renderer and the rect
1133 // if we haven't already
1134 if (!layerRenderer) {
1135 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document()->documentElement()->renderer()->hasBackground()));
1136 if (drawingRootBackground) {
1137 layerRenderer = view();
1142 if (FrameView* frameView = toRenderView(layerRenderer)->frameView()) {
1143 rw = frameView->contentsWidth();
1144 rh = frameView->contentsHeight();
1146 rw = layerRenderer->width();
1147 rh = layerRenderer->height();
1149 rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1150 -layerRenderer->marginTop(),
1151 max(layerRenderer->width() + layerRenderer->marginLeft() + layerRenderer->marginRight() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1152 max(layerRenderer->height() + layerRenderer->marginTop() + layerRenderer->marginBottom() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1154 layerRenderer = this;
1155 rendererRect = borderBoxRect();
1159 BackgroundImageGeometry geometry;
1160 layerRenderer->calculateBackgroundImageGeometry(curLayer, rendererRect, geometry);
1161 layerRenderer->repaintRectangle(geometry.destRect());
1162 if (geometry.destRect() == rendererRect)
1171 void RenderBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type, bool behindText)
1173 Frame* frame = this->frame();
1176 Page* page = frame->page();
1180 InlineBox* boxWrap = inlineBoxWrapper();
1181 RootInlineBox* r = boxWrap ? boxWrap->root() : 0;
1183 FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + r->selectionTop(), r->logicalWidth(), r->selectionHeight());
1184 FloatRect imageRect(paintOffset.x() + x(), rootRect.y(), width(), rootRect.height());
1185 page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, rootRect, behindText, false);
1187 FloatRect imageRect(paintOffset.x() + x(), paintOffset.y() + y(), width(), height());
1188 page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, imageRect, behindText, false);
1194 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1196 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1199 bool isControlClip = hasControlClip();
1200 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1202 if (!isControlClip && !isOverflowClip)
1205 if (paintInfo.phase == PaintPhaseOutline)
1206 paintInfo.phase = PaintPhaseChildOutlines;
1207 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1208 paintInfo.phase = PaintPhaseBlockBackground;
1209 paintObject(paintInfo, accumulatedOffset);
1210 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1212 IntRect clipRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion));
1213 paintInfo.context->save();
1214 if (style()->hasBorderRadius())
1215 paintInfo.context->addRoundedRectClip(style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())));
1216 paintInfo.context->clip(clipRect);
1220 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1222 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1224 paintInfo.context->restore();
1225 if (originalPhase == PaintPhaseOutline) {
1226 paintInfo.phase = PaintPhaseSelfOutline;
1227 paintObject(paintInfo, accumulatedOffset);
1228 paintInfo.phase = originalPhase;
1229 } else if (originalPhase == PaintPhaseChildBlockBackground)
1230 paintInfo.phase = originalPhase;
1233 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy)
1235 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1237 LayoutRect clipRect = borderBoxRectInRegion(region);
1238 clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1239 clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1241 // Subtract out scrollbars if we have them.
1243 clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1248 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1250 LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1251 LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1253 if (!style()->clipLeft().isAuto()) {
1254 LayoutUnit c = style()->clipLeft().calcValue(borderBoxRect.width());
1255 clipRect.move(c, 0);
1256 clipRect.contract(c, 0);
1259 // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1260 // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1262 if (!style()->clipRight().isAuto())
1263 clipRect.contract(width() - style()->clipRight().calcValue(width()), 0);
1265 if (!style()->clipTop().isAuto()) {
1266 LayoutUnit c = style()->clipTop().calcValue(borderBoxRect.height());
1267 clipRect.move(0, c);
1268 clipRect.contract(0, c);
1271 if (!style()->clipBottom().isAuto())
1272 clipRect.contract(0, height() - style()->clipBottom().calcValue(height()));
1277 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1279 RenderBlock* cb = containingBlock();
1280 if (shrinkToAvoidFloats() && !inRenderFlowThread())
1281 return cb->availableLogicalWidthForLine(logicalTop(), false);
1282 return cb->availableLogicalWidth();
1285 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
1288 return containingBlockLogicalWidthForContent();
1290 RenderBlock* cb = containingBlock();
1291 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1292 if (shrinkToAvoidFloats()) {
1293 LayoutUnit offsetFromLogicalTopOfRegion = region->offsetFromLogicalTopOfFirstPage() - offsetFromLogicalTopOfFirstPage;
1294 return cb->availableLogicalWidthForLine(max(logicalTop(), logicalTop() + offsetFromLogicalTopOfRegion), false, containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
1296 LayoutUnit result = cb->availableLogicalWidth();
1297 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
1300 return max(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1303 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1305 RenderBlock* cb = containingBlock();
1306 RenderStyle* containingBlockStyle = cb->style();
1307 Length logicalHeightLength = containingBlockStyle->logicalHeight();
1309 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1310 if (!logicalHeightLength.isFixed()) {
1311 // Rather than making the child be completely unconstrained, WinIE uses the viewport width and height
1312 // as a constraint. We do that for now as well even though it's likely being unconstrained is what the spec
1314 return containingBlockStyle->isHorizontalWritingMode() ? view()->frameView()->visibleHeight() : view()->frameView()->visibleWidth();
1317 // Use the content box logical height as specified by the style.
1318 return cb->computeContentBoxLogicalHeight(logicalHeightLength.value());
1321 void RenderBox::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
1323 if (repaintContainer == this)
1326 if (RenderView* v = view()) {
1327 if (v->layoutStateEnabled() && !repaintContainer) {
1328 LayoutState* layoutState = v->layoutState();
1329 LayoutSize offset = layoutState->m_paintOffset;
1330 offset.expand(x(), y());
1331 if (style()->position() == RelativePosition && layer())
1332 offset += layer()->relativePositionOffset();
1333 transformState.move(offset);
1338 bool containerSkipped;
1339 RenderObject* o = container(repaintContainer, &containerSkipped);
1343 bool isFixedPos = style()->position() == FixedPosition;
1344 bool hasTransform = hasLayer() && layer()->transform();
1346 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1347 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1348 fixed &= isFixedPos;
1350 fixed |= isFixedPos;
1354 LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1356 bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1357 if (useTransforms && shouldUseTransformFromContainer(o)) {
1358 TransformationMatrix t;
1359 getTransformFromContainer(o, containerOffset, t);
1360 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1362 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1364 if (containerSkipped) {
1365 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1366 // to just subtract the delta between the repaintContainer and o.
1367 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1368 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1372 if (o->isRenderFlowThread()) {
1373 // Transform from render flow coordinates into region coordinates.
1374 RenderRegion* region = toRenderFlowThread(o)->mapFromFlowToRegion(transformState);
1376 region->mapLocalToContainer(region->containerForRepaint(), fixed, useTransforms, transformState, wasFixed);
1380 o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
1383 void RenderBox::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1385 // We don't expect absoluteToLocal() to be called during layout (yet)
1386 ASSERT(!view() || !view()->layoutStateEnabled());
1388 bool isFixedPos = style()->position() == FixedPosition;
1389 bool hasTransform = hasLayer() && layer()->transform();
1391 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1392 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1393 fixed &= isFixedPos;
1395 fixed |= isFixedPos;
1397 RenderObject* o = container();
1401 o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1403 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
1405 bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1406 if (useTransforms && shouldUseTransformFromContainer(o)) {
1407 TransformationMatrix t;
1408 getTransformFromContainer(o, containerOffset, t);
1409 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1411 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1414 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point) const
1416 ASSERT(o == container());
1419 if (isRelPositioned())
1420 offset += relativePositionOffset();
1422 if (!isInline() || isReplaced()) {
1423 if (style()->position() != AbsolutePosition && style()->position() != FixedPosition && o->hasColumns()) {
1424 RenderBlock* block = toRenderBlock(o);
1425 LayoutRect columnRect(frameRect());
1426 block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1427 offset += toSize(columnRect.location());
1428 IntPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
1429 offset = toSize(block->flipForWritingModeIncludingColumns(LayoutPoint(offset)));
1430 o->adjustForColumns(offset, columnPoint);
1431 offset = block->flipForWritingMode(offset);
1433 offset += topLeftLocationOffset();
1436 if (o->hasOverflowClip())
1437 offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1439 if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1440 offset += toRenderInline(o)->relativePositionedInlineOffset(this);
1445 InlineBox* RenderBox::createInlineBox()
1447 return new (renderArena()) InlineBox(this);
1450 void RenderBox::dirtyLineBoxes(bool fullLayout)
1452 if (m_inlineBoxWrapper) {
1454 m_inlineBoxWrapper->destroy(renderArena());
1455 m_inlineBoxWrapper = 0;
1457 m_inlineBoxWrapper->dirtyLineBoxes();
1461 void RenderBox::positionLineBox(InlineBox* box)
1463 if (isPositioned()) {
1464 // Cache the x position only if we were an INLINE type originally.
1465 bool wasInline = style()->isOriginalDisplayInlineType();
1467 // The value is cached in the xPos of the box. We only need this value if
1468 // our object was inline originally, since otherwise it would have ended up underneath
1470 RootInlineBox* root = box->root();
1471 root->block()->setStaticInlinePositionForChild(this, root->lineTopWithLeading(), lroundf(box->logicalLeft()));
1472 if (style()->hasStaticInlinePosition(box->isHorizontal()))
1473 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1475 // Our object was a block originally, so we make our normal flow position be
1476 // just below the line box (as though all the inlines that came before us got
1477 // wrapped in an anonymous block, which is what would have happened had we been
1478 // in flow). This value was cached in the y() of the box.
1479 layer()->setStaticBlockPosition(box->logicalTop());
1480 if (style()->hasStaticBlockPosition(box->isHorizontal()))
1481 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1486 box->destroy(renderArena());
1487 } else if (isReplaced()) {
1488 setLocation(roundedLayoutPoint(FloatPoint(box->x(), box->y())));
1489 ASSERT(!m_inlineBoxWrapper);
1490 m_inlineBoxWrapper = box;
1494 void RenderBox::deleteLineBoxWrapper()
1496 if (m_inlineBoxWrapper) {
1497 if (!documentBeingDestroyed())
1498 m_inlineBoxWrapper->remove();
1499 m_inlineBoxWrapper->destroy(renderArena());
1500 m_inlineBoxWrapper = 0;
1504 LayoutRect RenderBox::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
1506 if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
1507 return LayoutRect();
1509 LayoutRect r = visualOverflowRect();
1511 RenderView* v = view();
1513 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1514 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1515 r.move(v->layoutDelta());
1519 if (style()->hasAppearance())
1520 // The theme may wish to inflate the rect used when repainting.
1521 theme()->adjustRepaintRect(this, r);
1523 // We have to use maximalOutlineSize() because a child might have an outline
1524 // that projects outside of our overflowRect.
1526 ASSERT(style()->outlineSize() <= v->maximalOutlineSize());
1527 r.inflate(v->maximalOutlineSize());
1531 computeRectForRepaint(repaintContainer, r);
1535 void RenderBox::computeRectForRepaint(RenderBoxModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1537 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1538 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1539 // offset corner for the enclosing container). This allows for a fully RL or BT document to repaint
1540 // properly even during layout, since the rect remains flipped all the way until the end.
1542 // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to
1543 // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the
1544 // physical coordinate space of the repaintContainer.
1545 if (RenderView* v = view()) {
1546 // LayoutState is only valid for root-relative, non-fixed position repainting
1547 if (v->layoutStateEnabled() && !repaintContainer && style()->position() != FixedPosition) {
1548 LayoutState* layoutState = v->layoutState();
1550 if (layer() && layer()->transform())
1551 rect = layer()->transform()->mapRect(rect);
1553 if (style()->position() == RelativePosition && layer())
1554 rect.move(layer()->relativePositionOffset());
1556 rect.moveBy(location());
1557 rect.move(layoutState->m_paintOffset);
1558 if (layoutState->m_clipped)
1559 rect.intersect(layoutState->m_clipRect);
1564 if (hasReflection())
1565 rect.unite(reflectedRect(rect));
1567 if (repaintContainer == this) {
1568 if (repaintContainer->style()->isFlippedBlocksWritingMode())
1569 flipForWritingMode(rect);
1573 bool containerSkipped;
1574 RenderObject* o = container(repaintContainer, &containerSkipped);
1578 if (isWritingModeRoot() && !isPositioned())
1579 flipForWritingMode(rect);
1580 LayoutPoint topLeft = rect.location();
1581 topLeft.move(x(), y());
1583 EPosition position = style()->position();
1585 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
1586 // in the parent's coordinate space that encloses us.
1587 if (layer() && layer()->transform()) {
1588 fixed = position == FixedPosition;
1589 rect = layer()->transform()->mapRect(rect);
1590 topLeft = rect.location();
1591 topLeft.move(x(), y());
1592 } else if (position == FixedPosition)
1595 if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1596 topLeft += toRenderInline(o)->relativePositionedInlineOffset(this);
1597 else if (position == RelativePosition && layer()) {
1598 // Apply the relative position offset when invalidating a rectangle. The layer
1599 // is translated, but the render box isn't, so we need to do this to get the
1600 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
1601 // flag on the RenderObject has been cleared, so use the one on the style().
1602 topLeft += layer()->relativePositionOffset();
1605 if (o->isBlockFlow() && position != AbsolutePosition && position != FixedPosition) {
1606 RenderBlock* cb = toRenderBlock(o);
1607 if (cb->hasColumns()) {
1608 LayoutRect repaintRect(topLeft, rect.size());
1609 cb->adjustRectForColumns(repaintRect);
1610 topLeft = repaintRect.location();
1615 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1616 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1617 if (o->hasOverflowClip()) {
1618 RenderBox* containerBox = toRenderBox(o);
1620 // o->height() is inaccurate if we're in the middle of a layout of |o|, so use the
1621 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
1622 // anyway if its size does change.
1623 topLeft -= containerBox->layer()->scrolledContentOffset(); // For overflow:auto/scroll/hidden.
1625 LayoutRect repaintRect(topLeft, rect.size());
1626 LayoutRect boxRect(LayoutPoint(), containerBox->layer()->size());
1627 rect = intersection(repaintRect, boxRect);
1631 rect.setLocation(topLeft);
1633 if (containerSkipped) {
1634 // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
1635 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1636 rect.move(-containerOffset);
1640 o->computeRectForRepaint(repaintContainer, rect, fixed);
1643 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& rect)
1645 LayoutUnit newX = x();
1646 LayoutUnit newY = y();
1647 LayoutUnit newWidth = width();
1648 LayoutUnit newHeight = height();
1649 if (rect.x() != newX || rect.y() != newY) {
1650 // The child moved. Invalidate the object's old and new positions. We have to do this
1651 // since the object may not have gotten a layout.
1654 repaintOverhangingFloats(true);
1655 m_frameRect = LayoutRect(newX, newY, newWidth, newHeight);
1657 repaintOverhangingFloats(true);
1661 void RenderBox::computeLogicalWidth()
1663 computeLogicalWidthInRegion();
1666 void RenderBox::computeLogicalWidthInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
1668 if (isPositioned()) {
1669 // FIXME: This calculation is not patched for block-flow yet.
1670 // https://bugs.webkit.org/show_bug.cgi?id=46500
1671 computePositionedLogicalWidth(region, offsetFromLogicalTopOfFirstPage);
1675 // If layout is limited to a subtree, the subtree root's logical width does not change.
1676 if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1679 // The parent box is flexing us, so it has increased or decreased our
1680 // width. Use the width from the style context.
1681 // FIXME: Account for block-flow in flexible boxes.
1682 // https://bugs.webkit.org/show_bug.cgi?id=46418
1683 if (hasOverrideWidth() && parent()->isFlexibleBoxIncludingDeprecated()) {
1684 setLogicalWidth(overrideWidth());
1688 // FIXME: Account for block-flow in flexible boxes.
1689 // https://bugs.webkit.org/show_bug.cgi?id=46418
1690 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1691 bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1692 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1694 Length logicalWidthLength = (treatAsReplaced) ? Length(computeReplacedLogicalWidth(), Fixed) : style()->logicalWidth();
1696 RenderBlock* cb = containingBlock();
1697 LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region, offsetFromLogicalTopOfFirstPage));
1698 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1699 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
1700 if (hasPerpendicularContainingBlock)
1701 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1703 if (isInline() && !isInlineBlockOrInlineTable()) {
1704 // just calculate margins
1705 setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1706 setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1707 if (treatAsReplaced)
1708 setLogicalWidth(max<LayoutUnit>(logicalWidthLength.calcFloatValue(0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth()));
1712 // Width calculations
1713 if (treatAsReplaced)
1714 setLogicalWidth(logicalWidthLength.value() + borderAndPaddingLogicalWidth());
1716 // Calculate LogicalWidth
1717 setLogicalWidth(computeLogicalWidthUsing(LogicalWidth, containerWidthInInlineDirection));
1719 // Calculate MaxLogicalWidth
1720 if (!style()->logicalMaxWidth().isUndefined()) {
1721 LayoutUnit maxLogicalWidth = computeLogicalWidthUsing(MaxLogicalWidth, containerWidthInInlineDirection);
1722 if (logicalWidth() > maxLogicalWidth) {
1723 setLogicalWidth(maxLogicalWidth);
1724 logicalWidthLength = style()->logicalMaxWidth();
1728 // Calculate MinLogicalWidth
1729 LayoutUnit minLogicalWidth = computeLogicalWidthUsing(MinLogicalWidth, containerWidthInInlineDirection);
1730 if (logicalWidth() < minLogicalWidth) {
1731 setLogicalWidth(minLogicalWidth);
1732 logicalWidthLength = style()->logicalMinWidth();
1736 // Fieldsets are currently the only objects that stretch to their minimum width.
1737 if (stretchesToMinIntrinsicLogicalWidth()) {
1738 setLogicalWidth(max(logicalWidth(), minPreferredLogicalWidth()));
1739 logicalWidthLength = Length(logicalWidth(), Fixed);
1742 // Margin calculations.
1743 if (logicalWidthLength.isAuto() || hasPerpendicularContainingBlock) {
1744 setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1745 setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1747 computeInlineDirectionMargins(cb, containerLogicalWidth, logicalWidth());
1749 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (logicalWidth() + marginStart() + marginEnd())
1750 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated())
1751 cb->setMarginEndForChild(this, containerLogicalWidth - logicalWidth() - cb->marginStartForChild(this));
1754 LayoutUnit RenderBox::computeLogicalWidthUsing(LogicalWidthType widthType, LayoutUnit availableLogicalWidth)
1756 LayoutUnit logicalWidthResult = logicalWidth();
1757 Length logicalWidth;
1758 if (widthType == LogicalWidth)
1759 logicalWidth = style()->logicalWidth();
1760 else if (widthType == MinLogicalWidth)
1761 logicalWidth = style()->logicalMinWidth();
1763 logicalWidth = style()->logicalMaxWidth();
1765 if (logicalWidth.isIntrinsicOrAuto()) {
1766 LayoutUnit marginStart = style()->marginStart().calcMinValue(availableLogicalWidth);
1767 LayoutUnit marginEnd = style()->marginEnd().calcMinValue(availableLogicalWidth);
1768 logicalWidthResult = availableLogicalWidth - marginStart - marginEnd;
1770 if (sizesToIntrinsicLogicalWidth(widthType)) {
1771 logicalWidthResult = max(logicalWidthResult, minPreferredLogicalWidth());
1772 logicalWidthResult = min(logicalWidthResult, maxPreferredLogicalWidth());
1774 } else // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
1775 logicalWidthResult = computeBorderBoxLogicalWidth(logicalWidth.calcValue(availableLogicalWidth));
1777 return logicalWidthResult;
1780 bool RenderBox::sizesToIntrinsicLogicalWidth(LogicalWidthType widthType) const
1782 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
1783 // but they allow text to sit on the same line as the marquee.
1784 if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
1787 // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both
1788 // min-width and width. max-width is only clamped if it is also intrinsic.
1789 Length logicalWidth = (widthType == MaxLogicalWidth) ? style()->logicalMaxWidth() : style()->logicalWidth();
1790 if (logicalWidth.type() == Intrinsic)
1793 // Children of a horizontal marquee do not fill the container by default.
1794 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
1795 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
1796 // block-flow (as well as how marquee overflow should relate to block flow).
1797 // https://bugs.webkit.org/show_bug.cgi?id=46472
1798 if (parent()->style()->overflowX() == OMARQUEE) {
1799 EMarqueeDirection dir = parent()->style()->marqueeDirection();
1800 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
1804 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
1805 // that don't stretch their kids lay out their children at their intrinsic widths.
1806 // FIXME: Think about block-flow here.
1807 // https://bugs.webkit.org/show_bug.cgi?id=46473
1808 if (parent()->isDeprecatedFlexibleBox()
1809 && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
1812 // Button, input, select, textarea, and legend treat
1813 // width value of 'auto' as 'intrinsic' unless it's in a
1814 // stretching vertical flexbox.
1815 // FIXME: Think about block-flow here.
1816 // https://bugs.webkit.org/show_bug.cgi?id=46473
1817 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)))
1820 if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
1826 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, int containerWidth, int childWidth)
1828 const RenderStyle* containingBlockStyle = containingBlock->style();
1829 Length marginStartLength = style()->marginStartUsing(containingBlockStyle);
1830 Length marginEndLength = style()->marginEndUsing(containingBlockStyle);
1832 if (isFloating() || isInline()) {
1833 // Inline blocks/tables and floats don't have their margins increased.
1834 containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1835 containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1839 // Case One: The object is being centered in the containing block's available logical width.
1840 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
1841 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
1842 containingBlock->setMarginStartForChild(this, max<LayoutUnit>(0, (containerWidth - childWidth) / 2));
1843 containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1847 // Case Two: The object is being pushed to the start of the containing block's available logical width.
1848 if (marginEndLength.isAuto() && childWidth < containerWidth) {
1849 containingBlock->setMarginStartForChild(this, marginStartLength.calcValue(containerWidth));
1850 containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1854 // Case Three: The object is being pushed to the end of the containing block's available logical width.
1855 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
1856 || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
1857 if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
1858 containingBlock->setMarginEndForChild(this, marginEndLength.calcValue(containerWidth));
1859 containingBlock->setMarginStartForChild(this, containerWidth - childWidth - containingBlock->marginEndForChild(this));
1863 // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3). In that case
1864 // auto margins will just turn into 0.
1865 containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1866 containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1869 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, RenderBoxRegionInfoFlags cacheFlag) const
1871 // Make sure nobody is trying to call this with a null region.
1875 // If we have computed our width in this region already, it will be cached, and we can
1877 RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
1878 if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
1881 // No cached value was found, so we have to compute our insets in this region.
1882 // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
1883 // support to cover all boxes.
1884 if (!inRenderFlowThread() || isFloating() || isReplaced() || isInline() || hasColumns()
1885 || isTableCell() || !isBlockFlow() || isRenderFlowThread())
1888 // FIXME: It's gross to cast away the const, but it would be a huge refactoring to
1889 // change all width computation to avoid updating any member variables, and it would be pretty lame to
1890 // make all the variables mutable as well.
1891 RenderFlowThread* flowThread = enclosingRenderFlowThread();
1892 if (flowThread->style()->writingMode() != style()->writingMode())
1895 LayoutUnit oldLogicalWidth = logicalWidth();
1896 LayoutUnit oldLogicalLeft = logicalLeft();
1897 LayoutUnit oldMarginStart = marginStart();
1898 LayoutUnit oldMarginEnd = marginEnd();
1900 RenderBox* mutableBox = const_cast<RenderBox*>(this);
1902 mutableBox->computeLogicalWidthInRegion(region, offsetFromLogicalTopOfFirstPage);
1904 // Now determine the insets based off where this object is supposed to be positioned.
1905 RenderBlock* cb = containingBlock();
1906 RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
1907 RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion,
1908 offsetFromLogicalTopOfFirstPage - logicalTop());
1909 LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
1910 LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
1912 LayoutUnit marginStartInRegion = marginStart();
1913 LayoutUnit startMarginDelta = marginStartInRegion - oldMarginStart;
1914 LayoutUnit logicalWidthInRegion = logicalWidth();
1915 LayoutUnit logicalLeftInRegion = logicalLeft();
1916 LayoutUnit widthDelta = logicalWidthInRegion - oldLogicalWidth;
1917 LayoutUnit logicalLeftDelta = isPositioned() ? logicalLeftInRegion - oldLogicalLeft : startMarginDelta;
1918 LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
1919 LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (oldLogicalLeft + oldLogicalWidth);
1920 LayoutUnit logicalRightDelta = isPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
1922 // Set our values back.
1923 mutableBox->setLogicalWidth(oldLogicalWidth);
1924 mutableBox->setLogicalLeft(oldLogicalLeft);
1925 mutableBox->setMarginStart(oldMarginStart);
1926 mutableBox->setMarginEnd(oldMarginEnd);
1928 LayoutUnit logicalLeftOffset = 0;
1930 if (!isPositioned() && avoidsFloats() && cb->containsFloats()) {
1931 LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(this, marginStartInRegion, logicalWidthInRegion,
1932 region, offsetFromLogicalTopOfFirstPage);
1933 if (cb->style()->isLeftToRightDirection())
1934 logicalLeftDelta += startPositionDelta;
1936 logicalRightDelta += startPositionDelta;
1939 if (cb->style()->isLeftToRightDirection())
1940 logicalLeftOffset += logicalLeftDelta;
1942 logicalLeftOffset -= (widthDelta + logicalRightDelta);
1944 LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
1945 bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
1946 || (style()->isLeftToRightDirection() && logicalLeftOffset)
1947 || (!style()->isLeftToRightDirection() && logicalRightOffset);
1949 // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
1950 if (cacheFlag == CacheRenderBoxRegionInfo)
1951 return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
1952 return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
1955 void RenderBox::computeLogicalHeight()
1957 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
1958 if (isTableCell() || (isInline() && !isReplaced()))
1963 computePositionedLogicalHeight();
1965 RenderBlock* cb = containingBlock();
1966 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1968 if (!hasPerpendicularContainingBlock)
1969 computeBlockDirectionMargins(cb);
1971 // For tables, calculate margins only.
1973 if (hasPerpendicularContainingBlock)
1974 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), logicalHeight());
1978 // FIXME: Account for block-flow in flexible boxes.
1979 // https://bugs.webkit.org/show_bug.cgi?id=46418
1980 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
1981 bool stretching = parent()->style()->boxAlign() == BSTRETCH;
1982 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
1983 bool checkMinMaxHeight = false;
1985 // The parent box is flexing us, so it has increased or decreased our height. We have to
1986 // grab our cached flexible height.
1987 // FIXME: Account for block-flow in flexible boxes.
1988 // https://bugs.webkit.org/show_bug.cgi?id=46418
1989 if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
1990 h = Length(overrideHeight() - borderAndPaddingLogicalHeight(), Fixed);
1991 else if (treatAsReplaced)
1992 h = Length(computeReplacedLogicalHeight(), Fixed);
1994 h = style()->logicalHeight();
1995 checkMinMaxHeight = true;
1998 // Block children of horizontal flexible boxes fill the height of the box.
1999 // FIXME: Account for block-flow in flexible boxes.
2000 // https://bugs.webkit.org/show_bug.cgi?id=46418
2001 if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
2002 && parent()->isStretchingChildren()) {
2003 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2004 checkMinMaxHeight = false;
2007 LayoutUnit heightResult;
2008 if (checkMinMaxHeight) {
2009 heightResult = computeLogicalHeightUsing(style()->logicalHeight());
2010 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2011 if (heightResult == -1)
2012 heightResult = logicalHeight();
2013 LayoutUnit minH = computeLogicalHeightUsing(style()->logicalMinHeight()); // Leave as -1 if unset.
2014 LayoutUnit maxH = style()->logicalMaxHeight().isUndefined() ? heightResult : computeLogicalHeightUsing(style()->logicalMaxHeight());
2016 maxH = heightResult;
2017 heightResult = min(maxH, heightResult);
2018 heightResult = max(minH, heightResult);
2020 // The only times we don't check min/max height are when a fixed length has
2021 // been given as an override. Just use that. The value has already been adjusted
2023 heightResult = h.value() + borderAndPaddingLogicalHeight();
2026 setLogicalHeight(heightResult);
2028 if (hasPerpendicularContainingBlock)
2029 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult);
2032 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
2033 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
2034 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
2035 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
2036 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2037 bool paginatedContentNeedsBaseHeight = document()->printing() && h.isPercent()
2038 && (isRoot() || (isBody() && document()->documentElement()->renderer()->style()->logicalHeight().isPercent()));
2039 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2040 // FIXME: Finish accounting for block flow here.
2041 // https://bugs.webkit.org/show_bug.cgi?id=46603
2042 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2043 LayoutUnit visHeight;
2044 if (document()->printing())
2045 visHeight = static_cast<LayoutUnit>(view()->pageLogicalHeight());
2047 if (isHorizontalWritingMode())
2048 visHeight = view()->viewHeight();
2050 visHeight = view()->viewWidth();
2053 setLogicalHeight(max(logicalHeight(), visHeight - margins));
2055 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2056 setLogicalHeight(max(logicalHeight(), visHeight - marginsBordersPadding));
2061 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& h)
2063 LayoutUnit logicalHeight = -1;
2066 logicalHeight = h.value();
2067 else if (h.isPercent())
2068 logicalHeight = computePercentageLogicalHeight(h);
2069 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2070 if (logicalHeight != -1) {
2071 logicalHeight = computeBorderBoxLogicalHeight(logicalHeight);
2072 return logicalHeight;
2075 return logicalHeight;
2078 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height)
2080 LayoutUnit result = -1;
2082 // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
2083 // block that may have a specified height and then use it. In strict mode, this violates the
2084 // specification, which states that percentage heights just revert to auto if the containing
2085 // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
2086 // only at explicit containers.
2087 bool skippedAutoHeightContainingBlock = false;
2088 RenderBlock* cb = containingBlock();
2089 while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isPositioned() && cb->style()->logicalHeight().isAuto()) {
2090 if (!document()->inQuirksMode() && !cb->isAnonymousBlock())
2092 skippedAutoHeightContainingBlock = true;
2093 cb = cb->containingBlock();
2094 cb->addPercentHeightDescendant(this);
2097 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2098 // explicitly specified that can be used for any percentage computations.
2099 // FIXME: We can't just check top/bottom here.
2100 // https://bugs.webkit.org/show_bug.cgi?id=46500
2101 bool isPositionedWithSpecifiedHeight = cb->isPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
2103 bool includeBorderPadding = isTable();
2105 // Table cells violate what the CSS spec says to do with heights. Basically we
2106 // don't care if the cell specified a height or not. We just always make ourselves
2107 // be a percentage of the cell's current content height.
2108 if (cb->isTableCell()) {
2109 if (!skippedAutoHeightContainingBlock) {
2110 if (!cb->hasOverrideHeight()) {
2111 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2112 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2113 // While we can't get all cases right, we can at least detect when the cell has a specified
2114 // height or when the table has a specified height. In these cases we want to initially have
2115 // no size and allow the flexing of the table or the cell to its specified height to cause us
2116 // to grow to fill the space. This could end up being wrong in some cases, but it is
2117 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2118 RenderTableCell* cell = toRenderTableCell(cb);
2119 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2123 result = cb->overrideHeight();
2124 includeBorderPadding = true;
2127 // Otherwise we only use our percentage height if our containing block had a specified
2129 else if (cb->style()->logicalHeight().isFixed())
2130 result = cb->computeContentBoxLogicalHeight(cb->style()->logicalHeight().value());
2131 else if (cb->style()->logicalHeight().isPercent() && !isPositionedWithSpecifiedHeight) {
2132 // We need to recur and compute the percentage height for our containing block.
2133 result = cb->computePercentageLogicalHeight(cb->style()->logicalHeight());
2134 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2136 result = cb->computeContentBoxLogicalHeight(result);
2137 } else if (cb->isRenderView() || (cb->isBody() && document()->inQuirksMode()) || isPositionedWithSpecifiedHeight) {
2138 // Don't allow this to affect the block' height() member variable, since this
2139 // can get called while the block is still laying out its kids.
2140 LayoutUnit oldHeight = cb->logicalHeight();
2141 cb->computeLogicalHeight();
2142 result = cb->contentLogicalHeight();
2143 cb->setLogicalHeight(oldHeight);
2144 } else if (cb->isRoot() && isPositioned())
2145 // Match the positioned objects behavior, which is that positioned objects will fill their viewport
2146 // always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
2147 result = cb->computeContentBoxLogicalHeight(cb->availableLogicalHeight());
2149 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2151 result = height.calcValue(result);
2152 if (includeBorderPadding) {
2153 // It is necessary to use the border-box to match WinIE's broken
2154 // box model. This is essential for sizing inside
2155 // table cells using percentage heights.
2156 result -= borderAndPaddingLogicalHeight();
2157 result = max<LayoutUnit>(0, result);
2163 LayoutUnit RenderBox::computeReplacedLogicalWidth(bool includeMaxWidth) const
2165 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), includeMaxWidth);
2168 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, bool includeMaxWidth) const
2170 LayoutUnit minLogicalWidth = computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2171 LayoutUnit maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2172 return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
2175 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2177 switch (logicalWidth.type()) {
2179 return computeContentBoxLogicalWidth(logicalWidth.value());
2181 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2182 // containing block's block-flow.
2183 // https://bugs.webkit.org/show_bug.cgi?id=46496
2184 const LayoutUnit cw = isPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2186 return computeContentBoxLogicalWidth(logicalWidth.calcMinValue(cw));
2190 return intrinsicLogicalWidth();
2194 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2196 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2199 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2201 LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2202 LayoutUnit maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2203 return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
2206 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2208 switch (logicalHeight.type()) {
2210 return computeContentBoxLogicalHeight(logicalHeight.value());
2213 RenderObject* cb = isPositioned() ? container() : containingBlock();
2214 while (cb->isAnonymous()) {
2215 cb = cb->containingBlock();
2216 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2219 // FIXME: This calculation is not patched for block-flow yet.
2220 // https://bugs.webkit.org/show_bug.cgi?id=46500
2221 if (cb->isPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2222 ASSERT(cb->isRenderBlock());
2223 RenderBlock* block = toRenderBlock(cb);
2224 LayoutUnit oldHeight = block->height();
2225 block->computeLogicalHeight();
2226 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentHeight());
2227 block->setHeight(oldHeight);
2228 return computeContentBoxLogicalHeight(logicalHeight.calcValue(newHeight));
2231 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2232 // containing block's block-flow.
2233 // https://bugs.webkit.org/show_bug.cgi?id=46496
2234 LayoutUnit availableHeight;
2236 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2238 availableHeight = toRenderBox(cb)->availableLogicalHeight();
2239 // It is necessary to use the border-box to match WinIE's broken
2240 // box model. This is essential for sizing inside
2241 // table cells using percentage heights.
2242 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
2243 // https://bugs.webkit.org/show_bug.cgi?id=46997
2244 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2245 if (cb->isTableCell()) {
2246 // Don't let table cells squeeze percent-height replaced elements
2247 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2248 availableHeight = max(availableHeight, intrinsicLogicalHeight());
2249 return logicalHeight.calcValue(availableHeight - borderAndPaddingLogicalHeight());
2251 cb = cb->containingBlock();
2254 return computeContentBoxLogicalHeight(logicalHeight.calcValue(availableHeight));
2257 return intrinsicLogicalHeight();
2261 LayoutUnit RenderBox::availableLogicalHeight() const
2263 return availableLogicalHeightUsing(style()->logicalHeight());
2266 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const
2269 return computeContentBoxLogicalHeight(h.value());
2272 return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
2274 // We need to stop here, since we don't want to increase the height of the table
2275 // artificially. We're going to rely on this cell getting expanded to some new
2276 // height, and then when we lay out again we'll use the calculation below.
2277 if (isTableCell() && (h.isAuto() || h.isPercent()))
2278 return overrideHeight() - borderAndPaddingLogicalWidth();
2280 if (h.isPercent()) {
2281 LayoutUnit availableHeight;
2282 // https://bugs.webkit.org/show_bug.cgi?id=64046
2283 // For absolutely positioned elements whose containing block is based on a block-level element,
2284 // the percentage is calculated with respect to the height of the padding box of that element
2286 availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2288 availableHeight = containingBlock()->availableLogicalHeight();
2289 return computeContentBoxLogicalHeight(h.calcValue(availableHeight));
2292 // FIXME: We can't just check top/bottom here.
2293 // https://bugs.webkit.org/show_bug.cgi?id=46500
2294 if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2295 RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2296 LayoutUnit oldHeight = block->logicalHeight();
2297 block->computeLogicalHeight();
2298 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
2299 block->setLogicalHeight(oldHeight);
2300 return computeContentBoxLogicalHeight(newHeight);
2303 return containingBlock()->availableLogicalHeight();
2306 void RenderBox::computeBlockDirectionMargins(RenderBlock* containingBlock)
2308 if (isTableCell()) {
2309 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
2310 // we may just do it with an extra anonymous block inside the cell.
2316 // Margins are calculated with respect to the logical width of
2317 // the containing block (8.3)
2318 LayoutUnit cw = containingBlockLogicalWidthForContent();
2320 RenderStyle* containingBlockStyle = containingBlock->style();
2321 containingBlock->setMarginBeforeForChild(this, style()->marginBeforeUsing(containingBlockStyle).calcMinValue(cw));
2322 containingBlock->setMarginAfterForChild(this, style()->marginAfterUsing(containingBlockStyle).calcMinValue(cw));
2325 int RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region,
2326 LayoutUnit offsetFromLogicalTopOfFirstPage, bool checkForPerpendicularWritingMode) const
2328 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2329 return containingBlockLogicalHeightForPositioned(containingBlock, false);
2331 if (containingBlock->isBox()) {
2332 const RenderBlock* cb = toRenderBlock(containingBlock);
2333 LayoutUnit result = cb->clientLogicalWidth();
2334 if (inRenderFlowThread()) {
2335 RenderBoxRegionInfo* boxInfo = 0;
2337 if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
2338 return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
2339 if (isWritingModeRoot()) {
2340 LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2341 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2342 cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2343 boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2345 } else if (region && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
2346 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
2347 boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
2350 return max(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
2355 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2357 const RenderInline* flow = toRenderInline(containingBlock);
2358 InlineFlowBox* first = flow->firstLineBox();
2359 InlineFlowBox* last = flow->lastLineBox();
2361 // If the containing block is empty, return a width of 0.
2362 if (!first || !last)
2365 LayoutUnit fromLeft;
2366 LayoutUnit fromRight;
2367 if (containingBlock->style()->isLeftToRightDirection()) {
2368 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2369 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2371 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2372 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2375 return max<LayoutUnit>(0, fromRight - fromLeft);
2378 int RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2380 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2381 return containingBlockLogicalWidthForPositioned(containingBlock, 0, 0, false);
2383 if (containingBlock->isBox()) {
2384 const RenderBlock* cb = toRenderBlock(containingBlock);
2385 LayoutUnit result = cb->clientLogicalHeight();
2386 if (inRenderFlowThread() && containingBlock->isRenderFlowThread() && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode())
2387 return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion();
2391 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2393 const RenderInline* flow = toRenderInline(containingBlock);
2394 InlineFlowBox* first = flow->firstLineBox();
2395 InlineFlowBox* last = flow->lastLineBox();
2397 // If the containing block is empty, return a height of 0.
2398 if (!first || !last)
2401 LayoutUnit heightResult;
2402 LayoutRect boundingBox = flow->linesBoundingBox();
2403 if (containingBlock->isHorizontalWritingMode())
2404 heightResult = boundingBox.height();
2406 heightResult = boundingBox.width();
2407 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2408 return heightResult;
2411 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
2413 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2416 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2417 if (child->parent()->style()->direction() == LTR) {
2418 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2419 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2420 if (curr->isBox()) {
2421 staticPosition += toRenderBox(curr)->logicalLeft();
2422 if (region && curr->isRenderBlock()) {
2423 const RenderBlock* cb = toRenderBlock(curr);
2424 region = cb->clampToStartAndEndRegions(region);
2425 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2427 staticPosition += boxInfo->logicalLeft();
2431 logicalLeft.setValue(Fixed, staticPosition);
2433 RenderBox* enclosingBox = child->parent()->enclosingBox();
2434 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
2435 for (RenderObject* curr = enclosingBox; curr; curr = curr->container()) {
2436 if (curr->isBox()) {
2437 if (curr != containerBlock)
2438 staticPosition -= toRenderBox(curr)->logicalLeft();
2439 if (curr == enclosingBox)
2440 staticPosition -= enclosingBox->logicalWidth();
2441 if (region && curr->isRenderBlock()) {
2442 const RenderBlock* cb = toRenderBlock(curr);
2443 region = cb->clampToStartAndEndRegions(region);
2444 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2446 if (curr != containerBlock)
2447 staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
2448 if (curr == enclosingBox)
2449 staticPosition += enclosingBox->logicalWidth() - boxInfo->logicalWidth();
2453 if (curr == containerBlock)
2456 logicalRight.setValue(Fixed, staticPosition);
2460 void RenderBox::computePositionedLogicalWidth(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
2463 computePositionedLogicalWidthReplaced(); // FIXME: Patch for regions when we add replaced element support.
2468 // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
2469 // the type 'static' in determining whether to calculate the static distance?
2470 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2472 // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
2473 // than or less than the computed width(). Be careful of box-sizing and
2474 // percentage issues.
2476 // The following is based off of the W3C Working Draft from April 11, 2006 of
2477 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2478 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2479 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2480 // correspond to text from the spec)
2483 // We don't use containingBlock(), since we may be positioned by an enclosing
2484 // relative positioned inline.
2485 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2487 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region, offsetFromLogicalTopOfFirstPage);
2489 // Use the container block's direction except when calculating the static distance
2490 // This conforms with the reference results for abspos-replaced-width-margin-000.htm
2491 // of the CSS 2.1 test suite
2492 TextDirection containerDirection = containerBlock->style()->direction();
2494 bool isHorizontal = isHorizontalWritingMode();
2495 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2496 const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2497 const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2498 LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
2499 LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
2501 Length logicalLeftLength = style()->logicalLeft();
2502 Length logicalRightLength = style()->logicalRight();
2504 /*---------------------------------------------------------------------------*\
2505 * For the purposes of this section and the next, the term "static position"
2506 * (of an element) refers, roughly, to the position an element would have had
2507 * in the normal flow. More precisely:
2509 * * The static position for 'left' is the distance from the left edge of the
2510 * containing block to the left margin edge of a hypothetical box that would
2511 * have been the first box of the element if its 'position' property had
2512 * been 'static' and 'float' had been 'none'. The value is negative if the
2513 * hypothetical box is to the left of the containing block.
2514 * * The static position for 'right' is the distance from the right edge of the
2515 * containing block to the right margin edge of the same hypothetical box as
2516 * above. The value is positive if the hypothetical box is to the left of the
2517 * containing block's edge.
2519 * But rather than actually calculating the dimensions of that hypothetical box,
2520 * user agents are free to make a guess at its probable position.
2522 * For the purposes of calculating the static position, the containing block of
2523 * fixed positioned elements is the initial containing block instead of the
2524 * viewport, and all scrollable boxes should be assumed to be scrolled to their
2526 \*---------------------------------------------------------------------------*/
2529 // Calculate the static distance if needed.
2530 computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
2532 // Calculate constraint equation values for 'width' case.
2533 LayoutUnit logicalWidthResult;
2534 LayoutUnit logicalLeftResult;
2535 computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2536 containerLogicalWidth, bordersPlusPadding,
2537 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2538 logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2539 setLogicalWidth(logicalWidthResult);
2540 setLogicalLeft(logicalLeftResult);
2542 // Calculate constraint equation values for 'max-width' case.
2543 if (!style()->logicalMaxWidth().isUndefined()) {
2544 LayoutUnit maxLogicalWidth;
2545 LayoutUnit maxMarginLogicalLeft;
2546 LayoutUnit maxMarginLogicalRight;
2547 LayoutUnit maxLogicalLeftPos;
2549 computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2550 containerLogicalWidth, bordersPlusPadding,
2551 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2552 maxLogicalWidth, maxMarginLogicalLeft, maxMarginLogicalRight, maxLogicalLeftPos);
2554 if (logicalWidth() > maxLogicalWidth) {
2555 setLogicalWidth(maxLogicalWidth);
2556 marginLogicalLeftAlias = maxMarginLogicalLeft;
2557 marginLogicalRightAlias = maxMarginLogicalRight;
2558 setLogicalLeft(maxLogicalLeftPos);
2562 // Calculate constraint equation values for 'min-width' case.
2563 if (!style()->logicalMinWidth().isZero()) {
2564 LayoutUnit minLogicalWidth;
2565 LayoutUnit minMarginLogicalLeft;
2566 LayoutUnit minMarginLogicalRight;
2567 LayoutUnit minLogicalLeftPos;
2569 computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2570 containerLogicalWidth, bordersPlusPadding,
2571 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2572 minLogicalWidth, minMarginLogicalLeft, minMarginLogicalRight, minLogicalLeftPos);
2574 if (logicalWidth() < minLogicalWidth) {
2575 setLogicalWidth(minLogicalWidth);
2576 marginLogicalLeftAlias = minMarginLogicalLeft;
2577 marginLogicalRightAlias = minMarginLogicalRight;
2578 setLogicalLeft(minLogicalLeftPos);
2582 if (stretchesToMinIntrinsicLogicalWidth() && logicalWidth() < minPreferredLogicalWidth() - bordersPlusPadding) {
2583 computePositionedLogicalWidthUsing(Length(minPreferredLogicalWidth() - bordersPlusPadding, Fixed), containerBlock, containerDirection,
2584 containerLogicalWidth, bordersPlusPadding,
2585 logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2586 logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2587 setLogicalWidth(logicalWidthResult);
2588 setLogicalLeft(logicalLeftResult);
2591 // Put logicalWidth() into correct form.
2592 setLogicalWidth(logicalWidth() + bordersPlusPadding);
2594 // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
2595 if (inRenderFlowThread() && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2596 LayoutUnit logicalLeftPos = logicalLeft();
2597 const RenderBlock* cb = toRenderBlock(containerBlock);
2598 LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2599 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2600 cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2601 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2603 logicalLeftPos += boxInfo->logicalLeft();
2604 setLogicalLeft(logicalLeftPos);
2609 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2611 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2612 // 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.
2613 if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2614 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2615 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2617 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2620 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2621 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2622 Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
2623 LayoutUnit& logicalWidthValue, LayoutUnit& marginLogicalLeftValue, LayoutUnit& marginLogicalRightValue, LayoutUnit& logicalLeftPos)
2625 // 'left' and 'right' cannot both be 'auto' because one would of been
2626 // converted to the static position already
2627 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2629 LayoutUnit logicalLeftValue = 0;
2631 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2632 bool logicalLeftIsAuto = logicalLeft.isAuto();
2633 bool logicalRightIsAuto = logicalRight.isAuto();
2635 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2636 /*-----------------------------------------------------------------------*\
2637 * If none of the three is 'auto': If both 'margin-left' and 'margin-
2638 * right' are 'auto', solve the equation under the extra constraint that
2639 * the two margins get equal values, unless this would make them negative,
2640 * in which case when direction of the containing block is 'ltr' ('rtl'),
2641 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2642 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2643 * solve the equation for that value. If the values are over-constrained,
2644 * ignore the value for 'left' (in case the 'direction' property of the
2645 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2646 * and solve for that value.
2647 \*-----------------------------------------------------------------------*/
2648 // NOTE: It is not necessary to solve for 'right' in the over constrained
2649 // case because the value is not used for any further calculations.
2651 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2652 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2654 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + logicalWidthValue + logicalRight.calcValue(containerLogicalWidth) + bordersPlusPadding);
2656 // Margins are now the only unknown
2657 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2658 // Both margins auto, solve for equality
2659 if (availableSpace >= 0) {
2660 marginLogicalLeftValue = availableSpace / 2; // split the difference
2661 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2663 // Use the containing block's direction rather than the parent block's
2664 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2665 if (containerDirection == LTR) {
2666 marginLogicalLeftValue = 0;
2667 marginLogicalRightValue = availableSpace; // will be negative
2669 marginLogicalLeftValue = availableSpace; // will be negative
2670 marginLogicalRightValue = 0;
2673 } else if (marginLogicalLeft.isAuto()) {
2674 // Solve for left margin
2675 marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2676 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
2677 } else if (marginLogicalRight.isAuto()) {
2678 // Solve for right margin
2679 marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2680 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
2682 // Over-constrained, solve for left if direction is RTL
2683 marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2684 marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2686 // Use the containing block's direction rather than the parent block's
2687 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2688 if (containerDirection == RTL)
2689 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
2692 /*--------------------------------------------------------------------*\
2693 * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
2694 * to 0, and pick the one of the following six rules that applies.
2696 * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
2697 * width is shrink-to-fit. Then solve for 'left'
2699 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2700 * ------------------------------------------------------------------
2701 * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
2702 * the 'direction' property of the containing block is 'ltr' set
2703 * 'left' to the static position, otherwise set 'right' to the
2704 * static position. Then solve for 'left' (if 'direction is 'rtl')
2705 * or 'right' (if 'direction' is 'ltr').
2706 * ------------------------------------------------------------------
2708 * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
2709 * width is shrink-to-fit . Then solve for 'right'
2710 * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
2712 * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
2714 * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
2717 * Calculation of the shrink-to-fit width is similar to calculating the
2718 * width of a table cell using the automatic table layout algorithm.
2719 * Roughly: calculate the preferred width by formatting the content
2720 * without breaking lines other than where explicit line breaks occur,
2721 * and also calculate the preferred minimum width, e.g., by trying all
2722 * possible line breaks. CSS 2.1 does not define the exact algorithm.
2723 * Thirdly, calculate the available width: this is found by solving
2724 * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
2727 * Then the shrink-to-fit width is:
2728 * min(max(preferred minimum width, available width), preferred width).
2729 \*--------------------------------------------------------------------*/
2730 // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
2731 // because the value is not used for any further calculations.
2733 // Calculate margins, 'auto' margins are ignored.
2734 marginLogicalLeftValue = marginLogicalLeft.calcMinValue(containerLogicalWidth);
2735 marginLogicalRightValue = marginLogicalRight.calcMinValue(containerLogicalWidth);
2737 const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
2739 // FIXME: Is there a faster way to find the correct case?
2740 // Use rule/case that applies.
2741 if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2742 // RULE 1: (use shrink-to-fit for width, and solve of left)
2743 LayoutUnit logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2745 // FIXME: would it be better to have shrink-to-fit in one step?
2746 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2747 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2748 LayoutUnit availableWidth = availableSpace - logicalRightValue;
2749 logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2750 logicalLeftValue = availableSpace - (logicalWidthValue + logicalRightValue);
2751 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
2752 // RULE 3: (use shrink-to-fit for width, and no need solve of right)
2753 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2755 // FIXME: would it be better to have shrink-to-fit in one step?
2756 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2757 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2758 LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2759 logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2760 } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2761 // RULE 4: (solve for left)
2762 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2763 logicalLeftValue = availableSpace - (logicalWidthValue + logicalRight.calcValue(containerLogicalWidth));
2764 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2765 // RULE 5: (solve for width)
2766 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2767 logicalWidthValue = availableSpace - (logicalLeftValue + logicalRight.calcValue(containerLogicalWidth));
2768 } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
2769 // RULE 6: (no need solve for right)
2770 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2771 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2775 // Use computed values to calculate the horizontal position.
2777 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
2778 // positioned, inline because right now, it is using the logical left position
2779 // of the first line box when really it should use the last line box. When
2780 // this is fixed elsewhere, this block should be removed.
2781 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2782 const RenderInline* flow = toRenderInline(containerBlock);
2783 InlineFlowBox* firstLine = flow->firstLineBox();
2784 InlineFlowBox* lastLine = flow->lastLineBox();
2785 if (firstLine && lastLine && firstLine != lastLine) {
2786 logicalLeftPos = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
2791 logicalLeftPos = logicalLeftValue + marginLogicalLeftValue;
2792 computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidthValue, containerBlock, containerLogicalWidth);
2795 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
2797 if (!logicalTop.isAuto() || !logicalBottom.isAuto())
2800 // FIXME: The static distance computation has not been patched for mixed writing modes.
2801 LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
2802 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2803 if (curr->isBox() && !curr->isTableRow())
2804 staticLogicalTop += toRenderBox(curr)->logicalTop();
2806 logicalTop.setValue(Fixed, staticLogicalTop);
2809 void RenderBox::computePositionedLogicalHeight()
2812 computePositionedLogicalHeightReplaced();
2816 // The following is based off of the W3C Working Draft from April 11, 2006 of
2817 // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
2818 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
2819 // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
2820 // correspond to text from the spec)
2823 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
2824 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2826 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
2828 bool isHorizontal = isHorizontalWritingMode();
2829 bool isFlipped = style()->isFlippedBlocksWritingMode();
2830 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
2831 const Length marginBefore = style()->marginBefore();
2832 const Length marginAfter = style()->marginAfter();
2833 LayoutUnit& marginBeforeAlias = isHorizontal ? (isFlipped ? m_marginBottom : m_marginTop) : (isFlipped ? m_marginRight: m_marginLeft);
2834 LayoutUnit& marginAfterAlias = isHorizontal ? (isFlipped ? m_marginTop : m_marginBottom) : (isFlipped ? m_marginLeft: m_marginRight);
2836 Length logicalTopLength = style()->logicalTop();
2837 Length logicalBottomLength = style()->logicalBottom();
2839 /*---------------------------------------------------------------------------*\
2840 * For the purposes of this section and the next, the term "static position"
2841 * (of an element) refers, roughly, to the position an element would have had
2842 * in the normal flow. More precisely, the static position for 'top' is the
2843 * distance from the top edge of the containing block to the top margin edge
2844 * of a hypothetical box that would have been the first box of the element if
2845 * its 'position' property had been 'static' and 'float' had been 'none'. The
2846 * value is negative if the hypothetical box is above the containing block.
2848 * But rather than actually calculating the dimensions of that hypothetical
2849 * box, user agents are free to make a guess at its probable position.
2851 * For the purposes of calculating the static position, the containing block
2852 * of fixed positioned elements is the initial containing block instead of
2854 \*---------------------------------------------------------------------------*/
2857 // Calculate the static distance if needed.
2858 computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
2860 LayoutUnit logicalHeightResult; // Needed to compute overflow.
2861 LayoutUnit logicalTopPos;
2863 // Calculate constraint equation values for 'height' case.
2864 computePositionedLogicalHeightUsing(style()->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2865 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2866 logicalHeightResult, marginBeforeAlias, marginAfterAlias, logicalTopPos);
2867 setLogicalTop(logicalTopPos);
2869 // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
2872 // Calculate constraint equation values for 'max-height' case.
2873 if (!style()->logicalMaxHeight().isUndefined()) {
2874 LayoutUnit maxLogicalHeight;
2875 LayoutUnit maxMarginBefore;
2876 LayoutUnit maxMarginAfter;
2877 LayoutUnit maxLogicalTopPos;
2879 computePositionedLogicalHeightUsing(style()->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2880 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2881 maxLogicalHeight, maxMarginBefore, maxMarginAfter, maxLogicalTopPos);
2883 if (logicalHeightResult > maxLogicalHeight) {
2884 logicalHeightResult = maxLogicalHeight;
2885 marginBeforeAlias = maxMarginBefore;
2886 marginAfterAlias = maxMarginAfter;
2887 setLogicalTop(maxLogicalTopPos);
2891 // Calculate constraint equation values for 'min-height' case.
2892 if (!style()->logicalMinHeight().isZero()) {
2893 LayoutUnit minLogicalHeight;
2894 LayoutUnit minMarginBefore;
2895 LayoutUnit minMarginAfter;
2896 LayoutUnit minLogicalTopPos;
2898 computePositionedLogicalHeightUsing(style()->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2899 logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2900 minLogicalHeight, minMarginBefore, minMarginAfter, minLogicalTopPos);
2902 if (logicalHeightResult < minLogicalHeight) {
2903 logicalHeightResult = minLogicalHeight;
2904 marginBeforeAlias = minMarginBefore;
2905 marginAfterAlias = minMarginAfter;
2906 setLogicalTop(minLogicalTopPos);
2910 // Set final height value.
2911 setLogicalHeight(logicalHeightResult + bordersPlusPadding);
2913 // Adjust logicalTop if we need to for perpendicular writing modes in regions.
2914 if (inRenderFlowThread() && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode()) {
2915 LayoutUnit logicalTopPos = logicalTop();
2916 const RenderBlock* cb = toRenderBlock(containerBlock);
2917 LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage() - logicalLeft();
2918 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2919 cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2920 RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2922 logicalTopPos += boxInfo->logicalLeft();
2923 setLogicalTop(logicalTopPos);
2928 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
2930 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2931 // 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.
2932 if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
2933 || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
2934 logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
2936 // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
2937 if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2938 if (child->isHorizontalWritingMode())
2939 logicalTopPos += containerBlock->borderBottom();
2941 logicalTopPos += containerBlock->borderRight();
2943 if (child->isHorizontalWritingMode())
2944 logicalTopPos += containerBlock->borderTop();
2946 logicalTopPos += containerBlock->borderLeft();
2950 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
2951 LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding,
2952 Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
2953 LayoutUnit& logicalHeightValue, LayoutUnit& marginBeforeValue, LayoutUnit& marginAfterValue, LayoutUnit& logicalTopPos)
2955 // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
2956 // converted to the static position in computePositionedLogicalHeight()
2957 ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
2959 LayoutUnit contentLogicalHeight = logicalHeight() - bordersPlusPadding;
2961 LayoutUnit logicalTopValue = 0;
2963 bool logicalHeightIsAuto = logicalHeightLength.isAuto();
2964 bool logicalTopIsAuto = logicalTop.isAuto();
2965 bool logicalBottomIsAuto = logicalBottom.isAuto();
2967 // Height is never unsolved for tables.
2969 logicalHeightLength.setValue(Fixed, contentLogicalHeight);
2970 logicalHeightIsAuto = false;
2973 if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
2974 /*-----------------------------------------------------------------------*\
2975 * If none of the three are 'auto': If both 'margin-top' and 'margin-
2976 * bottom' are 'auto', solve the equation under the extra constraint that
2977 * the two margins get equal values. If one of 'margin-top' or 'margin-
2978 * bottom' is 'auto', solve the equation for that value. If the values
2979 * are over-constrained, ignore the value for 'bottom' and solve for that
2981 \*-----------------------------------------------------------------------*/
2982 // NOTE: It is not necessary to solve for 'bottom' in the over constrained
2983 // case because the value is not used for any further calculations.
2985 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2986 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2988 const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight) + bordersPlusPadding);
2990 // Margins are now the only unknown
2991 if (marginBefore.isAuto() && marginAfter.isAuto()) {
2992 // Both margins auto, solve for equality
2993 // NOTE: This may result in negative values.
2994 marginBeforeValue = availableSpace / 2; // split the difference
2995 marginAfterValue = availableSpace - marginBeforeValue; // account for odd valued differences
2996 } else if (marginBefore.isAuto()) {
2997 // Solve for top margin
2998 marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
2999 marginBeforeValue = availableSpace - marginAfterValue;
3000 } else if (marginAfter.isAuto()) {
3001 // Solve for bottom margin
3002 marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
3003 marginAfterValue = availableSpace - marginBeforeValue;
3005 // Over-constrained, (no need solve for bottom)
3006 marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
3007 marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
3010 /*--------------------------------------------------------------------*\
3011 * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3012 * to 0, and pick the one of the following six rules that applies.
3014 * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3015 * the height is based on the content, and solve for 'top'.
3017 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3018 * ------------------------------------------------------------------
3019 * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3020 * set 'top' to the static position, and solve for 'bottom'.
3021 * ------------------------------------------------------------------
3023 * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3024 * the height is based on the content, and solve for 'bottom'.
3025 * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3027 * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3028 * solve for 'height'.
3029 * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3030 * solve for 'bottom'.
3031 \*--------------------------------------------------------------------*/
3032 // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3033 // because the value is not used for any further calculations.
3035 // Calculate margins, 'auto' margins are ignored.
3036 marginBeforeValue = marginBefore.calcMinValue(containerLogicalHeight);
3037 marginAfterValue = marginAfter.calcMinValue(containerLogicalHeight);
3039 const LayoutUnit availableSpace = containerLogicalHeight - (marginBeforeValue + marginAfterValue + bordersPlusPadding);
3041 // Use rule/case that applies.
3042 if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3043 // RULE 1: (height is content based, solve of top)
3044 logicalHeightValue = contentLogicalHeight;
3045 logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
3046 } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
3047 // RULE 3: (height is content based, no need solve of bottom)
3048 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3049 logicalHeightValue = contentLogicalHeight;
3050 } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3051 // RULE 4: (solve of top)
3052 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
3053 logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
3054 } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3055 // RULE 5: (solve of height)
3056 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3057 logicalHeightValue = max<LayoutUnit>(0, availableSpace - (logicalTopValue + logicalBottom.calcValue(containerLogicalHeight)));
3058 } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
3059 // RULE 6: (no need solve of bottom)
3060 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
3061 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3065 // Use computed values to calculate the vertical position.
3066 logicalTopPos = logicalTopValue + marginBeforeValue;
3067 computeLogicalTopPositionedOffset(logicalTopPos, this, logicalHeightValue, containerBlock, containerLogicalHeight);
3070 void RenderBox::computePositionedLogicalWidthReplaced()
3072 // The following is based off of the W3C Working Draft from April 11, 2006 of
3073 // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
3074 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
3075 // (block-style-comments in this function correspond to text from the spec and
3076 // the numbers correspond to numbers in spec)
3078 // We don't use containingBlock(), since we may be positioned by an enclosing
3079 // relative positioned inline.
3080 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3082 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
3084 // To match WinIE, in quirks mode use the parent's 'direction' property
3085 // instead of the the container block's.
3086 TextDirection containerDirection = containerBlock->style()->direction();
3088 // Variables to solve.
3089 bool isHorizontal = isHorizontalWritingMode();
3090 Length logicalLeft = style()->logicalLeft();
3091 Length logicalRight = style()->logicalRight();
3092 Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3093 Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3094 LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
3095 LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
3097 /*-----------------------------------------------------------------------*\
3098 * 1. The used value of 'width' is determined as for inline replaced
3100 \*-----------------------------------------------------------------------*/
3101 // NOTE: This value of width is FINAL in that the min/max width calculations
3102 // are dealt with in computeReplacedWidth(). This means that the steps to produce
3103 // correct max/min in the non-replaced version, are not necessary.
3104 setLogicalWidth(computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth());
3106 const LayoutUnit availableSpace = containerLogicalWidth - logicalWidth();
3108 /*-----------------------------------------------------------------------*\
3109 * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
3110 * of the containing block is 'ltr', set 'left' to the static position;
3111 * else if 'direction' is 'rtl', set 'right' to the static position.
3112 \*-----------------------------------------------------------------------*/
3114 computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, 0); // FIXME: Pass the region.
3116 /*-----------------------------------------------------------------------*\
3117 * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
3118 * or 'margin-right' with '0'.
3119 \*-----------------------------------------------------------------------*/
3120 if (logicalLeft.isAuto() || logicalRight.isAuto()) {
3121 if (marginLogicalLeft.isAuto())
3122 marginLogicalLeft.setValue(Fixed, 0);
3123 if (marginLogicalRight.isAuto())
3124 marginLogicalRight.setValue(Fixed, 0);
3127 /*-----------------------------------------------------------------------*\
3128 * 4. If at this point both 'margin-left' and 'margin-right' are still
3129 * 'auto', solve the equation under the extra constraint that the two
3130 * margins must get equal values, unless this would make them negative,
3131 * in which case when the direction of the containing block is 'ltr'
3132 * ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
3133 * 'margin-right' ('margin-left').
3134 \*-----------------------------------------------------------------------*/
3135 LayoutUnit logicalLeftValue = 0;
3136 LayoutUnit logicalRightValue = 0;
3138 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3139 // 'left' and 'right' cannot be 'auto' due to step 3
3140 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3142 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3143 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3145 LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
3146 if (difference > 0) {
3147 marginLogicalLeftAlias = difference / 2; // split the difference
3148 marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
3150 // Use the containing block's direction rather than the parent block's
3151 // per CSS 2.1 reference test abspos-replaced-width-margin-000.
3152 if (containerDirection == LTR) {
3153 marginLogicalLeftAlias = 0;
3154 marginLogicalRightAlias = difference; // will be negative
3156 marginLogicalLeftAlias = difference; // will be negative
3157 marginLogicalRightAlias = 0;
3161 /*-----------------------------------------------------------------------*\
3162 * 5. If at this point there is an 'auto' left, solve the equation for
3164 \*-----------------------------------------------------------------------*/
3165 } else if (logicalLeft.isAuto()) {
3166 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3167 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3168 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3171 logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3172 } else if (logicalRight.isAuto()) {
3173 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3174 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3175 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3177 // Solve for 'right'
3178 logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3179 } else if (marginLogicalLeft.isAuto()) {
3180 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3181 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3182 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3184 // Solve for 'margin-left'
3185 marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
3186 } else if (marginLogicalRight.isAuto()) {
3187 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3188 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3189 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3191 // Solve for 'margin-right'
3192 marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
3194 // Nothing is 'auto', just calculate the values.
3195 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3196 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3197 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3198 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3199 // If the containing block is right-to-left, then push the left position as far to the right as possible
3200 if (containerDirection == RTL) {
3201 int totalLogicalWidth = logicalWidth() + logicalLeftValue + logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias;
3202 logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
3206 /*-----------------------------------------------------------------------*\
3207 * 6. If at this point the values are over-constrained, ignore the value
3208 * for either 'left' (in case the 'direction' property of the
3209 * containing block is 'rtl') or 'right' (in case 'direction' is
3210 * 'ltr') and solve for that value.
3211 \*-----------------------------------------------------------------------*/
3212 // NOTE: Constraints imposed by the width of the containing block and its content have already been accounted for above.
3214 // FIXME: Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space, so that
3215 // can make the result here rather complicated to compute.
3217 // Use computed values to calculate the horizontal position.
3219 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3220 // positioned, inline containing block because right now, it is using the logical left position
3221 // of the first line box when really it should use the last line box. When
3222 // this is fixed elsewhere, this block should be removed.
3223 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3224 const RenderInline* flow = toRenderInli