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 "RenderFlowThread.h"
45 #include "RenderInline.h"
46 #include "RenderLayer.h"
47 #include "RenderPart.h"
48 #include "RenderRegion.h"
49 #include "RenderTableCell.h"
50 #include "RenderTheme.h"
51 #include "RenderView.h"
52 #include "ScrollbarTheme.h"
53 #include "TransformState.h"
61 using namespace HTMLNames;
63 // Used by flexible boxes when flexing this element and by table cells.
64 typedef WTF::HashMap<const RenderBox*, LayoutUnit> OverrideSizeMap;
65 static OverrideSizeMap* gOverrideHeightMap = 0;
66 static OverrideSizeMap* gOverrideWidthMap = 0;
68 bool RenderBox::s_hadOverflowClip = false;
70 RenderBox::RenderBox(Node* node)
71 : RenderBoxModelObject(node)
76 , m_minPreferredLogicalWidth(-1)
77 , m_maxPreferredLogicalWidth(-1)
78 , m_inlineBoxWrapper(0)
83 RenderBox::~RenderBox()
87 LayoutUnit RenderBox::marginBefore() const
89 switch (style()->writingMode()) {
90 case TopToBottomWritingMode:
92 case BottomToTopWritingMode:
93 return m_marginBottom;
94 case LeftToRightWritingMode:
96 case RightToLeftWritingMode:
103 LayoutUnit RenderBox::marginAfter() const
105 switch (style()->writingMode()) {
106 case TopToBottomWritingMode:
107 return m_marginBottom;
108 case BottomToTopWritingMode:
110 case LeftToRightWritingMode:
111 return m_marginRight;
112 case RightToLeftWritingMode:
115 ASSERT_NOT_REACHED();
116 return m_marginBottom;
119 LayoutUnit RenderBox::marginStart() const
121 if (isHorizontalWritingMode())
122 return style()->isLeftToRightDirection() ? m_marginLeft : m_marginRight;
123 return style()->isLeftToRightDirection() ? m_marginTop : m_marginBottom;
126 LayoutUnit RenderBox::marginEnd() const
128 if (isHorizontalWritingMode())
129 return style()->isLeftToRightDirection() ? m_marginRight : m_marginLeft;
130 return style()->isLeftToRightDirection() ? m_marginBottom : m_marginTop;
133 void RenderBox::setMarginStart(LayoutUnit margin)
135 if (isHorizontalWritingMode()) {
136 if (style()->isLeftToRightDirection())
137 m_marginLeft = margin;
139 m_marginRight = margin;
141 if (style()->isLeftToRightDirection())
142 m_marginTop = margin;
144 m_marginBottom = margin;
148 void RenderBox::setMarginEnd(LayoutUnit margin)
150 if (isHorizontalWritingMode()) {
151 if (style()->isLeftToRightDirection())
152 m_marginRight = margin;
154 m_marginLeft = margin;
156 if (style()->isLeftToRightDirection())
157 m_marginBottom = margin;
159 m_marginTop = margin;
163 void RenderBox::setMarginBefore(LayoutUnit margin)
165 switch (style()->writingMode()) {
166 case TopToBottomWritingMode:
167 m_marginTop = margin;
169 case BottomToTopWritingMode:
170 m_marginBottom = margin;
172 case LeftToRightWritingMode:
173 m_marginLeft = margin;
175 case RightToLeftWritingMode:
176 m_marginRight = margin;
181 void RenderBox::setMarginAfter(LayoutUnit margin)
183 switch (style()->writingMode()) {
184 case TopToBottomWritingMode:
185 m_marginBottom = margin;
187 case BottomToTopWritingMode:
188 m_marginTop = margin;
190 case LeftToRightWritingMode:
191 m_marginRight = margin;
193 case RightToLeftWritingMode:
194 m_marginLeft = margin;
199 void RenderBox::willBeDestroyed()
203 if (style() && (style()->logicalHeight().isPercent() || style()->logicalMinHeight().isPercent() || style()->logicalMaxHeight().isPercent()))
204 RenderBlock::removePercentHeightDescendant(this);
206 // If this renderer is owning renderer for the frameview's custom scrollbars,
207 // we need to clear it from the scrollbar. See webkit bug 64737.
208 if (style() && style()->hasPseudoStyle(SCROLLBAR) && frame() && frame()->view())
209 frame()->view()->clearOwningRendererForCustomScrollbars(this);
211 // If the following assertion fails, logicalHeight()/logicalMinHeight()/
212 // logicalMaxHeight() values are changed from a percent value to a non-percent
213 // value during laying out. It causes a use-after-free bug.
214 ASSERT(!RenderBlock::hasPercentHeightDescendant(this));
216 RenderBoxModelObject::willBeDestroyed();
219 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
221 ASSERT(isFloatingOrPositioned());
223 if (documentBeingDestroyed())
227 RenderBlock* parentBlock = 0;
228 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
229 if (curr->isRenderBlock()) {
230 RenderBlock* currBlock = toRenderBlock(curr);
231 if (!parentBlock || currBlock->containsFloat(this))
232 parentBlock = currBlock;
237 RenderObject* parent = parentBlock->parent();
238 if (parent && parent->isDeprecatedFlexibleBox())
239 parentBlock = toRenderBlock(parent);
241 parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
245 if (isPositioned()) {
246 for (RenderObject* curr = parent(); curr; curr = curr->parent()) {
247 if (curr->isRenderBlock())
248 toRenderBlock(curr)->removePositionedObject(this);
253 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
255 s_hadOverflowClip = hasOverflowClip();
258 // The background of the root element or the body element could propagate up to
259 // the canvas. Just dirty the entire canvas when our style changes substantially.
260 if (diff >= StyleDifferenceRepaint && node() &&
261 (node()->hasTagName(htmlTag) || node()->hasTagName(bodyTag)))
264 // When a layout hint happens and an object's position style changes, we have to do a layout
265 // to dirty the render tree using the old position value now.
266 if (diff == StyleDifferenceLayout && parent() && style()->position() != newStyle->position()) {
267 markContainingBlocksForLayout();
268 if (style()->position() == StaticPosition)
270 else if (newStyle->position() == AbsolutePosition || newStyle->position() == FixedPosition)
271 parent()->setChildNeedsLayout(true);
272 if (isFloating() && !isPositioned() && (newStyle->position() == AbsolutePosition || newStyle->position() == FixedPosition))
273 removeFloatingOrPositionedChildFromBlockLists();
275 } else if (newStyle && isBody())
278 if (FrameView *frameView = view()->frameView()) {
279 bool newStyleIsFixed = newStyle && newStyle->position() == FixedPosition;
280 bool oldStyleIsFixed = style() && style()->position() == FixedPosition;
281 if (newStyleIsFixed != oldStyleIsFixed) {
283 frameView->addFixedObject();
285 frameView->removeFixedObject();
289 RenderBoxModelObject::styleWillChange(diff, newStyle);
292 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
294 RenderBoxModelObject::styleDidChange(diff, oldStyle);
296 if (needsLayout() && oldStyle) {
297 if (oldStyle && (oldStyle->logicalHeight().isPercent() || oldStyle->logicalMinHeight().isPercent() || oldStyle->logicalMaxHeight().isPercent()))
298 RenderBlock::removePercentHeightDescendant(this);
300 // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
301 // 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
302 // to determine the new static position.
303 if (isPositioned() && style()->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != style()->marginBefore()
304 && parent() && !parent()->normalChildNeedsLayout())
305 parent()->setChildNeedsLayout(true);
308 // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
309 // new zoomed coordinate space.
310 if (hasOverflowClip() && oldStyle && style() && oldStyle->effectiveZoom() != style()->effectiveZoom()) {
311 if (int left = layer()->scrollXOffset()) {
312 left = (left / oldStyle->effectiveZoom()) * style()->effectiveZoom();
313 layer()->scrollToXOffset(left);
315 if (int top = layer()->scrollYOffset()) {
316 top = (top / oldStyle->effectiveZoom()) * style()->effectiveZoom();
317 layer()->scrollToYOffset(top);
321 bool isBodyRenderer = isBody();
322 bool isRootRenderer = isRoot();
324 // Set the text color if we're the body.
326 document()->setTextColor(style()->visitedDependentColor(CSSPropertyColor));
328 if (isRootRenderer || isBodyRenderer) {
329 // Propagate the new writing mode and direction up to the RenderView.
330 RenderView* viewRenderer = view();
331 RenderStyle* viewStyle = viewRenderer->style();
332 if (viewStyle->direction() != style()->direction() && (isRootRenderer || !document()->directionSetOnDocumentElement())) {
333 viewStyle->setDirection(style()->direction());
335 document()->documentElement()->renderer()->style()->setDirection(style()->direction());
336 setNeedsLayoutAndPrefWidthsRecalc();
339 if (viewStyle->writingMode() != style()->writingMode() && (isRootRenderer || !document()->writingModeSetOnDocumentElement())) {
340 viewStyle->setWritingMode(style()->writingMode());
341 viewRenderer->setHorizontalWritingMode(style()->isHorizontalWritingMode());
342 if (isBodyRenderer) {
343 document()->documentElement()->renderer()->style()->setWritingMode(style()->writingMode());
344 document()->documentElement()->renderer()->setHorizontalWritingMode(style()->isHorizontalWritingMode());
346 setNeedsLayoutAndPrefWidthsRecalc();
349 frame()->view()->recalculateScrollbarOverlayStyle();
353 void RenderBox::updateBoxModelInfoFromStyle()
355 RenderBoxModelObject::updateBoxModelInfoFromStyle();
357 bool isRootObject = isRoot();
358 bool isViewObject = isRenderView();
360 // The root and the RenderView always paint their backgrounds/borders.
361 if (isRootObject || isViewObject)
362 setHasBoxDecorations(true);
364 setPositioned(style()->position() == AbsolutePosition || style()->position() == FixedPosition);
365 setFloating(style()->isFloating() && (!isPositioned() || style()->floating() == PositionedFloat));
367 // We also handle <body> and <html>, whose overflow applies to the viewport.
368 if (style()->overflowX() != OVISIBLE && !isRootObject && (isRenderBlock() || isTableRow() || isTableSection())) {
369 bool boxHasOverflowClip = true;
371 // Overflow on the body can propagate to the viewport under the following conditions.
372 // (1) The root element is <html>.
373 // (2) We are the primary <body> (can be checked by looking at document.body).
374 // (3) The root element has visible overflow.
375 if (document()->documentElement()->hasTagName(htmlTag) &&
376 document()->body() == node() &&
377 document()->documentElement()->renderer()->style()->overflowX() == OVISIBLE)
378 boxHasOverflowClip = false;
381 // Check for overflow clip.
382 // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
383 if (boxHasOverflowClip) {
384 if (!s_hadOverflowClip)
385 // Erase the overflow
387 setHasOverflowClip();
391 setHasTransform(style()->hasTransformRelatedProperty());
392 setHasReflection(style()->boxReflect());
395 void RenderBox::layout()
397 ASSERT(needsLayout());
399 RenderObject* child = firstChild();
401 setNeedsLayout(false);
405 LayoutStateMaintainer statePusher(view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
407 child->layoutIfNeeded();
408 ASSERT(!child->needsLayout());
409 child = child->nextSibling();
412 setNeedsLayout(false);
415 // More IE extensions. clientWidth and clientHeight represent the interior of an object
416 // excluding border and scrollbar.
417 LayoutUnit RenderBox::clientWidth() const
419 return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
422 LayoutUnit RenderBox::clientHeight() const
424 return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
427 LayoutUnit RenderBox::scrollWidth() const
429 if (hasOverflowClip())
430 return layer()->scrollWidth();
431 // For objects with visible overflow, this matches IE.
432 // FIXME: Need to work right with writing modes.
433 if (style()->isLeftToRightDirection())
434 return max(clientWidth(), maxXLayoutOverflow() - borderLeft());
435 return clientWidth() - min<LayoutUnit>(0, minXLayoutOverflow() - borderLeft());
438 LayoutUnit RenderBox::scrollHeight() const
440 if (hasOverflowClip())
441 return layer()->scrollHeight();
442 // For objects with visible overflow, this matches IE.
443 // FIXME: Need to work right with writing modes.
444 return max(clientHeight(), maxYLayoutOverflow() - borderTop());
447 LayoutUnit RenderBox::scrollLeft() const
449 return hasOverflowClip() ? layer()->scrollXOffset() : 0;
452 LayoutUnit RenderBox::scrollTop() const
454 return hasOverflowClip() ? layer()->scrollYOffset() : 0;
457 void RenderBox::setScrollLeft(LayoutUnit newLeft)
459 if (hasOverflowClip())
460 layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
463 void RenderBox::setScrollTop(LayoutUnit newTop)
465 if (hasOverflowClip())
466 layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
469 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset)
471 rects.append(LayoutRect(accumulatedOffset, size()));
474 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed)
476 quads.append(localToAbsoluteQuad(FloatRect(0, 0, width(), height()), false, wasFixed));
479 void RenderBox::updateLayerTransform()
481 // Transform-origin depends on box size, so we need to update the layer transform after layout.
483 layer()->updateTransform();
486 LayoutRect RenderBox::absoluteContentBox() const
488 LayoutRect rect = contentBoxRect();
489 FloatPoint absPos = localToAbsolute(FloatPoint());
490 rect.move(absPos.x(), absPos.y());
494 FloatQuad RenderBox::absoluteContentQuad() const
496 LayoutRect rect = contentBoxRect();
497 return localToAbsoluteQuad(FloatRect(rect));
500 LayoutRect RenderBox::outlineBoundsForRepaint(RenderBoxModelObject* repaintContainer, LayoutPoint* cachedOffsetToRepaintContainer) const
502 LayoutRect box = borderBoundingBox();
503 adjustRectForOutlineAndShadow(box);
505 FloatQuad containerRelativeQuad = FloatRect(box);
506 if (cachedOffsetToRepaintContainer)
507 containerRelativeQuad.move(cachedOffsetToRepaintContainer->x(), cachedOffsetToRepaintContainer->y());
509 containerRelativeQuad = localToContainerQuad(containerRelativeQuad, repaintContainer);
511 box = containerRelativeQuad.enclosingBoundingBox();
513 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
514 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
515 box.move(view()->layoutDelta());
520 void RenderBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset)
522 if (!size().isEmpty())
523 rects.append(LayoutRect(additionalOffset, size()));
526 LayoutRect RenderBox::reflectionBox() const
529 if (!style()->boxReflect())
531 LayoutRect box = borderBoxRect();
533 switch (style()->boxReflect()->direction()) {
534 case ReflectionBelow:
535 result.move(0, box.height() + reflectionOffset());
537 case ReflectionAbove:
538 result.move(0, -box.height() - reflectionOffset());
541 result.move(-box.width() - reflectionOffset(), 0);
543 case ReflectionRight:
544 result.move(box.width() + reflectionOffset(), 0);
550 int RenderBox::reflectionOffset() const
552 if (!style()->boxReflect())
554 if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
555 return style()->boxReflect()->offset().calcValue(borderBoxRect().width());
556 return style()->boxReflect()->offset().calcValue(borderBoxRect().height());
559 LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
561 if (!style()->boxReflect())
564 LayoutRect box = borderBoxRect();
565 LayoutRect result = r;
566 switch (style()->boxReflect()->direction()) {
567 case ReflectionBelow:
568 result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
570 case ReflectionAbove:
571 result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
574 result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
576 case ReflectionRight:
577 result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
583 bool RenderBox::includeVerticalScrollbarSize() const
585 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
586 && (style()->overflowY() == OSCROLL || style()->overflowY() == OAUTO);
589 bool RenderBox::includeHorizontalScrollbarSize() const
591 return hasOverflowClip() && !layer()->hasOverlayScrollbars()
592 && (style()->overflowX() == OSCROLL || style()->overflowX() == OAUTO);
595 LayoutUnit RenderBox::verticalScrollbarWidth() const
597 return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
600 LayoutUnit RenderBox::horizontalScrollbarHeight() const
602 return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
605 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
607 RenderLayer* l = layer();
608 if (l && l->scroll(direction, granularity, multiplier)) {
614 if (stopNode && *stopNode && *stopNode == node())
617 RenderBlock* b = containingBlock();
618 if (b && !b->isRenderView())
619 return b->scroll(direction, granularity, multiplier, stopNode);
623 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
625 bool scrolled = false;
627 RenderLayer* l = layer();
630 // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
631 if (granularity == ScrollByDocument)
632 scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
634 if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), granularity, multiplier))
644 if (stopNode && *stopNode && *stopNode == node())
647 RenderBlock* b = containingBlock();
648 if (b && !b->isRenderView())
649 return b->logicalScroll(direction, granularity, multiplier, stopNode);
653 bool RenderBox::canBeScrolledAndHasScrollableArea() const
655 return canBeProgramaticallyScrolled() && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth());
658 bool RenderBox::canBeProgramaticallyScrolled() const
660 return (hasOverflowClip() && (scrollsOverflow() || (node() && node()->rendererIsEditable()))) || (node() && node()->isDocumentNode());
663 void RenderBox::autoscroll()
666 layer()->autoscroll();
669 void RenderBox::panScroll(const IntPoint& source)
672 layer()->panScrollFromPoint(source);
675 bool RenderBox::needsPreferredWidthsRecalculation() const
677 return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent();
680 LayoutUnit RenderBox::minPreferredLogicalWidth() const
682 if (preferredLogicalWidthsDirty())
683 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
685 return m_minPreferredLogicalWidth;
688 LayoutUnit RenderBox::maxPreferredLogicalWidth() const
690 if (preferredLogicalWidthsDirty())
691 const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
693 return m_maxPreferredLogicalWidth;
696 bool RenderBox::hasOverrideHeight() const
698 return gOverrideHeightMap && gOverrideHeightMap->contains(this);
701 bool RenderBox::hasOverrideWidth() const
703 return gOverrideWidthMap && gOverrideWidthMap->contains(this);
706 void RenderBox::setOverrideHeight(LayoutUnit height)
708 if (!gOverrideHeightMap)
709 gOverrideHeightMap = new OverrideSizeMap();
710 gOverrideHeightMap->set(this, height);
713 void RenderBox::setOverrideWidth(LayoutUnit width)
715 if (!gOverrideWidthMap)
716 gOverrideWidthMap = new OverrideSizeMap();
717 gOverrideWidthMap->set(this, width);
720 void RenderBox::clearOverrideSize()
722 if (hasOverrideHeight())
723 gOverrideHeightMap->remove(this);
724 if (hasOverrideWidth())
725 gOverrideWidthMap->remove(this);
728 LayoutUnit RenderBox::overrideWidth() const
730 return hasOverrideWidth() ? gOverrideWidthMap->get(this) : width();
733 LayoutUnit RenderBox::overrideHeight() const
735 return hasOverrideHeight() ? gOverrideHeightMap->get(this) : height();
738 LayoutUnit RenderBox::computeBorderBoxLogicalWidth(LayoutUnit width) const
740 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
741 if (style()->boxSizing() == CONTENT_BOX)
742 return width + bordersPlusPadding;
743 return max(width, bordersPlusPadding);
746 LayoutUnit RenderBox::computeBorderBoxLogicalHeight(LayoutUnit height) const
748 LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
749 if (style()->boxSizing() == CONTENT_BOX)
750 return height + bordersPlusPadding;
751 return max(height, bordersPlusPadding);
754 LayoutUnit RenderBox::computeContentBoxLogicalWidth(LayoutUnit width) const
756 if (style()->boxSizing() == BORDER_BOX)
757 width -= borderAndPaddingLogicalWidth();
758 return max<LayoutUnit>(0, width);
761 LayoutUnit RenderBox::computeContentBoxLogicalHeight(LayoutUnit height) const
763 if (style()->boxSizing() == BORDER_BOX)
764 height -= borderAndPaddingLogicalHeight();
765 return max<LayoutUnit>(0, height);
769 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
771 LayoutPoint adjustedLocation = accumulatedOffset + location();
774 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
775 if (!child->hasLayer() && child->nodeAtPoint(request, result, pointInContainer, adjustedLocation, action)) {
776 updateHitTestResult(result, pointInContainer - toLayoutSize(adjustedLocation));
781 // Check our bounds next. For this purpose always assume that we can only be hit in the
782 // foreground phase (which is true for replaced elements like images).
783 LayoutRect boundsRect(adjustedLocation, size());
784 if (visibleToHitTesting() && action == HitTestForeground && boundsRect.intersects(result.rectForPoint(pointInContainer))) {
785 updateHitTestResult(result, pointInContainer - toLayoutSize(adjustedLocation));
786 if (!result.addNodeToRectBasedTestResult(node(), pointInContainer, boundsRect))
793 // --------------------- painting stuff -------------------------------
795 void RenderBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
797 LayoutPoint adjustedPaintOffset = paintOffset + location();
798 // default implementation. Just pass paint through to the children
799 PaintInfo childInfo(paintInfo);
800 childInfo.updatePaintingRootForChildren(this);
801 for (RenderObject* child = firstChild(); child; child = child->nextSibling())
802 child->paint(childInfo, adjustedPaintOffset);
805 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
807 const FillLayer* bgLayer = style()->backgroundLayers();
808 Color bgColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
809 RenderObject* bodyObject = 0;
810 if (!hasBackground() && node() && node()->hasTagName(HTMLNames::htmlTag)) {
811 // Locate the <body> element using the DOM. This is easier than trying
812 // to crawl around a render tree with potential :before/:after content and
813 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
814 // render object very easily via the DOM.
815 HTMLElement* body = document()->body();
816 bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
818 bgLayer = bodyObject->style()->backgroundLayers();
819 bgColor = bodyObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
823 // The background of the box generated by the root element covers the entire canvas, so just use
824 // the RenderView's unscaledDocumentRect accessor.
825 paintFillLayers(paintInfo, bgColor, bgLayer, view()->unscaledDocumentRect(), BackgroundBleedNone, CompositeSourceOver, bodyObject);
828 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
830 if (context->paintingDisabled())
831 return BackgroundBleedNone;
833 const RenderStyle* style = this->style();
835 if (!style->hasBackground() || !style->hasBorder() || !style->hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
836 return BackgroundBleedNone;
838 AffineTransform ctm = context->getCTM();
839 FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
840 if (borderObscuresBackgroundEdge(contextScaling))
841 return BackgroundBleedShrinkBackground;
843 // FIXME: there is one more strategy possible, for opaque backgrounds and
844 // translucent borders. In that case we could avoid using a transparency layer,
845 // and paint the border first, and then paint the background clipped to the
846 // inside of the border.
848 return BackgroundBleedUseTransparencyLayer;
851 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
853 if (!paintInfo.shouldPaintWithinRoot(this))
855 LayoutRect paintRect(paintOffset, size());
857 // border-fit can adjust where we paint our border and background. If set, we snugly fit our line box descendants. (The iChat
858 // balloon layout is an example of this).
859 borderFitAdjust(paintRect);
861 // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
862 // custom shadows of their own.
863 paintBoxShadow(paintInfo, paintRect, style(), Normal);
865 BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
867 GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
868 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
869 // To avoid the background color bleeding out behind the border, we'll render background and border
870 // into a transparency layer, and then clip that in one go (which requires setting up the clip before
871 // beginning the layer).
872 RoundedRect border = style()->getRoundedBorderFor(paintRect);
874 paintInfo.context->addRoundedRectClip(border);
875 paintInfo.context->beginTransparencyLayer(1);
878 // If we have a native theme appearance, paint that before painting our background.
879 // The theme will tell us whether or not we should also paint the CSS background.
880 bool themePainted = style()->hasAppearance() && !theme()->paint(this, paintInfo, paintRect);
882 paintBackground(paintInfo, paintRect, bleedAvoidance);
884 if (style()->hasAppearance())
885 theme()->paintDecorations(this, paintInfo, paintRect);
887 paintBoxShadow(paintInfo, paintRect, style(), Inset);
889 // The theme will tell us whether or not we should also paint the CSS border.
890 if ((!style()->hasAppearance() || (!themePainted && theme()->paintBorderOnly(this, paintInfo, paintRect))) && style()->hasBorder())
891 paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
893 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
894 paintInfo.context->endTransparencyLayer();
897 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
900 paintRootBoxFillLayers(paintInfo);
901 else if (!isBody() || document()->documentElement()->renderer()->hasBackground()) {
902 // The <body> only paints its background if the root element has defined a background
903 // independent of the body.
904 if (!backgroundIsObscured())
905 paintFillLayers(paintInfo, style()->visitedDependentColor(CSSPropertyBackgroundColor), style()->backgroundLayers(), paintRect, bleedAvoidance);
909 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
911 if (!paintInfo.shouldPaintWithinRoot(this) || style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
914 LayoutRect paintRect = LayoutRect(paintOffset, size());
916 // border-fit can adjust where we paint our border and background. If set, we snugly fit our line box descendants. (The iChat
917 // balloon layout is an example of this).
918 borderFitAdjust(paintRect);
920 paintMaskImages(paintInfo, paintRect);
923 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
925 // Figure out if we need to push a transparency layer to render our mask.
926 bool pushTransparencyLayer = false;
927 bool compositedMask = hasLayer() && layer()->hasCompositedMask();
928 CompositeOperator compositeOp = CompositeSourceOver;
930 bool allMaskImagesLoaded = true;
932 if (!compositedMask) {
933 // If the context has a rotation, scale or skew, then use a transparency layer to avoid
934 // pixel cruft around the edge of the mask.
935 const AffineTransform& currentCTM = paintInfo.context->getCTM();
936 pushTransparencyLayer = !currentCTM.isIdentityOrTranslationOrFlipped();
938 StyleImage* maskBoxImage = style()->maskBoxImage().image();
939 const FillLayer* maskLayers = style()->maskLayers();
941 // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
943 allMaskImagesLoaded &= maskBoxImage->isLoaded();
946 allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
948 // Before all images have loaded, just use an empty transparency layer as the mask.
949 if (!allMaskImagesLoaded)
950 pushTransparencyLayer = true;
952 if (maskBoxImage && maskLayers->hasImage()) {
953 // We have a mask-box-image and mask-image, so need to composite them together before using the result as a mask.
954 pushTransparencyLayer = true;
956 // We have to use an extra image buffer to hold the mask. Multiple mask images need
957 // to composite together using source-over so that they can then combine into a single unified mask that
958 // can be composited with the content using destination-in. SVG images need to be able to set compositing modes
959 // as they draw images contained inside their sub-document, so we paint all our images into a separate buffer
960 // and composite that buffer as the mask.
961 // We have to check that the mask images to be rendered contain at least one image that can be actually used in rendering
962 // before pushing the transparency layer.
963 for (const FillLayer* fillLayer = maskLayers->next(); fillLayer; fillLayer = fillLayer->next()) {
964 if (fillLayer->hasImage() && fillLayer->image()->canRender(style()->effectiveZoom())) {
965 pushTransparencyLayer = true;
966 // We found one image that can be used in rendering, exit the loop
972 compositeOp = CompositeDestinationIn;
973 if (pushTransparencyLayer) {
974 paintInfo.context->setCompositeOperation(CompositeDestinationIn);
975 paintInfo.context->beginTransparencyLayer(1.0f);
976 compositeOp = CompositeSourceOver;
980 if (allMaskImagesLoaded) {
981 paintFillLayers(paintInfo, Color(), style()->maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
982 paintNinePieceImage(paintInfo.context, paintRect, style(), style()->maskBoxImage(), compositeOp);
985 if (pushTransparencyLayer)
986 paintInfo.context->endTransparencyLayer();
989 LayoutRect RenderBox::maskClipRect()
991 const NinePieceImage& maskBoxImage = style()->maskBoxImage();
992 if (maskBoxImage.image()) {
993 LayoutRect borderImageRect = borderBoxRect();
995 // Apply outsets to the border box.
996 LayoutUnit topOutset;
997 LayoutUnit rightOutset;
998 LayoutUnit bottomOutset;
999 LayoutUnit leftOutset;
1000 style()->getMaskBoxImageOutsets(topOutset, rightOutset, bottomOutset, leftOutset);
1002 borderImageRect.setX(borderImageRect.x() - leftOutset);
1003 borderImageRect.setY(borderImageRect.y() - topOutset);
1004 borderImageRect.setWidth(borderImageRect.width() + leftOutset + rightOutset);
1005 borderImageRect.setHeight(borderImageRect.height() + topOutset + bottomOutset);
1007 return borderImageRect;
1011 LayoutRect borderBox = borderBoxRect();
1012 for (const FillLayer* maskLayer = style()->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1013 if (maskLayer->image()) {
1014 BackgroundImageGeometry geometry;
1015 calculateBackgroundImageGeometry(maskLayer, borderBox, geometry);
1016 result.unite(geometry.destRect());
1022 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1023 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1028 paintFillLayers(paintInfo, c, fillLayer->next(), rect, bleedAvoidance, op, backgroundObject);
1029 paintFillLayer(paintInfo, c, fillLayer, rect, bleedAvoidance, op, backgroundObject);
1032 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1033 BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1035 paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, 0, IntSize(), op, backgroundObject);
1038 #if USE(ACCELERATED_COMPOSITING)
1039 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1041 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1042 if (curLayer->image() && image == curLayer->image()->data())
1050 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1055 if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1056 (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1061 bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
1062 if (!didFullRepaint)
1063 repaintLayerRectsForImage(image, style()->maskLayers(), false);
1066 #if USE(ACCELERATED_COMPOSITING)
1067 if (hasLayer() && layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
1068 layer()->contentChanged(RenderLayer::MaskImageChanged);
1072 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1074 LayoutRect rendererRect;
1075 RenderBox* layerRenderer = 0;
1077 for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1078 if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(style()->effectiveZoom())) {
1079 // Now that we know this image is being used, compute the renderer and the rect
1080 // if we haven't already
1081 if (!layerRenderer) {
1082 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document()->documentElement()->renderer()->hasBackground()));
1083 if (drawingRootBackground) {
1084 layerRenderer = view();
1089 if (FrameView* frameView = toRenderView(layerRenderer)->frameView()) {
1090 rw = frameView->contentsWidth();
1091 rh = frameView->contentsHeight();
1093 rw = layerRenderer->width();
1094 rh = layerRenderer->height();
1096 rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1097 -layerRenderer->marginTop(),
1098 max(layerRenderer->width() + layerRenderer->marginLeft() + layerRenderer->marginRight() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1099 max(layerRenderer->height() + layerRenderer->marginTop() + layerRenderer->marginBottom() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1101 layerRenderer = this;
1102 rendererRect = borderBoxRect();
1106 BackgroundImageGeometry geometry;
1107 layerRenderer->calculateBackgroundImageGeometry(curLayer, rendererRect, geometry);
1108 layerRenderer->repaintRectangle(geometry.destRect());
1109 if (geometry.destRect() == rendererRect)
1118 void RenderBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type, bool behindText)
1120 Frame* frame = this->frame();
1123 Page* page = frame->page();
1127 InlineBox* boxWrap = inlineBoxWrapper();
1128 RootInlineBox* r = boxWrap ? boxWrap->root() : 0;
1130 FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + r->selectionTop(), r->logicalWidth(), r->selectionHeight());
1131 FloatRect imageRect(paintOffset.x() + x(), rootRect.y(), width(), rootRect.height());
1132 page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, rootRect, behindText, false);
1134 FloatRect imageRect(paintOffset.x() + x(), paintOffset.y() + y(), width(), height());
1135 page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, imageRect, behindText, false);
1141 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1143 if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1146 bool isControlClip = hasControlClip();
1147 bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1149 if (!isControlClip && !isOverflowClip)
1152 if (paintInfo.phase == PaintPhaseOutline)
1153 paintInfo.phase = PaintPhaseChildOutlines;
1154 else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1155 paintInfo.phase = PaintPhaseBlockBackground;
1156 paintObject(paintInfo, accumulatedOffset);
1157 paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1159 IntRect clipRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset));
1160 paintInfo.context->save();
1161 if (style()->hasBorderRadius())
1162 paintInfo.context->addRoundedRectClip(style()->getRoundedBorderFor(LayoutRect(accumulatedOffset, size())));
1163 paintInfo.context->clip(clipRect);
1167 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1169 ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1171 paintInfo.context->restore();
1172 if (originalPhase == PaintPhaseOutline) {
1173 paintInfo.phase = PaintPhaseSelfOutline;
1174 paintObject(paintInfo, accumulatedOffset);
1175 paintInfo.phase = originalPhase;
1176 } else if (originalPhase == PaintPhaseChildBlockBackground)
1177 paintInfo.phase = originalPhase;
1180 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, OverlayScrollbarSizeRelevancy relevancy)
1182 // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1184 LayoutRect clipRect(location + LayoutSize(borderLeft(), borderTop()),
1185 size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1187 // Subtract out scrollbars if we have them.
1189 clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1194 LayoutRect RenderBox::clipRect(const LayoutPoint& location)
1196 LayoutRect clipRect(location, size());
1197 if (!style()->clipLeft().isAuto()) {
1198 LayoutUnit c = style()->clipLeft().calcValue(width());
1199 clipRect.move(c, 0);
1200 clipRect.contract(c, 0);
1203 if (!style()->clipRight().isAuto())
1204 clipRect.contract(width() - style()->clipRight().calcValue(width()), 0);
1206 if (!style()->clipTop().isAuto()) {
1207 LayoutUnit c = style()->clipTop().calcValue(height());
1208 clipRect.move(0, c);
1209 clipRect.contract(0, c);
1212 if (!style()->clipBottom().isAuto())
1213 clipRect.contract(0, height() - style()->clipBottom().calcValue(height()));
1218 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1220 RenderBlock* cb = containingBlock();
1221 if (shrinkToAvoidFloats())
1222 return cb->availableLogicalWidthForLine(y(), false);
1223 return cb->availableLogicalWidth();
1226 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1228 RenderBlock* cb = containingBlock();
1229 RenderStyle* containingBlockStyle = cb->style();
1230 Length logicalHeightLength = containingBlockStyle->logicalHeight();
1232 // FIXME: For now just support fixed heights. Eventually should support percentage heights as well.
1233 if (!logicalHeightLength.isFixed()) {
1234 // Rather than making the child be completely unconstrained, WinIE uses the viewport width and height
1235 // as a constraint. We do that for now as well even though it's likely being unconstrained is what the spec
1237 return containingBlockStyle->isHorizontalWritingMode() ? view()->frameView()->visibleHeight() : view()->frameView()->visibleWidth();
1240 // Use the content box logical height as specified by the style.
1241 return cb->computeContentBoxLogicalHeight(logicalHeightLength.value());
1244 void RenderBox::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
1246 if (repaintContainer == this)
1249 if (RenderView* v = view()) {
1250 if (v->layoutStateEnabled() && !repaintContainer) {
1251 LayoutState* layoutState = v->layoutState();
1252 LayoutSize offset = layoutState->m_paintOffset;
1253 offset.expand(x(), y());
1254 if (style()->position() == RelativePosition && layer())
1255 offset += layer()->relativePositionOffset();
1256 transformState.move(offset);
1261 bool containerSkipped;
1262 RenderObject* o = container(repaintContainer, &containerSkipped);
1266 bool isFixedPos = style()->position() == FixedPosition;
1267 bool hasTransform = hasLayer() && layer()->transform();
1269 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1270 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1271 fixed &= isFixedPos;
1273 fixed |= isFixedPos;
1277 LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1279 bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1280 if (useTransforms && shouldUseTransformFromContainer(o)) {
1281 TransformationMatrix t;
1282 getTransformFromContainer(o, containerOffset, t);
1283 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1285 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1287 if (containerSkipped) {
1288 // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1289 // to just subtract the delta between the repaintContainer and o.
1290 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1291 transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1295 if (o->isRenderFlowThread()) {
1296 // Transform from render flow coordinates into region coordinates.
1297 RenderRegion* region = toRenderFlowThread(o)->mapFromFlowToRegion(transformState);
1299 region->mapLocalToContainer(region->containerForRepaint(), fixed, useTransforms, transformState, wasFixed);
1303 o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
1306 void RenderBox::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1308 // We don't expect absoluteToLocal() to be called during layout (yet)
1309 ASSERT(!view() || !view()->layoutStateEnabled());
1311 bool isFixedPos = style()->position() == FixedPosition;
1312 bool hasTransform = hasLayer() && layer()->transform();
1314 // If this box has a transform, it acts as a fixed position container for fixed descendants,
1315 // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1316 fixed &= isFixedPos;
1318 fixed |= isFixedPos;
1320 RenderObject* o = container();
1324 o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1326 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
1328 bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1329 if (useTransforms && shouldUseTransformFromContainer(o)) {
1330 TransformationMatrix t;
1331 getTransformFromContainer(o, containerOffset, t);
1332 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1334 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1337 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point) const
1339 ASSERT(o == container());
1342 if (isRelPositioned())
1343 offset += relativePositionOffset();
1345 if (!isInline() || isReplaced()) {
1346 if (style()->position() != AbsolutePosition && style()->position() != FixedPosition) {
1347 if (o->hasColumns()) {
1348 LayoutRect columnRect(frameRect());
1349 toRenderBlock(o)->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1350 offset += LayoutSize(columnRect.location().x(), columnRect.location().y());
1351 columnRect.moveBy(point);
1352 o->adjustForColumns(offset, columnRect.location());
1354 offset += locationOffsetIncludingFlipping();
1356 offset += locationOffsetIncludingFlipping();
1359 if (o->hasOverflowClip())
1360 offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1362 if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1363 offset += toRenderInline(o)->relativePositionedInlineOffset(this);
1368 InlineBox* RenderBox::createInlineBox()
1370 return new (renderArena()) InlineBox(this);
1373 void RenderBox::dirtyLineBoxes(bool fullLayout)
1375 if (m_inlineBoxWrapper) {
1377 m_inlineBoxWrapper->destroy(renderArena());
1378 m_inlineBoxWrapper = 0;
1380 m_inlineBoxWrapper->dirtyLineBoxes();
1384 void RenderBox::positionLineBox(InlineBox* box)
1386 if (isPositioned()) {
1387 // Cache the x position only if we were an INLINE type originally.
1388 bool wasInline = style()->isOriginalDisplayInlineType();
1390 // The value is cached in the xPos of the box. We only need this value if
1391 // our object was inline originally, since otherwise it would have ended up underneath
1393 layer()->setStaticInlinePosition(lroundf(box->logicalLeft()));
1394 if (style()->hasStaticInlinePosition(box->isHorizontal()))
1395 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1397 // Our object was a block originally, so we make our normal flow position be
1398 // just below the line box (as though all the inlines that came before us got
1399 // wrapped in an anonymous block, which is what would have happened had we been
1400 // in flow). This value was cached in the y() of the box.
1401 layer()->setStaticBlockPosition(box->logicalTop());
1402 if (style()->hasStaticBlockPosition(box->isHorizontal()))
1403 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1408 box->destroy(renderArena());
1409 } else if (isReplaced()) {
1410 setLocation(roundedLayoutPoint(FloatPoint(box->x(), box->y())));
1411 if (m_inlineBoxWrapper)
1412 deleteLineBoxWrapper();
1413 m_inlineBoxWrapper = box;
1417 void RenderBox::deleteLineBoxWrapper()
1419 if (m_inlineBoxWrapper) {
1420 if (!documentBeingDestroyed())
1421 m_inlineBoxWrapper->remove();
1422 m_inlineBoxWrapper->destroy(renderArena());
1423 m_inlineBoxWrapper = 0;
1427 LayoutRect RenderBox::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
1429 if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
1430 return LayoutRect();
1432 LayoutRect r = visualOverflowRect();
1434 RenderView* v = view();
1436 // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1437 // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1438 r.move(v->layoutDelta());
1442 if (style()->hasAppearance())
1443 // The theme may wish to inflate the rect used when repainting.
1444 theme()->adjustRepaintRect(this, r);
1446 // We have to use maximalOutlineSize() because a child might have an outline
1447 // that projects outside of our overflowRect.
1449 ASSERT(style()->outlineSize() <= v->maximalOutlineSize());
1450 r.inflate(v->maximalOutlineSize());
1454 computeRectForRepaint(repaintContainer, r);
1458 void RenderBox::computeRectForRepaint(RenderBoxModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1460 // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1461 // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1462 // offset corner for the enclosing container). This allows for a fully RL or BT document to repaint
1463 // properly even during layout, since the rect remains flipped all the way until the end.
1465 // RenderView::computeRectForRepaint then converts the rect to physical coordinates. We also convert to
1466 // physical when we hit a repaintContainer boundary. Therefore the final rect returned is always in the
1467 // physical coordinate space of the repaintContainer.
1468 if (RenderView* v = view()) {
1469 // LayoutState is only valid for root-relative, non-fixed position repainting
1470 if (v->layoutStateEnabled() && !repaintContainer && style()->position() != FixedPosition) {
1471 LayoutState* layoutState = v->layoutState();
1473 if (layer() && layer()->transform())
1474 rect = layer()->transform()->mapRect(rect);
1476 if (style()->position() == RelativePosition && layer())
1477 rect.move(layer()->relativePositionOffset());
1479 rect.moveBy(location());
1480 rect.move(layoutState->m_paintOffset);
1481 if (layoutState->m_clipped)
1482 rect.intersect(layoutState->m_clipRect);
1487 if (hasReflection())
1488 rect.unite(reflectedRect(rect));
1490 if (repaintContainer == this) {
1491 if (repaintContainer->style()->isFlippedBlocksWritingMode())
1492 flipForWritingMode(rect);
1496 bool containerSkipped;
1497 RenderObject* o = container(repaintContainer, &containerSkipped);
1501 if (isWritingModeRoot() && !isPositioned())
1502 flipForWritingMode(rect);
1503 LayoutPoint topLeft = rect.location();
1504 topLeft.move(x(), y());
1506 EPosition position = style()->position();
1508 // We are now in our parent container's coordinate space. Apply our transform to obtain a bounding box
1509 // in the parent's coordinate space that encloses us.
1510 if (layer() && layer()->transform()) {
1511 fixed = position == FixedPosition;
1512 rect = layer()->transform()->mapRect(rect);
1513 topLeft = rect.location();
1514 topLeft.move(x(), y());
1515 } else if (position == FixedPosition)
1518 if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1519 topLeft += toRenderInline(o)->relativePositionedInlineOffset(this);
1520 else if (position == RelativePosition && layer()) {
1521 // Apply the relative position offset when invalidating a rectangle. The layer
1522 // is translated, but the render box isn't, so we need to do this to get the
1523 // right dirty rect. Since this is called from RenderObject::setStyle, the relative position
1524 // flag on the RenderObject has been cleared, so use the one on the style().
1525 topLeft += layer()->relativePositionOffset();
1528 if (o->isBlockFlow() && position != AbsolutePosition && position != FixedPosition) {
1529 RenderBlock* cb = toRenderBlock(o);
1530 if (cb->hasColumns()) {
1531 LayoutRect repaintRect(topLeft, rect.size());
1532 cb->adjustRectForColumns(repaintRect);
1533 topLeft = repaintRect.location();
1538 // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1539 // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1540 if (o->hasOverflowClip()) {
1541 RenderBox* containerBox = toRenderBox(o);
1543 // o->height() is inaccurate if we're in the middle of a layout of |o|, so use the
1544 // layer's size instead. Even if the layer's size is wrong, the layer itself will repaint
1545 // anyway if its size does change.
1546 topLeft -= containerBox->layer()->scrolledContentOffset(); // For overflow:auto/scroll/hidden.
1548 LayoutRect repaintRect(topLeft, rect.size());
1549 LayoutRect boxRect(LayoutPoint(), containerBox->layer()->size());
1550 rect = intersection(repaintRect, boxRect);
1554 rect.setLocation(topLeft);
1556 if (containerSkipped) {
1557 // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
1558 LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1559 rect.move(-containerOffset);
1563 o->computeRectForRepaint(repaintContainer, rect, fixed);
1566 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& rect)
1568 LayoutUnit newX = x();
1569 LayoutUnit newY = y();
1570 LayoutUnit newWidth = width();
1571 LayoutUnit newHeight = height();
1572 if (rect.x() != newX || rect.y() != newY) {
1573 // The child moved. Invalidate the object's old and new positions. We have to do this
1574 // since the object may not have gotten a layout.
1577 repaintOverhangingFloats(true);
1578 m_frameRect = LayoutRect(newX, newY, newWidth, newHeight);
1580 repaintOverhangingFloats(true);
1584 void RenderBox::computeLogicalWidth()
1586 if (isPositioned()) {
1587 // FIXME: This calculation is not patched for block-flow yet.
1588 // https://bugs.webkit.org/show_bug.cgi?id=46500
1589 computePositionedLogicalWidth();
1593 // If layout is limited to a subtree, the subtree root's logical width does not change.
1594 if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1597 // The parent box is flexing us, so it has increased or decreased our
1598 // width. Use the width from the style context.
1599 // FIXME: Account for block-flow in flexible boxes.
1600 // https://bugs.webkit.org/show_bug.cgi?id=46418
1601 if (hasOverrideWidth() && parent()->isFlexibleBoxIncludingDeprecated()) {
1602 setLogicalWidth(overrideWidth());
1606 // FIXME: Account for block-flow in flexible boxes.
1607 // https://bugs.webkit.org/show_bug.cgi?id=46418
1608 bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1609 bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1610 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1612 Length logicalWidthLength = (treatAsReplaced) ? Length(computeReplacedLogicalWidth(), Fixed) : style()->logicalWidth();
1614 RenderBlock* cb = containingBlock();
1615 LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContent());
1616 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1617 LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
1618 if (hasPerpendicularContainingBlock)
1619 containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1621 if (isInline() && !isInlineBlockOrInlineTable()) {
1622 // just calculate margins
1623 setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1624 setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1625 if (treatAsReplaced)
1626 setLogicalWidth(max<LayoutUnit>(logicalWidthLength.calcFloatValue(0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth()));
1630 // Width calculations
1631 if (treatAsReplaced)
1632 setLogicalWidth(logicalWidthLength.value() + borderAndPaddingLogicalWidth());
1634 // Calculate LogicalWidth
1635 setLogicalWidth(computeLogicalWidthUsing(LogicalWidth, containerWidthInInlineDirection));
1637 // Calculate MaxLogicalWidth
1638 if (!style()->logicalMaxWidth().isUndefined()) {
1639 LayoutUnit maxLogicalWidth = computeLogicalWidthUsing(MaxLogicalWidth, containerWidthInInlineDirection);
1640 if (logicalWidth() > maxLogicalWidth) {
1641 setLogicalWidth(maxLogicalWidth);
1642 logicalWidthLength = style()->logicalMaxWidth();
1646 // Calculate MinLogicalWidth
1647 LayoutUnit minLogicalWidth = computeLogicalWidthUsing(MinLogicalWidth, containerWidthInInlineDirection);
1648 if (logicalWidth() < minLogicalWidth) {
1649 setLogicalWidth(minLogicalWidth);
1650 logicalWidthLength = style()->logicalMinWidth();
1654 // Fieldsets are currently the only objects that stretch to their minimum width.
1655 if (stretchesToMinIntrinsicLogicalWidth()) {
1656 setLogicalWidth(max(logicalWidth(), minPreferredLogicalWidth()));
1657 logicalWidthLength = Length(logicalWidth(), Fixed);
1660 // Margin calculations.
1661 if (logicalWidthLength.isAuto() || hasPerpendicularContainingBlock) {
1662 setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1663 setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1665 computeInlineDirectionMargins(cb, containerLogicalWidth, logicalWidth());
1667 if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (logicalWidth() + marginStart() + marginEnd())
1668 && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated())
1669 cb->setMarginEndForChild(this, containerLogicalWidth - logicalWidth() - cb->marginStartForChild(this));
1672 LayoutUnit RenderBox::computeLogicalWidthUsing(LogicalWidthType widthType, LayoutUnit availableLogicalWidth)
1674 LayoutUnit logicalWidthResult = logicalWidth();
1675 Length logicalWidth;
1676 if (widthType == LogicalWidth)
1677 logicalWidth = style()->logicalWidth();
1678 else if (widthType == MinLogicalWidth)
1679 logicalWidth = style()->logicalMinWidth();
1681 logicalWidth = style()->logicalMaxWidth();
1683 if (logicalWidth.isIntrinsicOrAuto()) {
1684 LayoutUnit marginStart = style()->marginStart().calcMinValue(availableLogicalWidth);
1685 LayoutUnit marginEnd = style()->marginEnd().calcMinValue(availableLogicalWidth);
1686 if (availableLogicalWidth)
1687 logicalWidthResult = availableLogicalWidth - marginStart - marginEnd;
1689 if (sizesToIntrinsicLogicalWidth(widthType)) {
1690 logicalWidthResult = max(logicalWidthResult, minPreferredLogicalWidth());
1691 logicalWidthResult = min(logicalWidthResult, maxPreferredLogicalWidth());
1693 } else // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
1694 logicalWidthResult = computeBorderBoxLogicalWidth(logicalWidth.calcValue(availableLogicalWidth));
1696 return logicalWidthResult;
1699 bool RenderBox::sizesToIntrinsicLogicalWidth(LogicalWidthType widthType) const
1701 // Marquees in WinIE are like a mixture of blocks and inline-blocks. They size as though they're blocks,
1702 // but they allow text to sit on the same line as the marquee.
1703 if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
1706 // This code may look a bit strange. Basically width:intrinsic should clamp the size when testing both
1707 // min-width and width. max-width is only clamped if it is also intrinsic.
1708 Length logicalWidth = (widthType == MaxLogicalWidth) ? style()->logicalMaxWidth() : style()->logicalWidth();
1709 if (logicalWidth.type() == Intrinsic)
1712 // Children of a horizontal marquee do not fill the container by default.
1713 // FIXME: Need to deal with MAUTO value properly. It could be vertical.
1714 // FIXME: Think about block-flow here. Need to find out how marquee direction relates to
1715 // block-flow (as well as how marquee overflow should relate to block flow).
1716 // https://bugs.webkit.org/show_bug.cgi?id=46472
1717 if (parent()->style()->overflowX() == OMARQUEE) {
1718 EMarqueeDirection dir = parent()->style()->marqueeDirection();
1719 if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
1723 // Flexible horizontal boxes lay out children at their intrinsic widths. Also vertical boxes
1724 // that don't stretch their kids lay out their children at their intrinsic widths.
1725 // FIXME: Think about block-flow here.
1726 // https://bugs.webkit.org/show_bug.cgi?id=46473
1727 if (parent()->isDeprecatedFlexibleBox()
1728 && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
1731 // Button, input, select, textarea, and legend treat
1732 // width value of 'auto' as 'intrinsic' unless it's in a
1733 // stretching vertical flexbox.
1734 // FIXME: Think about block-flow here.
1735 // https://bugs.webkit.org/show_bug.cgi?id=46473
1736 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)))
1742 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, int containerWidth, int childWidth)
1744 const RenderStyle* containingBlockStyle = containingBlock->style();
1745 Length marginStartLength = style()->marginStartUsing(containingBlockStyle);
1746 Length marginEndLength = style()->marginEndUsing(containingBlockStyle);
1748 if (isFloating() || isInline()) {
1749 // Inline blocks/tables and floats don't have their margins increased.
1750 containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1751 containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1755 // Case One: The object is being centered in the containing block's available logical width.
1756 if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
1757 || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
1758 containingBlock->setMarginStartForChild(this, max<LayoutUnit>(0, (containerWidth - childWidth) / 2));
1759 containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1763 // Case Two: The object is being pushed to the start of the containing block's available logical width.
1764 if (marginEndLength.isAuto() && childWidth < containerWidth) {
1765 containingBlock->setMarginStartForChild(this, marginStartLength.calcValue(containerWidth));
1766 containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1770 // Case Three: The object is being pushed to the end of the containing block's available logical width.
1771 bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
1772 || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
1773 if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
1774 containingBlock->setMarginEndForChild(this, marginEndLength.calcValue(containerWidth));
1775 containingBlock->setMarginStartForChild(this, containerWidth - childWidth - containingBlock->marginEndForChild(this));
1779 // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3). In that case
1780 // auto margins will just turn into 0.
1781 containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1782 containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1785 void RenderBox::computeLogicalHeight()
1787 // Cell height is managed by the table and inline non-replaced elements do not support a height property.
1788 if (isTableCell() || (isInline() && !isReplaced()))
1792 if (isPositioned()) {
1793 // FIXME: This calculation is not patched for block-flow yet.
1794 // https://bugs.webkit.org/show_bug.cgi?id=46500
1795 computePositionedLogicalHeight();
1797 RenderBlock* cb = containingBlock();
1798 bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1800 if (!hasPerpendicularContainingBlock)
1801 computeBlockDirectionMargins(cb);
1803 // For tables, calculate margins only.
1805 if (hasPerpendicularContainingBlock)
1806 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), logicalHeight());
1810 // FIXME: Account for block-flow in flexible boxes.
1811 // https://bugs.webkit.org/show_bug.cgi?id=46418
1812 bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
1813 bool stretching = parent()->style()->boxAlign() == BSTRETCH;
1814 bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
1815 bool checkMinMaxHeight = false;
1817 // The parent box is flexing us, so it has increased or decreased our height. We have to
1818 // grab our cached flexible height.
1819 // FIXME: Account for block-flow in flexible boxes.
1820 // https://bugs.webkit.org/show_bug.cgi?id=46418
1821 if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
1822 h = Length(overrideHeight() - borderAndPaddingLogicalHeight(), Fixed);
1823 else if (treatAsReplaced)
1824 h = Length(computeReplacedLogicalHeight(), Fixed);
1826 h = style()->logicalHeight();
1827 checkMinMaxHeight = true;
1830 // Block children of horizontal flexible boxes fill the height of the box.
1831 // FIXME: Account for block-flow in flexible boxes.
1832 // https://bugs.webkit.org/show_bug.cgi?id=46418
1833 if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
1834 && parent()->isStretchingChildren()) {
1835 h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
1836 checkMinMaxHeight = false;
1839 LayoutUnit heightResult;
1840 if (checkMinMaxHeight) {
1841 heightResult = computeLogicalHeightUsing(style()->logicalHeight());
1842 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
1843 if (heightResult == -1)
1844 heightResult = logicalHeight();
1845 LayoutUnit minH = computeLogicalHeightUsing(style()->logicalMinHeight()); // Leave as -1 if unset.
1846 LayoutUnit maxH = style()->logicalMaxHeight().isUndefined() ? heightResult : computeLogicalHeightUsing(style()->logicalMaxHeight());
1848 maxH = heightResult;
1849 heightResult = min(maxH, heightResult);
1850 heightResult = max(minH, heightResult);
1852 // The only times we don't check min/max height are when a fixed length has
1853 // been given as an override. Just use that. The value has already been adjusted
1855 heightResult = h.value() + borderAndPaddingLogicalHeight();
1858 setLogicalHeight(heightResult);
1860 if (hasPerpendicularContainingBlock)
1861 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult);
1864 // WinIE quirk: The <html> block always fills the entire canvas in quirks mode. The <body> always fills the
1865 // <html> block in quirks mode. Only apply this quirk if the block is normal flow and no height
1866 // is specified. When we're printing, we also need this quirk if the body or root has a percentage
1867 // height since we don't set a height in RenderView when we're printing. So without this quirk, the
1868 // height has nothing to be a percentage of, and it ends up being 0. That is bad.
1869 bool paginatedContentNeedsBaseHeight = document()->printing() && h.isPercent()
1870 && (isRoot() || (isBody() && document()->documentElement()->renderer()->style()->logicalHeight().isPercent()));
1871 if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
1872 // FIXME: Finish accounting for block flow here.
1873 // https://bugs.webkit.org/show_bug.cgi?id=46603
1874 LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
1875 LayoutUnit visHeight;
1876 if (document()->printing())
1877 visHeight = static_cast<LayoutUnit>(view()->pageLogicalHeight());
1879 if (isHorizontalWritingMode())
1880 visHeight = view()->viewHeight();
1882 visHeight = view()->viewWidth();
1885 setLogicalHeight(max(logicalHeight(), visHeight - margins));
1887 LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
1888 setLogicalHeight(max(logicalHeight(), visHeight - marginsBordersPadding));
1893 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& h)
1895 LayoutUnit logicalHeight = -1;
1898 logicalHeight = h.value();
1899 else if (h.isPercent())
1900 logicalHeight = computePercentageLogicalHeight(h);
1901 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
1902 if (logicalHeight != -1) {
1903 logicalHeight = computeBorderBoxLogicalHeight(logicalHeight);
1904 return logicalHeight;
1907 return logicalHeight;
1910 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height)
1912 LayoutUnit result = -1;
1914 // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
1915 // block that may have a specified height and then use it. In strict mode, this violates the
1916 // specification, which states that percentage heights just revert to auto if the containing
1917 // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
1918 // only at explicit containers.
1919 bool skippedAutoHeightContainingBlock = false;
1920 RenderBlock* cb = containingBlock();
1921 while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isPositioned() && cb->style()->logicalHeight().isAuto()) {
1922 if (!document()->inQuirksMode() && !cb->isAnonymousBlock())
1924 skippedAutoHeightContainingBlock = true;
1925 cb = cb->containingBlock();
1926 cb->addPercentHeightDescendant(this);
1929 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
1930 // explicitly specified that can be used for any percentage computations.
1931 // FIXME: We can't just check top/bottom here.
1932 // https://bugs.webkit.org/show_bug.cgi?id=46500
1933 bool isPositionedWithSpecifiedHeight = cb->isPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
1935 bool includeBorderPadding = isTable();
1937 // Table cells violate what the CSS spec says to do with heights. Basically we
1938 // don't care if the cell specified a height or not. We just always make ourselves
1939 // be a percentage of the cell's current content height.
1940 if (cb->isTableCell()) {
1941 if (!skippedAutoHeightContainingBlock) {
1942 if (!cb->hasOverrideHeight()) {
1943 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
1944 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
1945 // While we can't get all cases right, we can at least detect when the cell has a specified
1946 // height or when the table has a specified height. In these cases we want to initially have
1947 // no size and allow the flexing of the table or the cell to its specified height to cause us
1948 // to grow to fill the space. This could end up being wrong in some cases, but it is
1949 // preferable to the alternative (sizing intrinsically and making the row end up too big).
1950 RenderTableCell* cell = toRenderTableCell(cb);
1951 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
1955 result = cb->overrideHeight();
1956 includeBorderPadding = true;
1959 // Otherwise we only use our percentage height if our containing block had a specified
1961 else if (cb->style()->logicalHeight().isFixed())
1962 result = cb->computeContentBoxLogicalHeight(cb->style()->logicalHeight().value());
1963 else if (cb->style()->logicalHeight().isPercent() && !isPositionedWithSpecifiedHeight) {
1964 // We need to recur and compute the percentage height for our containing block.
1965 result = cb->computePercentageLogicalHeight(cb->style()->logicalHeight());
1966 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
1968 result = cb->computeContentBoxLogicalHeight(result);
1969 } else if (cb->isRenderView() || (cb->isBody() && document()->inQuirksMode()) || isPositionedWithSpecifiedHeight) {
1970 // Don't allow this to affect the block' height() member variable, since this
1971 // can get called while the block is still laying out its kids.
1972 LayoutUnit oldHeight = cb->logicalHeight();
1973 cb->computeLogicalHeight();
1974 result = cb->contentLogicalHeight();
1975 cb->setLogicalHeight(oldHeight);
1976 } else if (cb->isRoot() && isPositioned())
1977 // Match the positioned objects behavior, which is that positioned objects will fill their viewport
1978 // always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
1979 result = cb->computeContentBoxLogicalHeight(cb->availableLogicalHeight());
1981 // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
1983 result = height.calcValue(result);
1984 if (includeBorderPadding) {
1985 // It is necessary to use the border-box to match WinIE's broken
1986 // box model. This is essential for sizing inside
1987 // table cells using percentage heights.
1988 result -= borderAndPaddingLogicalHeight();
1989 result = max<LayoutUnit>(0, result);
1995 LayoutUnit RenderBox::computeReplacedLogicalWidth(bool includeMaxWidth) const
1997 return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), includeMaxWidth);
2000 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, bool includeMaxWidth) const
2002 LayoutUnit minLogicalWidth = computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2003 LayoutUnit maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2004 return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
2007 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2009 switch (logicalWidth.type()) {
2011 return computeContentBoxLogicalWidth(logicalWidth.value());
2013 // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2014 // containing block's block-flow.
2015 // https://bugs.webkit.org/show_bug.cgi?id=46496
2016 const LayoutUnit cw = isPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2018 return computeContentBoxLogicalWidth(logicalWidth.calcMinValue(cw));
2022 return intrinsicLogicalWidth();
2026 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2028 return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2031 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2033 LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2034 LayoutUnit maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2035 return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
2038 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2040 switch (logicalHeight.type()) {
2042 return computeContentBoxLogicalHeight(logicalHeight.value());
2045 RenderObject* cb = isPositioned() ? container() : containingBlock();
2046 while (cb->isAnonymous()) {
2047 cb = cb->containingBlock();
2048 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2051 // FIXME: This calculation is not patched for block-flow yet.
2052 // https://bugs.webkit.org/show_bug.cgi?id=46500
2053 if (cb->isPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2054 ASSERT(cb->isRenderBlock());
2055 RenderBlock* block = toRenderBlock(cb);
2056 LayoutUnit oldHeight = block->height();
2057 block->computeLogicalHeight();
2058 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentHeight());
2059 block->setHeight(oldHeight);
2060 return computeContentBoxLogicalHeight(logicalHeight.calcValue(newHeight));
2063 // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2064 // containing block's block-flow.
2065 // https://bugs.webkit.org/show_bug.cgi?id=46496
2066 LayoutUnit availableHeight;
2068 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2070 availableHeight = toRenderBox(cb)->availableLogicalHeight();
2071 // It is necessary to use the border-box to match WinIE's broken
2072 // box model. This is essential for sizing inside
2073 // table cells using percentage heights.
2074 // FIXME: This needs to be made block-flow-aware. If the cell and image are perpendicular block-flows, this isn't right.
2075 // https://bugs.webkit.org/show_bug.cgi?id=46997
2076 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2077 if (cb->isTableCell()) {
2078 // Don't let table cells squeeze percent-height replaced elements
2079 // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2080 availableHeight = max(availableHeight, intrinsicLogicalHeight());
2081 return logicalHeight.calcValue(availableHeight - borderAndPaddingLogicalHeight());
2083 cb = cb->containingBlock();
2086 return computeContentBoxLogicalHeight(logicalHeight.calcValue(availableHeight));
2089 return intrinsicLogicalHeight();
2093 LayoutUnit RenderBox::availableLogicalHeight() const
2095 return availableLogicalHeightUsing(style()->logicalHeight());
2098 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const
2101 return computeContentBoxLogicalHeight(h.value());
2104 return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
2106 // We need to stop here, since we don't want to increase the height of the table
2107 // artificially. We're going to rely on this cell getting expanded to some new
2108 // height, and then when we lay out again we'll use the calculation below.
2109 if (isTableCell() && (h.isAuto() || h.isPercent()))
2110 return overrideHeight() - borderAndPaddingLogicalWidth();
2112 if (h.isPercent()) {
2113 LayoutUnit availableHeight;
2114 // https://bugs.webkit.org/show_bug.cgi?id=64046
2115 // For absolutely positioned elements whose containing block is based on a block-level element,
2116 // the percentage is calculated with respect to the height of the padding box of that element
2118 availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2120 availableHeight = containingBlock()->availableLogicalHeight();
2121 return computeContentBoxLogicalHeight(h.calcValue(availableHeight));
2124 // FIXME: We can't just check top/bottom here.
2125 // https://bugs.webkit.org/show_bug.cgi?id=46500
2126 if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2127 RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2128 LayoutUnit oldHeight = block->logicalHeight();
2129 block->computeLogicalHeight();
2130 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
2131 block->setLogicalHeight(oldHeight);
2132 return computeContentBoxLogicalHeight(newHeight);
2135 return containingBlock()->availableLogicalHeight();
2138 void RenderBox::computeBlockDirectionMargins(RenderBlock* containingBlock)
2140 if (isTableCell()) {
2141 // FIXME: Not right if we allow cells to have different directionality than the table. If we do allow this, though,
2142 // we may just do it with an extra anonymous block inside the cell.
2148 // Margins are calculated with respect to the logical width of
2149 // the containing block (8.3)
2150 LayoutUnit cw = containingBlockLogicalWidthForContent();
2152 RenderStyle* containingBlockStyle = containingBlock->style();
2153 containingBlock->setMarginBeforeForChild(this, style()->marginBeforeUsing(containingBlockStyle).calcMinValue(cw));
2154 containingBlock->setMarginAfterForChild(this, style()->marginAfterUsing(containingBlockStyle).calcMinValue(cw));
2157 int RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2159 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2160 return containingBlockLogicalHeightForPositioned(containingBlock, false);
2162 if (containingBlock->isBox())
2163 return toRenderBox(containingBlock)->clientLogicalWidth();
2165 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2167 const RenderInline* flow = toRenderInline(containingBlock);
2168 InlineFlowBox* first = flow->firstLineBox();
2169 InlineFlowBox* last = flow->lastLineBox();
2171 // If the containing block is empty, return a width of 0.
2172 if (!first || !last)
2175 LayoutUnit fromLeft;
2176 LayoutUnit fromRight;
2177 if (containingBlock->style()->isLeftToRightDirection()) {
2178 fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2179 fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2181 fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2182 fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2185 return max<LayoutUnit>(0, fromRight - fromLeft);
2188 int RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2190 if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2191 return containingBlockLogicalWidthForPositioned(containingBlock, false);
2193 if (containingBlock->isBox())
2194 return toRenderBox(containingBlock)->clientLogicalHeight();
2196 ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2198 const RenderInline* flow = toRenderInline(containingBlock);
2199 InlineFlowBox* first = flow->firstLineBox();
2200 InlineFlowBox* last = flow->lastLineBox();
2202 // If the containing block is empty, return a height of 0.
2203 if (!first || !last)
2206 LayoutUnit heightResult;
2207 LayoutRect boundingBox = flow->linesBoundingBox();
2208 if (containingBlock->isHorizontalWritingMode())
2209 heightResult = boundingBox.height();
2211 heightResult = boundingBox.width();
2212 heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2213 return heightResult;
2216 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, int containerLogicalWidth,
2217 TextDirection containerDirection)
2219 if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2222 // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2223 if (containerDirection == LTR) {
2224 LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2225 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2227 staticPosition += toRenderBox(curr)->logicalLeft();
2229 logicalLeft.setValue(Fixed, staticPosition);
2231 RenderBox* enclosingBox = child->parent()->enclosingBox();
2232 LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalRight();
2233 staticPosition -= enclosingBox->logicalWidth();
2234 for (RenderObject* curr = enclosingBox; curr && curr != containerBlock; curr = curr->container()) {
2236 staticPosition -= toRenderBox(curr)->logicalLeft();
2238 logicalRight.setValue(Fixed, staticPosition);
2242 void RenderBox::computePositionedLogicalWidth()
2245 computePositionedLogicalWidthReplaced();
2250 // FIXME 1: Which RenderObject's 'direction' property should used: the
2251 // containing block (cb) as the spec seems to imply, the parent (parent()) as
2252 // was previously done in calculating the static distances, or ourself, which
2253 // was also previously done for deciding what to override when you had
2254 // over-constrained margins? Also note that the container block is used
2255 // in similar situations in other parts of the RenderBox class (see computeLogicalWidth()
2256 // and computeMarginsInContainingBlockInlineDirection()). For now we are using the parent for quirks
2257 // mode and the containing block for strict mode.
2259 // FIXME 2: Should we still deal with these the cases of 'left' or 'right' having
2260 // the type 'static' in determining whether to calculate the static distance?
2261 // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2263 // FIXME 3: Can perhaps optimize out cases when max-width/min-width are greater
2264 // than or less than the computed width(). Be careful of box-sizing and
2265 // percentage issues.
2267 // The following is based off of the W3C Working Draft from April 11, 2006 of
2268 // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2269 // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2270 // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2271 // correspond to text from the spec)
2274 // We don't use containingBlock(), since we may be positioned by an enclosing
2275 // relative positioned inline.
2276 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2278 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
2280 // To match WinIE, in quirks mode use the parent's 'direction' property
2281 // instead of the the container block's.
2282 TextDirection containerDirection = (document()->inQuirksMode()) ? parent()->style()->direction() : containerBlock->style()->direction();
2284 bool isHorizontal = isHorizontalWritingMode();
2285 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2286 const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2287 const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2288 LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
2289 LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
2291 Length logicalLeft = style()->logicalLeft();
2292 Length logicalRight = style()->logicalRight();
2294 /*---------------------------------------------------------------------------*\
2295 * For the purposes of this section and the next, the term "static position"
2296 * (of an element) refers, roughly, to the position an element would have had
2297 * in the normal flow. More precisely:
2299 * * The static position for 'left' is the distance from the left edge of the
2300 * containing block to the left margin edge of a hypothetical box that would
2301 * have been the first box of the element if its 'position' property had
2302 * been 'static' and 'float' had been 'none'. The value is negative if the
2303 * hypothetical box is to the left of the containing block.
2304 * * The static position for 'right' is the distance from the right edge of the
2305 * containing block to the right margin edge of the same hypothetical box as
2306 * above. The value is positive if the hypothetical box is to the left of the
2307 * containing block's edge.
2309 * But rather than actually calculating the dimensions of that hypothetical box,
2310 * user agents are free to make a guess at its probable position.
2312 * For the purposes of calculating the static position, the containing block of
2313 * fixed positioned elements is the initial containing block instead of the
2314 * viewport, and all scrollable boxes should be assumed to be scrolled to their
2316 \*---------------------------------------------------------------------------*/
2319 // Calculate the static distance if needed.
2320 computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, containerDirection);
2322 // Calculate constraint equation values for 'width' case.
2323 LayoutUnit logicalWidthResult;
2324 LayoutUnit logicalLeftResult;
2325 computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2326 containerLogicalWidth, bordersPlusPadding,
2327 logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2328 logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2329 setLogicalWidth(logicalWidthResult);
2330 setLogicalLeft(logicalLeftResult);
2332 // Calculate constraint equation values for 'max-width' case.
2333 if (!style()->logicalMaxWidth().isUndefined()) {
2334 LayoutUnit maxLogicalWidth;
2335 LayoutUnit maxMarginLogicalLeft;
2336 LayoutUnit maxMarginLogicalRight;
2337 LayoutUnit maxLogicalLeftPos;
2339 computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2340 containerLogicalWidth, bordersPlusPadding,
2341 logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2342 maxLogicalWidth, maxMarginLogicalLeft, maxMarginLogicalRight, maxLogicalLeftPos);
2344 if (logicalWidth() > maxLogicalWidth) {
2345 setLogicalWidth(maxLogicalWidth);
2346 marginLogicalLeftAlias = maxMarginLogicalLeft;
2347 marginLogicalRightAlias = maxMarginLogicalRight;
2348 setLogicalLeft(maxLogicalLeftPos);
2352 // Calculate constraint equation values for 'min-width' case.
2353 if (!style()->logicalMinWidth().isZero()) {
2354 LayoutUnit minLogicalWidth;
2355 LayoutUnit minMarginLogicalLeft;
2356 LayoutUnit minMarginLogicalRight;
2357 LayoutUnit minLogicalLeftPos;
2359 computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2360 containerLogicalWidth, bordersPlusPadding,
2361 logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2362 minLogicalWidth, minMarginLogicalLeft, minMarginLogicalRight, minLogicalLeftPos);
2364 if (logicalWidth() < minLogicalWidth) {
2365 setLogicalWidth(minLogicalWidth);
2366 marginLogicalLeftAlias = minMarginLogicalLeft;
2367 marginLogicalRightAlias = minMarginLogicalRight;
2368 setLogicalLeft(minLogicalLeftPos);
2372 if (stretchesToMinIntrinsicLogicalWidth() && logicalWidth() < minPreferredLogicalWidth() - bordersPlusPadding) {
2373 computePositionedLogicalWidthUsing(Length(minPreferredLogicalWidth() - bordersPlusPadding, Fixed), containerBlock, containerDirection,
2374 containerLogicalWidth, bordersPlusPadding,
2375 logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2376 logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2377 setLogicalWidth(logicalWidthResult);
2378 setLogicalLeft(logicalLeftResult);
2381 // Put logicalWidth() into correct form.
2382 setLogicalWidth(logicalWidth() + bordersPlusPadding);
2385 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2387 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2388 // 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.
2389 if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2390 logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2391 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2393 logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2396 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2397 LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2398 Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
2399 LayoutUnit& logicalWidthValue, LayoutUnit& marginLogicalLeftValue, LayoutUnit& marginLogicalRightValue, LayoutUnit& logicalLeftPos)
2401 // 'left' and 'right' cannot both be 'auto' because one would of been
2402 // converted to the static position already
2403 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2405 LayoutUnit logicalLeftValue = 0;
2407 bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2408 bool logicalLeftIsAuto = logicalLeft.isAuto();
2409 bool logicalRightIsAuto = logicalRight.isAuto();
2411 if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2412 /*-----------------------------------------------------------------------*\
2413 * If none of the three is 'auto': If both 'margin-left' and 'margin-
2414 * right' are 'auto', solve the equation under the extra constraint that
2415 * the two margins get equal values, unless this would make them negative,
2416 * in which case when direction of the containing block is 'ltr' ('rtl'),
2417 * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2418 * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2419 * solve the equation for that value. If the values are over-constrained,
2420 * ignore the value for 'left' (in case the 'direction' property of the
2421 * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2422 * and solve for that value.
2423 \*-----------------------------------------------------------------------*/
2424 // NOTE: It is not necessary to solve for 'right' in the over constrained
2425 // case because the value is not used for any further calculations.
2427 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2428 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2430 const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + logicalWidthValue + logicalRight.calcValue(containerLogicalWidth) + bordersPlusPadding);
2432 // Margins are now the only unknown
2433 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2434 // Both margins auto, solve for equality
2435 if (availableSpace >= 0) {
2436 marginLogicalLeftValue = availableSpace / 2; // split the difference
2437 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2440 if (containerDirection == LTR) {
2441 marginLogicalLeftValue = 0;
2442 marginLogicalRightValue = availableSpace; // will be negative
2444 marginLogicalLeftValue = availableSpace; // will be negative
2445 marginLogicalRightValue = 0;
2448 } else if (marginLogicalLeft.isAuto()) {
2449 // Solve for left margin
2450 marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2451 marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
2452 } else if (marginLogicalRight.isAuto()) {
2453 // Solve for right margin
2454 marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2455 marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
2457 // Over-constrained, solve for left if direction is RTL
2458 marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2459 marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2461 // see FIXME 1 -- used to be "this->style()->direction()"
2462 if (containerDirection == RTL)
2463 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
2466 /*--------------------------------------------------------------------*\
2467 * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
2468 * to 0, and pick the one of the following six rules that applies.
2470 * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
2471 * width is shrink-to-fit. Then solve for 'left'
2473 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2474 * ------------------------------------------------------------------
2475 * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
2476 * the 'direction' property of the containing block is 'ltr' set
2477 * 'left' to the static position, otherwise set 'right' to the
2478 * static position. Then solve for 'left' (if 'direction is 'rtl')
2479 * or 'right' (if 'direction' is 'ltr').
2480 * ------------------------------------------------------------------
2482 * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
2483 * width is shrink-to-fit . Then solve for 'right'
2484 * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
2486 * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
2488 * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
2491 * Calculation of the shrink-to-fit width is similar to calculating the
2492 * width of a table cell using the automatic table layout algorithm.
2493 * Roughly: calculate the preferred width by formatting the content
2494 * without breaking lines other than where explicit line breaks occur,
2495 * and also calculate the preferred minimum width, e.g., by trying all
2496 * possible line breaks. CSS 2.1 does not define the exact algorithm.
2497 * Thirdly, calculate the available width: this is found by solving
2498 * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
2501 * Then the shrink-to-fit width is:
2502 * min(max(preferred minimum width, available width), preferred width).
2503 \*--------------------------------------------------------------------*/
2504 // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
2505 // because the value is not used for any further calculations.
2507 // Calculate margins, 'auto' margins are ignored.
2508 marginLogicalLeftValue = marginLogicalLeft.calcMinValue(containerLogicalWidth);
2509 marginLogicalRightValue = marginLogicalRight.calcMinValue(containerLogicalWidth);
2511 const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
2513 // FIXME: Is there a faster way to find the correct case?
2514 // Use rule/case that applies.
2515 if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2516 // RULE 1: (use shrink-to-fit for width, and solve of left)
2517 LayoutUnit logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2519 // FIXME: would it be better to have shrink-to-fit in one step?
2520 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2521 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2522 LayoutUnit availableWidth = availableSpace - logicalRightValue;
2523 logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2524 logicalLeftValue = availableSpace - (logicalWidthValue + logicalRightValue);
2525 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
2526 // RULE 3: (use shrink-to-fit for width, and no need solve of right)
2527 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2529 // FIXME: would it be better to have shrink-to-fit in one step?
2530 LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2531 LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2532 LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2533 logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2534 } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2535 // RULE 4: (solve for left)
2536 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2537 logicalLeftValue = availableSpace - (logicalWidthValue + logicalRight.calcValue(containerLogicalWidth));
2538 } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2539 // RULE 5: (solve for width)
2540 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2541 logicalWidthValue = availableSpace - (logicalLeftValue + logicalRight.calcValue(containerLogicalWidth));
2542 } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
2543 // RULE 6: (no need solve for right)
2544 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2545 logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2549 // Use computed values to calculate the horizontal position.
2551 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
2552 // positioned, inline because right now, it is using the logical left position
2553 // of the first line box when really it should use the last line box. When
2554 // this is fixed elsewhere, this block should be removed.
2555 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2556 const RenderInline* flow = toRenderInline(containerBlock);
2557 InlineFlowBox* firstLine = flow->firstLineBox();
2558 InlineFlowBox* lastLine = flow->lastLineBox();
2559 if (firstLine && lastLine && firstLine != lastLine) {
2560 logicalLeftPos = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
2565 logicalLeftPos = logicalLeftValue + marginLogicalLeftValue;
2566 computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidthValue, containerBlock, containerLogicalWidth);
2569 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
2571 if (!logicalTop.isAuto() || !logicalBottom.isAuto())
2574 // FIXME: The static distance computation has not been patched for mixed writing modes.
2575 LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
2576 for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2577 if (curr->isBox() && !curr->isTableRow())
2578 staticLogicalTop += toRenderBox(curr)->logicalTop();
2580 logicalTop.setValue(Fixed, staticLogicalTop);
2583 void RenderBox::computePositionedLogicalHeight()
2586 computePositionedLogicalHeightReplaced();
2590 // The following is based off of the W3C Working Draft from April 11, 2006 of
2591 // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
2592 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
2593 // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
2594 // correspond to text from the spec)
2597 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
2598 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2600 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
2602 bool isHorizontal = isHorizontalWritingMode();
2603 bool isFlipped = style()->isFlippedBlocksWritingMode();
2604 const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
2605 const Length marginBefore = style()->marginBefore();
2606 const Length marginAfter = style()->marginAfter();
2607 LayoutUnit& marginBeforeAlias = isHorizontal ? (isFlipped ? m_marginBottom : m_marginTop) : (isFlipped ? m_marginRight: m_marginLeft);
2608 LayoutUnit& marginAfterAlias = isHorizontal ? (isFlipped ? m_marginTop : m_marginBottom) : (isFlipped ? m_marginLeft: m_marginRight);
2610 Length logicalTop = style()->logicalTop();
2611 Length logicalBottom = style()->logicalBottom();
2613 /*---------------------------------------------------------------------------*\
2614 * For the purposes of this section and the next, the term "static position"
2615 * (of an element) refers, roughly, to the position an element would have had
2616 * in the normal flow. More precisely, the static position for 'top' is the
2617 * distance from the top edge of the containing block to the top margin edge
2618 * of a hypothetical box that would have been the first box of the element if
2619 * its 'position' property had been 'static' and 'float' had been 'none'. The
2620 * value is negative if the hypothetical box is above the containing block.
2622 * But rather than actually calculating the dimensions of that hypothetical
2623 * box, user agents are free to make a guess at its probable position.
2625 * For the purposes of calculating the static position, the containing block
2626 * of fixed positioned elements is the initial containing block instead of
2628 \*---------------------------------------------------------------------------*/
2631 // Calculate the static distance if needed.
2632 computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
2634 LayoutUnit logicalHeightResult; // Needed to compute overflow.
2635 LayoutUnit logicalTopPos;
2637 // Calculate constraint equation values for 'height' case.
2638 computePositionedLogicalHeightUsing(style()->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2639 logicalTop, logicalBottom, marginBefore, marginAfter,
2640 logicalHeightResult, marginBeforeAlias, marginAfterAlias, logicalTopPos);
2641 setLogicalTop(logicalTopPos);
2643 // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
2646 // Calculate constraint equation values for 'max-height' case.
2647 if (!style()->logicalMaxHeight().isUndefined()) {
2648 LayoutUnit maxLogicalHeight;
2649 LayoutUnit maxMarginBefore;
2650 LayoutUnit maxMarginAfter;
2651 LayoutUnit maxLogicalTopPos;
2653 computePositionedLogicalHeightUsing(style()->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2654 logicalTop, logicalBottom, marginBefore, marginAfter,
2655 maxLogicalHeight, maxMarginBefore, maxMarginAfter, maxLogicalTopPos);
2657 if (logicalHeightResult > maxLogicalHeight) {
2658 logicalHeightResult = maxLogicalHeight;
2659 marginBeforeAlias = maxMarginBefore;
2660 marginAfterAlias = maxMarginAfter;
2661 setLogicalTop(maxLogicalTopPos);
2665 // Calculate constraint equation values for 'min-height' case.
2666 if (!style()->logicalMinHeight().isZero()) {
2667 LayoutUnit minLogicalHeight;
2668 LayoutUnit minMarginBefore;
2669 LayoutUnit minMarginAfter;
2670 LayoutUnit minLogicalTopPos;
2672 computePositionedLogicalHeightUsing(style()->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2673 logicalTop, logicalBottom, marginBefore, marginAfter,
2674 minLogicalHeight, minMarginBefore, minMarginAfter, minLogicalTopPos);
2676 if (logicalHeightResult < minLogicalHeight) {
2677 logicalHeightResult = minLogicalHeight;
2678 marginBeforeAlias = minMarginBefore;
2679 marginAfterAlias = minMarginAfter;
2680 setLogicalTop(minLogicalTopPos);
2684 // Set final height value.
2685 setLogicalHeight(logicalHeightResult + bordersPlusPadding);
2688 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
2690 // Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2691 // 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.
2692 if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
2693 || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
2694 logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
2696 // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
2697 if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2698 if (child->isHorizontalWritingMode())
2699 logicalTopPos += containerBlock->borderBottom();
2701 logicalTopPos += containerBlock->borderRight();
2703 if (child->isHorizontalWritingMode())
2704 logicalTopPos += containerBlock->borderTop();
2706 logicalTopPos += containerBlock->borderLeft();
2710 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
2711 LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding,
2712 Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
2713 LayoutUnit& logicalHeightValue, LayoutUnit& marginBeforeValue, LayoutUnit& marginAfterValue, LayoutUnit& logicalTopPos)
2715 // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
2716 // converted to the static position in computePositionedLogicalHeight()
2717 ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
2719 LayoutUnit contentLogicalHeight = logicalHeight() - bordersPlusPadding;
2721 LayoutUnit logicalTopValue = 0;
2723 bool logicalHeightIsAuto = logicalHeightLength.isAuto();
2724 bool logicalTopIsAuto = logicalTop.isAuto();
2725 bool logicalBottomIsAuto = logicalBottom.isAuto();
2727 // Height is never unsolved for tables.
2729 logicalHeightLength.setValue(Fixed, contentLogicalHeight);
2730 logicalHeightIsAuto = false;
2733 if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
2734 /*-----------------------------------------------------------------------*\
2735 * If none of the three are 'auto': If both 'margin-top' and 'margin-
2736 * bottom' are 'auto', solve the equation under the extra constraint that
2737 * the two margins get equal values. If one of 'margin-top' or 'margin-
2738 * bottom' is 'auto', solve the equation for that value. If the values
2739 * are over-constrained, ignore the value for 'bottom' and solve for that
2741 \*-----------------------------------------------------------------------*/
2742 // NOTE: It is not necessary to solve for 'bottom' in the over constrained
2743 // case because the value is not used for any further calculations.
2745 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2746 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2748 const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight) + bordersPlusPadding);
2750 // Margins are now the only unknown
2751 if (marginBefore.isAuto() && marginAfter.isAuto()) {
2752 // Both margins auto, solve for equality
2753 // NOTE: This may result in negative values.
2754 marginBeforeValue = availableSpace / 2; // split the difference
2755 marginAfterValue = availableSpace - marginBeforeValue; // account for odd valued differences
2756 } else if (marginBefore.isAuto()) {
2757 // Solve for top margin
2758 marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
2759 marginBeforeValue = availableSpace - marginAfterValue;
2760 } else if (marginAfter.isAuto()) {
2761 // Solve for bottom margin
2762 marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
2763 marginAfterValue = availableSpace - marginBeforeValue;
2765 // Over-constrained, (no need solve for bottom)
2766 marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
2767 marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
2770 /*--------------------------------------------------------------------*\
2771 * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
2772 * to 0, and pick the one of the following six rules that applies.
2774 * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
2775 * the height is based on the content, and solve for 'top'.
2777 * OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2778 * ------------------------------------------------------------------
2779 * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
2780 * set 'top' to the static position, and solve for 'bottom'.
2781 * ------------------------------------------------------------------
2783 * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
2784 * the height is based on the content, and solve for 'bottom'.
2785 * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
2787 * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
2788 * solve for 'height'.
2789 * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
2790 * solve for 'bottom'.
2791 \*--------------------------------------------------------------------*/
2792 // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
2793 // because the value is not used for any further calculations.
2795 // Calculate margins, 'auto' margins are ignored.
2796 marginBeforeValue = marginBefore.calcMinValue(containerLogicalHeight);
2797 marginAfterValue = marginAfter.calcMinValue(containerLogicalHeight);
2799 const LayoutUnit availableSpace = containerLogicalHeight - (marginBeforeValue + marginAfterValue + bordersPlusPadding);
2801 // Use rule/case that applies.
2802 if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
2803 // RULE 1: (height is content based, solve of top)
2804 logicalHeightValue = contentLogicalHeight;
2805 logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
2806 } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
2807 // RULE 3: (height is content based, no need solve of bottom)
2808 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2809 logicalHeightValue = contentLogicalHeight;
2810 } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
2811 // RULE 4: (solve of top)
2812 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2813 logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
2814 } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
2815 // RULE 5: (solve of height)
2816 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2817 logicalHeightValue = max<LayoutUnit>(0, availableSpace - (logicalTopValue + logicalBottom.calcValue(containerLogicalHeight)));
2818 } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
2819 // RULE 6: (no need solve of bottom)
2820 logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2821 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2825 // Use computed values to calculate the vertical position.
2826 logicalTopPos = logicalTopValue + marginBeforeValue;
2827 computeLogicalTopPositionedOffset(logicalTopPos, this, logicalHeightValue, containerBlock, containerLogicalHeight);
2830 void RenderBox::computePositionedLogicalWidthReplaced()
2832 // The following is based off of the W3C Working Draft from April 11, 2006 of
2833 // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
2834 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
2835 // (block-style-comments in this function correspond to text from the spec and
2836 // the numbers correspond to numbers in spec)
2838 // We don't use containingBlock(), since we may be positioned by an enclosing
2839 // relative positioned inline.
2840 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2842 const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
2844 // To match WinIE, in quirks mode use the parent's 'direction' property
2845 // instead of the the container block's.
2846 TextDirection containerDirection = (document()->inQuirksMode()) ? parent()->style()->direction() : containerBlock->style()->direction();
2848 // Variables to solve.
2849 bool isHorizontal = isHorizontalWritingMode();
2850 Length logicalLeft = style()->logicalLeft();
2851 Length logicalRight = style()->logicalRight();
2852 Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2853 Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2854 LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
2855 LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
2857 /*-----------------------------------------------------------------------*\
2858 * 1. The used value of 'width' is determined as for inline replaced
2860 \*-----------------------------------------------------------------------*/
2861 // NOTE: This value of width is FINAL in that the min/max width calculations
2862 // are dealt with in computeReplacedWidth(). This means that the steps to produce
2863 // correct max/min in the non-replaced version, are not necessary.
2864 setLogicalWidth(computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth());
2865 const LayoutUnit availableSpace = containerLogicalWidth - logicalWidth();
2867 /*-----------------------------------------------------------------------*\
2868 * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
2869 * of the containing block is 'ltr', set 'left' to the static position;
2870 * else if 'direction' is 'rtl', set 'right' to the static position.
2871 \*-----------------------------------------------------------------------*/
2873 computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, containerDirection);
2875 /*-----------------------------------------------------------------------*\
2876 * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
2877 * or 'margin-right' with '0'.
2878 \*-----------------------------------------------------------------------*/
2879 if (logicalLeft.isAuto() || logicalRight.isAuto()) {
2880 if (marginLogicalLeft.isAuto())
2881 marginLogicalLeft.setValue(Fixed, 0);
2882 if (marginLogicalRight.isAuto())
2883 marginLogicalRight.setValue(Fixed, 0);
2886 /*-----------------------------------------------------------------------*\
2887 * 4. If at this point both 'margin-left' and 'margin-right' are still
2888 * 'auto', solve the equation under the extra constraint that the two
2889 * margins must get equal values, unless this would make them negative,
2890 * in which case when the direction of the containing block is 'ltr'
2891 * ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
2892 * 'margin-right' ('margin-left').
2893 \*-----------------------------------------------------------------------*/
2894 LayoutUnit logicalLeftValue = 0;
2895 LayoutUnit logicalRightValue = 0;
2897 if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2898 // 'left' and 'right' cannot be 'auto' due to step 3
2899 ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2901 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2902 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2904 LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
2905 if (difference > 0) {
2906 marginLogicalLeftAlias = difference / 2; // split the difference
2907 marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
2910 if (containerDirection == LTR) {
2911 marginLogicalLeftAlias = 0;
2912 marginLogicalRightAlias = difference; // will be negative
2914 marginLogicalLeftAlias = difference; // will be negative
2915 marginLogicalRightAlias = 0;
2919 /*-----------------------------------------------------------------------*\
2920 * 5. If at this point there is an 'auto' left, solve the equation for
2922 \*-----------------------------------------------------------------------*/
2923 } else if (logicalLeft.isAuto()) {
2924 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2925 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2926 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2929 logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
2930 } else if (logicalRight.isAuto()) {
2931 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2932 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2933 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2935 // Solve for 'right'
2936 logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
2937 } else if (marginLogicalLeft.isAuto()) {
2938 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2939 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2940 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2942 // Solve for 'margin-left'
2943 marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
2944 } else if (marginLogicalRight.isAuto()) {
2945 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2946 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2947 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2949 // Solve for 'margin-right'
2950 marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
2952 // Nothing is 'auto', just calculate the values.
2953 marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2954 marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2955 logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2956 logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2959 /*-----------------------------------------------------------------------*\
2960 * 6. If at this point the values are over-constrained, ignore the value
2961 * for either 'left' (in case the 'direction' property of the
2962 * containing block is 'rtl') or 'right' (in case 'direction' is
2963 * 'ltr') and solve for that value.
2964 \*-----------------------------------------------------------------------*/
2965 // NOTE: It is not necessary to solve for 'right' when the direction is
2966 // LTR because the value is not used.
2967 LayoutUnit totalLogicalWidth = logicalWidth() + logicalLeftValue + logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias;
2968 if (totalLogicalWidth > containerLogicalWidth && (containerDirection == RTL))
2969 logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
2971 // FIXME: Deal with differing writing modes here. Our offset needs to be in the containing block's coordinate space, so that
2972 // can make the result here rather complicated to compute.
2974 // Use computed values to calculate the horizontal position.
2976 // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
2977 // positioned, inline containing block because right now, it is using the logical left position
2978 // of the first line box when really it should use the last line box. When
2979 // this is fixed elsewhere, this block should be removed.
2980 if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2981 const RenderInline* flow = toRenderInline(containerBlock);
2982 InlineFlowBox* firstLine = flow->firstLineBox();
2983 InlineFlowBox* lastLine = flow->lastLineBox();
2984 if (firstLine && lastLine && firstLine != lastLine) {
2985 setLogicalLeft(logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft()));
2990 LayoutUnit logicalLeftPos = logicalLeftValue + marginLogicalLeftAlias;
2991 computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidth(), containerBlock, containerLogicalWidth);
2992 setLogicalLeft(logicalLeftPos);
2995 void RenderBox::computePositionedLogicalHeightReplaced()
2997 // The following is based off of the W3C Working Draft from April 11, 2006 of
2998 // CSS 2.1: Section 10.6.5 "Absolutely positioned, replaced elements"
2999 // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-height>
3000 // (block-style-comments in this function correspond to text from the spec and
3001 // the numbers correspond to numbers in spec)
3003 // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3004 const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3006 const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3008 // Variables to solve.
3009 bool isHorizontal = isHorizontalWritingMode();
3010 bool isFlipped = style()->isFlippedBlocksWritingMode();
3011 Length marginBefore = style()->marginBefore();
3012 Length marginAfter = style()->marginAfter();
3013 LayoutUnit& marginBeforeAlias = isHorizontal ? (isFlipped ? m_marginBottom : m_marginTop) : (isFlipped ? m_marginRight: m_marginLeft);
3014 LayoutUnit& marginAfterAlias = isHorizontal ? (isFlipped ? m_marginTop : m_marginBottom) : (isFlipped ? m_marginLeft: m_marginRight);
3016 Length logicalTop = style()->logicalTop();
3017 Length logicalBottom = style()->logicalBottom();
3019 /*-----------------------------------------------------------------------*\
3020 * 1. The used value of 'height' is determined as for inline replaced
3022 \*-----------------------------------------------------------------------*/
3023 // NOTE: This value of height is FINAL in that the min/max height calculations
3024 // are dealt with in computeReplacedHeight(). This means that the steps to produce
3025 // correct max/min in the non-replaced version, are not necessary.
3026 setLogicalHeight(computeReplacedLogicalHeight() + borderAndPaddingLogicalHeight());
3027 const LayoutUnit availableSpace = containerLogicalHeight - logicalHeight();
3029 /*-----------------------------------------------------------------------*\
3030 * 2. If both 'top' and 'bottom' have the value 'auto', replace 'top'
3031 * with the element's static position.
3032 \*-----------------------------------------------------------------------*/
3034 computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
3036 /*-----------------------------------------------------------------------*\
3037 * 3. If 'bottom' is 'auto', replace any 'auto' on 'margin-top' or
3038 * 'margin-bottom' with '0'.
3039 \*-----------------------------------------------------------------------*/
3040 // FIXME: The spec. says that this step should only be taken when bottom is
3041 // auto, but if only top is auto, this makes step 4 impossible.
3042 if (logicalTop.isAuto() || logicalBottom.isAuto()) {
3043 if (marginBefore.isAuto())
3044 marginBefore.setValue(Fixed, 0);
3045 if (marginAfter.isAuto())
3046 marginAfter.setValue(Fixed, 0);
3049 /*-----------------------------------------------------------------------*\
3050 * 4. If at this point both 'margin-top' and 'margin-bottom' are still
3051 * 'auto', solve the equation under the extra constraint that the two
3052 * margins must get equal values.
3053 \*-----------------------------------------------------------------------*/
3054 LayoutUnit logicalTopValue = 0;
3055 LayoutUnit logicalBottomValue = 0;
3057 if (marginBefore.isAuto() && marginAfter.isAuto()) {
3058 // 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
3059 ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
3061 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3062 logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3064 LayoutUnit difference = availableSpace - (logicalTopValue + logicalBottomValue);
3065 // NOTE: This may result in negative values.
3066 marginBeforeAlias = difference / 2; // split the difference
3067 marginAfterAlias = difference - marginBeforeAlias; // account for odd valued differences
3069 /*-----------------------------------------------------------------------*\
3070 * 5. If at this point there is only one 'auto' left, solve the equation
3072 \*-----------------------------------------------------------------------*/
3073 } else if (logicalTop.isAuto()) {
3074 marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3075 marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3076 logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3079 logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
3080 } else if (logicalBottom.isAuto()) {
3081 marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3082 marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3083 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3085 // Solve for 'bottom'
3086 // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3088 } else if (marginBefore.isAuto()) {
3089 marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3090 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3091 logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3093 // Solve for 'margin-top'
3094 marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
3095 } else if (marginAfter.isAuto()) {
3096 marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3097 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3098 logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3100 // Solve for 'margin-bottom'
3101 marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
3103 // Nothing is 'auto', just calculate the values.
3104 marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3105 marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3106 logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3107 // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3111 /*-----------------------------------------------------------------------*\
3112 * 6. If at this point the values are over-constrained, ignore the value
3113 * for 'bottom' and solve for that value.
3114 \*-----------------------------------------------------------------------*/
3115 // NOTE: It is not necessary to do this step because we don't end up using
3116 // the value of 'bottom' regardless of whether the values are over-constrained
3119 // Use computed values to calculate the vertical position.
3120 LayoutUnit logicalTopPos = logicalTopValue + marginBeforeAlias;
3121 computeLogicalTopPositionedOffset(logicalTopPos, this, logicalHeight(), containerBlock, containerLogicalHeight);
3122 setLogicalTop(logicalTopPos);
3125 LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
3127 // VisiblePositions at offsets inside containers either a) refer to the positions before/after
3128 // those containers (tables and select elements) or b) refer to the position inside an empty block.
3129 // They never refer to children.
3130 // FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.
3132 // FIXME: What about border and padding?
3133 LayoutRect rect(x(), y(), caretWidth, height());
3134 bool ltr = box ? box->isLeftToRightDirection() : style()->isLeftToRightDirection();
3136 if ((!caretOffset) ^ ltr)
3137 rect.move(LayoutSize(width() - caretWidth, 0));
3140 RootInlineBox* rootBox = box->root();
3141 LayoutUnit top = rootBox->lineTop();
3143 rect.setHeight(rootBox->lineBottom() - top);
3146 // If height of box is smaller than font height, use the latter one,
3147 // otherwise the caret might become invisible.
3149 // Also, if the box is not a replaced element, always use the font height.
3150 // This prevents the "big caret" bug described in:
3151 // <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
3153 // FIXME: ignoring :first-line, missing good reason to take care of
3154 LayoutUnit fontHeight = style()->fontMetrics().height();
3155 if (fontHeight > rect.height() || (!isReplaced() && !isTable()))
3156 rect.setHeight(fontHeight);
3158 if (extraWidthToEndOfLine)
3159 *extraWidthToEndOfLine = x() + width() - rect.maxX();
3161 // Move to local coords
3162 rect.moveBy(-location());
3166 VisiblePosition RenderBox::positionForPoint(const LayoutPoint& point)
3168 // no children...return this render object's element, if there is one, and offset 0
3170 return createVisiblePosition(node() ? firstPositionInOrBeforeNode(node()) : Position());
3172 if (isTable() && node()) {
3173 LayoutUnit right = contentWidth() + borderAndPaddingWidth();
3174 LayoutUnit bottom = contentHeight() + borderAndPaddingHeight();
3176 if (point.x() < 0 || point.x() > right || point.y() < 0 || point.y() > bottom) {
3177 if (point.x() <= right / 2)
3178 return createVisiblePosition(firstPositionInOrBeforeNode(node()));
3179 return createVisiblePosition(lastPositionInOrAfterNode(node()));
3183 // Pass off to the closest child.
3184 LayoutUnit minDist = numeric_limits<LayoutUnit>::max();
3185 RenderBox* closestRenderer = 0;
3186 LayoutPoint adjustedPoint = point;
3188 adjustedPoint.moveBy(location());
3190 for (RenderObject* renderObject = firstChild(); renderObject; renderObject = renderObject->nextSibling()) {
3191 if ((!renderObject->firstChild() && !renderObject->isInline() && !renderObject->isBlockFlow() )
3192 || renderObject->style()->visibility() != VISIBLE)
3195 if (!renderObject->isBox())
3198 RenderBox* renderer = toRenderBox(renderObject);
3200 LayoutUnit top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? 0 : renderer->y());
3201 LayoutUnit bottom = top + renderer->contentHeight();
3202 LayoutUnit left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? 0 : renderer->x());
3203 LayoutUnit right = left + renderer->contentWidth();
3205 if (point.x() <= right && point.x() >= left && point.y() <= top && point.y() >= bottom) {
3206 if (renderer->isTableRow())
3207 return renderer->positionForPoint(point + adjustedPoint - renderer->locationOffset());
3208 return renderer->positionForPoint(point - renderer->locationOffset());
3211 // Find the distance from (x, y) to the box. Split the space around the box into 8 pieces
3212 // and use a different compare depending on which piece (x, y) is in.
3214 if (point.x() > right) {
3215 if (point.y() < top)
3216 cmp = LayoutPoint(right, top);
3217 else if (point.y() > bottom)
3218 cmp = LayoutPoint(right, bottom);
3220 cmp = LayoutPoint(right, point.y());
3221 } else if (point.x() < left) {
3222 if (point.y() < top)
3223 cmp = LayoutPoint(left, top);
3224 else if (point.y() > bottom)
3225 cmp = LayoutPoint(left, bottom);
3227 cmp = LayoutPoint(left, point.y());
3229 if (point.y() < top)
3230 cmp = LayoutPoint(point.x(), top);
3232 cmp = LayoutPoint(point.x(), bottom);
3235 LayoutSize difference = cmp - point;
3237 LayoutUnit dist = difference.width() * difference.width() + difference.height() * difference.height();
3238 if (dist < minDist) {
3239 closestRenderer = renderer;
3244 if (closestRenderer)
3245 return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset());
3247 return createVisiblePosition(firstPositionInOrBeforeNode(node()));
3250 bool RenderBox::shrinkToAvoidFloats() const
3252 // Floating objects don't shrink. Objects that don't avoid floats don't shrink. Marquees don't shrink.
3253 if ((isInline() && !isHTMLMarquee()) || !avoidsFloats() || isFloating())
3256 // All auto-width objects that avoid floats should always use lineWidth.
3257 return style()->width().isAuto();
3260 bool RenderBox::avoidsFloats() const
3262 return isReplaced() || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isDeprecatedFlexItem();
3265 void RenderBox::addBoxShadowAndBorderOverflow()
3267 if (!style()->boxShadow() && !style()->hasBorderImageOutsets())
3270 bool isFlipped = style()->isFlippedBlocksWritingMode();
3271 bool isHorizontal = isHorizontalWritingMode();
3273 LayoutRect borderBox = borderBoxRect();
3274 LayoutUnit overflowMinX = borderBox.x();
3275 LayoutUnit overflowMaxX = borderBox.maxX();
3276 LayoutUnit overflowMinY = borderBox.y();
3277 LayoutUnit overflowMaxY = borderBox.maxY();
3279 // Compute box-shadow overflow first.
3280 if (style()->boxShadow()) {
3281 LayoutUnit shadowLeft;
3282 LayoutUnit shadowRight;
3283 LayoutUnit shadowTop;
3284 LayoutUnit shadowBottom;
3285 style()->getBoxShadowExtent(shadowTop, shadowRight, shadowBottom, shadowLeft);
3287 // In flipped blocks writing modes such as vertical-rl, the physical right shadow value is actually at the lower x-coordinate.
3288 overflowMinX = borderBox.x() + ((!isFlipped || isHorizontal) ? shadowLeft : -shadowRight);
3289 overflowMaxX = borderBox.maxX() + ((!isFlipped || isHorizontal) ? shadowRight : -shadowLeft);
3290 overflowMinY = borderBox.y() + ((!isFlipped || !isHorizontal) ? shadowTop : -shadowBottom);
3291 overflowMaxY = borderBox.maxY() + ((!isFlipped || !isHorizontal) ? shadowBottom : -shadowTop);
3294 // Now compute border-image-outset overflow.
3295 if (style()->hasBorderImageOutsets()) {
3296 LayoutUnit borderOutsetLeft;
3297 LayoutUnit borderOutsetRight;
3298 LayoutUnit borderOutsetTop;
3299 LayoutUnit borderOutsetBottom;
3300 style()->getBorderImageOutsets(borderOutsetTop, borderOutsetRight, borderOutsetBottom, borderOutsetLeft);
3302 // In flipped blocks writing modes, the physical sides are inverted. For example in vertical-rl, the right
3303 // border is at the lower x coordinate value.
3304 overflowMinX = min(overflowMinX, borderBox.x() - ((!isFlipped || isHorizontal) ? borderOutsetLeft : borderOutsetRight));
3305 overflowMaxX = max(overflowMaxX, borderBox.maxX() + ((!isFlipped || isHorizontal) ? borderOutsetRight : borderOutsetLeft));
3306 overflowMinY = min(overflowMinY, borderBox.y() - ((!isFlipped || !isHorizontal) ? borderOutsetTop : borderOutsetBottom));
3307 overflowMaxY = max(overflowMaxY, borderBox.maxY() + ((!isFlipped || !isHorizontal) ? borderOutsetBottom : borderOutsetTop));
3310 // Add in the final overflow with shadows and outsets combined.
3311 addVisualOverflow(LayoutRect(overflowMinX, overflowMinY, overflowMaxX - overflowMinX, overflowMaxY - overflowMinY));
3314 void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta)
3316 // Only propagate layout overflow from the child if the child isn't clipping its overflow. If it is, then
3317 // its overflow is internal to it, and we don't care about it. layoutOverflowRectForPropagation takes care of this
3318 // and just propagates the border box rect instead.
3319 LayoutRect childLayoutOverflowRect = child->layoutOverflowRectForPropagation(style());
3320 childLayoutOverflowRect.move(delta);
3321 addLayoutOverflow(childLayoutOverflowRect);
3323 // Add in visual overflow from the child. Even if the child clips its overflow, it may still
3324 // have visual overflow of its own set from box shadows or reflections. It is unnecessary to propagate this
3325 // overflow if we are clipping our own overflow.
3326 if (child->hasSelfPaintingLayer() || hasOverflowClip())
3328 LayoutRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
3329 childVisualOverflowRect.move(delta);
3330 addVisualOverflow(childVisualOverflowRect);
3333 void RenderBox::addLayoutOverflow(const LayoutRect& rect)
3335 LayoutRect clientBox = clientBoxRect();
3336 if (clientBox.contains(rect) || rect.isEmpty())
3339 // For overflow clip objects, we don't want to propagate overflow into unreachable areas.
3340 LayoutRect overflowRect(rect);
3341 if (hasOverflowClip() || isRenderView()) {
3342 // Overflow is in the block's coordinate space and thus is flipped for horizontal-bt and vertical-rl
3343 // writing modes. At this stage that is actually a simplification, since we can treat horizontal-tb/bt as the same
3344 // and vertical-lr/rl as the same.
3345 bool hasTopOverflow = !style()->isLeftToRightDirection() && !isHorizontalWritingMode();
3346 bool hasLeftOverflow = !style()->isLeftToRightDirection() && isHorizontalWritingMode();
3348 if (!hasTopOverflow)
3349 overflowRect.shiftYEdgeTo(max(overflowRect.y(), clientBox.y()));
3351 overflowRect.shiftMaxYEdgeTo(min(overflowRect.maxY(), clientBox.maxY()));
3352 if (!hasLeftOverflow)
3353 overflowRect.shiftXEdgeTo(max(overflowRect.x(), clientBox.x()));
3355 overflowRect.shiftMaxXEdgeTo(min(overflowRect.maxX(), clientBox.maxX()));
3357 // Now re-test with the adjusted rectangle and see if it has become unreachable or fully
3359 if (clientBox.contains(overflowRect) || overflowRect.isEmpty())
3364 m_overflow = adoptPtr(new RenderOverflow(clientBox, borderBoxRect()));
3366 m_overflow->addLayoutOverflow(overflowRect);
3369 void RenderBox::addVisualOverflow(const LayoutRect& rect)
3371 LayoutRect borderBox = borderBoxRect();
3372 if (borderBox.contains(rect) || rect.isEmpty())
3376 m_overflow = adoptPtr(new RenderOverflow(clientBoxRect(), borderBox));
3378 m_overflow->addVisualOverflow(rect);
3381 void RenderBox::clearLayoutOverflow()
3386 if (visualOverflowRect() == borderBoxRect()) {
3391 m_overflow->resetLayoutOverflow(borderBoxRect());
3394 static bool percentageLogicalHeightIsResolvable(const RenderBox* box)
3396 // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
3397 // block that may have a specified height and then use it. In strict mode, this violates the
3398 // specification, which states that percentage heights just revert to auto if the containing
3399 // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
3400 // only at explicit containers.
3401 const RenderBlock* cb = box->containingBlock();
3402 while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isPositioned() && cb->style()->logicalHeight().isAuto()) {
3403 if (!box->document()->inQuirksMode() && !cb->isAnonymousBlock())
3405 cb = cb->containingBlock();
3408 // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
3409 // explicitly specified that can be used for any percentage computations.
3410 // FIXME: We can't just check top/bottom here.
3411 // https://bugs.webkit.org/show_bug.cgi?id=46500
3412 bool isPositionedWithSpecifiedHeight = cb->isPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
3414 // Table cells violate what the CSS spec says to do with heights. Basically we
3415 // don't care if the cell specified a height or not. We just always make ourselves
3416 // be a percentage of the cell's current content height.
3417 if (cb->isTableCell())
3420 // Otherwise we only use our percentage height if our containing block had a specified
3422 if (cb->style()->logicalHeight().isFixed())
3424 if (cb->style()->logicalHeight().isPercent() && !isPositionedWithSpecifiedHeight)
3425 return percentageLogicalHeightIsResolvable(cb);
3426 if (cb->isRenderView() || (cb->isBody() && box->document()->inQuirksMode()) || isPositionedWithSpecifiedHeight)
3428 if (cb->isRoot() && box->isPositioned()) {
3429 // Match the positioned objects behavior, which is that positioned objects will fill their viewport
3430 // always. Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
3437 bool RenderBox::hasUnsplittableScrollingOverflow() const
3439 // We will paginate as long as we don't scroll overflow in the pagination direction.
3440 bool isHorizontal = isHorizontalWritingMode();
3441 if ((isHorizontal && !scrollsOverflowY()) || (!isHorizontal && !scrollsOverflowX()))
3444 // We do have overflow. We'll still be willing to paginate as long as the block
3445 // has auto logical height, auto or undefined max-logical-height and a zero or auto min-logical-height.
3446 // Note this is just a heuristic, and it's still possible to have overflow under these
3447 // conditions, but it should work out to be good enough for common cases. Paginating overflow
3448 // with scrollbars present is not the end of the world and is what we used to do in the old model anyway.
3449 return !style()->logicalHeight().isIntrinsicOrAuto()
3450 || (!style()->logicalMaxHeight().isIntrinsicOrAuto() && !style()->logicalMaxHeight().isUndefined() && (!style()->logicalMaxHeight().isPercent() || percentageLogicalHeightIsResolvable(this)))
3451 || (!style()->logicalMinHeight().isIntrinsicOrAuto() && style()->logicalMinHeight().isPositive() && (!style()->logicalMinHeight().isPercent() || percentageLogicalHeightIsResolvable(this)));
3454 LayoutUnit RenderBox::lineHeight(bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
3457 return direction == HorizontalLine ? m_marginTop + height() + m_marginBottom : m_marginRight + width() + m_marginLeft;
3461 LayoutUnit RenderBox::baselinePosition(FontBaseline baselineType, bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
3464 LayoutUnit result = direction == HorizontalLine ? m_marginTop + height() + m_marginBottom : m_marginRight + width() + m_marginLeft;
3465 if (baselineType == AlphabeticBaseline)
3467 return result - result / 2;
3473 RenderLayer* RenderBox::enclosingFloatPaintingLayer() const
3475 const RenderObject* curr = this;
3477 RenderLayer* layer = curr->hasLayer() && curr->isBox() ? toRenderBoxModelObject(curr)->layer() : 0;
3478 if (layer && layer->isSelfPaintingLayer())
3480 curr = curr->parent();
3485 LayoutRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* parentStyle) const
3487 LayoutRect rect = visualOverflowRectForPropagation(parentStyle);
3488 if (!parentStyle->isHorizontalWritingMode())
3489 return rect.transposedRect();
3493 LayoutRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) const
3495 // If the writing modes of the child and parent match, then we don't have to
3496 // do anything fancy. Just return the result.
3497 LayoutRect rect = visualOverflowRect();
3498 if (parentStyle->writingMode() == style()->writingMode())
3501 // We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
3502 // in a particular axis, then we have to flip the rect along that axis.
3503 if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
3504 rect.setX(width() - rect.maxX());
3505 else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
3506 rect.setY(height() - rect.maxY());
3511 LayoutRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* parentStyle) const
3513 LayoutRect rect = layoutOverflowRectForPropagation(parentStyle);
3514 if (!parentStyle->isHorizontalWritingMode())
3515 return rect.transposedRect();
3519 LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) const
3521 // Only propagate interior layout overflow if we don't clip it.
3522 LayoutRect rect = borderBoxRect();
3523 if (!hasOverflowClip())
3524 rect.unite(layoutOverflowRect());
3526 bool hasTransform = hasLayer() && layer()->transform();
3527 if (isRelPositioned() || hasTransform) {
3528 // If we are relatively positioned or if we have a transform, then we have to convert
3529 // this rectangle into physical coordinates, apply relative positioning and transforms
3530 // to it, and then convert it back.
3531 flipForWritingMode(rect);
3534 rect = layer()->currentTransform().mapRect(rect);
3536 if (isRelPositioned())
3537 rect.move(relativePositionOffsetX(), relativePositionOffsetY());
3539 // Now we need to flip back.
3540 flipForWritingMode(rect);
3543 // If the writing modes of the child and parent match, then we don't have to
3544 // do anything fancy. Just return the result.
3545 if (parentStyle->writingMode() == style()->writingMode())
3548 // We are putting ourselves into our parent's coordinate space. If there is a flipped block mismatch
3549 // in a particular axis, then we have to flip the rect along that axis.
3550 if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
3551 rect.setX(width() - rect.maxX());
3552 else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
3553 rect.setY(height() - rect.maxY());
3558 LayoutPoint RenderBox::flipForWritingMode(const RenderBox* child, const LayoutPoint& point, FlippingAdjustment adjustment) const
3560 if (!style()->isFlippedBlocksWritingMode())
3563 // The child is going to add in its x() and y(), so we have to make sure it ends up in
3565 if (isHorizontalWritingMode())
3566 return LayoutPoint(point.x(), point.y() + height() - child->height() - child->y() - (adjustment == ParentToChildFlippingAdjustment ? child->y() : 0));
3567 return LayoutPoint(point.x() + width() - child->width() - child->x() - (adjustment == ParentToChildFlippingAdjustment ? child->x() : 0), point.y());
3570 void RenderBox::flipForWritingMode(IntRect& rect) const
3572 if (!style()->isFlippedBlocksWritingMode())
3575 if (isHorizontalWritingMode())
3576 rect.setY(height() - rect.maxY());
3578 rect.setX(width() - rect.maxX());
3581 int RenderBox::flipForWritingMode(int position) const
3583 if (!style()->isFlippedBlocksWritingMode())
3585 return logicalHeight() - position;
3588 IntPoint RenderBox::flipForWritingMode(const IntPoint& position) const
3590 if (!style()->isFlippedBlocksWritingMode())
3592 return isHorizontalWritingMode() ? IntPoint(position.x(), height() - position.y()) : IntPoint(width() - position.x(), position.y());
3595 LayoutPoint RenderBox::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
3597 if (!hasColumns() || !style()->isFlippedBlocksWritingMode())
3598 return flipForWritingMode(point);
3599 return toRenderBlock(this)->flipForWritingModeIncludingColumns(point);
3602 IntSize RenderBox::flipForWritingMode(const IntSize& offset) const
3604 if (!style()->isFlippedBlocksWritingMode())
3606 return isHorizontalWritingMode() ? IntSize(offset.width(), height() - offset.height()) : IntSize(width() - offset.width(), offset.height());
3609 FloatPoint RenderBox::flipForWritingMode(const FloatPoint& position) const
3611 if (!style()->isFlippedBlocksWritingMode())
3613 return isHorizontalWritingMode() ? FloatPoint(position.x(), height() - position.y()) : FloatPoint(width() - position.x(), position.y());
3616 void RenderBox::flipForWritingMode(FloatRect& rect) const
3618 if (!style()->isFlippedBlocksWritingMode())
3621 if (isHorizontalWritingMode())
3622 rect.setY(height() - rect.maxY());
3624 rect.setX(width() - rect.maxX());
3627 LayoutSize RenderBox::locationOffsetIncludingFlipping() const
3629 RenderBlock* containerBlock = containingBlock();
3630 if (!containerBlock || containerBlock == this)
3631 return locationOffset();
3633 LayoutRect rect(frameRect());
3634 containerBlock->flipForWritingMode(rect); // FIXME: This is wrong if we are an absolutely positioned object enclosed by a relative-positioned inline.
3635 return LayoutSize(rect.x(), rect.y());
3638 } // namespace WebCore