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