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