1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
7  *
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.
12  *
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.
17  *
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.
22  *
23  */
24 
25 #include "config.h"
26 #include "RenderBox.h"
27 
28 #include "CachedImage.h"
29 #include "Chrome.h"
30 #include "ChromeClient.h"
31 #include "Document.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"
40 #include "Frame.h"
41 #include "Page.h"
42 #include "PaintInfo.h"
43 #include "RenderArena.h"
44 #include "RenderFlexibleBox.h"
45 #include "RenderInline.h"
46 #include "RenderLayer.h"
47 #include "RenderTableCell.h"
48 #include "RenderTheme.h"
49 #include "RenderView.h"
50 #include "ScrollbarTheme.h"
51 #include "TransformState.h"
52 #include <algorithm>
53 #include <math.h>
54 
55 using namespace std;
56 
57 namespace WebCore {
58 
59 using namespace HTMLNames;
60 
61 // Used by flexible boxes when flexing this element.
62 typedef WTF::HashMap<const RenderBox*, int> OverrideSizeMap;
63 static OverrideSizeMap* gOverrideSizeMap = 0;
64 
65 bool RenderBox::s_hadOverflowClip = false;
66 
RenderBox(Node * node)67 RenderBox::RenderBox(Node* node)
68     : RenderBoxModelObject(node)
69     , m_marginLeft(0)
70     , m_marginRight(0)
71     , m_marginTop(0)
72     , m_marginBottom(0)
73     , m_minPreferredLogicalWidth(-1)
74     , m_maxPreferredLogicalWidth(-1)
75     , m_inlineBoxWrapper(0)
76 {
77     setIsBox();
78 }
79 
~RenderBox()80 RenderBox::~RenderBox()
81 {
82 }
83 
marginBefore() const84 int RenderBox::marginBefore() const
85 {
86     switch (style()->writingMode()) {
87     case TopToBottomWritingMode:
88         return m_marginTop;
89     case BottomToTopWritingMode:
90         return m_marginBottom;
91     case LeftToRightWritingMode:
92         return m_marginLeft;
93     case RightToLeftWritingMode:
94         return m_marginRight;
95     }
96     ASSERT_NOT_REACHED();
97     return m_marginTop;
98 }
99 
marginAfter() const100 int RenderBox::marginAfter() const
101 {
102     switch (style()->writingMode()) {
103     case TopToBottomWritingMode:
104         return m_marginBottom;
105     case BottomToTopWritingMode:
106         return m_marginTop;
107     case LeftToRightWritingMode:
108         return m_marginRight;
109     case RightToLeftWritingMode:
110         return m_marginLeft;
111     }
112     ASSERT_NOT_REACHED();
113     return m_marginBottom;
114 }
115 
marginStart() const116 int RenderBox::marginStart() const
117 {
118     if (isHorizontalWritingMode())
119         return style()->isLeftToRightDirection() ? m_marginLeft : m_marginRight;
120     return style()->isLeftToRightDirection() ? m_marginTop : m_marginBottom;
121 }
122 
marginEnd() const123 int RenderBox::marginEnd() const
124 {
125     if (isHorizontalWritingMode())
126         return style()->isLeftToRightDirection() ? m_marginRight : m_marginLeft;
127     return style()->isLeftToRightDirection() ? m_marginBottom : m_marginTop;
128 }
129 
setMarginStart(int margin)130 void RenderBox::setMarginStart(int margin)
131 {
132     if (isHorizontalWritingMode()) {
133         if (style()->isLeftToRightDirection())
134             m_marginLeft = margin;
135         else
136             m_marginRight = margin;
137     } else {
138         if (style()->isLeftToRightDirection())
139             m_marginTop = margin;
140         else
141             m_marginBottom = margin;
142     }
143 }
144 
setMarginEnd(int margin)145 void RenderBox::setMarginEnd(int margin)
146 {
147     if (isHorizontalWritingMode()) {
148         if (style()->isLeftToRightDirection())
149             m_marginRight = margin;
150         else
151             m_marginLeft = margin;
152     } else {
153         if (style()->isLeftToRightDirection())
154             m_marginBottom = margin;
155         else
156             m_marginTop = margin;
157     }
158 }
159 
setMarginBefore(int margin)160 void RenderBox::setMarginBefore(int margin)
161 {
162     switch (style()->writingMode()) {
163     case TopToBottomWritingMode:
164         m_marginTop = margin;
165         break;
166     case BottomToTopWritingMode:
167         m_marginBottom = margin;
168         break;
169     case LeftToRightWritingMode:
170         m_marginLeft = margin;
171         break;
172     case RightToLeftWritingMode:
173         m_marginRight = margin;
174         break;
175     }
176 }
177 
setMarginAfter(int margin)178 void RenderBox::setMarginAfter(int margin)
179 {
180     switch (style()->writingMode()) {
181     case TopToBottomWritingMode:
182         m_marginBottom = margin;
183         break;
184     case BottomToTopWritingMode:
185         m_marginTop = margin;
186         break;
187     case LeftToRightWritingMode:
188         m_marginRight = margin;
189         break;
190     case RightToLeftWritingMode:
191         m_marginLeft = margin;
192         break;
193     }
194 }
195 
destroy()196 void RenderBox::destroy()
197 {
198     // A lot of the code in this function is just pasted into
199     // RenderWidget::destroy. If anything in this function changes,
200     // be sure to fix RenderWidget::destroy() as well.
201     if (hasOverrideSize())
202         gOverrideSizeMap->remove(this);
203 
204     if (style() && (style()->logicalHeight().isPercent() || style()->logicalMinHeight().isPercent() || style()->logicalMaxHeight().isPercent()))
205         RenderBlock::removePercentHeightDescendant(this);
206 
207     // If this renderer is owning renderer for the frameview's custom scrollbars,
208     // we need to clear it from the scrollbar. See webkit bug 64737.
209     if (style() && style()->hasPseudoStyle(SCROLLBAR) && frame() && frame()->view())
210         frame()->view()->clearOwningRendererForCustomScrollbars(this);
211 
212     RenderBoxModelObject::destroy();
213 }
214 
removeFloatingOrPositionedChildFromBlockLists()215 void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
216 {
217     ASSERT(isFloatingOrPositioned());
218 
219     if (documentBeingDestroyed())
220         return;
221 
222     if (isFloating()) {
223         RenderBlock* parentBlock = 0;
224         for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
225             if (curr->isRenderBlock()) {
226                 RenderBlock* currBlock = toRenderBlock(curr);
227                 if (!parentBlock || currBlock->containsFloat(this))
228                     parentBlock = currBlock;
229             }
230         }
231 
232         if (parentBlock) {
233             RenderObject* parent = parentBlock->parent();
234             if (parent && parent->isFlexibleBox())
235                 parentBlock = toRenderBlock(parent);
236 
237             parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
238         }
239     }
240 
241     if (isPositioned()) {
242         for (RenderObject* curr = parent(); curr; curr = curr->parent()) {
243             if (curr->isRenderBlock())
244                 toRenderBlock(curr)->removePositionedObject(this);
245         }
246     }
247 }
248 
styleWillChange(StyleDifference diff,const RenderStyle * newStyle)249 void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
250 {
251     s_hadOverflowClip = hasOverflowClip();
252 
253     if (style()) {
254         // The background of the root element or the body element could propagate up to
255         // the canvas.  Just dirty the entire canvas when our style changes substantially.
256         if (diff >= StyleDifferenceRepaint && node() &&
257                 (node()->hasTagName(htmlTag) || node()->hasTagName(bodyTag)))
258             view()->repaint();
259 
260         // When a layout hint happens and an object's position style changes, we have to do a layout
261         // to dirty the render tree using the old position value now.
262         if (diff == StyleDifferenceLayout && parent() && style()->position() != newStyle->position()) {
263             markContainingBlocksForLayout();
264             if (style()->position() == StaticPosition)
265                 repaint();
266             else if (newStyle->position() == AbsolutePosition || newStyle->position() == FixedPosition)
267                 parent()->setChildNeedsLayout(true);
268             if (isFloating() && !isPositioned() && (newStyle->position() == AbsolutePosition || newStyle->position() == FixedPosition))
269                 removeFloatingOrPositionedChildFromBlockLists();
270         }
271     } else if (newStyle && isBody())
272         view()->repaint();
273 
274     if (FrameView *frameView = view()->frameView()) {
275         bool newStyleIsFixed = newStyle && newStyle->position() == FixedPosition;
276         bool oldStyleIsFixed = style() && style()->position() == FixedPosition;
277         if (newStyleIsFixed != oldStyleIsFixed) {
278             if (newStyleIsFixed)
279                 frameView->addFixedObject();
280             else
281                 frameView->removeFixedObject();
282         }
283     }
284 
285     RenderBoxModelObject::styleWillChange(diff, newStyle);
286 }
287 
styleDidChange(StyleDifference diff,const RenderStyle * oldStyle)288 void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
289 {
290     RenderBoxModelObject::styleDidChange(diff, oldStyle);
291 
292     if (needsLayout() && oldStyle) {
293         if (oldStyle && (oldStyle->logicalHeight().isPercent() || oldStyle->logicalMinHeight().isPercent() || oldStyle->logicalMaxHeight().isPercent()))
294             RenderBlock::removePercentHeightDescendant(this);
295 
296         // Normally we can do optimized positioning layout for absolute/fixed positioned objects. There is one special case, however, which is
297         // 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
298         // to determine the new static position.
299         if (isPositioned() && style()->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != style()->marginBefore()
300             && parent() && !parent()->normalChildNeedsLayout())
301             parent()->setChildNeedsLayout(true);
302     }
303 
304     // If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
305     // new zoomed coordinate space.
306     if (hasOverflowClip() && oldStyle && style() && oldStyle->effectiveZoom() != style()->effectiveZoom()) {
307         if (int left = layer()->scrollXOffset()) {
308             left = (left / oldStyle->effectiveZoom()) * style()->effectiveZoom();
309             layer()->scrollToXOffset(left);
310         }
311         if (int top = layer()->scrollYOffset()) {
312             top = (top / oldStyle->effectiveZoom()) * style()->effectiveZoom();
313             layer()->scrollToYOffset(top);
314         }
315     }
316 
317     bool isBodyRenderer = isBody();
318     bool isRootRenderer = isRoot();
319 
320     // Set the text color if we're the body.
321     if (isBodyRenderer)
322         document()->setTextColor(style()->visitedDependentColor(CSSPropertyColor));
323 
324     if (isRootRenderer || isBodyRenderer) {
325         // Propagate the new writing mode and direction up to the RenderView.
326         RenderView* viewRenderer = view();
327         RenderStyle* viewStyle = viewRenderer->style();
328         if (viewStyle->direction() != style()->direction() && (isRootRenderer || !document()->directionSetOnDocumentElement())) {
329             viewStyle->setDirection(style()->direction());
330             if (isBodyRenderer)
331                 document()->documentElement()->renderer()->style()->setDirection(style()->direction());
332             setNeedsLayoutAndPrefWidthsRecalc();
333         }
334 
335         if (viewStyle->writingMode() != style()->writingMode() && (isRootRenderer || !document()->writingModeSetOnDocumentElement())) {
336             viewStyle->setWritingMode(style()->writingMode());
337             viewRenderer->setHorizontalWritingMode(style()->isHorizontalWritingMode());
338             if (isBodyRenderer) {
339                 document()->documentElement()->renderer()->style()->setWritingMode(style()->writingMode());
340                 document()->documentElement()->renderer()->setHorizontalWritingMode(style()->isHorizontalWritingMode());
341             }
342             setNeedsLayoutAndPrefWidthsRecalc();
343         }
344     }
345 }
346 
updateBoxModelInfoFromStyle()347 void RenderBox::updateBoxModelInfoFromStyle()
348 {
349     RenderBoxModelObject::updateBoxModelInfoFromStyle();
350 
351     bool isRootObject = isRoot();
352     bool isViewObject = isRenderView();
353 
354     // The root and the RenderView always paint their backgrounds/borders.
355     if (isRootObject || isViewObject)
356         setHasBoxDecorations(true);
357 
358     setPositioned(style()->position() == AbsolutePosition || style()->position() == FixedPosition);
359     setFloating(!isPositioned() && style()->isFloating());
360 
361     // We also handle <body> and <html>, whose overflow applies to the viewport.
362     if (style()->overflowX() != OVISIBLE && !isRootObject && (isRenderBlock() || isTableRow() || isTableSection())) {
363         bool boxHasOverflowClip = true;
364         if (isBody()) {
365             // Overflow on the body can propagate to the viewport under the following conditions.
366             // (1) The root element is <html>.
367             // (2) We are the primary <body> (can be checked by looking at document.body).
368             // (3) The root element has visible overflow.
369             if (document()->documentElement()->hasTagName(htmlTag) &&
370                 document()->body() == node() &&
371                 document()->documentElement()->renderer()->style()->overflowX() == OVISIBLE)
372                 boxHasOverflowClip = false;
373         }
374 
375         // Check for overflow clip.
376         // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
377         if (boxHasOverflowClip) {
378             if (!s_hadOverflowClip)
379                 // Erase the overflow
380                 repaint();
381             setHasOverflowClip();
382         }
383     }
384 
385     setHasTransform(style()->hasTransformRelatedProperty());
386     setHasReflection(style()->boxReflect());
387 }
388 
layout()389 void RenderBox::layout()
390 {
391     ASSERT(needsLayout());
392 
393     RenderObject* child = firstChild();
394     if (!child) {
395         setNeedsLayout(false);
396         return;
397     }
398 
399     LayoutStateMaintainer statePusher(view(), this, IntSize(x(), y()), style()->isFlippedBlocksWritingMode());
400     while (child) {
401         child->layoutIfNeeded();
402         ASSERT(!child->needsLayout());
403         child = child->nextSibling();
404     }
405     statePusher.pop();
406     setNeedsLayout(false);
407 }
408 
409 // More IE extensions.  clientWidth and clientHeight represent the interior of an object
410 // excluding border and scrollbar.
clientWidth() const411 int RenderBox::clientWidth() const
412 {
413     return width() - borderLeft() - borderRight() - verticalScrollbarWidth();
414 }
415 
clientHeight() const416 int RenderBox::clientHeight() const
417 {
418     return height() - borderTop() - borderBottom() - horizontalScrollbarHeight();
419 }
420 
scrollWidth() const421 int RenderBox::scrollWidth() const
422 {
423     if (hasOverflowClip())
424         return layer()->scrollWidth();
425     // For objects with visible overflow, this matches IE.
426     // FIXME: Need to work right with writing modes.
427     if (style()->isLeftToRightDirection())
428         return max(clientWidth(), maxXLayoutOverflow() - borderLeft());
429     return clientWidth() - min(0, minXLayoutOverflow() - borderLeft());
430 }
431 
scrollHeight() const432 int RenderBox::scrollHeight() const
433 {
434     if (hasOverflowClip())
435         return layer()->scrollHeight();
436     // For objects with visible overflow, this matches IE.
437     // FIXME: Need to work right with writing modes.
438     return max(clientHeight(), maxYLayoutOverflow() - borderTop());
439 }
440 
scrollLeft() const441 int RenderBox::scrollLeft() const
442 {
443     return hasOverflowClip() ? layer()->scrollXOffset() : 0;
444 }
445 
scrollTop() const446 int RenderBox::scrollTop() const
447 {
448     return hasOverflowClip() ? layer()->scrollYOffset() : 0;
449 }
450 
setScrollLeft(int newLeft)451 void RenderBox::setScrollLeft(int newLeft)
452 {
453     if (hasOverflowClip())
454         layer()->scrollToXOffset(newLeft);
455 }
456 
setScrollTop(int newTop)457 void RenderBox::setScrollTop(int newTop)
458 {
459     if (hasOverflowClip())
460         layer()->scrollToYOffset(newTop);
461 }
462 
absoluteRects(Vector<IntRect> & rects,int tx,int ty)463 void RenderBox::absoluteRects(Vector<IntRect>& rects, int tx, int ty)
464 {
465     rects.append(IntRect(tx, ty, width(), height()));
466 }
467 
absoluteQuads(Vector<FloatQuad> & quads)468 void RenderBox::absoluteQuads(Vector<FloatQuad>& quads)
469 {
470     quads.append(localToAbsoluteQuad(FloatRect(0, 0, width(), height())));
471 }
472 
updateLayerTransform()473 void RenderBox::updateLayerTransform()
474 {
475     // Transform-origin depends on box size, so we need to update the layer transform after layout.
476     if (hasLayer())
477         layer()->updateTransform();
478 }
479 
absoluteContentBox() const480 IntRect RenderBox::absoluteContentBox() const
481 {
482     IntRect rect = contentBoxRect();
483     FloatPoint absPos = localToAbsolute(FloatPoint());
484     rect.move(absPos.x(), absPos.y());
485     return rect;
486 }
487 
absoluteContentQuad() const488 FloatQuad RenderBox::absoluteContentQuad() const
489 {
490     IntRect rect = contentBoxRect();
491     return localToAbsoluteQuad(FloatRect(rect));
492 }
493 
outlineBoundsForRepaint(RenderBoxModelObject * repaintContainer,IntPoint * cachedOffsetToRepaintContainer) const494 IntRect RenderBox::outlineBoundsForRepaint(RenderBoxModelObject* repaintContainer, IntPoint* cachedOffsetToRepaintContainer) const
495 {
496     IntRect box = borderBoundingBox();
497     adjustRectForOutlineAndShadow(box);
498 
499     FloatQuad containerRelativeQuad = FloatRect(box);
500     if (cachedOffsetToRepaintContainer)
501         containerRelativeQuad.move(cachedOffsetToRepaintContainer->x(), cachedOffsetToRepaintContainer->y());
502     else
503         containerRelativeQuad = localToContainerQuad(containerRelativeQuad, repaintContainer);
504 
505     box = containerRelativeQuad.enclosingBoundingBox();
506 
507     // FIXME: layoutDelta needs to be applied in parts before/after transforms and
508     // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
509     box.move(view()->layoutDelta());
510 
511     return box;
512 }
513 
addFocusRingRects(Vector<IntRect> & rects,int tx,int ty)514 void RenderBox::addFocusRingRects(Vector<IntRect>& rects, int tx, int ty)
515 {
516     if (width() && height())
517         rects.append(IntRect(tx, ty, width(), height()));
518 }
519 
reflectionBox() const520 IntRect RenderBox::reflectionBox() const
521 {
522     IntRect result;
523     if (!style()->boxReflect())
524         return result;
525     IntRect box = borderBoxRect();
526     result = box;
527     switch (style()->boxReflect()->direction()) {
528         case ReflectionBelow:
529             result.move(0, box.height() + reflectionOffset());
530             break;
531         case ReflectionAbove:
532             result.move(0, -box.height() - reflectionOffset());
533             break;
534         case ReflectionLeft:
535             result.move(-box.width() - reflectionOffset(), 0);
536             break;
537         case ReflectionRight:
538             result.move(box.width() + reflectionOffset(), 0);
539             break;
540     }
541     return result;
542 }
543 
reflectionOffset() const544 int RenderBox::reflectionOffset() const
545 {
546     if (!style()->boxReflect())
547         return 0;
548     if (style()->boxReflect()->direction() == ReflectionLeft || style()->boxReflect()->direction() == ReflectionRight)
549         return style()->boxReflect()->offset().calcValue(borderBoxRect().width());
550     return style()->boxReflect()->offset().calcValue(borderBoxRect().height());
551 }
552 
reflectedRect(const IntRect & r) const553 IntRect RenderBox::reflectedRect(const IntRect& r) const
554 {
555     if (!style()->boxReflect())
556         return IntRect();
557 
558     IntRect box = borderBoxRect();
559     IntRect result = r;
560     switch (style()->boxReflect()->direction()) {
561         case ReflectionBelow:
562             result.setY(box.maxY() + reflectionOffset() + (box.maxY() - r.maxY()));
563             break;
564         case ReflectionAbove:
565             result.setY(box.y() - reflectionOffset() - box.height() + (box.maxY() - r.maxY()));
566             break;
567         case ReflectionLeft:
568             result.setX(box.x() - reflectionOffset() - box.width() + (box.maxX() - r.maxX()));
569             break;
570         case ReflectionRight:
571             result.setX(box.maxX() + reflectionOffset() + (box.maxX() - r.maxX()));
572             break;
573     }
574     return result;
575 }
576 
includeVerticalScrollbarSize() const577 bool RenderBox::includeVerticalScrollbarSize() const
578 {
579     return hasOverflowClip() && !layer()->hasOverlayScrollbars()
580         && (style()->overflowY() == OSCROLL || style()->overflowY() == OAUTO);
581 }
582 
includeHorizontalScrollbarSize() const583 bool RenderBox::includeHorizontalScrollbarSize() const
584 {
585     return hasOverflowClip() && !layer()->hasOverlayScrollbars()
586         && (style()->overflowX() == OSCROLL || style()->overflowX() == OAUTO);
587 }
588 
verticalScrollbarWidth() const589 int RenderBox::verticalScrollbarWidth() const
590 {
591     return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
592 }
593 
horizontalScrollbarHeight() const594 int RenderBox::horizontalScrollbarHeight() const
595 {
596     return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
597 }
598 
scroll(ScrollDirection direction,ScrollGranularity granularity,float multiplier,Node ** stopNode)599 bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
600 {
601     RenderLayer* l = layer();
602     if (l && l->scroll(direction, granularity, multiplier)) {
603         if (stopNode)
604             *stopNode = node();
605         return true;
606     }
607 
608     if (stopNode && *stopNode && *stopNode == node())
609         return true;
610 
611     RenderBlock* b = containingBlock();
612     if (b && !b->isRenderView())
613         return b->scroll(direction, granularity, multiplier, stopNode);
614     return false;
615 }
616 
logicalScroll(ScrollLogicalDirection direction,ScrollGranularity granularity,float multiplier,Node ** stopNode)617 bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
618 {
619     bool scrolled = false;
620 
621     RenderLayer* l = layer();
622     if (l) {
623 #if PLATFORM(MAC)
624         // On Mac only we reset the inline direction position when doing a document scroll (e.g., hitting Home/End).
625         if (granularity == ScrollByDocument)
626             scrolled = l->scroll(logicalToPhysical(ScrollInlineDirectionBackward, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), ScrollByDocument, multiplier);
627 #endif
628         if (l->scroll(logicalToPhysical(direction, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()), granularity, multiplier))
629             scrolled = true;
630 
631         if (scrolled) {
632             if (stopNode)
633                 *stopNode = node();
634             return true;
635         }
636     }
637 
638     if (stopNode && *stopNode && *stopNode == node())
639         return true;
640 
641     RenderBlock* b = containingBlock();
642     if (b && !b->isRenderView())
643         return b->logicalScroll(direction, granularity, multiplier, stopNode);
644     return false;
645 }
646 
canBeScrolledAndHasScrollableArea() const647 bool RenderBox::canBeScrolledAndHasScrollableArea() const
648 {
649     return canBeProgramaticallyScrolled(false) && (scrollHeight() != clientHeight() || scrollWidth() != clientWidth());
650 }
651 
canBeProgramaticallyScrolled(bool) const652 bool RenderBox::canBeProgramaticallyScrolled(bool) const
653 {
654     return (hasOverflowClip() && (scrollsOverflow() || (node() && node()->rendererIsEditable()))) || (node() && node()->isDocumentNode());
655 }
656 
autoscroll()657 void RenderBox::autoscroll()
658 {
659     if (layer())
660         layer()->autoscroll();
661 }
662 
panScroll(const IntPoint & source)663 void RenderBox::panScroll(const IntPoint& source)
664 {
665     if (layer())
666         layer()->panScrollFromPoint(source);
667 }
668 
minPreferredLogicalWidth() const669 int RenderBox::minPreferredLogicalWidth() const
670 {
671     if (preferredLogicalWidthsDirty())
672         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
673 
674     return m_minPreferredLogicalWidth;
675 }
676 
maxPreferredLogicalWidth() const677 int RenderBox::maxPreferredLogicalWidth() const
678 {
679     if (preferredLogicalWidthsDirty())
680         const_cast<RenderBox*>(this)->computePreferredLogicalWidths();
681 
682     return m_maxPreferredLogicalWidth;
683 }
684 
overrideSize() const685 int RenderBox::overrideSize() const
686 {
687     if (!hasOverrideSize())
688         return -1;
689     return gOverrideSizeMap->get(this);
690 }
691 
setOverrideSize(int s)692 void RenderBox::setOverrideSize(int s)
693 {
694     if (s == -1) {
695         if (hasOverrideSize()) {
696             setHasOverrideSize(false);
697             gOverrideSizeMap->remove(this);
698         }
699     } else {
700         if (!gOverrideSizeMap)
701             gOverrideSizeMap = new OverrideSizeMap();
702         setHasOverrideSize(true);
703         gOverrideSizeMap->set(this, s);
704     }
705 }
706 
overrideWidth() const707 int RenderBox::overrideWidth() const
708 {
709     return hasOverrideSize() ? overrideSize() : width();
710 }
711 
overrideHeight() const712 int RenderBox::overrideHeight() const
713 {
714     return hasOverrideSize() ? overrideSize() : height();
715 }
716 
computeBorderBoxLogicalWidth(int width) const717 int RenderBox::computeBorderBoxLogicalWidth(int width) const
718 {
719     int bordersPlusPadding = borderAndPaddingLogicalWidth();
720     if (style()->boxSizing() == CONTENT_BOX)
721         return width + bordersPlusPadding;
722     return max(width, bordersPlusPadding);
723 }
724 
computeBorderBoxLogicalHeight(int height) const725 int RenderBox::computeBorderBoxLogicalHeight(int height) const
726 {
727     int bordersPlusPadding = borderAndPaddingLogicalHeight();
728     if (style()->boxSizing() == CONTENT_BOX)
729         return height + bordersPlusPadding;
730     return max(height, bordersPlusPadding);
731 }
732 
computeContentBoxLogicalWidth(int width) const733 int RenderBox::computeContentBoxLogicalWidth(int width) const
734 {
735     if (style()->boxSizing() == BORDER_BOX)
736         width -= borderAndPaddingLogicalWidth();
737     return max(0, width);
738 }
739 
computeContentBoxLogicalHeight(int height) const740 int RenderBox::computeContentBoxLogicalHeight(int height) const
741 {
742     if (style()->boxSizing() == BORDER_BOX)
743         height -= borderAndPaddingLogicalHeight();
744     return max(0, height);
745 }
746 
747 // Hit Testing
nodeAtPoint(const HitTestRequest & request,HitTestResult & result,int xPos,int yPos,int tx,int ty,HitTestAction action)748 bool RenderBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, int xPos, int yPos, int tx, int ty, HitTestAction action)
749 {
750     tx += x();
751     ty += y();
752 
753     // Check kids first.
754     for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
755         if (!child->hasLayer() && child->nodeAtPoint(request, result, xPos, yPos, tx, ty, action)) {
756             updateHitTestResult(result, IntPoint(xPos - tx, yPos - ty));
757             return true;
758         }
759     }
760 
761     // Check our bounds next. For this purpose always assume that we can only be hit in the
762     // foreground phase (which is true for replaced elements like images).
763     IntRect boundsRect = IntRect(tx, ty, width(), height());
764     if (visibleToHitTesting() && action == HitTestForeground && boundsRect.intersects(result.rectForPoint(xPos, yPos))) {
765         updateHitTestResult(result, IntPoint(xPos - tx, yPos - ty));
766         if (!result.addNodeToRectBasedTestResult(node(), xPos, yPos, boundsRect))
767             return true;
768     }
769 
770     return false;
771 }
772 
773 // --------------------- painting stuff -------------------------------
774 
paint(PaintInfo & paintInfo,int tx,int ty)775 void RenderBox::paint(PaintInfo& paintInfo, int tx, int ty)
776 {
777     tx += x();
778     ty += y();
779 
780     // default implementation. Just pass paint through to the children
781     PaintInfo childInfo(paintInfo);
782     childInfo.updatePaintingRootForChildren(this);
783     for (RenderObject* child = firstChild(); child; child = child->nextSibling())
784         child->paint(childInfo, tx, ty);
785 }
786 
paintRootBoxFillLayers(const PaintInfo & paintInfo)787 void RenderBox::paintRootBoxFillLayers(const PaintInfo& paintInfo)
788 {
789     const FillLayer* bgLayer = style()->backgroundLayers();
790     Color bgColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
791     RenderObject* bodyObject = 0;
792     if (!hasBackground() && node() && node()->hasTagName(HTMLNames::htmlTag)) {
793         // Locate the <body> element using the DOM.  This is easier than trying
794         // to crawl around a render tree with potential :before/:after content and
795         // anonymous blocks created by inline <body> tags etc.  We can locate the <body>
796         // render object very easily via the DOM.
797         HTMLElement* body = document()->body();
798         bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
799         if (bodyObject) {
800             bgLayer = bodyObject->style()->backgroundLayers();
801             bgColor = bodyObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
802         }
803     }
804 
805     // The background of the box generated by the root element covers the entire canvas, so just use
806     // the RenderView's docTop/Left/Width/Height accessors.
807     paintFillLayers(paintInfo, bgColor, bgLayer, view()->docLeft(), view()->docTop(), view()->docWidth(), view()->docHeight(), BackgroundBleedNone, CompositeSourceOver, bodyObject);
808 }
809 
paintBoxDecorations(PaintInfo & paintInfo,int tx,int ty)810 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, int tx, int ty)
811 {
812     if (!paintInfo.shouldPaintWithinRoot(this))
813         return;
814     return paintBoxDecorationsWithSize(paintInfo, tx, ty, width(), height());
815 }
816 
determineBackgroundBleedAvoidance(GraphicsContext * context) const817 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
818 {
819     if (context->paintingDisabled())
820         return BackgroundBleedNone;
821 
822     const RenderStyle* style = this->style();
823 
824     if (!style->hasBackground() || !style->hasBorder() || !style->hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
825         return BackgroundBleedNone;
826 
827     AffineTransform ctm = context->getCTM();
828     FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
829     if (borderObscuresBackgroundEdge(contextScaling))
830         return BackgroundBleedShrinkBackground;
831 
832     // FIXME: there is one more strategy possible, for opaque backgrounds and
833     // translucent borders. In that case we could avoid using a transparency layer,
834     // and paint the border first, and then paint the background clipped to the
835     // inside of the border.
836 
837     return BackgroundBleedUseTransparencyLayer;
838 }
839 
paintBoxDecorationsWithSize(PaintInfo & paintInfo,int tx,int ty,int width,int height)840 void RenderBox::paintBoxDecorationsWithSize(PaintInfo& paintInfo, int tx, int ty, int width, int height)
841 {
842     // border-fit can adjust where we paint our border and background.  If set, we snugly fit our line box descendants.  (The iChat
843     // balloon layout is an example of this).
844     borderFitAdjust(tx, width);
845 
846     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
847     // custom shadows of their own.
848     paintBoxShadow(paintInfo.context, tx, ty, width, height, style(), Normal);
849 
850     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
851 
852     GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
853     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
854         // To avoid the background color bleeding out behind the border, we'll render background and border
855         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
856         // beginning the layer).
857         RoundedIntRect border = style()->getRoundedBorderFor(IntRect(tx, ty, width, height));
858         stateSaver.save();
859         paintInfo.context->addRoundedRectClip(border);
860         paintInfo.context->beginTransparencyLayer(1);
861     }
862 
863     // If we have a native theme appearance, paint that before painting our background.
864     // The theme will tell us whether or not we should also paint the CSS background.
865     bool themePainted = style()->hasAppearance() && !theme()->paint(this, paintInfo, IntRect(tx, ty, width, height));
866     if (!themePainted) {
867         if (isRoot())
868             paintRootBoxFillLayers(paintInfo);
869         else if (!isBody() || document()->documentElement()->renderer()->hasBackground()) {
870             // The <body> only paints its background if the root element has defined a background
871             // independent of the body.
872             paintFillLayers(paintInfo, style()->visitedDependentColor(CSSPropertyBackgroundColor), style()->backgroundLayers(), tx, ty, width, height, bleedAvoidance);
873         }
874         if (style()->hasAppearance())
875             theme()->paintDecorations(this, paintInfo, IntRect(tx, ty, width, height));
876     }
877     paintBoxShadow(paintInfo.context, tx, ty, width, height, style(), Inset);
878 
879     // The theme will tell us whether or not we should also paint the CSS border.
880     if ((!style()->hasAppearance() || (!themePainted && theme()->paintBorderOnly(this, paintInfo, IntRect(tx, ty, width, height)))) && style()->hasBorder())
881         paintBorder(paintInfo.context, tx, ty, width, height, style(), bleedAvoidance);
882 
883     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
884         paintInfo.context->endTransparencyLayer();
885 }
886 
paintMask(PaintInfo & paintInfo,int tx,int ty)887 void RenderBox::paintMask(PaintInfo& paintInfo, int tx, int ty)
888 {
889     if (!paintInfo.shouldPaintWithinRoot(this) || style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
890         return;
891 
892     int w = width();
893     int h = height();
894 
895     // border-fit can adjust where we paint our border and background.  If set, we snugly fit our line box descendants.  (The iChat
896     // balloon layout is an example of this).
897     borderFitAdjust(tx, w);
898 
899     paintMaskImages(paintInfo, tx, ty, w, h);
900 }
901 
paintMaskImages(const PaintInfo & paintInfo,int tx,int ty,int w,int h)902 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, int tx, int ty, int w, int h)
903 {
904     // Figure out if we need to push a transparency layer to render our mask.
905     bool pushTransparencyLayer = false;
906     bool compositedMask = hasLayer() && layer()->hasCompositedMask();
907     CompositeOperator compositeOp = CompositeSourceOver;
908 
909     bool allMaskImagesLoaded = true;
910 
911     if (!compositedMask) {
912         // If the context has a rotation, scale or skew, then use a transparency layer to avoid
913         // pixel cruft around the edge of the mask.
914         const AffineTransform& currentCTM = paintInfo.context->getCTM();
915         pushTransparencyLayer = !currentCTM.isIdentityOrTranslationOrFlipped();
916 
917         StyleImage* maskBoxImage = style()->maskBoxImage().image();
918         const FillLayer* maskLayers = style()->maskLayers();
919 
920         // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
921         if (maskBoxImage)
922             allMaskImagesLoaded &= maskBoxImage->isLoaded();
923 
924         if (maskLayers)
925             allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
926 
927         // Before all images have loaded, just use an empty transparency layer as the mask.
928         if (!allMaskImagesLoaded)
929             pushTransparencyLayer = true;
930 
931         if (maskBoxImage && maskLayers->hasImage()) {
932             // We have a mask-box-image and mask-image, so need to composite them together before using the result as a mask.
933             pushTransparencyLayer = true;
934         } else {
935             // We have to use an extra image buffer to hold the mask. Multiple mask images need
936             // to composite together using source-over so that they can then combine into a single unified mask that
937             // can be composited with the content using destination-in.  SVG images need to be able to set compositing modes
938             // as they draw images contained inside their sub-document, so we paint all our images into a separate buffer
939             // and composite that buffer as the mask.
940             // We have to check that the mask images to be rendered contain at least one image that can be actually used in rendering
941             // before pushing the transparency layer.
942             for (const FillLayer* fillLayer = maskLayers->next(); fillLayer; fillLayer = fillLayer->next()) {
943                 if (fillLayer->hasImage() && fillLayer->image()->canRender(style()->effectiveZoom())) {
944                     pushTransparencyLayer = true;
945                     // We found one image that can be used in rendering, exit the loop
946                     break;
947                 }
948             }
949         }
950 
951         compositeOp = CompositeDestinationIn;
952         if (pushTransparencyLayer) {
953             paintInfo.context->setCompositeOperation(CompositeDestinationIn);
954             paintInfo.context->beginTransparencyLayer(1.0f);
955             compositeOp = CompositeSourceOver;
956         }
957     }
958 
959     if (allMaskImagesLoaded) {
960         paintFillLayers(paintInfo, Color(), style()->maskLayers(), tx, ty, w, h, BackgroundBleedNone, compositeOp);
961         paintNinePieceImage(paintInfo.context, tx, ty, w, h, style(), style()->maskBoxImage(), compositeOp);
962     }
963 
964     if (pushTransparencyLayer)
965         paintInfo.context->endTransparencyLayer();
966 }
967 
maskClipRect()968 IntRect RenderBox::maskClipRect()
969 {
970     IntRect bbox = borderBoxRect();
971     if (style()->maskBoxImage().image())
972         return bbox;
973 
974     IntRect result;
975     for (const FillLayer* maskLayer = style()->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
976         if (maskLayer->image()) {
977             IntRect maskRect;
978             IntPoint phase;
979             IntSize tileSize;
980             calculateBackgroundImageGeometry(maskLayer, bbox.x(), bbox.y(), bbox.width(), bbox.height(), maskRect, phase, tileSize);
981             result.unite(maskRect);
982         }
983     }
984     return result;
985 }
986 
paintFillLayers(const PaintInfo & paintInfo,const Color & c,const FillLayer * fillLayer,int tx,int ty,int width,int height,BackgroundBleedAvoidance bleedAvoidance,CompositeOperator op,RenderObject * backgroundObject)987 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, int tx, int ty, int width, int height,
988     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
989 {
990     if (!fillLayer)
991         return;
992 
993     paintFillLayers(paintInfo, c, fillLayer->next(), tx, ty, width, height, bleedAvoidance, op, backgroundObject);
994     paintFillLayer(paintInfo, c, fillLayer, tx, ty, width, height, bleedAvoidance, op, backgroundObject);
995 }
996 
paintFillLayer(const PaintInfo & paintInfo,const Color & c,const FillLayer * fillLayer,int tx,int ty,int width,int height,BackgroundBleedAvoidance bleedAvoidance,CompositeOperator op,RenderObject * backgroundObject)997 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, int tx, int ty, int width, int height,
998     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
999 {
1000     paintFillLayerExtended(paintInfo, c, fillLayer, tx, ty, width, height, bleedAvoidance, 0, 0, 0, op, backgroundObject);
1001 }
1002 
1003 #if USE(ACCELERATED_COMPOSITING)
layersUseImage(WrappedImagePtr image,const FillLayer * layers)1004 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1005 {
1006     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1007         if (curLayer->image() && image == curLayer->image()->data())
1008             return true;
1009     }
1010 
1011     return false;
1012 }
1013 #endif
1014 
imageChanged(WrappedImagePtr image,const IntRect *)1015 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1016 {
1017     if (!parent())
1018         return;
1019 
1020     if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1021         (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1022         repaint();
1023         return;
1024     }
1025 
1026     bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
1027     if (!didFullRepaint)
1028         repaintLayerRectsForImage(image, style()->maskLayers(), false);
1029 
1030 
1031 #if USE(ACCELERATED_COMPOSITING)
1032     if (hasLayer() && layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
1033         layer()->contentChanged(RenderLayer::MaskImageChanged);
1034 #endif
1035 }
1036 
repaintLayerRectsForImage(WrappedImagePtr image,const FillLayer * layers,bool drawingBackground)1037 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1038 {
1039     IntRect rendererRect;
1040     RenderBox* layerRenderer = 0;
1041 
1042     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1043         if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(style()->effectiveZoom())) {
1044             // Now that we know this image is being used, compute the renderer and the rect
1045             // if we haven't already
1046             if (!layerRenderer) {
1047                 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document()->documentElement()->renderer()->hasBackground()));
1048                 if (drawingRootBackground) {
1049                     layerRenderer = view();
1050 
1051                     int rw;
1052                     int rh;
1053 
1054                     if (FrameView* frameView = toRenderView(layerRenderer)->frameView()) {
1055                         rw = frameView->contentsWidth();
1056                         rh = frameView->contentsHeight();
1057                     } else {
1058                         rw = layerRenderer->width();
1059                         rh = layerRenderer->height();
1060                     }
1061                     rendererRect = IntRect(-layerRenderer->marginLeft(),
1062                         -layerRenderer->marginTop(),
1063                         max(layerRenderer->width() + layerRenderer->marginLeft() + layerRenderer->marginRight() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1064                         max(layerRenderer->height() + layerRenderer->marginTop() + layerRenderer->marginBottom() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1065                 } else {
1066                     layerRenderer = this;
1067                     rendererRect = borderBoxRect();
1068                 }
1069             }
1070 
1071             IntRect repaintRect;
1072             IntPoint phase;
1073             IntSize tileSize;
1074             layerRenderer->calculateBackgroundImageGeometry(curLayer, rendererRect.x(), rendererRect.y(), rendererRect.width(), rendererRect.height(), repaintRect, phase, tileSize);
1075             layerRenderer->repaintRectangle(repaintRect);
1076             if (repaintRect == rendererRect)
1077                 return true;
1078         }
1079     }
1080     return false;
1081 }
1082 
1083 #if PLATFORM(MAC)
1084 
paintCustomHighlight(int tx,int ty,const AtomicString & type,bool behindText)1085 void RenderBox::paintCustomHighlight(int tx, int ty, const AtomicString& type, bool behindText)
1086 {
1087     Frame* frame = this->frame();
1088     if (!frame)
1089         return;
1090     Page* page = frame->page();
1091     if (!page)
1092         return;
1093 
1094     InlineBox* boxWrap = inlineBoxWrapper();
1095     RootInlineBox* r = boxWrap ? boxWrap->root() : 0;
1096     if (r) {
1097         FloatRect rootRect(tx + r->x(), ty + r->selectionTop(), r->logicalWidth(), r->selectionHeight());
1098         FloatRect imageRect(tx + x(), rootRect.y(), width(), rootRect.height());
1099         page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, rootRect, behindText, false);
1100     } else {
1101         FloatRect imageRect(tx + x(), ty + y(), width(), height());
1102         page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, imageRect, behindText, false);
1103     }
1104 }
1105 
1106 #endif
1107 
pushContentsClip(PaintInfo & paintInfo,int tx,int ty)1108 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, int tx, int ty)
1109 {
1110     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1111         return false;
1112 
1113     bool isControlClip = hasControlClip();
1114     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1115 
1116     if (!isControlClip && !isOverflowClip)
1117         return false;
1118 
1119     if (paintInfo.phase == PaintPhaseOutline)
1120         paintInfo.phase = PaintPhaseChildOutlines;
1121     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1122         paintInfo.phase = PaintPhaseBlockBackground;
1123         paintObject(paintInfo, tx, ty);
1124         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1125     }
1126     IntRect clipRect(isControlClip ? controlClipRect(tx, ty) : overflowClipRect(tx, ty));
1127     paintInfo.context->save();
1128     if (style()->hasBorderRadius())
1129         paintInfo.context->addRoundedRectClip(style()->getRoundedBorderFor(IntRect(tx, ty, width(), height())));
1130     paintInfo.context->clip(clipRect);
1131     return true;
1132 }
1133 
popContentsClip(PaintInfo & paintInfo,PaintPhase originalPhase,int tx,int ty)1134 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, int tx, int ty)
1135 {
1136     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1137 
1138     paintInfo.context->restore();
1139     if (originalPhase == PaintPhaseOutline) {
1140         paintInfo.phase = PaintPhaseSelfOutline;
1141         paintObject(paintInfo, tx, ty);
1142         paintInfo.phase = originalPhase;
1143     } else if (originalPhase == PaintPhaseChildBlockBackground)
1144         paintInfo.phase = originalPhase;
1145 }
1146 
overflowClipRect(int tx,int ty,OverlayScrollbarSizeRelevancy relevancy)1147 IntRect RenderBox::overflowClipRect(int tx, int ty, OverlayScrollbarSizeRelevancy relevancy)
1148 {
1149     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1150     // here.
1151 
1152     int bLeft = borderLeft();
1153     int bTop = borderTop();
1154 
1155     int clipX = tx + bLeft;
1156     int clipY = ty + bTop;
1157     int clipWidth = width() - bLeft - borderRight();
1158     int clipHeight = height() - bTop - borderBottom();
1159 
1160     // Subtract out scrollbars if we have them.
1161     if (layer()) {
1162         clipWidth -= layer()->verticalScrollbarWidth(relevancy);
1163         clipHeight -= layer()->horizontalScrollbarHeight(relevancy);
1164     }
1165 
1166     return IntRect(clipX, clipY, clipWidth, clipHeight);
1167 }
1168 
clipRect(int tx,int ty)1169 IntRect RenderBox::clipRect(int tx, int ty)
1170 {
1171     int clipX = tx;
1172     int clipY = ty;
1173     int clipWidth = width();
1174     int clipHeight = height();
1175 
1176     if (!style()->clipLeft().isAuto()) {
1177         int c = style()->clipLeft().calcValue(width());
1178         clipX += c;
1179         clipWidth -= c;
1180     }
1181 
1182     if (!style()->clipRight().isAuto())
1183         clipWidth -= width() - style()->clipRight().calcValue(width());
1184 
1185     if (!style()->clipTop().isAuto()) {
1186         int c = style()->clipTop().calcValue(height());
1187         clipY += c;
1188         clipHeight -= c;
1189     }
1190 
1191     if (!style()->clipBottom().isAuto())
1192         clipHeight -= height() - style()->clipBottom().calcValue(height());
1193 
1194     return IntRect(clipX, clipY, clipWidth, clipHeight);
1195 }
1196 
containingBlockLogicalWidthForContent() const1197 int RenderBox::containingBlockLogicalWidthForContent() const
1198 {
1199     RenderBlock* cb = containingBlock();
1200     if (shrinkToAvoidFloats())
1201         return cb->availableLogicalWidthForLine(y(), false);
1202     return cb->availableLogicalWidth();
1203 }
1204 
perpendicularContainingBlockLogicalHeight() const1205 int RenderBox::perpendicularContainingBlockLogicalHeight() const
1206 {
1207     RenderBlock* cb = containingBlock();
1208     RenderStyle* containingBlockStyle = cb->style();
1209     Length logicalHeightLength = containingBlockStyle->logicalHeight();
1210 
1211     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1212     if (!logicalHeightLength.isFixed()) {
1213         // Rather than making the child be completely unconstrained, WinIE uses the viewport width and height
1214         // as a constraint.  We do that for now as well even though it's likely being unconstrained is what the spec
1215         // will decide.
1216         return containingBlockStyle->isHorizontalWritingMode() ? view()->frameView()->visibleHeight() : view()->frameView()->visibleWidth();
1217     }
1218 
1219     // Use the content box logical height as specified by the style.
1220     return cb->computeContentBoxLogicalHeight(logicalHeightLength.value());
1221 }
1222 
mapLocalToContainer(RenderBoxModelObject * repaintContainer,bool fixed,bool useTransforms,TransformState & transformState) const1223 void RenderBox::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState) const
1224 {
1225     if (repaintContainer == this)
1226         return;
1227 
1228     if (RenderView* v = view()) {
1229         if (v->layoutStateEnabled() && !repaintContainer) {
1230             LayoutState* layoutState = v->layoutState();
1231             IntSize offset = layoutState->m_paintOffset;
1232             offset.expand(x(), y());
1233             if (style()->position() == RelativePosition && layer())
1234                 offset += layer()->relativePositionOffset();
1235             transformState.move(offset);
1236             return;
1237         }
1238     }
1239 
1240     bool containerSkipped;
1241     RenderObject* o = container(repaintContainer, &containerSkipped);
1242     if (!o)
1243         return;
1244 
1245     bool isFixedPos = style()->position() == FixedPosition;
1246     bool hasTransform = hasLayer() && layer()->transform();
1247     if (hasTransform) {
1248         // If this box has a transform, it acts as a fixed position container for fixed descendants,
1249         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1250         fixed &= isFixedPos;
1251     } else
1252         fixed |= isFixedPos;
1253 
1254     IntSize containerOffset = offsetFromContainer(o, roundedIntPoint(transformState.mappedPoint()));
1255 
1256     bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1257     if (useTransforms && shouldUseTransformFromContainer(o)) {
1258         TransformationMatrix t;
1259         getTransformFromContainer(o, containerOffset, t);
1260         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1261     } else
1262         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1263 
1264     if (containerSkipped) {
1265         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1266         // to just subtract the delta between the repaintContainer and o.
1267         IntSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1268         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1269         return;
1270     }
1271 
1272     o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState);
1273 }
1274 
mapAbsoluteToLocalPoint(bool fixed,bool useTransforms,TransformState & transformState) const1275 void RenderBox::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1276 {
1277     // We don't expect absoluteToLocal() to be called during layout (yet)
1278     ASSERT(!view() || !view()->layoutStateEnabled());
1279 
1280     bool isFixedPos = style()->position() == FixedPosition;
1281     bool hasTransform = hasLayer() && layer()->transform();
1282     if (hasTransform) {
1283         // If this box has a transform, it acts as a fixed position container for fixed descendants,
1284         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1285         fixed &= isFixedPos;
1286     } else
1287         fixed |= isFixedPos;
1288 
1289     RenderObject* o = container();
1290     if (!o)
1291         return;
1292 
1293     o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1294 
1295     IntSize containerOffset = offsetFromContainer(o, IntPoint());
1296 
1297     bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1298     if (useTransforms && shouldUseTransformFromContainer(o)) {
1299         TransformationMatrix t;
1300         getTransformFromContainer(o, containerOffset, t);
1301         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1302     } else
1303         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1304 }
1305 
offsetFromContainer(RenderObject * o,const IntPoint & point) const1306 IntSize RenderBox::offsetFromContainer(RenderObject* o, const IntPoint& point) const
1307 {
1308     ASSERT(o == container());
1309 
1310     IntSize offset;
1311     if (isRelPositioned())
1312         offset += relativePositionOffset();
1313 
1314     if (!isInline() || isReplaced()) {
1315         if (style()->position() != AbsolutePosition && style()->position() != FixedPosition) {
1316             if (o->hasColumns()) {
1317                 IntRect columnRect(frameRect());
1318                 toRenderBlock(o)->flipForWritingModeIncludingColumns(columnRect);
1319                 offset += IntSize(columnRect.location().x(), columnRect.location().y());
1320                 columnRect.move(point.x(), point.y());
1321                 o->adjustForColumns(offset, columnRect.location());
1322             } else
1323                 offset += locationOffsetIncludingFlipping();
1324         } else
1325             offset += locationOffsetIncludingFlipping();
1326     }
1327 
1328     if (o->hasOverflowClip())
1329         offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1330 
1331     if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1332         offset += toRenderInline(o)->relativePositionedInlineOffset(this);
1333 
1334     return offset;
1335 }
1336 
createInlineBox()1337 InlineBox* RenderBox::createInlineBox()
1338 {
1339     return new (renderArena()) InlineBox(this);
1340 }
1341 
dirtyLineBoxes(bool fullLayout)1342 void RenderBox::dirtyLineBoxes(bool fullLayout)
1343 {
1344     if (m_inlineBoxWrapper) {
1345         if (fullLayout) {
1346             m_inlineBoxWrapper->destroy(renderArena());
1347             m_inlineBoxWrapper = 0;
1348         } else
1349             m_inlineBoxWrapper->dirtyLineBoxes();
1350     }
1351 }
1352 
positionLineBox(InlineBox * box)1353 void RenderBox::positionLineBox(InlineBox* box)
1354 {
1355     if (isPositioned()) {
1356         // Cache the x position only if we were an INLINE type originally.
1357         bool wasInline = style()->isOriginalDisplayInlineType();
1358         if (wasInline) {
1359             // The value is cached in the xPos of the box.  We only need this value if
1360             // our object was inline originally, since otherwise it would have ended up underneath
1361             // the inlines.
1362             layer()->setStaticInlinePosition(lroundf(box->logicalLeft()));
1363             if (style()->hasStaticInlinePosition(box->isHorizontal()))
1364                 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1365         } else {
1366             // Our object was a block originally, so we make our normal flow position be
1367             // just below the line box (as though all the inlines that came before us got
1368             // wrapped in an anonymous block, which is what would have happened had we been
1369             // in flow).  This value was cached in the y() of the box.
1370             layer()->setStaticBlockPosition(box->logicalTop());
1371             if (style()->hasStaticBlockPosition(box->isHorizontal()))
1372                 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1373         }
1374 
1375         // Nuke the box.
1376         box->remove();
1377         box->destroy(renderArena());
1378     } else if (isReplaced()) {
1379         setLocation(lroundf(box->x()), lroundf(box->y()));
1380         if (m_inlineBoxWrapper)
1381             deleteLineBoxWrapper();
1382         m_inlineBoxWrapper = box;
1383     }
1384 }
1385 
deleteLineBoxWrapper()1386 void RenderBox::deleteLineBoxWrapper()
1387 {
1388     if (m_inlineBoxWrapper) {
1389         if (!documentBeingDestroyed())
1390             m_inlineBoxWrapper->remove();
1391         m_inlineBoxWrapper->destroy(renderArena());
1392         m_inlineBoxWrapper = 0;
1393     }
1394 }
1395 
clippedOverflowRectForRepaint(RenderBoxModelObject * repaintContainer)1396 IntRect RenderBox::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer)
1397 {
1398     if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
1399         return IntRect();
1400 
1401     IntRect r = visualOverflowRect();
1402 
1403     RenderView* v = view();
1404     if (v) {
1405         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1406         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1407         r.move(v->layoutDelta());
1408     }
1409 
1410     if (style()) {
1411         if (style()->hasAppearance())
1412             // The theme may wish to inflate the rect used when repainting.
1413             theme()->adjustRepaintRect(this, r);
1414 
1415         // We have to use maximalOutlineSize() because a child might have an outline
1416         // that projects outside of our overflowRect.
1417         if (v) {
1418             ASSERT(style()->outlineSize() <= v->maximalOutlineSize());
1419             r.inflate(v->maximalOutlineSize());
1420         }
1421     }
1422 
1423     computeRectForRepaint(repaintContainer, r);
1424     return r;
1425 }
1426 
computeRectForRepaint(RenderBoxModelObject * repaintContainer,IntRect & rect,bool fixed)1427 void RenderBox::computeRectForRepaint(RenderBoxModelObject* repaintContainer, IntRect& rect, bool fixed)
1428 {
1429     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1430     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1431     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
1432     // properly even during layout, since the rect remains flipped all the way until the end.
1433     //
1434     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
1435     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
1436     // physical coordinate space of the repaintContainer.
1437     if (RenderView* v = view()) {
1438         // LayoutState is only valid for root-relative, non-fixed position repainting
1439         if (v->layoutStateEnabled() && !repaintContainer && style()->position() != FixedPosition) {
1440             LayoutState* layoutState = v->layoutState();
1441 
1442             if (layer() && layer()->transform())
1443                 rect = layer()->transform()->mapRect(rect);
1444 
1445             if (style()->position() == RelativePosition && layer())
1446                 rect.move(layer()->relativePositionOffset());
1447 
1448             rect.move(x(), y());
1449             rect.move(layoutState->m_paintOffset);
1450             if (layoutState->m_clipped)
1451                 rect.intersect(layoutState->m_clipRect);
1452             return;
1453         }
1454     }
1455 
1456     if (hasReflection())
1457         rect.unite(reflectedRect(rect));
1458 
1459     if (repaintContainer == this) {
1460         if (repaintContainer->style()->isFlippedBlocksWritingMode())
1461             flipForWritingMode(rect);
1462         return;
1463     }
1464 
1465     bool containerSkipped;
1466     RenderObject* o = container(repaintContainer, &containerSkipped);
1467     if (!o)
1468         return;
1469 
1470     if (isWritingModeRoot() && !isPositioned())
1471         flipForWritingMode(rect);
1472     IntPoint topLeft = rect.location();
1473     topLeft.move(x(), y());
1474 
1475     EPosition position = style()->position();
1476 
1477     // We are now in our parent container's coordinate space.  Apply our transform to obtain a bounding box
1478     // in the parent's coordinate space that encloses us.
1479     if (layer() && layer()->transform()) {
1480         fixed = position == FixedPosition;
1481         rect = layer()->transform()->mapRect(rect);
1482         topLeft = rect.location();
1483         topLeft.move(x(), y());
1484     } else if (position == FixedPosition)
1485         fixed = true;
1486 
1487     if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1488         topLeft += toRenderInline(o)->relativePositionedInlineOffset(this);
1489     else if (position == RelativePosition && layer()) {
1490         // Apply the relative position offset when invalidating a rectangle.  The layer
1491         // is translated, but the render box isn't, so we need to do this to get the
1492         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
1493         // flag on the RenderObject has been cleared, so use the one on the style().
1494         topLeft += layer()->relativePositionOffset();
1495     }
1496 
1497     if (o->isBlockFlow() && position != AbsolutePosition && position != FixedPosition) {
1498         RenderBlock* cb = toRenderBlock(o);
1499         if (cb->hasColumns()) {
1500             IntRect repaintRect(topLeft, rect.size());
1501             cb->adjustRectForColumns(repaintRect);
1502             topLeft = repaintRect.location();
1503             rect = repaintRect;
1504         }
1505     }
1506 
1507     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1508     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1509     if (o->hasOverflowClip()) {
1510         RenderBox* containerBox = toRenderBox(o);
1511 
1512         // o->height() is inaccurate if we're in the middle of a layout of |o|, so use the
1513         // layer's size instead.  Even if the layer's size is wrong, the layer itself will repaint
1514         // anyway if its size does change.
1515         topLeft -= containerBox->layer()->scrolledContentOffset(); // For overflow:auto/scroll/hidden.
1516 
1517         IntRect repaintRect(topLeft, rect.size());
1518         IntRect boxRect(0, 0, containerBox->layer()->width(), containerBox->layer()->height());
1519         rect = intersection(repaintRect, boxRect);
1520         if (rect.isEmpty())
1521             return;
1522     } else
1523         rect.setLocation(topLeft);
1524 
1525     if (containerSkipped) {
1526         // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
1527         IntSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1528         rect.move(-containerOffset);
1529         return;
1530     }
1531 
1532     o->computeRectForRepaint(repaintContainer, rect, fixed);
1533 }
1534 
repaintDuringLayoutIfMoved(const IntRect & rect)1535 void RenderBox::repaintDuringLayoutIfMoved(const IntRect& rect)
1536 {
1537     int newX = x();
1538     int newY = y();
1539     int newWidth = width();
1540     int newHeight = height();
1541     if (rect.x() != newX || rect.y() != newY) {
1542         // The child moved.  Invalidate the object's old and new positions.  We have to do this
1543         // since the object may not have gotten a layout.
1544         m_frameRect = rect;
1545         repaint();
1546         repaintOverhangingFloats(true);
1547         m_frameRect = IntRect(newX, newY, newWidth, newHeight);
1548         repaint();
1549         repaintOverhangingFloats(true);
1550     }
1551 }
1552 
computeLogicalWidth()1553 void RenderBox::computeLogicalWidth()
1554 {
1555     if (isPositioned()) {
1556         // FIXME: This calculation is not patched for block-flow yet.
1557         // https://bugs.webkit.org/show_bug.cgi?id=46500
1558         computePositionedLogicalWidth();
1559         return;
1560     }
1561 
1562     // If layout is limited to a subtree, the subtree root's logical width does not change.
1563     if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1564         return;
1565 
1566     // The parent box is flexing us, so it has increased or decreased our
1567     // width.  Use the width from the style context.
1568     // FIXME: Account for block-flow in flexible boxes.
1569     // https://bugs.webkit.org/show_bug.cgi?id=46418
1570     if (hasOverrideSize() &&  parent()->style()->boxOrient() == HORIZONTAL
1571             && parent()->isFlexibleBox() && parent()->isFlexingChildren()) {
1572         setLogicalWidth(overrideSize());
1573         return;
1574     }
1575 
1576     // FIXME: Account for block-flow in flexible boxes.
1577     // https://bugs.webkit.org/show_bug.cgi?id=46418
1578     bool inVerticalBox = parent()->isFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1579     bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1580     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1581 
1582     Length logicalWidthLength = (treatAsReplaced) ? Length(computeReplacedLogicalWidth(), Fixed) : style()->logicalWidth();
1583 
1584     RenderBlock* cb = containingBlock();
1585     int containerLogicalWidth = max(0, containingBlockLogicalWidthForContent());
1586     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1587     int containerWidthInInlineDirection = containerLogicalWidth;
1588     if (hasPerpendicularContainingBlock)
1589         containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1590 
1591     if (isInline() && !isInlineBlockOrInlineTable()) {
1592         // just calculate margins
1593         setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1594         setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1595         if (treatAsReplaced)
1596             setLogicalWidth(max(logicalWidthLength.value() + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth()));
1597         return;
1598     }
1599 
1600     // Width calculations
1601     if (treatAsReplaced)
1602         setLogicalWidth(logicalWidthLength.value() + borderAndPaddingLogicalWidth());
1603     else {
1604         // Calculate LogicalWidth
1605         setLogicalWidth(computeLogicalWidthUsing(LogicalWidth, containerWidthInInlineDirection));
1606 
1607         // Calculate MaxLogicalWidth
1608         if (!style()->logicalMaxWidth().isUndefined()) {
1609             int maxLogicalWidth = computeLogicalWidthUsing(MaxLogicalWidth, containerWidthInInlineDirection);
1610             if (logicalWidth() > maxLogicalWidth) {
1611                 setLogicalWidth(maxLogicalWidth);
1612                 logicalWidthLength = style()->logicalMaxWidth();
1613             }
1614         }
1615 
1616         // Calculate MinLogicalWidth
1617         int minLogicalWidth = computeLogicalWidthUsing(MinLogicalWidth, containerWidthInInlineDirection);
1618         if (logicalWidth() < minLogicalWidth) {
1619             setLogicalWidth(minLogicalWidth);
1620             logicalWidthLength = style()->logicalMinWidth();
1621         }
1622     }
1623 
1624     // Fieldsets are currently the only objects that stretch to their minimum width.
1625     if (stretchesToMinIntrinsicLogicalWidth()) {
1626         setLogicalWidth(max(logicalWidth(), minPreferredLogicalWidth()));
1627         logicalWidthLength = Length(logicalWidth(), Fixed);
1628     }
1629 
1630     // Margin calculations.
1631     if (logicalWidthLength.isAuto() || hasPerpendicularContainingBlock || isFloating() || isInline()) {
1632         setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1633         setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1634     } else
1635         computeInlineDirectionMargins(cb, containerLogicalWidth, logicalWidth());
1636 
1637     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (logicalWidth() + marginStart() + marginEnd())
1638             && !isFloating() && !isInline() && !cb->isFlexibleBox())
1639         cb->setMarginEndForChild(this, containerLogicalWidth - logicalWidth() - cb->marginStartForChild(this));
1640 }
1641 
computeLogicalWidthUsing(LogicalWidthType widthType,int availableLogicalWidth)1642 int RenderBox::computeLogicalWidthUsing(LogicalWidthType widthType, int availableLogicalWidth)
1643 {
1644     int logicalWidthResult = logicalWidth();
1645     Length logicalWidth;
1646     if (widthType == LogicalWidth)
1647         logicalWidth = style()->logicalWidth();
1648     else if (widthType == MinLogicalWidth)
1649         logicalWidth = style()->logicalMinWidth();
1650     else
1651         logicalWidth = style()->logicalMaxWidth();
1652 
1653     if (logicalWidth.isIntrinsicOrAuto()) {
1654         int marginStart = style()->marginStart().calcMinValue(availableLogicalWidth);
1655         int marginEnd = style()->marginEnd().calcMinValue(availableLogicalWidth);
1656         if (availableLogicalWidth)
1657             logicalWidthResult = availableLogicalWidth - marginStart - marginEnd;
1658 
1659         if (sizesToIntrinsicLogicalWidth(widthType)) {
1660             logicalWidthResult = max(logicalWidthResult, minPreferredLogicalWidth());
1661             logicalWidthResult = min(logicalWidthResult, maxPreferredLogicalWidth());
1662         }
1663     } else // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
1664         logicalWidthResult = computeBorderBoxLogicalWidth(logicalWidth.calcValue(availableLogicalWidth));
1665 
1666     return logicalWidthResult;
1667 }
1668 
sizesToIntrinsicLogicalWidth(LogicalWidthType widthType) const1669 bool RenderBox::sizesToIntrinsicLogicalWidth(LogicalWidthType widthType) const
1670 {
1671     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
1672     // but they allow text to sit on the same line as the marquee.
1673     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
1674         return true;
1675 
1676     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
1677     // min-width and width.  max-width is only clamped if it is also intrinsic.
1678     Length logicalWidth = (widthType == MaxLogicalWidth) ? style()->logicalMaxWidth() : style()->logicalWidth();
1679     if (logicalWidth.type() == Intrinsic)
1680         return true;
1681 
1682     // Children of a horizontal marquee do not fill the container by default.
1683     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
1684     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
1685     // block-flow (as well as how marquee overflow should relate to block flow).
1686     // https://bugs.webkit.org/show_bug.cgi?id=46472
1687     if (parent()->style()->overflowX() == OMARQUEE) {
1688         EMarqueeDirection dir = parent()->style()->marqueeDirection();
1689         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
1690             return true;
1691     }
1692 
1693     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
1694     // that don't stretch their kids lay out their children at their intrinsic widths.
1695     // FIXME: Think about block-flow here.
1696     // https://bugs.webkit.org/show_bug.cgi?id=46473
1697     if (parent()->isFlexibleBox()
1698             && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
1699         return true;
1700 
1701     // Button, input, select, textarea, and legend treat
1702     // width value of 'auto' as 'intrinsic' unless it's in a
1703     // stretching vertical flexbox.
1704     // FIXME: Think about block-flow here.
1705     // https://bugs.webkit.org/show_bug.cgi?id=46473
1706     if (logicalWidth.type() == Auto && !(parent()->isFlexibleBox() && parent()->style()->boxOrient() == VERTICAL && parent()->style()->boxAlign() == BSTRETCH) && node() && (node()->hasTagName(inputTag) || node()->hasTagName(selectTag) || node()->hasTagName(buttonTag) || node()->hasTagName(textareaTag) || node()->hasTagName(legendTag)))
1707         return true;
1708 
1709     return false;
1710 }
1711 
computeInlineDirectionMargins(RenderBlock * containingBlock,int containerWidth,int childWidth)1712 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, int containerWidth, int childWidth)
1713 {
1714     const RenderStyle* containingBlockStyle = containingBlock->style();
1715     Length marginStartLength = style()->marginStartUsing(containingBlockStyle);
1716     Length marginEndLength = style()->marginEndUsing(containingBlockStyle);
1717 
1718     // Case One: The object is being centered in the containing block's available logical width.
1719     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
1720         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
1721         containingBlock->setMarginStartForChild(this, max(0, (containerWidth - childWidth) / 2));
1722         containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1723         return;
1724     }
1725 
1726     // Case Two: The object is being pushed to the start of the containing block's available logical width.
1727     if (marginEndLength.isAuto() && childWidth < containerWidth) {
1728         containingBlock->setMarginStartForChild(this, marginStartLength.calcValue(containerWidth));
1729         containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1730         return;
1731     }
1732 
1733     // Case Three: The object is being pushed to the end of the containing block's available logical width.
1734     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
1735         || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
1736     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
1737         containingBlock->setMarginEndForChild(this, marginEndLength.calcValue(containerWidth));
1738         containingBlock->setMarginStartForChild(this, containerWidth - childWidth - containingBlock->marginEndForChild(this));
1739         return;
1740     }
1741 
1742     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
1743     // auto margins will just turn into 0.
1744     containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1745     containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1746 }
1747 
computeLogicalHeight()1748 void RenderBox::computeLogicalHeight()
1749 {
1750     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
1751     if (isTableCell() || (isInline() && !isReplaced()))
1752         return;
1753 
1754     Length h;
1755     if (isPositioned()) {
1756         // FIXME: This calculation is not patched for block-flow yet.
1757         // https://bugs.webkit.org/show_bug.cgi?id=46500
1758         computePositionedLogicalHeight();
1759     } else {
1760         RenderBlock* cb = containingBlock();
1761         bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1762 
1763         if (!hasPerpendicularContainingBlock)
1764             computeBlockDirectionMargins(cb);
1765 
1766         // For tables, calculate margins only.
1767         if (isTable()) {
1768             if (hasPerpendicularContainingBlock)
1769                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), logicalHeight());
1770             return;
1771         }
1772 
1773         // FIXME: Account for block-flow in flexible boxes.
1774         // https://bugs.webkit.org/show_bug.cgi?id=46418
1775         bool inHorizontalBox = parent()->isFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
1776         bool stretching = parent()->style()->boxAlign() == BSTRETCH;
1777         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
1778         bool checkMinMaxHeight = false;
1779 
1780         // The parent box is flexing us, so it has increased or decreased our height.  We have to
1781         // grab our cached flexible height.
1782         // FIXME: Account for block-flow in flexible boxes.
1783         // https://bugs.webkit.org/show_bug.cgi?id=46418
1784         if (hasOverrideSize() && parent()->isFlexibleBox() && parent()->style()->boxOrient() == VERTICAL
1785                 && parent()->isFlexingChildren())
1786             h = Length(overrideSize() - borderAndPaddingLogicalHeight(), Fixed);
1787         else if (treatAsReplaced)
1788             h = Length(computeReplacedLogicalHeight(), Fixed);
1789         else {
1790             h = style()->logicalHeight();
1791             checkMinMaxHeight = true;
1792         }
1793 
1794         // Block children of horizontal flexible boxes fill the height of the box.
1795         // FIXME: Account for block-flow in flexible boxes.
1796         // https://bugs.webkit.org/show_bug.cgi?id=46418
1797         if (h.isAuto() && parent()->isFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
1798                 && parent()->isStretchingChildren()) {
1799             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
1800             checkMinMaxHeight = false;
1801         }
1802 
1803         int heightResult;
1804         if (checkMinMaxHeight) {
1805             heightResult = computeLogicalHeightUsing(style()->logicalHeight());
1806             if (heightResult == -1)
1807                 heightResult = logicalHeight();
1808             int minH = computeLogicalHeightUsing(style()->logicalMinHeight()); // Leave as -1 if unset.
1809             int maxH = style()->logicalMaxHeight().isUndefined() ? heightResult : computeLogicalHeightUsing(style()->logicalMaxHeight());
1810             if (maxH == -1)
1811                 maxH = heightResult;
1812             heightResult = min(maxH, heightResult);
1813             heightResult = max(minH, heightResult);
1814         } else {
1815             // The only times we don't check min/max height are when a fixed length has
1816             // been given as an override.  Just use that.  The value has already been adjusted
1817             // for box-sizing.
1818             heightResult = h.value() + borderAndPaddingLogicalHeight();
1819         }
1820 
1821         setLogicalHeight(heightResult);
1822 
1823         if (hasPerpendicularContainingBlock)
1824             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult);
1825     }
1826 
1827     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
1828     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
1829     // is specified. When we're printing, we also need this quirk if the body or root has a percentage
1830     // height since we don't set a height in RenderView when we're printing. So without this quirk, the
1831     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
1832     bool paginatedContentNeedsBaseHeight = document()->printing() && h.isPercent()
1833         && (isRoot() || (isBody() && document()->documentElement()->renderer()->style()->logicalHeight().isPercent()));
1834     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
1835         // FIXME: Finish accounting for block flow here.
1836         // https://bugs.webkit.org/show_bug.cgi?id=46603
1837         int margins = collapsedMarginBefore() + collapsedMarginAfter();
1838         int visHeight;
1839         if (document()->printing())
1840             visHeight = static_cast<int>(view()->pageLogicalHeight());
1841         else  {
1842             if (isHorizontalWritingMode())
1843                 visHeight = view()->viewHeight();
1844             else
1845                 visHeight = view()->viewWidth();
1846         }
1847         if (isRoot())
1848             setLogicalHeight(max(logicalHeight(), visHeight - margins));
1849         else {
1850             int marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
1851             setLogicalHeight(max(logicalHeight(), visHeight - marginsBordersPadding));
1852         }
1853     }
1854 }
1855 
computeLogicalHeightUsing(const Length & h)1856 int RenderBox::computeLogicalHeightUsing(const Length& h)
1857 {
1858     int logicalHeight = -1;
1859     if (!h.isAuto()) {
1860         if (h.isFixed())
1861             logicalHeight = h.value();
1862         else if (h.isPercent())
1863             logicalHeight = computePercentageLogicalHeight(h);
1864         if (logicalHeight != -1) {
1865             logicalHeight = computeBorderBoxLogicalHeight(logicalHeight);
1866             return logicalHeight;
1867         }
1868     }
1869     return logicalHeight;
1870 }
1871 
computePercentageLogicalHeight(const Length & height)1872 int RenderBox::computePercentageLogicalHeight(const Length& height)
1873 {
1874     int result = -1;
1875 
1876     // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
1877     // block that may have a specified height and then use it. In strict mode, this violates the
1878     // specification, which states that percentage heights just revert to auto if the containing
1879     // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
1880     // only at explicit containers.
1881     bool skippedAutoHeightContainingBlock = false;
1882     RenderBlock* cb = containingBlock();
1883     while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isPositioned() && cb->style()->logicalHeight().isAuto()) {
1884         if (!document()->inQuirksMode() && !cb->isAnonymousBlock())
1885             break;
1886         skippedAutoHeightContainingBlock = true;
1887         cb = cb->containingBlock();
1888         cb->addPercentHeightDescendant(this);
1889     }
1890 
1891     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
1892     // explicitly specified that can be used for any percentage computations.
1893     // FIXME: We can't just check top/bottom here.
1894     // https://bugs.webkit.org/show_bug.cgi?id=46500
1895     bool isPositionedWithSpecifiedHeight = cb->isPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
1896 
1897     bool includeBorderPadding = isTable();
1898 
1899     // Table cells violate what the CSS spec says to do with heights.  Basically we
1900     // don't care if the cell specified a height or not.  We just always make ourselves
1901     // be a percentage of the cell's current content height.
1902     if (cb->isTableCell()) {
1903         if (!skippedAutoHeightContainingBlock) {
1904             result = cb->overrideSize();
1905             if (result == -1) {
1906                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
1907                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
1908                 // While we can't get all cases right, we can at least detect when the cell has a specified
1909                 // height or when the table has a specified height.  In these cases we want to initially have
1910                 // no size and allow the flexing of the table or the cell to its specified height to cause us
1911                 // to grow to fill the space.  This could end up being wrong in some cases, but it is
1912                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
1913                 RenderTableCell* cell = toRenderTableCell(cb);
1914                 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
1915                     return 0;
1916                 return -1;
1917             }
1918             includeBorderPadding = true;
1919         }
1920     }
1921     // Otherwise we only use our percentage height if our containing block had a specified
1922     // height.
1923     else if (cb->style()->logicalHeight().isFixed())
1924         result = cb->computeContentBoxLogicalHeight(cb->style()->logicalHeight().value());
1925     else if (cb->style()->logicalHeight().isPercent() && !isPositionedWithSpecifiedHeight) {
1926         // We need to recur and compute the percentage height for our containing block.
1927         result = cb->computePercentageLogicalHeight(cb->style()->logicalHeight());
1928         if (result != -1)
1929             result = cb->computeContentBoxLogicalHeight(result);
1930     } else if (cb->isRenderView() || (cb->isBody() && document()->inQuirksMode()) || isPositionedWithSpecifiedHeight) {
1931         // Don't allow this to affect the block' height() member variable, since this
1932         // can get called while the block is still laying out its kids.
1933         int oldHeight = cb->logicalHeight();
1934         cb->computeLogicalHeight();
1935         result = cb->contentLogicalHeight();
1936         cb->setLogicalHeight(oldHeight);
1937     } else if (cb->isRoot() && isPositioned())
1938         // Match the positioned objects behavior, which is that positioned objects will fill their viewport
1939         // always.  Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
1940         result = cb->computeContentBoxLogicalHeight(cb->availableLogicalHeight());
1941 
1942     if (result != -1) {
1943         result = height.calcValue(result);
1944         if (includeBorderPadding) {
1945             // It is necessary to use the border-box to match WinIE's broken
1946             // box model.  This is essential for sizing inside
1947             // table cells using percentage heights.
1948             result -= borderAndPaddingLogicalHeight();
1949             result = max(0, result);
1950         }
1951     }
1952     return result;
1953 }
1954 
computeReplacedLogicalWidth(bool includeMaxWidth) const1955 int RenderBox::computeReplacedLogicalWidth(bool includeMaxWidth) const
1956 {
1957     int logicalWidth = computeReplacedLogicalWidthUsing(style()->logicalWidth());
1958     int minLogicalWidth = computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
1959     int maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
1960 
1961     return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
1962 }
1963 
computeReplacedLogicalWidthUsing(Length logicalWidth) const1964 int RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
1965 {
1966     switch (logicalWidth.type()) {
1967         case Fixed:
1968             return computeContentBoxLogicalWidth(logicalWidth.value());
1969         case Percent: {
1970             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
1971             // containing block's block-flow.
1972             // https://bugs.webkit.org/show_bug.cgi?id=46496
1973             const int cw = isPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
1974             if (cw > 0)
1975                 return computeContentBoxLogicalWidth(logicalWidth.calcMinValue(cw));
1976         }
1977         // fall through
1978         default:
1979             return intrinsicLogicalWidth();
1980      }
1981 }
1982 
computeReplacedLogicalHeight() const1983 int RenderBox::computeReplacedLogicalHeight() const
1984 {
1985     int logicalHeight = computeReplacedLogicalHeightUsing(style()->logicalHeight());
1986     int minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
1987     int maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
1988 
1989     return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
1990 }
1991 
computeReplacedLogicalHeightUsing(Length logicalHeight) const1992 int RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
1993 {
1994     switch (logicalHeight.type()) {
1995         case Fixed:
1996             return computeContentBoxLogicalHeight(logicalHeight.value());
1997         case Percent:
1998         {
1999             RenderObject* cb = isPositioned() ? container() : containingBlock();
2000             while (cb->isAnonymous()) {
2001                 cb = cb->containingBlock();
2002                 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2003             }
2004 
2005             // FIXME: This calculation is not patched for block-flow yet.
2006             // https://bugs.webkit.org/show_bug.cgi?id=46500
2007             if (cb->isPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2008                 ASSERT(cb->isRenderBlock());
2009                 RenderBlock* block = toRenderBlock(cb);
2010                 int oldHeight = block->height();
2011                 block->computeLogicalHeight();
2012                 int newHeight = block->computeContentBoxLogicalHeight(block->contentHeight());
2013                 block->setHeight(oldHeight);
2014                 return computeContentBoxLogicalHeight(logicalHeight.calcValue(newHeight));
2015             }
2016 
2017             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2018             // containing block's block-flow.
2019             // https://bugs.webkit.org/show_bug.cgi?id=46496
2020             int availableHeight = isPositioned() ? containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb)) : toRenderBox(cb)->availableLogicalHeight();
2021 
2022             // It is necessary to use the border-box to match WinIE's broken
2023             // box model.  This is essential for sizing inside
2024             // table cells using percentage heights.
2025             // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
2026             // https://bugs.webkit.org/show_bug.cgi?id=46997
2027             while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2028                 if (cb->isTableCell()) {
2029                     // Don't let table cells squeeze percent-height replaced elements
2030                     // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2031                     availableHeight = max(availableHeight, intrinsicLogicalHeight());
2032                     return logicalHeight.calcValue(availableHeight - borderAndPaddingLogicalHeight());
2033                 }
2034                 cb = cb->containingBlock();
2035             }
2036 
2037             return computeContentBoxLogicalHeight(logicalHeight.calcValue(availableHeight));
2038         }
2039         default:
2040             return intrinsicLogicalHeight();
2041     }
2042 }
2043 
availableLogicalHeight() const2044 int RenderBox::availableLogicalHeight() const
2045 {
2046     return availableLogicalHeightUsing(style()->logicalHeight());
2047 }
2048 
availableLogicalHeightUsing(const Length & h) const2049 int RenderBox::availableLogicalHeightUsing(const Length& h) const
2050 {
2051     if (h.isFixed())
2052         return computeContentBoxLogicalHeight(h.value());
2053 
2054     if (isRenderView())
2055         return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
2056 
2057     // We need to stop here, since we don't want to increase the height of the table
2058     // artificially.  We're going to rely on this cell getting expanded to some new
2059     // height, and then when we lay out again we'll use the calculation below.
2060     if (isTableCell() && (h.isAuto() || h.isPercent()))
2061         return overrideSize() - borderAndPaddingLogicalWidth();
2062 
2063     if (h.isPercent())
2064        return computeContentBoxLogicalHeight(h.calcValue(containingBlock()->availableLogicalHeight()));
2065 
2066     // FIXME: We can't just check top/bottom here.
2067     // https://bugs.webkit.org/show_bug.cgi?id=46500
2068     if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2069         RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2070         int oldHeight = block->logicalHeight();
2071         block->computeLogicalHeight();
2072         int newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
2073         block->setLogicalHeight(oldHeight);
2074         return computeContentBoxLogicalHeight(newHeight);
2075     }
2076 
2077     return containingBlock()->availableLogicalHeight();
2078 }
2079 
computeBlockDirectionMargins(RenderBlock * containingBlock)2080 void RenderBox::computeBlockDirectionMargins(RenderBlock* containingBlock)
2081 {
2082     if (isTableCell()) {
2083         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
2084         // we may just do it with an extra anonymous block inside the cell.
2085         setMarginBefore(0);
2086         setMarginAfter(0);
2087         return;
2088     }
2089 
2090     // Margins are calculated with respect to the logical width of
2091     // the containing block (8.3)
2092     int cw = containingBlockLogicalWidthForContent();
2093 
2094     RenderStyle* containingBlockStyle = containingBlock->style();
2095     containingBlock->setMarginBeforeForChild(this, style()->marginBeforeUsing(containingBlockStyle).calcMinValue(cw));
2096     containingBlock->setMarginAfterForChild(this, style()->marginAfterUsing(containingBlockStyle).calcMinValue(cw));
2097 }
2098 
containingBlockLogicalWidthForPositioned(const RenderBoxModelObject * containingBlock,bool checkForPerpendicularWritingMode) const2099 int RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2100 {
2101     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2102         return containingBlockLogicalHeightForPositioned(containingBlock, false);
2103 
2104     if (containingBlock->isBox())
2105         return toRenderBox(containingBlock)->clientLogicalWidth();
2106 
2107     ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2108 
2109     const RenderInline* flow = toRenderInline(containingBlock);
2110     InlineFlowBox* first = flow->firstLineBox();
2111     InlineFlowBox* last = flow->lastLineBox();
2112 
2113     // If the containing block is empty, return a width of 0.
2114     if (!first || !last)
2115         return 0;
2116 
2117     int fromLeft;
2118     int fromRight;
2119     if (containingBlock->style()->isLeftToRightDirection()) {
2120         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2121         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2122     } else {
2123         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2124         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2125     }
2126 
2127     return max(0, (fromRight - fromLeft));
2128 }
2129 
containingBlockLogicalHeightForPositioned(const RenderBoxModelObject * containingBlock,bool checkForPerpendicularWritingMode) const2130 int RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2131 {
2132     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2133         return containingBlockLogicalWidthForPositioned(containingBlock, false);
2134 
2135     if (containingBlock->isBox())
2136         return toRenderBox(containingBlock)->clientLogicalHeight();
2137 
2138     ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2139 
2140     const RenderInline* flow = toRenderInline(containingBlock);
2141     InlineFlowBox* first = flow->firstLineBox();
2142     InlineFlowBox* last = flow->lastLineBox();
2143 
2144     // If the containing block is empty, return a height of 0.
2145     if (!first || !last)
2146         return 0;
2147 
2148     int heightResult;
2149     IntRect boundingBox = flow->linesBoundingBox();
2150     if (containingBlock->isHorizontalWritingMode())
2151         heightResult = boundingBox.height();
2152     else
2153         heightResult = boundingBox.width();
2154     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2155     return heightResult;
2156 }
2157 
computeInlineStaticDistance(Length & logicalLeft,Length & logicalRight,const RenderBox * child,const RenderBoxModelObject * containerBlock,int containerLogicalWidth,TextDirection containerDirection)2158 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, int containerLogicalWidth,
2159                                         TextDirection containerDirection)
2160 {
2161     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2162         return;
2163 
2164     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2165     if (containerDirection == LTR) {
2166         int staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2167         for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2168             if (curr->isBox())
2169                 staticPosition += toRenderBox(curr)->logicalLeft();
2170         }
2171         logicalLeft.setValue(Fixed, staticPosition);
2172     } else {
2173         RenderBox* enclosingBox = child->parent()->enclosingBox();
2174         int staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalRight();
2175         staticPosition -= enclosingBox->logicalWidth();
2176         for (RenderObject* curr = enclosingBox; curr && curr != containerBlock; curr = curr->container()) {
2177             if (curr->isBox())
2178                 staticPosition -= toRenderBox(curr)->logicalLeft();
2179         }
2180         logicalRight.setValue(Fixed, staticPosition);
2181     }
2182 }
2183 
computePositionedLogicalWidth()2184 void RenderBox::computePositionedLogicalWidth()
2185 {
2186     if (isReplaced()) {
2187         computePositionedLogicalWidthReplaced();
2188         return;
2189     }
2190 
2191     // QUESTIONS
2192     // FIXME 1: Which RenderObject's 'direction' property should used: the
2193     // containing block (cb) as the spec seems to imply, the parent (parent()) as
2194     // was previously done in calculating the static distances, or ourself, which
2195     // was also previously done for deciding what to override when you had
2196     // over-constrained margins?  Also note that the container block is used
2197     // in similar situations in other parts of the RenderBox class (see computeLogicalWidth()
2198     // and computeMarginsInContainingBlockInlineDirection()). For now we are using the parent for quirks
2199     // mode and the containing block for strict mode.
2200 
2201     // FIXME 2: Should we still deal with these the cases of 'left' or 'right' having
2202     // the type 'static' in determining whether to calculate the static distance?
2203     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2204 
2205     // FIXME 3: Can perhaps optimize out cases when max-width/min-width are greater
2206     // than or less than the computed width().  Be careful of box-sizing and
2207     // percentage issues.
2208 
2209     // The following is based off of the W3C Working Draft from April 11, 2006 of
2210     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2211     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2212     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2213     // correspond to text from the spec)
2214 
2215 
2216     // We don't use containingBlock(), since we may be positioned by an enclosing
2217     // relative positioned inline.
2218     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2219 
2220     const int containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
2221 
2222     // To match WinIE, in quirks mode use the parent's 'direction' property
2223     // instead of the the container block's.
2224     TextDirection containerDirection = (document()->inQuirksMode()) ? parent()->style()->direction() : containerBlock->style()->direction();
2225 
2226     bool isHorizontal = isHorizontalWritingMode();
2227     const int bordersPlusPadding = borderAndPaddingLogicalWidth();
2228     const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2229     const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2230     int& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
2231     int& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
2232 
2233     Length logicalLeft = style()->logicalLeft();
2234     Length logicalRight = style()->logicalRight();
2235 
2236     /*---------------------------------------------------------------------------*\
2237      * For the purposes of this section and the next, the term "static position"
2238      * (of an element) refers, roughly, to the position an element would have had
2239      * in the normal flow. More precisely:
2240      *
2241      * * The static position for 'left' is the distance from the left edge of the
2242      *   containing block to the left margin edge of a hypothetical box that would
2243      *   have been the first box of the element if its 'position' property had
2244      *   been 'static' and 'float' had been 'none'. The value is negative if the
2245      *   hypothetical box is to the left of the containing block.
2246      * * The static position for 'right' is the distance from the right edge of the
2247      *   containing block to the right margin edge of the same hypothetical box as
2248      *   above. The value is positive if the hypothetical box is to the left of the
2249      *   containing block's edge.
2250      *
2251      * But rather than actually calculating the dimensions of that hypothetical box,
2252      * user agents are free to make a guess at its probable position.
2253      *
2254      * For the purposes of calculating the static position, the containing block of
2255      * fixed positioned elements is the initial containing block instead of the
2256      * viewport, and all scrollable boxes should be assumed to be scrolled to their
2257      * origin.
2258     \*---------------------------------------------------------------------------*/
2259 
2260     // see FIXME 2
2261     // Calculate the static distance if needed.
2262     computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, containerDirection);
2263 
2264     // Calculate constraint equation values for 'width' case.
2265     int logicalWidthResult;
2266     int logicalLeftResult;
2267     computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2268                                        containerLogicalWidth, bordersPlusPadding,
2269                                        logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2270                                        logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2271     setLogicalWidth(logicalWidthResult);
2272     setLogicalLeft(logicalLeftResult);
2273 
2274     // Calculate constraint equation values for 'max-width' case.
2275     if (!style()->logicalMaxWidth().isUndefined()) {
2276         int maxLogicalWidth;
2277         int maxMarginLogicalLeft;
2278         int maxMarginLogicalRight;
2279         int maxLogicalLeftPos;
2280 
2281         computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2282                                            containerLogicalWidth, bordersPlusPadding,
2283                                            logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2284                                            maxLogicalWidth, maxMarginLogicalLeft, maxMarginLogicalRight, maxLogicalLeftPos);
2285 
2286         if (logicalWidth() > maxLogicalWidth) {
2287             setLogicalWidth(maxLogicalWidth);
2288             marginLogicalLeftAlias = maxMarginLogicalLeft;
2289             marginLogicalRightAlias = maxMarginLogicalRight;
2290             setLogicalLeft(maxLogicalLeftPos);
2291         }
2292     }
2293 
2294     // Calculate constraint equation values for 'min-width' case.
2295     if (!style()->logicalMinWidth().isZero()) {
2296         int minLogicalWidth;
2297         int minMarginLogicalLeft;
2298         int minMarginLogicalRight;
2299         int minLogicalLeftPos;
2300 
2301         computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2302                                            containerLogicalWidth, bordersPlusPadding,
2303                                            logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2304                                            minLogicalWidth, minMarginLogicalLeft, minMarginLogicalRight, minLogicalLeftPos);
2305 
2306         if (logicalWidth() < minLogicalWidth) {
2307             setLogicalWidth(minLogicalWidth);
2308             marginLogicalLeftAlias = minMarginLogicalLeft;
2309             marginLogicalRightAlias = minMarginLogicalRight;
2310             setLogicalLeft(minLogicalLeftPos);
2311         }
2312     }
2313 
2314     if (stretchesToMinIntrinsicLogicalWidth() && logicalWidth() < minPreferredLogicalWidth() - bordersPlusPadding) {
2315         computePositionedLogicalWidthUsing(Length(minPreferredLogicalWidth() - bordersPlusPadding, Fixed), containerBlock, containerDirection,
2316                                            containerLogicalWidth, bordersPlusPadding,
2317                                            logicalLeft, logicalRight, marginLogicalLeft, marginLogicalRight,
2318                                            logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2319         setLogicalWidth(logicalWidthResult);
2320         setLogicalLeft(logicalLeftResult);
2321     }
2322 
2323     // Put logicalWidth() into correct form.
2324     setLogicalWidth(logicalWidth() + bordersPlusPadding);
2325 }
2326 
computeLogicalLeftPositionedOffset(int & logicalLeftPos,const RenderBox * child,int logicalWidthValue,const RenderBoxModelObject * containerBlock,int containerLogicalWidth)2327 static void computeLogicalLeftPositionedOffset(int& logicalLeftPos, const RenderBox* child, int logicalWidthValue, const RenderBoxModelObject* containerBlock, int containerLogicalWidth)
2328 {
2329     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2330     // 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.
2331     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2332         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2333         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2334     } else
2335         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2336 }
2337 
computePositionedLogicalWidthUsing(Length logicalWidth,const RenderBoxModelObject * containerBlock,TextDirection containerDirection,int containerLogicalWidth,int bordersPlusPadding,Length logicalLeft,Length logicalRight,Length marginLogicalLeft,Length marginLogicalRight,int & logicalWidthValue,int & marginLogicalLeftValue,int & marginLogicalRightValue,int & logicalLeftPos)2338 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2339                                                    int containerLogicalWidth, int bordersPlusPadding,
2340                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
2341                                                    int& logicalWidthValue, int& marginLogicalLeftValue, int& marginLogicalRightValue, int& logicalLeftPos)
2342 {
2343     // 'left' and 'right' cannot both be 'auto' because one would of been
2344     // converted to the static position already
2345     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2346 
2347     int logicalLeftValue = 0;
2348 
2349     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2350     bool logicalLeftIsAuto = logicalLeft.isAuto();
2351     bool logicalRightIsAuto = logicalRight.isAuto();
2352 
2353     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2354         /*-----------------------------------------------------------------------*\
2355          * If none of the three is 'auto': If both 'margin-left' and 'margin-
2356          * right' are 'auto', solve the equation under the extra constraint that
2357          * the two margins get equal values, unless this would make them negative,
2358          * in which case when direction of the containing block is 'ltr' ('rtl'),
2359          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2360          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2361          * solve the equation for that value. If the values are over-constrained,
2362          * ignore the value for 'left' (in case the 'direction' property of the
2363          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2364          * and solve for that value.
2365         \*-----------------------------------------------------------------------*/
2366         // NOTE:  It is not necessary to solve for 'right' in the over constrained
2367         // case because the value is not used for any further calculations.
2368 
2369         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2370         logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2371 
2372         const int availableSpace = containerLogicalWidth - (logicalLeftValue + logicalWidthValue + logicalRight.calcValue(containerLogicalWidth) + bordersPlusPadding);
2373 
2374         // Margins are now the only unknown
2375         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2376             // Both margins auto, solve for equality
2377             if (availableSpace >= 0) {
2378                 marginLogicalLeftValue = availableSpace / 2; // split the difference
2379                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2380             } else {
2381                 // see FIXME 1
2382                 if (containerDirection == LTR) {
2383                     marginLogicalLeftValue = 0;
2384                     marginLogicalRightValue = availableSpace; // will be negative
2385                 } else {
2386                     marginLogicalLeftValue = availableSpace; // will be negative
2387                     marginLogicalRightValue = 0;
2388                 }
2389             }
2390         } else if (marginLogicalLeft.isAuto()) {
2391             // Solve for left margin
2392             marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2393             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
2394         } else if (marginLogicalRight.isAuto()) {
2395             // Solve for right margin
2396             marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2397             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
2398         } else {
2399             // Over-constrained, solve for left if direction is RTL
2400             marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2401             marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2402 
2403             // see FIXME 1 -- used to be "this->style()->direction()"
2404             if (containerDirection == RTL)
2405                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
2406         }
2407     } else {
2408         /*--------------------------------------------------------------------*\
2409          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
2410          * to 0, and pick the one of the following six rules that applies.
2411          *
2412          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
2413          *    width is shrink-to-fit. Then solve for 'left'
2414          *
2415          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2416          * ------------------------------------------------------------------
2417          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
2418          *    the 'direction' property of the containing block is 'ltr' set
2419          *    'left' to the static position, otherwise set 'right' to the
2420          *    static position. Then solve for 'left' (if 'direction is 'rtl')
2421          *    or 'right' (if 'direction' is 'ltr').
2422          * ------------------------------------------------------------------
2423          *
2424          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
2425          *    width is shrink-to-fit . Then solve for 'right'
2426          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
2427          *    for 'left'
2428          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
2429          *    for 'width'
2430          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
2431          *    for 'right'
2432          *
2433          * Calculation of the shrink-to-fit width is similar to calculating the
2434          * width of a table cell using the automatic table layout algorithm.
2435          * Roughly: calculate the preferred width by formatting the content
2436          * without breaking lines other than where explicit line breaks occur,
2437          * and also calculate the preferred minimum width, e.g., by trying all
2438          * possible line breaks. CSS 2.1 does not define the exact algorithm.
2439          * Thirdly, calculate the available width: this is found by solving
2440          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
2441          * to 0.
2442          *
2443          * Then the shrink-to-fit width is:
2444          * min(max(preferred minimum width, available width), preferred width).
2445         \*--------------------------------------------------------------------*/
2446         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
2447         // because the value is not used for any further calculations.
2448 
2449         // Calculate margins, 'auto' margins are ignored.
2450         marginLogicalLeftValue = marginLogicalLeft.calcMinValue(containerLogicalWidth);
2451         marginLogicalRightValue = marginLogicalRight.calcMinValue(containerLogicalWidth);
2452 
2453         const int availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
2454 
2455         // FIXME: Is there a faster way to find the correct case?
2456         // Use rule/case that applies.
2457         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2458             // RULE 1: (use shrink-to-fit for width, and solve of left)
2459             int logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2460 
2461             // FIXME: would it be better to have shrink-to-fit in one step?
2462             int preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2463             int preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2464             int availableWidth = availableSpace - logicalRightValue;
2465             logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2466             logicalLeftValue = availableSpace - (logicalWidthValue + logicalRightValue);
2467         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
2468             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
2469             logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2470 
2471             // FIXME: would it be better to have shrink-to-fit in one step?
2472             int preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2473             int preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2474             int availableWidth = availableSpace - logicalLeftValue;
2475             logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2476         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2477             // RULE 4: (solve for left)
2478             logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2479             logicalLeftValue = availableSpace - (logicalWidthValue + logicalRight.calcValue(containerLogicalWidth));
2480         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2481             // RULE 5: (solve for width)
2482             logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2483             logicalWidthValue = availableSpace - (logicalLeftValue + logicalRight.calcValue(containerLogicalWidth));
2484         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
2485             // RULE 6: (no need solve for right)
2486             logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2487             logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2488         }
2489     }
2490 
2491     // Use computed values to calculate the horizontal position.
2492 
2493     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
2494     // positioned, inline because right now, it is using the logical left position
2495     // of the first line box when really it should use the last line box.  When
2496     // this is fixed elsewhere, this block should be removed.
2497     if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2498         const RenderInline* flow = toRenderInline(containerBlock);
2499         InlineFlowBox* firstLine = flow->firstLineBox();
2500         InlineFlowBox* lastLine = flow->lastLineBox();
2501         if (firstLine && lastLine && firstLine != lastLine) {
2502             logicalLeftPos = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
2503             return;
2504         }
2505     }
2506 
2507     logicalLeftPos = logicalLeftValue + marginLogicalLeftValue;
2508     computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidthValue, containerBlock, containerLogicalWidth);
2509 }
2510 
computeBlockStaticDistance(Length & logicalTop,Length & logicalBottom,const RenderBox * child,const RenderBoxModelObject * containerBlock)2511 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
2512 {
2513     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
2514         return;
2515 
2516     // FIXME: The static distance computation has not been patched for mixed writing modes.
2517     int staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
2518     for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2519         if (curr->isBox() && !curr->isTableRow())
2520             staticLogicalTop += toRenderBox(curr)->logicalTop();
2521     }
2522     logicalTop.setValue(Fixed, staticLogicalTop);
2523 }
2524 
computePositionedLogicalHeight()2525 void RenderBox::computePositionedLogicalHeight()
2526 {
2527     if (isReplaced()) {
2528         computePositionedLogicalHeightReplaced();
2529         return;
2530     }
2531 
2532     // The following is based off of the W3C Working Draft from April 11, 2006 of
2533     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
2534     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
2535     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
2536     // correspond to text from the spec)
2537 
2538 
2539     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
2540     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2541 
2542     const int containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
2543 
2544     bool isHorizontal = isHorizontalWritingMode();
2545     bool isFlipped = style()->isFlippedBlocksWritingMode();
2546     const int bordersPlusPadding = borderAndPaddingLogicalHeight();
2547     const Length marginBefore = style()->marginBefore();
2548     const Length marginAfter = style()->marginAfter();
2549     int& marginBeforeAlias = isHorizontal ? (isFlipped ? m_marginBottom : m_marginTop) : (isFlipped ? m_marginRight: m_marginLeft);
2550     int& marginAfterAlias = isHorizontal ? (isFlipped ? m_marginTop : m_marginBottom) : (isFlipped ? m_marginLeft: m_marginRight);
2551 
2552     Length logicalTop = style()->logicalTop();
2553     Length logicalBottom = style()->logicalBottom();
2554 
2555     /*---------------------------------------------------------------------------*\
2556      * For the purposes of this section and the next, the term "static position"
2557      * (of an element) refers, roughly, to the position an element would have had
2558      * in the normal flow. More precisely, the static position for 'top' is the
2559      * distance from the top edge of the containing block to the top margin edge
2560      * of a hypothetical box that would have been the first box of the element if
2561      * its 'position' property had been 'static' and 'float' had been 'none'. The
2562      * value is negative if the hypothetical box is above the containing block.
2563      *
2564      * But rather than actually calculating the dimensions of that hypothetical
2565      * box, user agents are free to make a guess at its probable position.
2566      *
2567      * For the purposes of calculating the static position, the containing block
2568      * of fixed positioned elements is the initial containing block instead of
2569      * the viewport.
2570     \*---------------------------------------------------------------------------*/
2571 
2572     // see FIXME 2
2573     // Calculate the static distance if needed.
2574     computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
2575 
2576     int logicalHeightResult; // Needed to compute overflow.
2577     int logicalTopPos;
2578 
2579     // Calculate constraint equation values for 'height' case.
2580     computePositionedLogicalHeightUsing(style()->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2581                                         logicalTop, logicalBottom, marginBefore, marginAfter,
2582                                         logicalHeightResult, marginBeforeAlias, marginAfterAlias, logicalTopPos);
2583     setLogicalTop(logicalTopPos);
2584 
2585     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
2586     // see FIXME 3
2587 
2588     // Calculate constraint equation values for 'max-height' case.
2589     if (!style()->logicalMaxHeight().isUndefined()) {
2590         int maxLogicalHeight;
2591         int maxMarginBefore;
2592         int maxMarginAfter;
2593         int maxLogicalTopPos;
2594 
2595         computePositionedLogicalHeightUsing(style()->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2596                                             logicalTop, logicalBottom, marginBefore, marginAfter,
2597                                             maxLogicalHeight, maxMarginBefore, maxMarginAfter, maxLogicalTopPos);
2598 
2599         if (logicalHeightResult > maxLogicalHeight) {
2600             logicalHeightResult = maxLogicalHeight;
2601             marginBeforeAlias = maxMarginBefore;
2602             marginAfterAlias = maxMarginAfter;
2603             setLogicalTop(maxLogicalTopPos);
2604         }
2605     }
2606 
2607     // Calculate constraint equation values for 'min-height' case.
2608     if (!style()->logicalMinHeight().isZero()) {
2609         int minLogicalHeight;
2610         int minMarginBefore;
2611         int minMarginAfter;
2612         int minLogicalTopPos;
2613 
2614         computePositionedLogicalHeightUsing(style()->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2615                                             logicalTop, logicalBottom, marginBefore, marginAfter,
2616                                             minLogicalHeight, minMarginBefore, minMarginAfter, minLogicalTopPos);
2617 
2618         if (logicalHeightResult < minLogicalHeight) {
2619             logicalHeightResult = minLogicalHeight;
2620             marginBeforeAlias = minMarginBefore;
2621             marginAfterAlias = minMarginAfter;
2622             setLogicalTop(minLogicalTopPos);
2623         }
2624     }
2625 
2626     // Set final height value.
2627     setLogicalHeight(logicalHeightResult + bordersPlusPadding);
2628 }
2629 
computeLogicalTopPositionedOffset(int & logicalTopPos,const RenderBox * child,int logicalHeightValue,const RenderBoxModelObject * containerBlock,int containerLogicalHeight)2630 static void computeLogicalTopPositionedOffset(int& logicalTopPos, const RenderBox* child, int logicalHeightValue, const RenderBoxModelObject* containerBlock, int containerLogicalHeight)
2631 {
2632     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2633     // 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.
2634     if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
2635         || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
2636         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
2637 
2638     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
2639     if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2640         if (child->isHorizontalWritingMode())
2641             logicalTopPos += containerBlock->borderBottom();
2642         else
2643             logicalTopPos += containerBlock->borderRight();
2644     } else {
2645         if (child->isHorizontalWritingMode())
2646             logicalTopPos += containerBlock->borderTop();
2647         else
2648             logicalTopPos += containerBlock->borderLeft();
2649     }
2650 }
2651 
computePositionedLogicalHeightUsing(Length logicalHeightLength,const RenderBoxModelObject * containerBlock,int containerLogicalHeight,int bordersPlusPadding,Length logicalTop,Length logicalBottom,Length marginBefore,Length marginAfter,int & logicalHeightValue,int & marginBeforeValue,int & marginAfterValue,int & logicalTopPos)2652 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
2653                                                     int containerLogicalHeight, int bordersPlusPadding,
2654                                                     Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
2655                                                     int& logicalHeightValue, int& marginBeforeValue, int& marginAfterValue, int& logicalTopPos)
2656 {
2657     // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
2658     // converted to the static position in computePositionedLogicalHeight()
2659     ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
2660 
2661     int contentLogicalHeight = logicalHeight() - bordersPlusPadding;
2662 
2663     int logicalTopValue = 0;
2664 
2665     bool logicalHeightIsAuto = logicalHeightLength.isAuto();
2666     bool logicalTopIsAuto = logicalTop.isAuto();
2667     bool logicalBottomIsAuto = logicalBottom.isAuto();
2668 
2669     // Height is never unsolved for tables.
2670     if (isTable()) {
2671         logicalHeightLength.setValue(Fixed, contentLogicalHeight);
2672         logicalHeightIsAuto = false;
2673     }
2674 
2675     if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
2676         /*-----------------------------------------------------------------------*\
2677          * If none of the three are 'auto': If both 'margin-top' and 'margin-
2678          * bottom' are 'auto', solve the equation under the extra constraint that
2679          * the two margins get equal values. If one of 'margin-top' or 'margin-
2680          * bottom' is 'auto', solve the equation for that value. If the values
2681          * are over-constrained, ignore the value for 'bottom' and solve for that
2682          * value.
2683         \*-----------------------------------------------------------------------*/
2684         // NOTE:  It is not necessary to solve for 'bottom' in the over constrained
2685         // case because the value is not used for any further calculations.
2686 
2687         logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2688         logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2689 
2690         const int availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight) + bordersPlusPadding);
2691 
2692         // Margins are now the only unknown
2693         if (marginBefore.isAuto() && marginAfter.isAuto()) {
2694             // Both margins auto, solve for equality
2695             // NOTE: This may result in negative values.
2696             marginBeforeValue = availableSpace / 2; // split the difference
2697             marginAfterValue = availableSpace - marginBeforeValue; // account for odd valued differences
2698         } else if (marginBefore.isAuto()) {
2699             // Solve for top margin
2700             marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
2701             marginBeforeValue = availableSpace - marginAfterValue;
2702         } else if (marginAfter.isAuto()) {
2703             // Solve for bottom margin
2704             marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
2705             marginAfterValue = availableSpace - marginBeforeValue;
2706         } else {
2707             // Over-constrained, (no need solve for bottom)
2708             marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
2709             marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
2710         }
2711     } else {
2712         /*--------------------------------------------------------------------*\
2713          * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
2714          * to 0, and pick the one of the following six rules that applies.
2715          *
2716          * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
2717          *    the height is based on the content, and solve for 'top'.
2718          *
2719          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2720          * ------------------------------------------------------------------
2721          * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
2722          *    set 'top' to the static position, and solve for 'bottom'.
2723          * ------------------------------------------------------------------
2724          *
2725          * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
2726          *    the height is based on the content, and solve for 'bottom'.
2727          * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
2728          *    solve for 'top'.
2729          * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
2730          *    solve for 'height'.
2731          * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
2732          *    solve for 'bottom'.
2733         \*--------------------------------------------------------------------*/
2734         // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
2735         // because the value is not used for any further calculations.
2736 
2737         // Calculate margins, 'auto' margins are ignored.
2738         marginBeforeValue = marginBefore.calcMinValue(containerLogicalHeight);
2739         marginAfterValue = marginAfter.calcMinValue(containerLogicalHeight);
2740 
2741         const int availableSpace = containerLogicalHeight - (marginBeforeValue + marginAfterValue + bordersPlusPadding);
2742 
2743         // Use rule/case that applies.
2744         if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
2745             // RULE 1: (height is content based, solve of top)
2746             logicalHeightValue = contentLogicalHeight;
2747             logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
2748         } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
2749             // RULE 3: (height is content based, no need solve of bottom)
2750             logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2751             logicalHeightValue = contentLogicalHeight;
2752         } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
2753             // RULE 4: (solve of top)
2754             logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2755             logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
2756         } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
2757             // RULE 5: (solve of height)
2758             logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2759             logicalHeightValue = max(0, availableSpace - (logicalTopValue + logicalBottom.calcValue(containerLogicalHeight)));
2760         } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
2761             // RULE 6: (no need solve of bottom)
2762             logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
2763             logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
2764         }
2765     }
2766 
2767     // Use computed values to calculate the vertical position.
2768     logicalTopPos = logicalTopValue + marginBeforeValue;
2769     computeLogicalTopPositionedOffset(logicalTopPos, this, logicalHeightValue, containerBlock, containerLogicalHeight);
2770 }
2771 
computePositionedLogicalWidthReplaced()2772 void RenderBox::computePositionedLogicalWidthReplaced()
2773 {
2774     // The following is based off of the W3C Working Draft from April 11, 2006 of
2775     // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
2776     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
2777     // (block-style-comments in this function correspond to text from the spec and
2778     // the numbers correspond to numbers in spec)
2779 
2780     // We don't use containingBlock(), since we may be positioned by an enclosing
2781     // relative positioned inline.
2782     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2783 
2784     const int containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
2785 
2786     // To match WinIE, in quirks mode use the parent's 'direction' property
2787     // instead of the the container block's.
2788     TextDirection containerDirection = (document()->inQuirksMode()) ? parent()->style()->direction() : containerBlock->style()->direction();
2789 
2790     // Variables to solve.
2791     bool isHorizontal = isHorizontalWritingMode();
2792     Length logicalLeft = style()->logicalLeft();
2793     Length logicalRight = style()->logicalRight();
2794     Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2795     Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2796     int& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
2797     int& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
2798 
2799     /*-----------------------------------------------------------------------*\
2800      * 1. The used value of 'width' is determined as for inline replaced
2801      *    elements.
2802     \*-----------------------------------------------------------------------*/
2803     // NOTE: This value of width is FINAL in that the min/max width calculations
2804     // are dealt with in computeReplacedWidth().  This means that the steps to produce
2805     // correct max/min in the non-replaced version, are not necessary.
2806     setLogicalWidth(computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth());
2807     const int availableSpace = containerLogicalWidth - logicalWidth();
2808 
2809     /*-----------------------------------------------------------------------*\
2810      * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
2811      *    of the containing block is 'ltr', set 'left' to the static position;
2812      *    else if 'direction' is 'rtl', set 'right' to the static position.
2813     \*-----------------------------------------------------------------------*/
2814     // see FIXME 2
2815     computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, containerDirection);
2816 
2817     /*-----------------------------------------------------------------------*\
2818      * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
2819      *    or 'margin-right' with '0'.
2820     \*-----------------------------------------------------------------------*/
2821     if (logicalLeft.isAuto() || logicalRight.isAuto()) {
2822         if (marginLogicalLeft.isAuto())
2823             marginLogicalLeft.setValue(Fixed, 0);
2824         if (marginLogicalRight.isAuto())
2825             marginLogicalRight.setValue(Fixed, 0);
2826     }
2827 
2828     /*-----------------------------------------------------------------------*\
2829      * 4. If at this point both 'margin-left' and 'margin-right' are still
2830      *    'auto', solve the equation under the extra constraint that the two
2831      *    margins must get equal values, unless this would make them negative,
2832      *    in which case when the direction of the containing block is 'ltr'
2833      *    ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
2834      *    'margin-right' ('margin-left').
2835     \*-----------------------------------------------------------------------*/
2836     int logicalLeftValue = 0;
2837     int logicalRightValue = 0;
2838 
2839     if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2840         // 'left' and 'right' cannot be 'auto' due to step 3
2841         ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2842 
2843         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2844         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2845 
2846         int difference = availableSpace - (logicalLeftValue + logicalRightValue);
2847         if (difference > 0) {
2848             marginLogicalLeftAlias = difference / 2; // split the difference
2849             marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
2850         } else {
2851             // see FIXME 1
2852             if (containerDirection == LTR) {
2853                 marginLogicalLeftAlias = 0;
2854                 marginLogicalRightAlias = difference; // will be negative
2855             } else {
2856                 marginLogicalLeftAlias = difference; // will be negative
2857                 marginLogicalRightAlias = 0;
2858             }
2859         }
2860 
2861     /*-----------------------------------------------------------------------*\
2862      * 5. If at this point there is an 'auto' left, solve the equation for
2863      *    that value.
2864     \*-----------------------------------------------------------------------*/
2865     } else if (logicalLeft.isAuto()) {
2866         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2867         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2868         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2869 
2870         // Solve for 'left'
2871         logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
2872     } else if (logicalRight.isAuto()) {
2873         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2874         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2875         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2876 
2877         // Solve for 'right'
2878         logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
2879     } else if (marginLogicalLeft.isAuto()) {
2880         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2881         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2882         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2883 
2884         // Solve for 'margin-left'
2885         marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
2886     } else if (marginLogicalRight.isAuto()) {
2887         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2888         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2889         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2890 
2891         // Solve for 'margin-right'
2892         marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
2893     } else {
2894         // Nothing is 'auto', just calculate the values.
2895         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
2896         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
2897         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2898         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2899     }
2900 
2901     /*-----------------------------------------------------------------------*\
2902      * 6. If at this point the values are over-constrained, ignore the value
2903      *    for either 'left' (in case the 'direction' property of the
2904      *    containing block is 'rtl') or 'right' (in case 'direction' is
2905      *    'ltr') and solve for that value.
2906     \*-----------------------------------------------------------------------*/
2907     // NOTE:  It is not necessary to solve for 'right' when the direction is
2908     // LTR because the value is not used.
2909     int totalLogicalWidth = logicalWidth() + logicalLeftValue + logicalRightValue +  marginLogicalLeftAlias + marginLogicalRightAlias;
2910     if (totalLogicalWidth > containerLogicalWidth && (containerDirection == RTL))
2911         logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
2912 
2913     // FIXME: Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space, so that
2914     // can make the result here rather complicated to compute.
2915 
2916     // Use computed values to calculate the horizontal position.
2917 
2918     // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
2919     // positioned, inline containing block because right now, it is using the logical left position
2920     // of the first line box when really it should use the last line box.  When
2921     // this is fixed elsewhere, this block should be removed.
2922     if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2923         const RenderInline* flow = toRenderInline(containerBlock);
2924         InlineFlowBox* firstLine = flow->firstLineBox();
2925         InlineFlowBox* lastLine = flow->lastLineBox();
2926         if (firstLine && lastLine && firstLine != lastLine) {
2927             setLogicalLeft(logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft()));
2928             return;
2929         }
2930     }
2931 
2932     int logicalLeftPos = logicalLeftValue + marginLogicalLeftAlias;
2933     computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidth(), containerBlock, containerLogicalWidth);
2934     setLogicalLeft(logicalLeftPos);
2935 }
2936 
computePositionedLogicalHeightReplaced()2937 void RenderBox::computePositionedLogicalHeightReplaced()
2938 {
2939     // The following is based off of the W3C Working Draft from April 11, 2006 of
2940     // CSS 2.1: Section 10.6.5 "Absolutely positioned, replaced elements"
2941     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-height>
2942     // (block-style-comments in this function correspond to text from the spec and
2943     // the numbers correspond to numbers in spec)
2944 
2945     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
2946     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2947 
2948     const int containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
2949 
2950     // Variables to solve.
2951     bool isHorizontal = isHorizontalWritingMode();
2952     bool isFlipped = style()->isFlippedBlocksWritingMode();
2953     Length marginBefore = style()->marginBefore();
2954     Length marginAfter = style()->marginAfter();
2955     int& marginBeforeAlias = isHorizontal ? (isFlipped ? m_marginBottom : m_marginTop) : (isFlipped ? m_marginRight: m_marginLeft);
2956     int& marginAfterAlias = isHorizontal ? (isFlipped ? m_marginTop : m_marginBottom) : (isFlipped ? m_marginLeft: m_marginRight);
2957 
2958     Length logicalTop = style()->logicalTop();
2959     Length logicalBottom = style()->logicalBottom();
2960 
2961     /*-----------------------------------------------------------------------*\
2962      * 1. The used value of 'height' is determined as for inline replaced
2963      *    elements.
2964     \*-----------------------------------------------------------------------*/
2965     // NOTE: This value of height is FINAL in that the min/max height calculations
2966     // are dealt with in computeReplacedHeight().  This means that the steps to produce
2967     // correct max/min in the non-replaced version, are not necessary.
2968     setLogicalHeight(computeReplacedLogicalHeight() + borderAndPaddingLogicalHeight());
2969     const int availableSpace = containerLogicalHeight - logicalHeight();
2970 
2971     /*-----------------------------------------------------------------------*\
2972      * 2. If both 'top' and 'bottom' have the value 'auto', replace 'top'
2973      *    with the element's static position.
2974     \*-----------------------------------------------------------------------*/
2975     // see FIXME 2
2976     computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
2977 
2978     /*-----------------------------------------------------------------------*\
2979      * 3. If 'bottom' is 'auto', replace any 'auto' on 'margin-top' or
2980      *    'margin-bottom' with '0'.
2981     \*-----------------------------------------------------------------------*/
2982     // FIXME: The spec. says that this step should only be taken when bottom is
2983     // auto, but if only top is auto, this makes step 4 impossible.
2984     if (logicalTop.isAuto() || logicalBottom.isAuto()) {
2985         if (marginBefore.isAuto())
2986             marginBefore.setValue(Fixed, 0);
2987         if (marginAfter.isAuto())
2988             marginAfter.setValue(Fixed, 0);
2989     }
2990 
2991     /*-----------------------------------------------------------------------*\
2992      * 4. If at this point both 'margin-top' and 'margin-bottom' are still
2993      *    'auto', solve the equation under the extra constraint that the two
2994      *    margins must get equal values.
2995     \*-----------------------------------------------------------------------*/
2996     int logicalTopValue = 0;
2997     int logicalBottomValue = 0;
2998 
2999     if (marginBefore.isAuto() && marginAfter.isAuto()) {
3000         // 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
3001         ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
3002 
3003         logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3004         logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3005 
3006         int difference = availableSpace - (logicalTopValue + logicalBottomValue);
3007         // NOTE: This may result in negative values.
3008         marginBeforeAlias =  difference / 2; // split the difference
3009         marginAfterAlias = difference - marginBeforeAlias; // account for odd valued differences
3010 
3011     /*-----------------------------------------------------------------------*\
3012      * 5. If at this point there is only one 'auto' left, solve the equation
3013      *    for that value.
3014     \*-----------------------------------------------------------------------*/
3015     } else if (logicalTop.isAuto()) {
3016         marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3017         marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3018         logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3019 
3020         // Solve for 'top'
3021         logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
3022     } else if (logicalBottom.isAuto()) {
3023         marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3024         marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3025         logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3026 
3027         // Solve for 'bottom'
3028         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3029         // use the value.
3030     } else if (marginBefore.isAuto()) {
3031         marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3032         logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3033         logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3034 
3035         // Solve for 'margin-top'
3036         marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
3037     } else if (marginAfter.isAuto()) {
3038         marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3039         logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3040         logicalBottomValue = logicalBottom.calcValue(containerLogicalHeight);
3041 
3042         // Solve for 'margin-bottom'
3043         marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
3044     } else {
3045         // Nothing is 'auto', just calculate the values.
3046         marginBeforeAlias = marginBefore.calcValue(containerLogicalHeight);
3047         marginAfterAlias = marginAfter.calcValue(containerLogicalHeight);
3048         logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3049         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3050         // use the value.
3051      }
3052 
3053     /*-----------------------------------------------------------------------*\
3054      * 6. If at this point the values are over-constrained, ignore the value
3055      *    for 'bottom' and solve for that value.
3056     \*-----------------------------------------------------------------------*/
3057     // NOTE: It is not necessary to do this step because we don't end up using
3058     // the value of 'bottom' regardless of whether the values are over-constrained
3059     // or not.
3060 
3061     // Use computed values to calculate the vertical position.
3062     int logicalTopPos = logicalTopValue + marginBeforeAlias;
3063     computeLogicalTopPositionedOffset(logicalTopPos, this, logicalHeight(), containerBlock, containerLogicalHeight);
3064     setLogicalTop(logicalTopPos);
3065 }
3066 
localCaretRect(InlineBox * box,int caretOffset,int * extraWidthToEndOfLine)3067 IntRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, int* extraWidthToEndOfLine)
3068 {
3069     // VisiblePositions at offsets inside containers either a) refer to the positions before/after
3070     // those containers (tables and select elements) or b) refer to the position inside an empty block.
3071     // They never refer to children.
3072     // FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.
3073 
3074     // FIXME: What about border and padding?
3075     IntRect rect(x(), y(), caretWidth, height());
3076     bool ltr = box ? box->isLeftToRightDirection() : style()->isLeftToRightDirection();
3077 
3078     if ((!caretOffset) ^ ltr)
3079         rect.move(IntSize(width() - caretWidth, 0));
3080 
3081     if (box) {
3082         RootInlineBox* rootBox = box->root();
3083         int top = rootBox->lineTop();
3084         rect.setY(top);
3085         rect.setHeight(rootBox->lineBottom() - top);
3086     }
3087 
3088     // If height of box is smaller than font height, use the latter one,
3089     // otherwise the caret might become invisible.
3090     //
3091     // Also, if the box is not a replaced element, always use the font height.
3092     // This prevents the "big caret" bug described in:
3093     // <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
3094     //
3095     // FIXME: ignoring :first-line, missing good reason to take care of
3096     int fontHeight = style()->fontMetrics().height();
3097     if (fontHeight > rect.height() || (!isReplaced() && !isTable()))
3098         rect.setHeight(fontHeight);
3099 
3100     if (extraWidthToEndOfLine)
3101         *extraWidthToEndOfLine = x() + width() - rect.maxX();
3102 
3103     // Move to local coords
3104     rect.move(-x(), -y());
3105     return rect;
3106 }
3107 
positionForPoint(const IntPoint & point)3108 VisiblePosition RenderBox::positionForPoint(const IntPoint& point)
3109 {
3110     // no children...return this render object's element, if there is one, and offset 0
3111     if (!firstChild())
3112         return createVisiblePosition(node() ? firstPositionInOrBeforeNode(node()) : Position(0, 0));
3113 
3114     int xPos = point.x();
3115     int yPos = point.y();
3116 
3117     if (isTable() && node()) {
3118         int right = contentWidth() + borderAndPaddingWidth();
3119         int bottom = contentHeight() + borderAndPaddingHeight();
3120 
3121         if (xPos < 0 || xPos > right || yPos < 0 || yPos > bottom) {
3122             if (xPos <= right / 2)
3123                 return createVisiblePosition(firstPositionInOrBeforeNode(node()));
3124             return createVisiblePosition(lastPositionInOrAfterNode(node()));
3125         }
3126     }
3127 
3128     // Pass off to the closest child.
3129     int minDist = INT_MAX;
3130     RenderBox* closestRenderer = 0;
3131     int newX = xPos;
3132     int newY = yPos;
3133     if (isTableRow()) {
3134         newX += x();
3135         newY += y();
3136     }
3137     for (RenderObject* renderObject = firstChild(); renderObject; renderObject = renderObject->nextSibling()) {
3138         if ((!renderObject->firstChild() && !renderObject->isInline() && !renderObject->isBlockFlow() )
3139             || renderObject->style()->visibility() != VISIBLE)
3140             continue;
3141 
3142         if (!renderObject->isBox())
3143             continue;
3144 
3145         RenderBox* renderer = toRenderBox(renderObject);
3146 
3147         int top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? 0 : renderer->y());
3148         int bottom = top + renderer->contentHeight();
3149         int left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? 0 : renderer->x());
3150         int right = left + renderer->contentWidth();
3151 
3152         if (xPos <= right && xPos >= left && yPos <= top && yPos >= bottom) {
3153             if (renderer->isTableRow())
3154                 return renderer->positionForCoordinates(xPos + newX - renderer->x(), yPos + newY - renderer->y());
3155             return renderer->positionForCoordinates(xPos - renderer->x(), yPos - renderer->y());
3156         }
3157 
3158         // Find the distance from (x, y) to the box.  Split the space around the box into 8 pieces
3159         // and use a different compare depending on which piece (x, y) is in.
3160         IntPoint cmp;
3161         if (xPos > right) {
3162             if (yPos < top)
3163                 cmp = IntPoint(right, top);
3164             else if (yPos > bottom)
3165                 cmp = IntPoint(right, bottom);
3166             else
3167                 cmp = IntPoint(right, yPos);
3168         } else if (xPos < left) {
3169             if (yPos < top)
3170                 cmp = IntPoint(left, top);
3171             else if (yPos > bottom)
3172                 cmp = IntPoint(left, bottom);
3173             else
3174                 cmp = IntPoint(left, yPos);
3175         } else {
3176             if (yPos < top)
3177                 cmp = IntPoint(xPos, top);
3178             else
3179                 cmp = IntPoint(xPos, bottom);
3180         }
3181 
3182         int x1minusx2 = cmp.x() - xPos;
3183         int y1minusy2 = cmp.y() - yPos;
3184 
3185         int dist = x1minusx2 * x1minusx2 + y1minusy2 * y1minusy2;
3186         if (dist < minDist) {
3187             closestRenderer = renderer;
3188             minDist = dist;
3189         }
3190     }
3191 
3192     if (closestRenderer)
3193         return closestRenderer->positionForCoordinates(newX - closestRenderer->x(), newY - closestRenderer->y());
3194 
3195     return createVisiblePosition(firstPositionInOrBeforeNode(node()));
3196 }
3197 
shrinkToAvoidFloats() const3198 bool RenderBox::shrinkToAvoidFloats() const
3199 {
3200     // Floating objects don't shrink.  Objects that don't avoid floats don't shrink.  Marquees don't shrink.
3201     if ((isInline() && !isHTMLMarquee()) || !avoidsFloats() || isFloating())
3202         return false;
3203 
3204     // All auto-width objects that avoid floats should always use lineWidth.
3205     return style()->width().isAuto();
3206 }
3207 
avoidsFloats() const3208 bool RenderBox::avoidsFloats() const
3209 {
3210     return isReplaced() || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isDeprecatedFlexItem();
3211 }
3212 
addShadowOverflow()3213 void RenderBox::addShadowOverflow()
3214 {
3215     int shadowLeft;
3216     int shadowRight;
3217     int shadowTop;
3218     int shadowBottom;
3219     style()->getBoxShadowExtent(shadowTop, shadowRight, shadowBottom, shadowLeft);
3220     IntRect borderBox = borderBoxRect();
3221     int overflowLeft = borderBox.x() + shadowLeft;
3222     int overflowRight = borderBox.maxX() + shadowRight;
3223     int overflowTop = borderBox.y() + shadowTop;
3224     int overflowBottom = borderBox.maxY() + shadowBottom;
3225     addVisualOverflow(IntRect(overflowLeft, overflowTop, overflowRight - overflowLeft, overflowBottom - overflowTop));
3226 }
3227 
addOverflowFromChild(RenderBox * child,const IntSize & delta)3228 void RenderBox::addOverflowFromChild(RenderBox* child, const IntSize& delta)
3229 {
3230     // Only propagate layout overflow from the child if the child isn't clipping its overflow.  If it is, then
3231     // its overflow is internal to it, and we don't care about it.  layoutOverflowRectForPropagation takes care of this
3232     // and just propagates the border box rect instead.
3233     IntRect childLayoutOverflowRect = child->layoutOverflowRectForPropagation(style());
3234     childLayoutOverflowRect.move(delta);
3235     addLayoutOverflow(childLayoutOverflowRect);
3236 
3237     // Add in visual overflow from the child.  Even if the child clips its overflow, it may still
3238     // have visual overflow of its own set from box shadows or reflections.  It is unnecessary to propagate this
3239     // overflow if we are clipping our own overflow.
3240     if (child->hasSelfPaintingLayer() || hasOverflowClip())
3241         return;
3242     IntRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
3243     childVisualOverflowRect.move(delta);
3244     addVisualOverflow(childVisualOverflowRect);
3245 }
3246 
addLayoutOverflow(const IntRect & rect)3247 void RenderBox::addLayoutOverflow(const IntRect& rect)
3248 {
3249     IntRect clientBox = clientBoxRect();
3250     if (clientBox.contains(rect) || rect.isEmpty())
3251         return;
3252 
3253     // For overflow clip objects, we don't want to propagate overflow into unreachable areas.
3254     IntRect overflowRect(rect);
3255     if (hasOverflowClip() || isRenderView()) {
3256         // Overflow is in the block's coordinate space and thus is flipped for horizontal-bt and vertical-rl
3257         // writing modes.  At this stage that is actually a simplification, since we can treat horizontal-tb/bt as the same
3258         // and vertical-lr/rl as the same.
3259         bool hasTopOverflow = !style()->isLeftToRightDirection() && !isHorizontalWritingMode();
3260         bool hasLeftOverflow = !style()->isLeftToRightDirection() && isHorizontalWritingMode();
3261 
3262         if (!hasTopOverflow)
3263             overflowRect.shiftYEdgeTo(max(overflowRect.y(), clientBox.y()));
3264         else
3265             overflowRect.shiftMaxYEdgeTo(min(overflowRect.maxY(), clientBox.maxY()));
3266         if (!hasLeftOverflow)
3267             overflowRect.shiftXEdgeTo(max(overflowRect.x(), clientBox.x()));
3268         else
3269             overflowRect.shiftMaxXEdgeTo(min(overflowRect.maxX(), clientBox.maxX()));
3270 
3271         // Now re-test with the adjusted rectangle and see if it has become unreachable or fully
3272         // contained.
3273         if (clientBox.contains(overflowRect) || overflowRect.isEmpty())
3274             return;
3275     }
3276 
3277     if (!m_overflow)
3278         m_overflow = adoptPtr(new RenderOverflow(clientBox, borderBoxRect()));
3279 
3280     m_overflow->addLayoutOverflow(overflowRect);
3281 }
3282 
addVisualOverflow(const IntRect & rect)3283 void RenderBox::addVisualOverflow(const IntRect& rect)
3284 {
3285     IntRect borderBox = borderBoxRect();
3286     if (borderBox.contains(rect) || rect.isEmpty())
3287         return;
3288 
3289     if (!m_overflow)
3290         m_overflow = adoptPtr(new RenderOverflow(clientBoxRect(), borderBox));
3291 
3292     m_overflow->addVisualOverflow(rect);
3293 }
3294 
clearLayoutOverflow()3295 void RenderBox::clearLayoutOverflow()
3296 {
3297     if (!m_overflow)
3298         return;
3299 
3300     if (visualOverflowRect() == borderBoxRect()) {
3301         m_overflow.clear();
3302         return;
3303     }
3304 
3305     m_overflow->resetLayoutOverflow(borderBoxRect());
3306 }
3307 
lineHeight(bool,LineDirectionMode direction,LinePositionMode) const3308 int RenderBox::lineHeight(bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
3309 {
3310     if (isReplaced())
3311         return direction == HorizontalLine ? m_marginTop + height() + m_marginBottom : m_marginRight + width() + m_marginLeft;
3312     return 0;
3313 }
3314 
baselinePosition(FontBaseline baselineType,bool,LineDirectionMode direction,LinePositionMode) const3315 int RenderBox::baselinePosition(FontBaseline baselineType, bool /*firstLine*/, LineDirectionMode direction, LinePositionMode /*linePositionMode*/) const
3316 {
3317     if (isReplaced()) {
3318         int result = direction == HorizontalLine ? m_marginTop + height() + m_marginBottom : m_marginRight + width() + m_marginLeft;
3319         if (baselineType == AlphabeticBaseline)
3320             return result;
3321         return result - result / 2;
3322     }
3323     return 0;
3324 }
3325 
3326 
enclosingFloatPaintingLayer() const3327 RenderLayer* RenderBox::enclosingFloatPaintingLayer() const
3328 {
3329     const RenderObject* curr = this;
3330     while (curr) {
3331         RenderLayer* layer = curr->hasLayer() && curr->isBox() ? toRenderBoxModelObject(curr)->layer() : 0;
3332         if (layer && layer->isSelfPaintingLayer())
3333             return layer;
3334         curr = curr->parent();
3335     }
3336     return 0;
3337 }
3338 
logicalVisualOverflowRectForPropagation(RenderStyle * parentStyle) const3339 IntRect RenderBox::logicalVisualOverflowRectForPropagation(RenderStyle* parentStyle) const
3340 {
3341     IntRect rect = visualOverflowRectForPropagation(parentStyle);
3342     if (!parentStyle->isHorizontalWritingMode())
3343         return rect.transposedRect();
3344     return rect;
3345 }
3346 
visualOverflowRectForPropagation(RenderStyle * parentStyle) const3347 IntRect RenderBox::visualOverflowRectForPropagation(RenderStyle* parentStyle) const
3348 {
3349     // If the writing modes of the child and parent match, then we don't have to
3350     // do anything fancy. Just return the result.
3351     IntRect rect = visualOverflowRect();
3352     if (parentStyle->writingMode() == style()->writingMode())
3353         return rect;
3354 
3355     // We are putting ourselves into our parent's coordinate space.  If there is a flipped block mismatch
3356     // in a particular axis, then we have to flip the rect along that axis.
3357     if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
3358         rect.setX(width() - rect.maxX());
3359     else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
3360         rect.setY(height() - rect.maxY());
3361 
3362     return rect;
3363 }
3364 
logicalLayoutOverflowRectForPropagation(RenderStyle * parentStyle) const3365 IntRect RenderBox::logicalLayoutOverflowRectForPropagation(RenderStyle* parentStyle) const
3366 {
3367     IntRect rect = layoutOverflowRectForPropagation(parentStyle);
3368     if (!parentStyle->isHorizontalWritingMode())
3369         return rect.transposedRect();
3370     return rect;
3371 }
3372 
layoutOverflowRectForPropagation(RenderStyle * parentStyle) const3373 IntRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle) const
3374 {
3375     // Only propagate interior layout overflow if we don't clip it.
3376     IntRect rect = borderBoxRect();
3377     if (!hasOverflowClip())
3378         rect.unite(layoutOverflowRect());
3379 
3380     bool hasTransform = hasLayer() && layer()->transform();
3381     if (isRelPositioned() || hasTransform) {
3382         // If we are relatively positioned or if we have a transform, then we have to convert
3383         // this rectangle into physical coordinates, apply relative positioning and transforms
3384         // to it, and then convert it back.
3385         flipForWritingMode(rect);
3386 
3387         if (hasTransform)
3388             rect = layer()->currentTransform().mapRect(rect);
3389 
3390         if (isRelPositioned())
3391             rect.move(relativePositionOffsetX(), relativePositionOffsetY());
3392 
3393         // Now we need to flip back.
3394         flipForWritingMode(rect);
3395     }
3396 
3397     // If the writing modes of the child and parent match, then we don't have to
3398     // do anything fancy. Just return the result.
3399     if (parentStyle->writingMode() == style()->writingMode())
3400         return rect;
3401 
3402     // We are putting ourselves into our parent's coordinate space.  If there is a flipped block mismatch
3403     // in a particular axis, then we have to flip the rect along that axis.
3404     if (style()->writingMode() == RightToLeftWritingMode || parentStyle->writingMode() == RightToLeftWritingMode)
3405         rect.setX(width() - rect.maxX());
3406     else if (style()->writingMode() == BottomToTopWritingMode || parentStyle->writingMode() == BottomToTopWritingMode)
3407         rect.setY(height() - rect.maxY());
3408 
3409     return rect;
3410 }
3411 
flipForWritingMode(const RenderBox * child,const IntPoint & point,FlippingAdjustment adjustment) const3412 IntPoint RenderBox::flipForWritingMode(const RenderBox* child, const IntPoint& point, FlippingAdjustment adjustment) const
3413 {
3414     if (!style()->isFlippedBlocksWritingMode())
3415         return point;
3416 
3417     // The child is going to add in its x() and y(), so we have to make sure it ends up in
3418     // the right place.
3419     if (isHorizontalWritingMode())
3420         return IntPoint(point.x(), point.y() + height() - child->height() - child->y() - (adjustment == ParentToChildFlippingAdjustment ? child->y() : 0));
3421     return IntPoint(point.x() + width() - child->width() - child->x() - (adjustment == ParentToChildFlippingAdjustment ? child->x() : 0), point.y());
3422 }
3423 
flipForWritingMode(IntRect & rect) const3424 void RenderBox::flipForWritingMode(IntRect& rect) const
3425 {
3426     if (!style()->isFlippedBlocksWritingMode())
3427         return;
3428 
3429     if (isHorizontalWritingMode())
3430         rect.setY(height() - rect.maxY());
3431     else
3432         rect.setX(width() - rect.maxX());
3433 }
3434 
flipForWritingMode(int position) const3435 int RenderBox::flipForWritingMode(int position) const
3436 {
3437     if (!style()->isFlippedBlocksWritingMode())
3438         return position;
3439     return logicalHeight() - position;
3440 }
3441 
flipForWritingMode(const IntPoint & position) const3442 IntPoint RenderBox::flipForWritingMode(const IntPoint& position) const
3443 {
3444     if (!style()->isFlippedBlocksWritingMode())
3445         return position;
3446     return isHorizontalWritingMode() ? IntPoint(position.x(), height() - position.y()) : IntPoint(width() - position.x(), position.y());
3447 }
3448 
flipForWritingModeIncludingColumns(const IntPoint & point) const3449 IntPoint RenderBox::flipForWritingModeIncludingColumns(const IntPoint& point) const
3450 {
3451     if (!hasColumns() || !style()->isFlippedBlocksWritingMode())
3452         return flipForWritingMode(point);
3453     return toRenderBlock(this)->flipForWritingModeIncludingColumns(point);
3454 }
3455 
flipForWritingMode(const IntSize & offset) const3456 IntSize RenderBox::flipForWritingMode(const IntSize& offset) const
3457 {
3458     if (!style()->isFlippedBlocksWritingMode())
3459         return offset;
3460     return isHorizontalWritingMode() ? IntSize(offset.width(), height() - offset.height()) : IntSize(width() - offset.width(), offset.height());
3461 }
3462 
flipForWritingMode(const FloatPoint & position) const3463 FloatPoint RenderBox::flipForWritingMode(const FloatPoint& position) const
3464 {
3465     if (!style()->isFlippedBlocksWritingMode())
3466         return position;
3467     return isHorizontalWritingMode() ? FloatPoint(position.x(), height() - position.y()) : FloatPoint(width() - position.x(), position.y());
3468 }
3469 
flipForWritingMode(FloatRect & rect) const3470 void RenderBox::flipForWritingMode(FloatRect& rect) const
3471 {
3472     if (!style()->isFlippedBlocksWritingMode())
3473         return;
3474 
3475     if (isHorizontalWritingMode())
3476         rect.setY(height() - rect.maxY());
3477     else
3478         rect.setX(width() - rect.maxX());
3479 }
3480 
locationOffsetIncludingFlipping() const3481 IntSize RenderBox::locationOffsetIncludingFlipping() const
3482 {
3483     RenderBlock* containerBlock = containingBlock();
3484     if (!containerBlock || containerBlock == this)
3485         return locationOffset();
3486 
3487     IntRect rect(frameRect());
3488     containerBlock->flipForWritingMode(rect); // FIXME: This is wrong if we are an absolutely positioned object enclosed by a relative-positioned inline.
3489     return IntSize(rect.x(), rect.y());
3490 }
3491 
3492 } // namespace WebCore
3493