Rename flex-align to flex-item-align.
[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()->position() == AbsolutePosition || style()->position() == FixedPosition);
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     const FillLayer* bgLayer = style()->backgroundLayers();
862     Color bgColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
863     RenderObject* bodyObject = 0;
864     if (!hasBackground() && node() && node()->hasTagName(HTMLNames::htmlTag)) {
865         // Locate the <body> element using the DOM.  This is easier than trying
866         // to crawl around a render tree with potential :before/:after content and
867         // anonymous blocks created by inline <body> tags etc.  We can locate the <body>
868         // render object very easily via the DOM.
869         HTMLElement* body = document()->body();
870         bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
871         if (bodyObject) {
872             bgLayer = bodyObject->style()->backgroundLayers();
873             bgColor = bodyObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
874         }
875     }
876
877     paintFillLayers(paintInfo, bgColor, bgLayer, view()->backgroundRect(this), BackgroundBleedNone, CompositeSourceOver, bodyObject);
878 }
879
880 BackgroundBleedAvoidance RenderBox::determineBackgroundBleedAvoidance(GraphicsContext* context) const
881 {
882     if (context->paintingDisabled())
883         return BackgroundBleedNone;
884
885     const RenderStyle* style = this->style();
886
887     if (!style->hasBackground() || !style->hasBorder() || !style->hasBorderRadius() || borderImageIsLoadedAndCanBeRendered())
888         return BackgroundBleedNone;
889
890     AffineTransform ctm = context->getCTM();
891     FloatSize contextScaling(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
892     if (borderObscuresBackgroundEdge(contextScaling))
893         return BackgroundBleedShrinkBackground;
894     
895     // FIXME: there is one more strategy possible, for opaque backgrounds and
896     // translucent borders. In that case we could avoid using a transparency layer,
897     // and paint the border first, and then paint the background clipped to the
898     // inside of the border.
899
900     return BackgroundBleedUseTransparencyLayer;
901 }
902
903 void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
904 {
905     if (!paintInfo.shouldPaintWithinRoot(this))
906         return;
907
908     LayoutRect paintRect = borderBoxRectInRegion(paintInfo.renderRegion);
909     paintRect.moveBy(paintOffset);
910
911     // border-fit can adjust where we paint our border and background.  If set, we snugly fit our line box descendants.  (The iChat
912     // balloon layout is an example of this).
913     borderFitAdjust(paintRect);
914
915     // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
916     // custom shadows of their own.
917     paintBoxShadow(paintInfo, paintRect, style(), Normal);
918
919     BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
920
921     GraphicsContextStateSaver stateSaver(*paintInfo.context, false);
922     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
923         // To avoid the background color bleeding out behind the border, we'll render background and border
924         // into a transparency layer, and then clip that in one go (which requires setting up the clip before
925         // beginning the layer).
926         RoundedRect border = style()->getRoundedBorderFor(paintRect);
927         stateSaver.save();
928         paintInfo.context->addRoundedRectClip(border);
929         paintInfo.context->beginTransparencyLayer(1);
930     }
931     
932     // If we have a native theme appearance, paint that before painting our background.
933     // The theme will tell us whether or not we should also paint the CSS background.
934     bool themePainted = style()->hasAppearance() && !theme()->paint(this, paintInfo, paintRect);
935     if (!themePainted) {
936         paintBackground(paintInfo, paintRect, bleedAvoidance);
937
938         if (style()->hasAppearance())
939             theme()->paintDecorations(this, paintInfo, paintRect);
940     }
941     paintBoxShadow(paintInfo, paintRect, style(), Inset);
942
943     // The theme will tell us whether or not we should also paint the CSS border.
944     if ((!style()->hasAppearance() || (!themePainted && theme()->paintBorderOnly(this, paintInfo, paintRect))) && style()->hasBorder())
945         paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
946
947     if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
948         paintInfo.context->endTransparencyLayer();
949 }
950
951 void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
952 {
953     if (isRoot())
954         paintRootBoxFillLayers(paintInfo);
955     else if (!isBody() || (document()->documentElement()->renderer() && document()->documentElement()->renderer()->hasBackground())) {
956         // The <body> only paints its background if the root element has defined a background
957         // independent of the body.
958         if (!backgroundIsObscured())
959             paintFillLayers(paintInfo, style()->visitedDependentColor(CSSPropertyBackgroundColor), style()->backgroundLayers(), paintRect, bleedAvoidance);
960     }
961 }
962
963 void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
964 {
965     if (!paintInfo.shouldPaintWithinRoot(this) || style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask || paintInfo.context->paintingDisabled())
966         return;
967
968     LayoutRect paintRect = LayoutRect(paintOffset, size());
969
970     // border-fit can adjust where we paint our border and background.  If set, we snugly fit our line box descendants.  (The iChat
971     // balloon layout is an example of this).
972     borderFitAdjust(paintRect);
973
974     paintMaskImages(paintInfo, paintRect);
975 }
976
977 void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
978 {
979     // Figure out if we need to push a transparency layer to render our mask.
980     bool pushTransparencyLayer = false;
981     bool compositedMask = hasLayer() && layer()->hasCompositedMask();
982     CompositeOperator compositeOp = CompositeSourceOver;
983
984     bool allMaskImagesLoaded = true;
985     
986     if (!compositedMask) {
987         // If the context has a rotation, scale or skew, then use a transparency layer to avoid
988         // pixel cruft around the edge of the mask.
989         const AffineTransform& currentCTM = paintInfo.context->getCTM();
990         pushTransparencyLayer = !currentCTM.isIdentityOrTranslationOrFlipped();
991
992         StyleImage* maskBoxImage = style()->maskBoxImage().image();
993         const FillLayer* maskLayers = style()->maskLayers();
994
995         // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content.
996         if (maskBoxImage)
997             allMaskImagesLoaded &= maskBoxImage->isLoaded();
998
999         if (maskLayers)
1000             allMaskImagesLoaded &= maskLayers->imagesAreLoaded();
1001
1002         // Before all images have loaded, just use an empty transparency layer as the mask.
1003         if (!allMaskImagesLoaded)
1004             pushTransparencyLayer = true;
1005
1006         bool hasMaskLayerWithImage = maskLayers->hasImage();
1007         if (maskBoxImage && hasMaskLayerWithImage) {
1008             // We have a mask-box-image and mask-image, so need to composite them together before using the result as a mask.
1009             pushTransparencyLayer = true;
1010         } else if (hasMaskLayerWithImage) {
1011             // We have to use an extra image buffer to hold the mask. Multiple mask images need
1012             // to composite together using source-over so that they can then combine into a single unified mask that
1013             // can be composited with the content using destination-in.  SVG images need to be able to set compositing modes
1014             // as they draw images contained inside their sub-document, so we paint all our images into a separate buffer
1015             // and composite that buffer as the mask.
1016             // We have to check that the mask images to be rendered contain at least one image that can be actually used in rendering
1017             // before pushing the transparency layer.
1018             for (const FillLayer* fillLayer = maskLayers->next(); fillLayer; fillLayer = fillLayer->next()) {
1019                 if (fillLayer->image() && fillLayer->image()->canRender(this, style()->effectiveZoom())) {
1020                     pushTransparencyLayer = true;
1021                     // We found one image that can be used in rendering, exit the loop
1022                     break;
1023                 }
1024             }
1025         }
1026         
1027         compositeOp = CompositeDestinationIn;
1028         if (pushTransparencyLayer) {
1029             paintInfo.context->setCompositeOperation(CompositeDestinationIn);
1030             paintInfo.context->beginTransparencyLayer(1.0f);
1031             compositeOp = CompositeSourceOver;
1032         }
1033     }
1034
1035     if (allMaskImagesLoaded) {
1036         paintFillLayers(paintInfo, Color(), style()->maskLayers(), paintRect, BackgroundBleedNone, compositeOp);
1037         paintNinePieceImage(paintInfo.context, paintRect, style(), style()->maskBoxImage(), compositeOp);
1038     }
1039     
1040     if (pushTransparencyLayer)
1041         paintInfo.context->endTransparencyLayer();
1042 }
1043
1044 LayoutRect RenderBox::maskClipRect()
1045 {
1046     const NinePieceImage& maskBoxImage = style()->maskBoxImage();
1047     if (maskBoxImage.image()) {
1048         LayoutRect borderImageRect = borderBoxRect();
1049         
1050         // Apply outsets to the border box.
1051         LayoutUnit topOutset;
1052         LayoutUnit rightOutset;
1053         LayoutUnit bottomOutset;
1054         LayoutUnit leftOutset;
1055         style()->getMaskBoxImageOutsets(topOutset, rightOutset, bottomOutset, leftOutset);
1056          
1057         borderImageRect.setX(borderImageRect.x() - leftOutset);
1058         borderImageRect.setY(borderImageRect.y() - topOutset);
1059         borderImageRect.setWidth(borderImageRect.width() + leftOutset + rightOutset);
1060         borderImageRect.setHeight(borderImageRect.height() + topOutset + bottomOutset);
1061
1062         return borderImageRect;
1063     }
1064     
1065     LayoutRect result;
1066     LayoutRect borderBox = borderBoxRect();
1067     for (const FillLayer* maskLayer = style()->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1068         if (maskLayer->image()) {
1069             BackgroundImageGeometry geometry;
1070             calculateBackgroundImageGeometry(maskLayer, borderBox, geometry);
1071             result.unite(geometry.destRect());
1072         }
1073     }
1074     return result;
1075 }
1076
1077 void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1078     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1079 {
1080     if (!fillLayer)
1081         return;
1082
1083     paintFillLayers(paintInfo, c, fillLayer->next(), rect, bleedAvoidance, op, backgroundObject);
1084     paintFillLayer(paintInfo, c, fillLayer, rect, bleedAvoidance, op, backgroundObject);
1085 }
1086
1087 void RenderBox::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer* fillLayer, const LayoutRect& rect,
1088     BackgroundBleedAvoidance bleedAvoidance, CompositeOperator op, RenderObject* backgroundObject)
1089 {
1090     paintFillLayerExtended(paintInfo, c, fillLayer, rect, bleedAvoidance, 0, IntSize(), op, backgroundObject);
1091 }
1092
1093 #if USE(ACCELERATED_COMPOSITING)
1094 static bool layersUseImage(WrappedImagePtr image, const FillLayer* layers)
1095 {
1096     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1097         if (curLayer->image() && image == curLayer->image()->data())
1098             return true;
1099     }
1100
1101     return false;
1102 }
1103 #endif
1104
1105 void RenderBox::imageChanged(WrappedImagePtr image, const IntRect*)
1106 {
1107     if (!parent())
1108         return;
1109
1110     if ((style()->borderImage().image() && style()->borderImage().image()->data() == image) ||
1111         (style()->maskBoxImage().image() && style()->maskBoxImage().image()->data() == image)) {
1112         repaint();
1113         return;
1114     }
1115
1116     bool didFullRepaint = repaintLayerRectsForImage(image, style()->backgroundLayers(), true);
1117     if (!didFullRepaint)
1118         repaintLayerRectsForImage(image, style()->maskLayers(), false);
1119
1120
1121 #if USE(ACCELERATED_COMPOSITING)
1122     if (hasLayer() && layer()->hasCompositedMask() && layersUseImage(image, style()->maskLayers()))
1123         layer()->contentChanged(RenderLayer::MaskImageChanged);
1124 #endif
1125 }
1126
1127 bool RenderBox::repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground)
1128 {
1129     LayoutRect rendererRect;
1130     RenderBox* layerRenderer = 0;
1131
1132     for (const FillLayer* curLayer = layers; curLayer; curLayer = curLayer->next()) {
1133         if (curLayer->image() && image == curLayer->image()->data() && curLayer->image()->canRender(this, style()->effectiveZoom())) {
1134             // Now that we know this image is being used, compute the renderer and the rect
1135             // if we haven't already
1136             if (!layerRenderer) {
1137                 bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document()->documentElement()->renderer()->hasBackground()));
1138                 if (drawingRootBackground) {
1139                     layerRenderer = view();
1140
1141                     LayoutUnit rw;
1142                     LayoutUnit rh;
1143
1144                     if (FrameView* frameView = toRenderView(layerRenderer)->frameView()) {
1145                         rw = frameView->contentsWidth();
1146                         rh = frameView->contentsHeight();
1147                     } else {
1148                         rw = layerRenderer->width();
1149                         rh = layerRenderer->height();
1150                     }
1151                     rendererRect = LayoutRect(-layerRenderer->marginLeft(),
1152                         -layerRenderer->marginTop(),
1153                         max(layerRenderer->width() + layerRenderer->marginLeft() + layerRenderer->marginRight() + layerRenderer->borderLeft() + layerRenderer->borderRight(), rw),
1154                         max(layerRenderer->height() + layerRenderer->marginTop() + layerRenderer->marginBottom() + layerRenderer->borderTop() + layerRenderer->borderBottom(), rh));
1155                 } else {
1156                     layerRenderer = this;
1157                     rendererRect = borderBoxRect();
1158                 }
1159             }
1160
1161             BackgroundImageGeometry geometry;
1162             layerRenderer->calculateBackgroundImageGeometry(curLayer, rendererRect, geometry);
1163             layerRenderer->repaintRectangle(geometry.destRect());
1164             if (geometry.destRect() == rendererRect)
1165                 return true;
1166         }
1167     }
1168     return false;
1169 }
1170
1171 #if PLATFORM(MAC)
1172
1173 void RenderBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type, bool behindText)
1174 {
1175     Frame* frame = this->frame();
1176     if (!frame)
1177         return;
1178     Page* page = frame->page();
1179     if (!page)
1180         return;
1181
1182     InlineBox* boxWrap = inlineBoxWrapper();
1183     RootInlineBox* r = boxWrap ? boxWrap->root() : 0;
1184     if (r) {
1185         FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + r->selectionTop(), r->logicalWidth(), r->selectionHeight());
1186         FloatRect imageRect(paintOffset.x() + x(), rootRect.y(), width(), rootRect.height());
1187         page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, rootRect, behindText, false);
1188     } else {
1189         FloatRect imageRect(paintOffset.x() + x(), paintOffset.y() + y(), width(), height());
1190         page->chrome()->client()->paintCustomHighlight(node(), type, imageRect, imageRect, behindText, false);
1191     }
1192 }
1193
1194 #endif
1195
1196 bool RenderBox::pushContentsClip(PaintInfo& paintInfo, const LayoutPoint& accumulatedOffset)
1197 {
1198     if (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseSelfOutline || paintInfo.phase == PaintPhaseMask)
1199         return false;
1200         
1201     bool isControlClip = hasControlClip();
1202     bool isOverflowClip = hasOverflowClip() && !layer()->isSelfPaintingLayer();
1203     
1204     if (!isControlClip && !isOverflowClip)
1205         return false;
1206     
1207     if (paintInfo.phase == PaintPhaseOutline)
1208         paintInfo.phase = PaintPhaseChildOutlines;
1209     else if (paintInfo.phase == PaintPhaseChildBlockBackground) {
1210         paintInfo.phase = PaintPhaseBlockBackground;
1211         paintObject(paintInfo, accumulatedOffset);
1212         paintInfo.phase = PaintPhaseChildBlockBackgrounds;
1213     }
1214     IntRect clipRect(isControlClip ? controlClipRect(accumulatedOffset) : overflowClipRect(accumulatedOffset, paintInfo.renderRegion));
1215     paintInfo.context->save();
1216     if (style()->hasBorderRadius())
1217         paintInfo.context->addRoundedRectClip(style()->getRoundedInnerBorderFor(LayoutRect(accumulatedOffset, size())));
1218     paintInfo.context->clip(clipRect);
1219     return true;
1220 }
1221
1222 void RenderBox::popContentsClip(PaintInfo& paintInfo, PaintPhase originalPhase, const LayoutPoint& accumulatedOffset)
1223 {
1224     ASSERT(hasControlClip() || (hasOverflowClip() && !layer()->isSelfPaintingLayer()));
1225
1226     paintInfo.context->restore();
1227     if (originalPhase == PaintPhaseOutline) {
1228         paintInfo.phase = PaintPhaseSelfOutline;
1229         paintObject(paintInfo, accumulatedOffset);
1230         paintInfo.phase = originalPhase;
1231     } else if (originalPhase == PaintPhaseChildBlockBackground)
1232         paintInfo.phase = originalPhase;
1233 }
1234
1235 LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion* region, OverlayScrollbarSizeRelevancy relevancy)
1236 {
1237     // FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the property
1238     // here.
1239     LayoutRect clipRect = borderBoxRectInRegion(region);
1240     clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
1241     clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
1242
1243     // Subtract out scrollbars if we have them.
1244     if (layer())
1245         clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
1246
1247     return clipRect;
1248 }
1249
1250 LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region)
1251 {
1252     LayoutRect borderBoxRect = borderBoxRectInRegion(region);
1253     LayoutRect clipRect = LayoutRect(borderBoxRect.location() + location, borderBoxRect.size());
1254
1255     if (!style()->clipLeft().isAuto()) {
1256         LayoutUnit c = style()->clipLeft().calcValue(borderBoxRect.width());
1257         clipRect.move(c, 0);
1258         clipRect.contract(c, 0);
1259     }
1260
1261     // We don't use the region-specific border box's width and height since clip offsets are (stupidly) specified
1262     // from the left and top edges. Therefore it's better to avoid constraining to smaller widths and heights.
1263
1264     if (!style()->clipRight().isAuto())
1265         clipRect.contract(width() - style()->clipRight().calcValue(width()), 0);
1266
1267     if (!style()->clipTop().isAuto()) {
1268         LayoutUnit c = style()->clipTop().calcValue(borderBoxRect.height());
1269         clipRect.move(0, c);
1270         clipRect.contract(0, c);
1271     }
1272
1273     if (!style()->clipBottom().isAuto())
1274         clipRect.contract(0, height() - style()->clipBottom().calcValue(height()));
1275
1276     return clipRect;
1277 }
1278
1279 LayoutUnit RenderBox::containingBlockLogicalWidthForContent() const
1280 {
1281     RenderBlock* cb = containingBlock();
1282     if (shrinkToAvoidFloats() && !inRenderFlowThread())
1283         return cb->availableLogicalWidthForLine(logicalTop(), false);
1284     return cb->availableLogicalWidth();
1285 }
1286
1287 LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
1288 {
1289     if (!region)
1290         return containingBlockLogicalWidthForContent();
1291
1292     RenderBlock* cb = containingBlock();
1293     RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
1294     if (shrinkToAvoidFloats()) {
1295         LayoutUnit offsetFromLogicalTopOfRegion = region->offsetFromLogicalTopOfFirstPage() - offsetFromLogicalTopOfFirstPage;
1296         return cb->availableLogicalWidthForLine(max(logicalTop(), logicalTop() + offsetFromLogicalTopOfRegion), false, containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
1297     }
1298     LayoutUnit result = cb->availableLogicalWidth();
1299     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
1300     if (!boxInfo)
1301         return result;
1302     return max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
1303 }
1304
1305 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
1306 {
1307     RenderBlock* cb = containingBlock();
1308     RenderStyle* containingBlockStyle = cb->style();
1309     Length logicalHeightLength = containingBlockStyle->logicalHeight();
1310     
1311     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
1312     if (!logicalHeightLength.isFixed()) {
1313         // Rather than making the child be completely unconstrained, WinIE uses the viewport width and height
1314         // as a constraint.  We do that for now as well even though it's likely being unconstrained is what the spec
1315         // will decide.
1316         return containingBlockStyle->isHorizontalWritingMode() ? view()->frameView()->visibleHeight() : view()->frameView()->visibleWidth();
1317     }
1318     
1319     // Use the content box logical height as specified by the style.
1320     return cb->computeContentBoxLogicalHeight(logicalHeightLength.value());
1321 }
1322
1323 void RenderBox::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
1324 {
1325     if (repaintContainer == this)
1326         return;
1327
1328     if (RenderView* v = view()) {
1329         if (v->layoutStateEnabled() && !repaintContainer) {
1330             LayoutState* layoutState = v->layoutState();
1331             LayoutSize offset = layoutState->m_paintOffset;
1332             offset.expand(x(), y());
1333             if (style()->position() == RelativePosition && layer())
1334                 offset += layer()->relativePositionOffset();
1335             transformState.move(offset);
1336             return;
1337         }
1338     }
1339
1340     bool containerSkipped;
1341     RenderObject* o = container(repaintContainer, &containerSkipped);
1342     if (!o)
1343         return;
1344
1345     bool isFixedPos = style()->position() == FixedPosition;
1346     bool hasTransform = hasLayer() && layer()->transform();
1347     if (hasTransform) {
1348         // If this box has a transform, it acts as a fixed position container for fixed descendants,
1349         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1350         fixed &= isFixedPos;
1351     } else
1352         fixed |= isFixedPos;
1353     if (wasFixed)
1354         *wasFixed = fixed;
1355     
1356     LayoutSize containerOffset = offsetFromContainer(o, roundedLayoutPoint(transformState.mappedPoint()));
1357     
1358     bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
1359     if (useTransforms && shouldUseTransformFromContainer(o)) {
1360         TransformationMatrix t;
1361         getTransformFromContainer(o, containerOffset, t);
1362         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1363     } else
1364         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1365
1366     if (containerSkipped) {
1367         // There can't be a transform between repaintContainer and o, because transforms create containers, so it should be safe
1368         // to just subtract the delta between the repaintContainer and o.
1369         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1370         transformState.move(-containerOffset.width(), -containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
1371         return;
1372     }
1373
1374     if (o->isRenderFlowThread()) {
1375         // Transform from render flow coordinates into region coordinates.
1376         RenderRegion* region = toRenderFlowThread(o)->mapFromFlowToRegion(transformState);
1377         if (region)
1378             region->mapLocalToContainer(region->containerForRepaint(), fixed, useTransforms, transformState, wasFixed);
1379         return;
1380     }
1381
1382     o->mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
1383 }
1384
1385 void RenderBox::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
1386 {
1387     // We don't expect absoluteToLocal() to be called during layout (yet)
1388     ASSERT(!view() || !view()->layoutStateEnabled());
1389     
1390     bool isFixedPos = style()->position() == FixedPosition;
1391     bool hasTransform = hasLayer() && layer()->transform();
1392     if (hasTransform) {
1393         // If this box has a transform, it acts as a fixed position container for fixed descendants,
1394         // and may itself also be fixed position. So propagate 'fixed' up only if this box is fixed position.
1395         fixed &= isFixedPos;
1396     } else
1397         fixed |= isFixedPos;
1398
1399     RenderBoxModelObject::mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
1400 }
1401
1402 LayoutSize RenderBox::offsetFromContainer(RenderObject* o, const LayoutPoint& point) const
1403 {
1404     ASSERT(o == container());
1405
1406     LayoutSize offset;    
1407     if (isRelPositioned())
1408         offset += relativePositionOffset();
1409
1410     if (!isInline() || isReplaced()) {
1411         if (style()->position() != AbsolutePosition && style()->position() != FixedPosition && o->hasColumns()) {
1412             RenderBlock* block = toRenderBlock(o);
1413             LayoutRect columnRect(frameRect());
1414             block->adjustStartEdgeForWritingModeIncludingColumns(columnRect);
1415             offset += toSize(columnRect.location());
1416             LayoutPoint columnPoint = block->flipForWritingModeIncludingColumns(point + offset);
1417             offset = toLayoutSize(block->flipForWritingModeIncludingColumns(toLayoutPoint(offset)));
1418             o->adjustForColumns(offset, columnPoint);
1419             offset = block->flipForWritingMode(offset);
1420         } else
1421             offset += topLeftLocationOffset();
1422     }
1423
1424     if (o->hasOverflowClip())
1425         offset -= toRenderBox(o)->layer()->scrolledContentOffset();
1426
1427     if (style()->position() == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1428         offset += toRenderInline(o)->relativePositionedInlineOffset(this);
1429
1430     return offset;
1431 }
1432
1433 InlineBox* RenderBox::createInlineBox()
1434 {
1435     return new (renderArena()) InlineBox(this);
1436 }
1437
1438 void RenderBox::dirtyLineBoxes(bool fullLayout)
1439 {
1440     if (m_inlineBoxWrapper) {
1441         if (fullLayout) {
1442             m_inlineBoxWrapper->destroy(renderArena());
1443             m_inlineBoxWrapper = 0;
1444         } else
1445             m_inlineBoxWrapper->dirtyLineBoxes();
1446     }
1447 }
1448
1449 void RenderBox::positionLineBox(InlineBox* box)
1450 {
1451     if (isPositioned()) {
1452         // Cache the x position only if we were an INLINE type originally.
1453         bool wasInline = style()->isOriginalDisplayInlineType();
1454         if (wasInline) {
1455             // The value is cached in the xPos of the box.  We only need this value if
1456             // our object was inline originally, since otherwise it would have ended up underneath
1457             // the inlines.
1458             RootInlineBox* root = box->root();
1459             root->block()->setStaticInlinePositionForChild(this, root->lineTopWithLeading(), lroundf(box->logicalLeft()));
1460             if (style()->hasStaticInlinePosition(box->isHorizontal()))
1461                 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1462         } else {
1463             // Our object was a block originally, so we make our normal flow position be
1464             // just below the line box (as though all the inlines that came before us got
1465             // wrapped in an anonymous block, which is what would have happened had we been
1466             // in flow).  This value was cached in the y() of the box.
1467             layer()->setStaticBlockPosition(box->logicalTop());
1468             if (style()->hasStaticBlockPosition(box->isHorizontal()))
1469                 setChildNeedsLayout(true, false); // Just go ahead and mark the positioned object as needing layout, so it will update its position properly.
1470         }
1471
1472         // Nuke the box.
1473         box->remove();
1474         box->destroy(renderArena());
1475     } else if (isReplaced()) {
1476         setLocation(roundedLayoutPoint(box->topLeft()));
1477         // m_inlineBoxWrapper should already be 0. Deleting it is a safeguard against security issues.
1478         ASSERT(!m_inlineBoxWrapper);
1479         if (m_inlineBoxWrapper)
1480             deleteLineBoxWrapper();
1481         m_inlineBoxWrapper = box;
1482     }
1483 }
1484
1485 void RenderBox::deleteLineBoxWrapper()
1486 {
1487     if (m_inlineBoxWrapper) {
1488         if (!documentBeingDestroyed())
1489             m_inlineBoxWrapper->remove();
1490         m_inlineBoxWrapper->destroy(renderArena());
1491         m_inlineBoxWrapper = 0;
1492     }
1493 }
1494
1495 LayoutRect RenderBox::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
1496 {
1497     if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
1498         return LayoutRect();
1499
1500     LayoutRect r = visualOverflowRect();
1501
1502     RenderView* v = view();
1503     if (v) {
1504         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
1505         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
1506         r.move(v->layoutDelta());
1507     }
1508     
1509     if (style()) {
1510         // We have to use maximalOutlineSize() because a child might have an outline
1511         // that projects outside of our overflowRect.
1512         if (v) {
1513             ASSERT(style()->outlineSize() <= v->maximalOutlineSize());
1514             r.inflate(v->maximalOutlineSize());
1515         }
1516     }
1517     
1518     computeRectForRepaint(repaintContainer, r);
1519     return r;
1520 }
1521
1522 void RenderBox::computeRectForRepaint(RenderBoxModelObject* repaintContainer, LayoutRect& rect, bool fixed) const
1523 {
1524     // The rect we compute at each step is shifted by our x/y offset in the parent container's coordinate space.
1525     // Only when we cross a writing mode boundary will we have to possibly flipForWritingMode (to convert into a more appropriate
1526     // offset corner for the enclosing container).  This allows for a fully RL or BT document to repaint
1527     // properly even during layout, since the rect remains flipped all the way until the end.
1528     //
1529     // RenderView::computeRectForRepaint then converts the rect to physical coordinates.  We also convert to
1530     // physical when we hit a repaintContainer boundary.  Therefore the final rect returned is always in the
1531     // physical coordinate space of the repaintContainer.
1532     if (RenderView* v = view()) {
1533         // LayoutState is only valid for root-relative, non-fixed position repainting
1534         if (v->layoutStateEnabled() && !repaintContainer && style()->position() != FixedPosition) {
1535             LayoutState* layoutState = v->layoutState();
1536
1537             if (layer() && layer()->transform())
1538                 rect = layer()->transform()->mapRect(rect);
1539
1540             if (style()->position() == RelativePosition && layer())
1541                 rect.move(layer()->relativePositionOffset());
1542
1543             rect.moveBy(location());
1544             rect.move(layoutState->m_paintOffset);
1545             if (layoutState->m_clipped)
1546                 rect.intersect(layoutState->m_clipRect);
1547             return;
1548         }
1549     }
1550
1551     if (hasReflection())
1552         rect.unite(reflectedRect(rect));
1553
1554     if (repaintContainer == this) {
1555         if (repaintContainer->style()->isFlippedBlocksWritingMode())
1556             flipForWritingMode(rect);
1557         return;
1558     }
1559
1560     bool containerSkipped;
1561     RenderObject* o = container(repaintContainer, &containerSkipped);
1562     if (!o)
1563         return;
1564
1565     if (isWritingModeRoot() && !isPositioned())
1566         flipForWritingMode(rect);
1567
1568 #if ENABLE(CSS_FILTERS)
1569     if (style()->hasFilterOutsets()) {
1570         LayoutUnit topOutset;
1571         LayoutUnit rightOutset;
1572         LayoutUnit bottomOutset;
1573         LayoutUnit leftOutset;
1574         style()->filter().getOutsets(topOutset, rightOutset, bottomOutset, leftOutset);
1575         rect.move(-leftOutset, -topOutset);
1576         rect.expand(leftOutset + rightOutset, topOutset + bottomOutset);
1577     }
1578 #endif
1579
1580     LayoutPoint topLeft = rect.location();
1581     topLeft.move(x(), y());
1582
1583     EPosition position = style()->position();
1584
1585     // We are now in our parent container's coordinate space.  Apply our transform to obtain a bounding box
1586     // in the parent's coordinate space that encloses us.
1587     if (layer() && layer()->transform()) {
1588         fixed = position == FixedPosition;
1589         rect = layer()->transform()->mapRect(rect);
1590         topLeft = rect.location();
1591         topLeft.move(x(), y());
1592     } else if (position == FixedPosition)
1593         fixed = true;
1594
1595     if (position == AbsolutePosition && o->isRelPositioned() && o->isRenderInline())
1596         topLeft += toRenderInline(o)->relativePositionedInlineOffset(this);
1597     else if (position == RelativePosition && layer()) {
1598         // Apply the relative position offset when invalidating a rectangle.  The layer
1599         // is translated, but the render box isn't, so we need to do this to get the
1600         // right dirty rect.  Since this is called from RenderObject::setStyle, the relative position
1601         // flag on the RenderObject has been cleared, so use the one on the style().
1602         topLeft += layer()->relativePositionOffset();
1603     }
1604     
1605     if (o->isBlockFlow() && position != AbsolutePosition && position != FixedPosition) {
1606         RenderBlock* cb = toRenderBlock(o);
1607         if (cb->hasColumns()) {
1608             LayoutRect repaintRect(topLeft, rect.size());
1609             cb->adjustRectForColumns(repaintRect);
1610             topLeft = repaintRect.location();
1611             rect = repaintRect;
1612         }
1613     }
1614
1615     // FIXME: We ignore the lightweight clipping rect that controls use, since if |o| is in mid-layout,
1616     // its controlClipRect will be wrong. For overflow clip we use the values cached by the layer.
1617     if (o->hasOverflowClip()) {
1618         RenderBox* containerBox = toRenderBox(o);
1619
1620         // o->height() is inaccurate if we're in the middle of a layout of |o|, so use the
1621         // layer's size instead.  Even if the layer's size is wrong, the layer itself will repaint
1622         // anyway if its size does change.
1623         topLeft -= containerBox->layer()->scrolledContentOffset(); // For overflow:auto/scroll/hidden.
1624
1625         LayoutRect repaintRect(topLeft, rect.size());
1626         LayoutRect boxRect(LayoutPoint(), containerBox->layer()->size());
1627         rect = intersection(repaintRect, boxRect);
1628         if (rect.isEmpty())
1629             return;
1630     } else
1631         rect.setLocation(topLeft);
1632
1633     if (containerSkipped) {
1634         // If the repaintContainer is below o, then we need to map the rect into repaintContainer's coordinates.
1635         LayoutSize containerOffset = repaintContainer->offsetFromAncestorContainer(o);
1636         rect.move(-containerOffset);
1637         return;
1638     }
1639
1640     o->computeRectForRepaint(repaintContainer, rect, fixed);
1641 }
1642
1643 void RenderBox::repaintDuringLayoutIfMoved(const LayoutRect& rect)
1644 {
1645     LayoutUnit newX = x();
1646     LayoutUnit newY = y();
1647     LayoutUnit newWidth = width();
1648     LayoutUnit newHeight = height();
1649     if (rect.x() != newX || rect.y() != newY) {
1650         // The child moved.  Invalidate the object's old and new positions.  We have to do this
1651         // since the object may not have gotten a layout.
1652         m_frameRect = rect;
1653         repaint();
1654         repaintOverhangingFloats(true);
1655         m_frameRect = LayoutRect(newX, newY, newWidth, newHeight);
1656         repaint();
1657         repaintOverhangingFloats(true);
1658     }
1659 }
1660
1661 void RenderBox::computeLogicalWidth()
1662 {
1663     computeLogicalWidthInRegion();
1664 }
1665
1666 void RenderBox::computeLogicalWidthInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
1667 {
1668     if (isPositioned()) {
1669         // FIXME: This calculation is not patched for block-flow yet.
1670         // https://bugs.webkit.org/show_bug.cgi?id=46500
1671         computePositionedLogicalWidth(region, offsetFromLogicalTopOfFirstPage);
1672         return;
1673     }
1674
1675     // If layout is limited to a subtree, the subtree root's logical width does not change.
1676     if (node() && view()->frameView() && view()->frameView()->layoutRoot(true) == this)
1677         return;
1678
1679     // The parent box is flexing us, so it has increased or decreased our
1680     // width.  Use the width from the style context.
1681     // FIXME: Account for block-flow in flexible boxes.
1682     // https://bugs.webkit.org/show_bug.cgi?id=46418
1683     if (hasOverrideWidth() && parent()->isFlexibleBoxIncludingDeprecated()) {
1684         setLogicalWidth(overrideWidth());
1685         return;
1686     }
1687
1688     // FIXME: Account for block-flow in flexible boxes.
1689     // https://bugs.webkit.org/show_bug.cgi?id=46418
1690     bool inVerticalBox = parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == VERTICAL);
1691     bool stretching = (parent()->style()->boxAlign() == BSTRETCH);
1692     bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inVerticalBox || !stretching);
1693
1694     Length logicalWidthLength = (treatAsReplaced) ? Length(computeReplacedLogicalWidth(), Fixed) : style()->logicalWidth();
1695
1696     RenderBlock* cb = containingBlock();
1697     LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region, offsetFromLogicalTopOfFirstPage));
1698     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1699     LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
1700     if (hasPerpendicularContainingBlock)
1701         containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
1702     
1703     if (isInline() && !isInlineBlockOrInlineTable()) {
1704         // just calculate margins
1705         setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1706         setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1707         if (treatAsReplaced)
1708             setLogicalWidth(max<LayoutUnit>(logicalWidthLength.calcFloatValue(0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth()));
1709         return;
1710     }
1711
1712     // Width calculations
1713     if (treatAsReplaced)
1714         setLogicalWidth(logicalWidthLength.value() + borderAndPaddingLogicalWidth());
1715     else {
1716         // Calculate LogicalWidth
1717         setLogicalWidth(computeLogicalWidthUsing(LogicalWidth, containerWidthInInlineDirection));
1718
1719         // Calculate MaxLogicalWidth
1720         if (!style()->logicalMaxWidth().isUndefined()) {
1721             LayoutUnit maxLogicalWidth = computeLogicalWidthUsing(MaxLogicalWidth, containerWidthInInlineDirection);
1722             if (logicalWidth() > maxLogicalWidth) {
1723                 setLogicalWidth(maxLogicalWidth);
1724                 logicalWidthLength = style()->logicalMaxWidth();
1725             }
1726         }
1727
1728         // Calculate MinLogicalWidth
1729         LayoutUnit minLogicalWidth = computeLogicalWidthUsing(MinLogicalWidth, containerWidthInInlineDirection);
1730         if (logicalWidth() < minLogicalWidth) {
1731             setLogicalWidth(minLogicalWidth);
1732             logicalWidthLength = style()->logicalMinWidth();
1733         }
1734     }
1735
1736     // Fieldsets are currently the only objects that stretch to their minimum width.
1737     if (stretchesToMinIntrinsicLogicalWidth()) {
1738         setLogicalWidth(max(logicalWidth(), minPreferredLogicalWidth()));
1739         logicalWidthLength = Length(logicalWidth(), Fixed);
1740     }
1741
1742     // Margin calculations.
1743     if (logicalWidthLength.isAuto() || hasPerpendicularContainingBlock) {
1744         setMarginStart(style()->marginStart().calcMinValue(containerLogicalWidth));
1745         setMarginEnd(style()->marginEnd().calcMinValue(containerLogicalWidth));
1746     } else
1747         computeInlineDirectionMargins(cb, containerLogicalWidth, logicalWidth());
1748
1749     if (!hasPerpendicularContainingBlock && containerLogicalWidth && containerLogicalWidth != (logicalWidth() + marginStart() + marginEnd())
1750             && !isFloating() && !isInline() && !cb->isFlexibleBoxIncludingDeprecated())
1751         cb->setMarginEndForChild(this, containerLogicalWidth - logicalWidth() - cb->marginStartForChild(this));
1752 }
1753
1754 LayoutUnit RenderBox::computeLogicalWidthUsing(LogicalWidthType widthType, LayoutUnit availableLogicalWidth)
1755 {
1756     LayoutUnit logicalWidthResult = logicalWidth();
1757     Length logicalWidth;
1758     if (widthType == LogicalWidth)
1759         logicalWidth = style()->logicalWidth();
1760     else if (widthType == MinLogicalWidth)
1761         logicalWidth = style()->logicalMinWidth();
1762     else
1763         logicalWidth = style()->logicalMaxWidth();
1764
1765     if (logicalWidth.isIntrinsicOrAuto()) {
1766         LayoutUnit marginStart = style()->marginStart().calcMinValue(availableLogicalWidth);
1767         LayoutUnit marginEnd = style()->marginEnd().calcMinValue(availableLogicalWidth);
1768         logicalWidthResult = availableLogicalWidth - marginStart - marginEnd;
1769
1770         if (sizesToIntrinsicLogicalWidth(widthType)) {
1771             logicalWidthResult = max(logicalWidthResult, minPreferredLogicalWidth());
1772             logicalWidthResult = min(logicalWidthResult, maxPreferredLogicalWidth());
1773         }
1774     } else // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
1775         logicalWidthResult = computeBorderBoxLogicalWidth(logicalWidth.calcValue(availableLogicalWidth)); 
1776
1777     return logicalWidthResult;
1778 }
1779
1780 bool RenderBox::sizesToIntrinsicLogicalWidth(LogicalWidthType widthType) const
1781 {
1782     // Marquees in WinIE are like a mixture of blocks and inline-blocks.  They size as though they're blocks,
1783     // but they allow text to sit on the same line as the marquee.
1784     if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee()))
1785         return true;
1786
1787     // This code may look a bit strange.  Basically width:intrinsic should clamp the size when testing both
1788     // min-width and width.  max-width is only clamped if it is also intrinsic.
1789     Length logicalWidth = (widthType == MaxLogicalWidth) ? style()->logicalMaxWidth() : style()->logicalWidth();
1790     if (logicalWidth.type() == Intrinsic)
1791         return true;
1792
1793     // Children of a horizontal marquee do not fill the container by default.
1794     // FIXME: Need to deal with MAUTO value properly.  It could be vertical.
1795     // FIXME: Think about block-flow here.  Need to find out how marquee direction relates to
1796     // block-flow (as well as how marquee overflow should relate to block flow).
1797     // https://bugs.webkit.org/show_bug.cgi?id=46472
1798     if (parent()->style()->overflowX() == OMARQUEE) {
1799         EMarqueeDirection dir = parent()->style()->marqueeDirection();
1800         if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT)
1801             return true;
1802     }
1803
1804     // Flexible box items should shrink wrap, so we lay them out at their intrinsic widths.
1805     // In the case of columns that have a stretch alignment, we go ahead and layout at the
1806     // stretched size to avoid an extra layout when applying alignment.
1807     if (parent()->isFlexibleBox() && (!parent()->style()->isColumnFlexDirection() || style()->flexItemAlign() != AlignStretch))
1808         return true;
1809
1810     // Flexible horizontal boxes lay out children at their intrinsic widths.  Also vertical boxes
1811     // that don't stretch their kids lay out their children at their intrinsic widths.
1812     // FIXME: Think about block-flow here.
1813     // https://bugs.webkit.org/show_bug.cgi?id=46473
1814     if (parent()->isDeprecatedFlexibleBox()
1815             && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH))
1816         return true;
1817
1818     // Button, input, select, textarea, and legend treat
1819     // width value of 'auto' as 'intrinsic' unless it's in a
1820     // stretching vertical flexbox.
1821     // FIXME: Think about block-flow here.
1822     // https://bugs.webkit.org/show_bug.cgi?id=46473
1823     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)))
1824         return true;
1825
1826     if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
1827         return true;
1828
1829     return false;
1830 }
1831
1832 void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth)
1833 {
1834     const RenderStyle* containingBlockStyle = containingBlock->style();
1835     Length marginStartLength = style()->marginStartUsing(containingBlockStyle);
1836     Length marginEndLength = style()->marginEndUsing(containingBlockStyle);
1837
1838     if (isFloating() || isInline()) {
1839         // Inline blocks/tables and floats don't have their margins increased.
1840         containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1841         containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1842         return;
1843     }
1844
1845     // Case One: The object is being centered in the containing block's available logical width.
1846     if ((marginStartLength.isAuto() && marginEndLength.isAuto() && childWidth < containerWidth)
1847         || (!marginStartLength.isAuto() && !marginEndLength.isAuto() && containingBlock->style()->textAlign() == WEBKIT_CENTER)) {
1848         containingBlock->setMarginStartForChild(this, max<LayoutUnit>(0, (containerWidth - childWidth) / 2));
1849         containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1850         return;
1851     } 
1852     
1853     // Case Two: The object is being pushed to the start of the containing block's available logical width.
1854     if (marginEndLength.isAuto() && childWidth < containerWidth) {
1855         containingBlock->setMarginStartForChild(this, marginStartLength.calcValue(containerWidth));
1856         containingBlock->setMarginEndForChild(this, containerWidth - childWidth - containingBlock->marginStartForChild(this));
1857         return;
1858     } 
1859     
1860     // Case Three: The object is being pushed to the end of the containing block's available logical width.
1861     bool pushToEndFromTextAlign = !marginEndLength.isAuto() && ((!containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_LEFT)
1862         || (containingBlockStyle->isLeftToRightDirection() && containingBlockStyle->textAlign() == WEBKIT_RIGHT));
1863     if ((marginStartLength.isAuto() && childWidth < containerWidth) || pushToEndFromTextAlign) {
1864         containingBlock->setMarginEndForChild(this, marginEndLength.calcValue(containerWidth));
1865         containingBlock->setMarginStartForChild(this, containerWidth - childWidth - containingBlock->marginEndForChild(this));
1866         return;
1867     } 
1868     
1869     // Case Four: Either no auto margins, or our width is >= the container width (css2.1, 10.3.3).  In that case
1870     // auto margins will just turn into 0.
1871     containingBlock->setMarginStartForChild(this, marginStartLength.calcMinValue(containerWidth));
1872     containingBlock->setMarginEndForChild(this, marginEndLength.calcMinValue(containerWidth));
1873 }
1874
1875 RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, RenderBoxRegionInfoFlags cacheFlag) const
1876 {
1877     // Make sure nobody is trying to call this with a null region.
1878     if (!region)
1879         return 0;
1880
1881     // If we have computed our width in this region already, it will be cached, and we can
1882     // just return it.
1883     RenderBoxRegionInfo* boxInfo = region->renderBoxRegionInfo(this);
1884     if (boxInfo && cacheFlag == CacheRenderBoxRegionInfo)
1885         return boxInfo;
1886
1887     // No cached value was found, so we have to compute our insets in this region.
1888     // FIXME: For now we limit this computation to normal RenderBlocks. Future patches will expand
1889     // support to cover all boxes.
1890     if (!inRenderFlowThread() || isFloating() || isReplaced() || isInline() || hasColumns()
1891         || isTableCell() || !isBlockFlow() || isRenderFlowThread())
1892         return 0;
1893
1894     // FIXME: It's gross to cast away the const, but it would be a huge refactoring to
1895     // change all width computation to avoid updating any member variables, and it would be pretty lame to
1896     // make all the variables mutable as well.
1897     RenderFlowThread* flowThread = enclosingRenderFlowThread();
1898     if (flowThread->style()->writingMode() != style()->writingMode())
1899         return 0;
1900
1901     LayoutUnit oldLogicalWidth = logicalWidth();
1902     LayoutUnit oldLogicalLeft = logicalLeft();
1903     LayoutUnit oldMarginStart = marginStart();
1904     LayoutUnit oldMarginEnd = marginEnd();
1905
1906     RenderBox* mutableBox = const_cast<RenderBox*>(this);
1907     
1908     mutableBox->computeLogicalWidthInRegion(region, offsetFromLogicalTopOfFirstPage);
1909
1910     // Now determine the insets based off where this object is supposed to be positioned.
1911     RenderBlock* cb = containingBlock();
1912     RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
1913     RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion,
1914         offsetFromLogicalTopOfFirstPage - logicalTop());
1915     LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
1916     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
1917     
1918     LayoutUnit marginStartInRegion = marginStart();
1919     LayoutUnit startMarginDelta = marginStartInRegion - oldMarginStart;
1920     LayoutUnit logicalWidthInRegion = logicalWidth();
1921     LayoutUnit logicalLeftInRegion = logicalLeft();
1922     LayoutUnit widthDelta = logicalWidthInRegion - oldLogicalWidth;
1923     LayoutUnit logicalLeftDelta = isPositioned() ? logicalLeftInRegion - oldLogicalLeft : startMarginDelta;
1924     LayoutUnit logicalRightInRegion = containingBlockLogicalWidthInRegion - (logicalLeftInRegion + logicalWidthInRegion);
1925     LayoutUnit oldLogicalRight = containingBlockLogicalWidth - (oldLogicalLeft + oldLogicalWidth);
1926     LayoutUnit logicalRightDelta = isPositioned() ? logicalRightInRegion - oldLogicalRight : startMarginDelta;
1927
1928     // Set our values back.
1929     mutableBox->setLogicalWidth(oldLogicalWidth);
1930     mutableBox->setLogicalLeft(oldLogicalLeft);
1931     mutableBox->setMarginStart(oldMarginStart);
1932     mutableBox->setMarginEnd(oldMarginEnd);
1933
1934     LayoutUnit logicalLeftOffset = 0;
1935     
1936     if (!isPositioned() && avoidsFloats() && cb->containsFloats()) {
1937         LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(this, marginStartInRegion, logicalWidthInRegion,
1938             region, offsetFromLogicalTopOfFirstPage);
1939         if (cb->style()->isLeftToRightDirection())
1940             logicalLeftDelta += startPositionDelta;
1941         else
1942             logicalRightDelta += startPositionDelta;
1943     }
1944
1945     if (cb->style()->isLeftToRightDirection())
1946         logicalLeftOffset += logicalLeftDelta;
1947     else
1948         logicalLeftOffset -= (widthDelta + logicalRightDelta);
1949     
1950     LayoutUnit logicalRightOffset = logicalWidth() - (logicalLeftOffset + logicalWidthInRegion);
1951     bool isShifted = (containingBlockInfo && containingBlockInfo->isShifted())
1952             || (style()->isLeftToRightDirection() && logicalLeftOffset)
1953             || (!style()->isLeftToRightDirection() && logicalRightOffset);
1954
1955     // FIXME: Although it's unlikely, these boxes can go outside our bounds, and so we will need to incorporate them into overflow.
1956     if (cacheFlag == CacheRenderBoxRegionInfo)
1957         return region->setRenderBoxRegionInfo(this, logicalLeftOffset, logicalWidthInRegion, isShifted);
1958     return new RenderBoxRegionInfo(logicalLeftOffset, logicalWidthInRegion, isShifted);
1959 }
1960
1961 void RenderBox::computeLogicalHeight()
1962 {
1963     // Cell height is managed by the table and inline non-replaced elements do not support a height property.
1964     if (isTableCell() || (isInline() && !isReplaced()))
1965         return;
1966
1967     Length h;
1968     if (isPositioned())
1969         computePositionedLogicalHeight();
1970     else {
1971         RenderBlock* cb = containingBlock();
1972         bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
1973     
1974         if (!hasPerpendicularContainingBlock)
1975             computeBlockDirectionMargins(cb);
1976
1977         // For tables, calculate margins only.
1978         if (isTable()) {
1979             if (hasPerpendicularContainingBlock)
1980                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), logicalHeight());
1981             return;
1982         }
1983
1984         // FIXME: Account for block-flow in flexible boxes.
1985         // https://bugs.webkit.org/show_bug.cgi?id=46418
1986         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
1987         bool stretching = parent()->style()->boxAlign() == BSTRETCH;
1988         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
1989         bool checkMinMaxHeight = false;
1990
1991         // The parent box is flexing us, so it has increased or decreased our height.  We have to
1992         // grab our cached flexible height.
1993         // FIXME: Account for block-flow in flexible boxes.
1994         // https://bugs.webkit.org/show_bug.cgi?id=46418
1995         if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
1996             h = Length(overrideHeight() - borderAndPaddingLogicalHeight(), Fixed);
1997         else if (treatAsReplaced)
1998             h = Length(computeReplacedLogicalHeight(), Fixed);
1999         else {
2000             h = style()->logicalHeight();
2001             checkMinMaxHeight = true;
2002         }
2003
2004         // Block children of horizontal flexible boxes fill the height of the box.
2005         // FIXME: Account for block-flow in flexible boxes.
2006         // https://bugs.webkit.org/show_bug.cgi?id=46418
2007         if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
2008                 && parent()->isStretchingChildren()) {
2009             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2010             checkMinMaxHeight = false;
2011         }
2012
2013         LayoutUnit heightResult;
2014         if (checkMinMaxHeight) {
2015             heightResult = computeLogicalHeightUsing(style()->logicalHeight());
2016             // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2017             if (heightResult == -1)
2018                 heightResult = logicalHeight();
2019             LayoutUnit minH = computeLogicalHeightUsing(style()->logicalMinHeight()); // Leave as -1 if unset.
2020             LayoutUnit maxH = style()->logicalMaxHeight().isUndefined() ? heightResult : computeLogicalHeightUsing(style()->logicalMaxHeight());
2021             if (maxH == -1)
2022                 maxH = heightResult;
2023             heightResult = min(maxH, heightResult);
2024             heightResult = max(minH, heightResult);
2025         } else {
2026             // The only times we don't check min/max height are when a fixed length has
2027             // been given as an override.  Just use that.  The value has already been adjusted
2028             // for box-sizing.
2029             heightResult = h.value() + borderAndPaddingLogicalHeight();
2030         }
2031
2032         setLogicalHeight(heightResult);
2033         
2034         if (hasPerpendicularContainingBlock)
2035             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult);
2036     }
2037
2038     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2039     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2040     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2041     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2042     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2043     bool paginatedContentNeedsBaseHeight = document()->printing() && h.isPercent()
2044         && (isRoot() || (isBody() && document()->documentElement()->renderer()->style()->logicalHeight().isPercent()));
2045     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2046         // FIXME: Finish accounting for block flow here.
2047         // https://bugs.webkit.org/show_bug.cgi?id=46603
2048         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2049         LayoutUnit visHeight;
2050         if (document()->printing())
2051             visHeight = static_cast<LayoutUnit>(view()->pageLogicalHeight());
2052         else  {
2053             if (isHorizontalWritingMode())
2054                 visHeight = view()->viewHeight();
2055             else
2056                 visHeight = view()->viewWidth();
2057         }
2058         if (isRoot())
2059             setLogicalHeight(max(logicalHeight(), visHeight - margins));
2060         else {
2061             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2062             setLogicalHeight(max(logicalHeight(), visHeight - marginsBordersPadding));
2063         }
2064     }
2065 }
2066
2067 LayoutUnit RenderBox::computeLogicalHeightUsing(const Length& h)
2068 {
2069     LayoutUnit logicalHeight = -1;
2070     if (!h.isAuto()) {
2071         if (h.isFixed())
2072             logicalHeight = h.value();
2073         else if (h.isPercent())
2074             logicalHeight = computePercentageLogicalHeight(h);
2075         // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2076         if (logicalHeight != -1) {
2077             logicalHeight = computeBorderBoxLogicalHeight(logicalHeight);
2078             return logicalHeight;
2079         }
2080     }
2081     return logicalHeight;
2082 }
2083
2084 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height)
2085 {
2086     LayoutUnit result = -1;
2087     
2088     // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
2089     // block that may have a specified height and then use it. In strict mode, this violates the
2090     // specification, which states that percentage heights just revert to auto if the containing
2091     // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
2092     // only at explicit containers.
2093     bool skippedAutoHeightContainingBlock = false;
2094     RenderBlock* cb = containingBlock();
2095     while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isPositioned() && cb->style()->logicalHeight().isAuto()) {
2096         if (!document()->inQuirksMode() && !cb->isAnonymousBlock())
2097             break;
2098         skippedAutoHeightContainingBlock = true;
2099         cb = cb->containingBlock();
2100         cb->addPercentHeightDescendant(this);
2101     }
2102
2103     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2104     // explicitly specified that can be used for any percentage computations.
2105     // FIXME: We can't just check top/bottom here.
2106     // https://bugs.webkit.org/show_bug.cgi?id=46500
2107     bool isPositionedWithSpecifiedHeight = cb->isPositioned() && (!cb->style()->logicalHeight().isAuto() || (!cb->style()->top().isAuto() && !cb->style()->bottom().isAuto()));
2108
2109     bool includeBorderPadding = isTable();
2110
2111     // Table cells violate what the CSS spec says to do with heights.  Basically we
2112     // don't care if the cell specified a height or not.  We just always make ourselves
2113     // be a percentage of the cell's current content height.
2114     if (cb->isTableCell()) {
2115         if (!skippedAutoHeightContainingBlock) {
2116             if (!cb->hasOverrideHeight()) {
2117                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2118                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2119                 // While we can't get all cases right, we can at least detect when the cell has a specified
2120                 // height or when the table has a specified height.  In these cases we want to initially have
2121                 // no size and allow the flexing of the table or the cell to its specified height to cause us
2122                 // to grow to fill the space.  This could end up being wrong in some cases, but it is
2123                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2124                 RenderTableCell* cell = toRenderTableCell(cb);
2125                 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2126                     return 0;
2127                 return -1;
2128             }
2129             result = cb->overrideHeight();
2130             includeBorderPadding = true;
2131         }
2132     }
2133     // Otherwise we only use our percentage height if our containing block had a specified
2134     // height.
2135     else if (cb->style()->logicalHeight().isFixed())
2136         result = cb->computeContentBoxLogicalHeight(cb->style()->logicalHeight().value());
2137     else if (cb->style()->logicalHeight().isPercent() && !isPositionedWithSpecifiedHeight) {
2138         // We need to recur and compute the percentage height for our containing block.
2139         result = cb->computePercentageLogicalHeight(cb->style()->logicalHeight());
2140         // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2141         if (result != -1)
2142             result = cb->computeContentBoxLogicalHeight(result);
2143     } else if (cb->isRenderView() || (cb->isBody() && document()->inQuirksMode()) || isPositionedWithSpecifiedHeight) {
2144         // Don't allow this to affect the block' height() member variable, since this
2145         // can get called while the block is still laying out its kids.
2146         LayoutUnit oldHeight = cb->logicalHeight();
2147         cb->computeLogicalHeight();
2148         result = cb->contentLogicalHeight();
2149         cb->setLogicalHeight(oldHeight);
2150     } else if (cb->isRoot() && isPositioned())
2151         // Match the positioned objects behavior, which is that positioned objects will fill their viewport
2152         // always.  Note we could only hit this case by recurring into computePercentageLogicalHeight on a positioned containing block.
2153         result = cb->computeContentBoxLogicalHeight(cb->availableLogicalHeight());
2154
2155     // FIXME: Use < 0 or roughlyEquals when we move to float, see https://bugs.webkit.org/show_bug.cgi?id=66148
2156     if (result != -1) {
2157         result = height.calcValue(result);
2158         if (includeBorderPadding) {
2159             // It is necessary to use the border-box to match WinIE's broken
2160             // box model.  This is essential for sizing inside
2161             // table cells using percentage heights.
2162             result -= borderAndPaddingLogicalHeight();
2163             result = max<LayoutUnit>(0, result);
2164         }
2165     }
2166     return result;
2167 }
2168
2169 LayoutUnit RenderBox::computeReplacedLogicalWidth(bool includeMaxWidth) const
2170 {
2171     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(style()->logicalWidth()), includeMaxWidth);
2172 }
2173
2174 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, bool includeMaxWidth) const
2175 {
2176     LayoutUnit minLogicalWidth = computeReplacedLogicalWidthUsing(style()->logicalMinWidth());
2177     LayoutUnit maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(style()->logicalMaxWidth());
2178     return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
2179 }
2180
2181 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) const
2182 {
2183     switch (logicalWidth.type()) {
2184         case Fixed:
2185             return computeContentBoxLogicalWidth(logicalWidth.value());
2186         case Percent: {
2187             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2188             // containing block's block-flow.
2189             // https://bugs.webkit.org/show_bug.cgi?id=46496
2190             const LayoutUnit cw = isPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2191             if (cw > 0)
2192                 return computeContentBoxLogicalWidth(logicalWidth.calcMinValue(cw));
2193         }
2194         // fall through
2195         default:
2196             return intrinsicLogicalWidth();
2197      }
2198 }
2199
2200 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2201 {
2202     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(style()->logicalHeight()));
2203 }
2204
2205 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2206 {
2207     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(style()->logicalMinHeight());
2208     LayoutUnit maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
2209     return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
2210 }
2211
2212 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(Length logicalHeight) const
2213 {
2214     switch (logicalHeight.type()) {
2215         case Fixed:
2216             return computeContentBoxLogicalHeight(logicalHeight.value());
2217         case Percent:
2218         {
2219             RenderObject* cb = isPositioned() ? container() : containingBlock();
2220             while (cb->isAnonymous()) {
2221                 cb = cb->containingBlock();
2222                 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2223             }
2224
2225             // FIXME: This calculation is not patched for block-flow yet.
2226             // https://bugs.webkit.org/show_bug.cgi?id=46500
2227             if (cb->isPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2228                 ASSERT(cb->isRenderBlock());
2229                 RenderBlock* block = toRenderBlock(cb);
2230                 LayoutUnit oldHeight = block->height();
2231                 block->computeLogicalHeight();
2232                 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentHeight());
2233                 block->setHeight(oldHeight);
2234                 return computeContentBoxLogicalHeight(logicalHeight.calcValue(newHeight));
2235             }
2236             
2237             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2238             // containing block's block-flow.
2239             // https://bugs.webkit.org/show_bug.cgi?id=46496
2240             LayoutUnit availableHeight;
2241             if (isPositioned())
2242                 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2243             else {
2244                 availableHeight =  toRenderBox(cb)->availableLogicalHeight();
2245                 // It is necessary to use the border-box to match WinIE's broken
2246                 // box model.  This is essential for sizing inside
2247                 // table cells using percentage heights.
2248                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
2249                 // https://bugs.webkit.org/show_bug.cgi?id=46997
2250                 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2251                     if (cb->isTableCell()) {
2252                         // Don't let table cells squeeze percent-height replaced elements
2253                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2254                         availableHeight = max(availableHeight, intrinsicLogicalHeight());
2255                         return logicalHeight.calcValue(availableHeight - borderAndPaddingLogicalHeight());
2256                     }
2257                     cb = cb->containingBlock();
2258                 }
2259             }
2260             return computeContentBoxLogicalHeight(logicalHeight.calcValue(availableHeight));
2261         }
2262         default:
2263             return intrinsicLogicalHeight();
2264     }
2265 }
2266
2267 LayoutUnit RenderBox::availableLogicalHeight() const
2268 {
2269     return availableLogicalHeightUsing(style()->logicalHeight());
2270 }
2271
2272 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const
2273 {
2274     if (h.isFixed())
2275         return computeContentBoxLogicalHeight(h.value());
2276
2277     if (isRenderView())
2278         return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
2279
2280     // We need to stop here, since we don't want to increase the height of the table
2281     // artificially.  We're going to rely on this cell getting expanded to some new
2282     // height, and then when we lay out again we'll use the calculation below.
2283     if (isTableCell() && (h.isAuto() || h.isPercent()))
2284         return overrideHeight() - borderAndPaddingLogicalWidth();
2285
2286     if (h.isPercent()) {
2287         LayoutUnit availableHeight;
2288         // https://bugs.webkit.org/show_bug.cgi?id=64046
2289         // For absolutely positioned elements whose containing block is based on a block-level element,
2290         // the percentage is calculated with respect to the height of the padding box of that element
2291         if (isPositioned())
2292             availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2293         else
2294             availableHeight = containingBlock()->availableLogicalHeight();
2295         return computeContentBoxLogicalHeight(h.calcValue(availableHeight));
2296     }
2297
2298     // FIXME: We can't just check top/bottom here.
2299     // https://bugs.webkit.org/show_bug.cgi?id=46500
2300     if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2301         RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2302         LayoutUnit oldHeight = block->logicalHeight();
2303         block->computeLogicalHeight();
2304         LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
2305         block->setLogicalHeight(oldHeight);
2306         return computeContentBoxLogicalHeight(newHeight);
2307     }
2308
2309     return containingBlock()->availableLogicalHeight();
2310 }
2311
2312 void RenderBox::computeBlockDirectionMargins(RenderBlock* containingBlock)
2313 {
2314     if (isTableCell()) {
2315         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
2316         // we may just do it with an extra anonymous block inside the cell.
2317         setMarginBefore(0);
2318         setMarginAfter(0);
2319         return;
2320     }
2321
2322     // Margins are calculated with respect to the logical width of
2323     // the containing block (8.3)
2324     LayoutUnit cw = containingBlockLogicalWidthForContent();
2325
2326     RenderStyle* containingBlockStyle = containingBlock->style();
2327     containingBlock->setMarginBeforeForChild(this, style()->marginBeforeUsing(containingBlockStyle).calcMinValue(cw));
2328     containingBlock->setMarginAfterForChild(this, style()->marginAfterUsing(containingBlockStyle).calcMinValue(cw));
2329 }
2330
2331 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region,
2332     LayoutUnit offsetFromLogicalTopOfFirstPage, bool checkForPerpendicularWritingMode) const
2333 {
2334     // Container for position:fixed is the frame.
2335     Frame* frame = view() ? view()->frame(): 0;
2336     FrameView* frameView = view() ? view()->frameView() : 0;
2337     if (shouldLayoutFixedElementRelativeToFrame(frame, frameView))
2338         return (view()->isHorizontalWritingMode() ? frameView->visibleWidth() : frameView->visibleHeight()) / frame->frameScaleFactor();
2339
2340     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2341         return containingBlockLogicalHeightForPositioned(containingBlock, false);
2342
2343     if (containingBlock->isBox()) {
2344         const RenderBlock* cb = toRenderBlock(containingBlock);
2345         LayoutUnit result = cb->clientLogicalWidth();
2346         if (inRenderFlowThread()) {
2347             RenderBoxRegionInfo* boxInfo = 0;
2348             if (!region) {
2349                 if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
2350                     return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
2351                 if (isWritingModeRoot()) {
2352                     LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2353                     RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2354                     cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2355                     boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2356                 }
2357             } else if (region && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
2358                 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
2359                 boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
2360             }
2361             if (boxInfo)
2362                 return max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
2363         }
2364         return result;
2365     }
2366
2367     ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2368
2369     const RenderInline* flow = toRenderInline(containingBlock);
2370     InlineFlowBox* first = flow->firstLineBox();
2371     InlineFlowBox* last = flow->lastLineBox();
2372
2373     // If the containing block is empty, return a width of 0.
2374     if (!first || !last)
2375         return 0;
2376
2377     LayoutUnit fromLeft;
2378     LayoutUnit fromRight;
2379     if (containingBlock->style()->isLeftToRightDirection()) {
2380         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2381         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2382     } else {
2383         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2384         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2385     }
2386
2387     return max<LayoutUnit>(0, fromRight - fromLeft);
2388 }
2389
2390 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2391 {
2392     Frame* frame = view() ? view()->frame(): 0;
2393     FrameView* frameView = view() ? view()->frameView() : 0;
2394     if (shouldLayoutFixedElementRelativeToFrame(frame, frameView))
2395         return (view()->isHorizontalWritingMode() ? frameView->visibleHeight() : frameView->visibleWidth()) / frame->frameScaleFactor();
2396
2397     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2398         return containingBlockLogicalWidthForPositioned(containingBlock, 0, 0, false);
2399
2400     if (containingBlock->isBox()) {
2401         const RenderBlock* cb = toRenderBlock(containingBlock);
2402         LayoutUnit result = cb->clientLogicalHeight();
2403         if (inRenderFlowThread() && containingBlock->isRenderFlowThread() && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode())
2404             return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion();
2405         return result;
2406     }
2407         
2408     ASSERT(containingBlock->isRenderInline() && containingBlock->isRelPositioned());
2409
2410     const RenderInline* flow = toRenderInline(containingBlock);
2411     InlineFlowBox* first = flow->firstLineBox();
2412     InlineFlowBox* last = flow->lastLineBox();
2413
2414     // If the containing block is empty, return a height of 0.
2415     if (!first || !last)
2416         return 0;
2417
2418     LayoutUnit heightResult;
2419     LayoutRect boundingBox = flow->linesBoundingBox();
2420     if (containingBlock->isHorizontalWritingMode())
2421         heightResult = boundingBox.height();
2422     else
2423         heightResult = boundingBox.width();
2424     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2425     return heightResult;
2426 }
2427
2428 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
2429 {
2430     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2431         return;
2432
2433     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2434     if (child->parent()->style()->direction() == LTR) {
2435         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2436         for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2437             if (curr->isBox()) {
2438                 staticPosition += toRenderBox(curr)->logicalLeft();
2439                 if (region && curr->isRenderBlock()) {
2440                     const RenderBlock* cb = toRenderBlock(curr);
2441                     region = cb->clampToStartAndEndRegions(region);
2442                     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2443                     if (boxInfo)
2444                         staticPosition += boxInfo->logicalLeft();
2445                 }
2446             }
2447         }
2448         logicalLeft.setValue(Fixed, staticPosition);
2449     } else {
2450         RenderBox* enclosingBox = child->parent()->enclosingBox();
2451         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
2452         for (RenderObject* curr = enclosingBox; curr; curr = curr->container()) {
2453             if (curr->isBox()) {
2454                 if (curr != containerBlock)
2455                     staticPosition -= toRenderBox(curr)->logicalLeft();
2456                 if (curr == enclosingBox)
2457                     staticPosition -= enclosingBox->logicalWidth();
2458                 if (region && curr->isRenderBlock()) {
2459                      const RenderBlock* cb = toRenderBlock(curr);
2460                      region = cb->clampToStartAndEndRegions(region);
2461                      RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2462                      if (boxInfo) {
2463                         if (curr != containerBlock)
2464                             staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
2465                         if (curr == enclosingBox)
2466                             staticPosition += enclosingBox->logicalWidth() - boxInfo->logicalWidth();
2467                     }
2468                 }
2469             }
2470             if (curr == containerBlock)
2471                 break;
2472         }
2473         logicalRight.setValue(Fixed, staticPosition);
2474     }
2475 }
2476
2477 void RenderBox::computePositionedLogicalWidth(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
2478 {
2479     if (isReplaced()) {
2480         computePositionedLogicalWidthReplaced(); // FIXME: Patch for regions when we add replaced element support.
2481         return;
2482     }
2483
2484     // QUESTIONS
2485     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
2486     // the type 'static' in determining whether to calculate the static distance?
2487     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2488
2489     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
2490     // than or less than the computed width().  Be careful of box-sizing and
2491     // percentage issues.
2492
2493     // The following is based off of the W3C Working Draft from April 11, 2006 of
2494     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2495     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2496     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2497     // correspond to text from the spec)
2498
2499
2500     // We don't use containingBlock(), since we may be positioned by an enclosing
2501     // relative positioned inline.
2502     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2503     
2504     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region, offsetFromLogicalTopOfFirstPage);
2505
2506     // Use the container block's direction except when calculating the static distance
2507     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
2508     // of the CSS 2.1 test suite
2509     TextDirection containerDirection = containerBlock->style()->direction();
2510
2511     bool isHorizontal = isHorizontalWritingMode();
2512     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2513     const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2514     const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2515     LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
2516     LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
2517
2518     Length logicalLeftLength = style()->logicalLeft();
2519     Length logicalRightLength = style()->logicalRight();
2520
2521     /*---------------------------------------------------------------------------*\
2522      * For the purposes of this section and the next, the term "static position"
2523      * (of an element) refers, roughly, to the position an element would have had
2524      * in the normal flow. More precisely:
2525      *
2526      * * The static position for 'left' is the distance from the left edge of the
2527      *   containing block to the left margin edge of a hypothetical box that would
2528      *   have been the first box of the element if its 'position' property had
2529      *   been 'static' and 'float' had been 'none'. The value is negative if the
2530      *   hypothetical box is to the left of the containing block.
2531      * * The static position for 'right' is the distance from the right edge of the
2532      *   containing block to the right margin edge of the same hypothetical box as
2533      *   above. The value is positive if the hypothetical box is to the left of the
2534      *   containing block's edge.
2535      *
2536      * But rather than actually calculating the dimensions of that hypothetical box,
2537      * user agents are free to make a guess at its probable position.
2538      *
2539      * For the purposes of calculating the static position, the containing block of
2540      * fixed positioned elements is the initial containing block instead of the
2541      * viewport, and all scrollable boxes should be assumed to be scrolled to their
2542      * origin.
2543     \*---------------------------------------------------------------------------*/
2544
2545     // see FIXME 1
2546     // Calculate the static distance if needed.
2547     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
2548     
2549     // Calculate constraint equation values for 'width' case.
2550     LayoutUnit logicalWidthResult;
2551     LayoutUnit logicalLeftResult;
2552     computePositionedLogicalWidthUsing(style()->logicalWidth(), containerBlock, containerDirection,
2553                                        containerLogicalWidth, bordersPlusPadding,
2554                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2555                                        logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2556     setLogicalWidth(logicalWidthResult);
2557     setLogicalLeft(logicalLeftResult);
2558
2559     // Calculate constraint equation values for 'max-width' case.
2560     if (!style()->logicalMaxWidth().isUndefined()) {
2561         LayoutUnit maxLogicalWidth;
2562         LayoutUnit maxMarginLogicalLeft;
2563         LayoutUnit maxMarginLogicalRight;
2564         LayoutUnit maxLogicalLeftPos;
2565
2566         computePositionedLogicalWidthUsing(style()->logicalMaxWidth(), containerBlock, containerDirection,
2567                                            containerLogicalWidth, bordersPlusPadding,
2568                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2569                                            maxLogicalWidth, maxMarginLogicalLeft, maxMarginLogicalRight, maxLogicalLeftPos);
2570
2571         if (logicalWidth() > maxLogicalWidth) {
2572             setLogicalWidth(maxLogicalWidth);
2573             marginLogicalLeftAlias = maxMarginLogicalLeft;
2574             marginLogicalRightAlias = maxMarginLogicalRight;
2575             setLogicalLeft(maxLogicalLeftPos);
2576         }
2577     }
2578
2579     // Calculate constraint equation values for 'min-width' case.
2580     if (!style()->logicalMinWidth().isZero()) {
2581         LayoutUnit minLogicalWidth;
2582         LayoutUnit minMarginLogicalLeft;
2583         LayoutUnit minMarginLogicalRight;
2584         LayoutUnit minLogicalLeftPos;
2585
2586         computePositionedLogicalWidthUsing(style()->logicalMinWidth(), containerBlock, containerDirection,
2587                                            containerLogicalWidth, bordersPlusPadding,
2588                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2589                                            minLogicalWidth, minMarginLogicalLeft, minMarginLogicalRight, minLogicalLeftPos);
2590
2591         if (logicalWidth() < minLogicalWidth) {
2592             setLogicalWidth(minLogicalWidth);
2593             marginLogicalLeftAlias = minMarginLogicalLeft;
2594             marginLogicalRightAlias = minMarginLogicalRight;
2595             setLogicalLeft(minLogicalLeftPos);
2596         }
2597     }
2598
2599     if (stretchesToMinIntrinsicLogicalWidth() && logicalWidth() < minPreferredLogicalWidth() - bordersPlusPadding) {
2600         computePositionedLogicalWidthUsing(Length(minPreferredLogicalWidth() - bordersPlusPadding, Fixed), containerBlock, containerDirection,
2601                                            containerLogicalWidth, bordersPlusPadding,
2602                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2603                                            logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2604         setLogicalWidth(logicalWidthResult);
2605         setLogicalLeft(logicalLeftResult);
2606     }
2607
2608     // Put logicalWidth() into correct form.
2609     setLogicalWidth(logicalWidth() + bordersPlusPadding);
2610     
2611     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
2612     if (inRenderFlowThread() && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2613         LayoutUnit logicalLeftPos = logicalLeft();
2614         const RenderBlock* cb = toRenderBlock(containerBlock);
2615         LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2616         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2617         cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2618         RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2619         if (boxInfo) {
2620             logicalLeftPos += boxInfo->logicalLeft();
2621             setLogicalLeft(logicalLeftPos);
2622         }
2623     }
2624 }
2625
2626 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2627 {
2628     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2629     // 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.
2630     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2631         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2632         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2633     } else
2634         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2635 }
2636
2637 void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2638                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2639                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
2640                                                    LayoutUnit& logicalWidthValue, LayoutUnit& marginLogicalLeftValue, LayoutUnit& marginLogicalRightValue, LayoutUnit& logicalLeftPos)
2641 {
2642     // 'left' and 'right' cannot both be 'auto' because one would of been
2643     // converted to the static position already
2644     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2645
2646     LayoutUnit logicalLeftValue = 0;
2647
2648     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2649     bool logicalLeftIsAuto = logicalLeft.isAuto();
2650     bool logicalRightIsAuto = logicalRight.isAuto();
2651
2652     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2653         /*-----------------------------------------------------------------------*\
2654          * If none of the three is 'auto': If both 'margin-left' and 'margin-
2655          * right' are 'auto', solve the equation under the extra constraint that
2656          * the two margins get equal values, unless this would make them negative,
2657          * in which case when direction of the containing block is 'ltr' ('rtl'),
2658          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2659          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2660          * solve the equation for that value. If the values are over-constrained,
2661          * ignore the value for 'left' (in case the 'direction' property of the
2662          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2663          * and solve for that value.
2664         \*-----------------------------------------------------------------------*/
2665         // NOTE:  It is not necessary to solve for 'right' in the over constrained
2666         // case because the value is not used for any further calculations.
2667
2668         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2669         logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2670
2671         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + logicalWidthValue + logicalRight.calcValue(containerLogicalWidth) + bordersPlusPadding);
2672
2673         // Margins are now the only unknown
2674         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2675             // Both margins auto, solve for equality
2676             if (availableSpace >= 0) {
2677                 marginLogicalLeftValue = availableSpace / 2; // split the difference
2678                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2679             } else {
2680                 // Use the containing block's direction rather than the parent block's
2681                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2682                 if (containerDirection == LTR) {
2683                     marginLogicalLeftValue = 0;
2684                     marginLogicalRightValue = availableSpace; // will be negative
2685                 } else {
2686                     marginLogicalLeftValue = availableSpace; // will be negative
2687                     marginLogicalRightValue = 0;
2688                 }
2689             }
2690         } else if (marginLogicalLeft.isAuto()) {
2691             // Solve for left margin
2692             marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2693             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
2694         } else if (marginLogicalRight.isAuto()) {
2695             // Solve for right margin
2696             marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2697             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
2698         } else {
2699             // Over-constrained, solve for left if direction is RTL
2700             marginLogicalLeftValue = marginLogicalLeft.calcValue(containerLogicalWidth);
2701             marginLogicalRightValue = marginLogicalRight.calcValue(containerLogicalWidth);
2702
2703             // Use the containing block's direction rather than the parent block's
2704             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2705             if (containerDirection == RTL)
2706                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
2707         }
2708     } else {
2709         /*--------------------------------------------------------------------*\
2710          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
2711          * to 0, and pick the one of the following six rules that applies.
2712          *
2713          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
2714          *    width is shrink-to-fit. Then solve for 'left'
2715          *
2716          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2717          * ------------------------------------------------------------------
2718          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
2719          *    the 'direction' property of the containing block is 'ltr' set
2720          *    'left' to the static position, otherwise set 'right' to the
2721          *    static position. Then solve for 'left' (if 'direction is 'rtl')
2722          *    or 'right' (if 'direction' is 'ltr').
2723          * ------------------------------------------------------------------
2724          *
2725          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
2726          *    width is shrink-to-fit . Then solve for 'right'
2727          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
2728          *    for 'left'
2729          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
2730          *    for 'width'
2731          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
2732          *    for 'right'
2733          *
2734          * Calculation of the shrink-to-fit width is similar to calculating the
2735          * width of a table cell using the automatic table layout algorithm.
2736          * Roughly: calculate the preferred width by formatting the content
2737          * without breaking lines other than where explicit line breaks occur,
2738          * and also calculate the preferred minimum width, e.g., by trying all
2739          * possible line breaks. CSS 2.1 does not define the exact algorithm.
2740          * Thirdly, calculate the available width: this is found by solving
2741          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
2742          * to 0.
2743          *
2744          * Then the shrink-to-fit width is:
2745          * min(max(preferred minimum width, available width), preferred width).
2746         \*--------------------------------------------------------------------*/
2747         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
2748         // because the value is not used for any further calculations.
2749
2750         // Calculate margins, 'auto' margins are ignored.
2751         marginLogicalLeftValue = marginLogicalLeft.calcMinValue(containerLogicalWidth);
2752         marginLogicalRightValue = marginLogicalRight.calcMinValue(containerLogicalWidth);
2753
2754         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
2755
2756         // FIXME: Is there a faster way to find the correct case?
2757         // Use rule/case that applies.
2758         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2759             // RULE 1: (use shrink-to-fit for width, and solve of left)
2760             LayoutUnit logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
2761
2762             // FIXME: would it be better to have shrink-to-fit in one step?
2763             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2764             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2765             LayoutUnit availableWidth = availableSpace - logicalRightValue;
2766             logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2767             logicalLeftValue = availableSpace - (logicalWidthValue + logicalRightValue);
2768         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
2769             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
2770             logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2771
2772             // FIXME: would it be better to have shrink-to-fit in one step?
2773             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2774             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2775             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2776             logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2777         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2778             // RULE 4: (solve for left)
2779             logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2780             logicalLeftValue = availableSpace - (logicalWidthValue + logicalRight.calcValue(containerLogicalWidth));
2781         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2782             // RULE 5: (solve for width)
2783             logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2784             logicalWidthValue = availableSpace - (logicalLeftValue + logicalRight.calcValue(containerLogicalWidth));
2785         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
2786             // RULE 6: (no need solve for right)
2787             logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
2788             logicalWidthValue = computeContentBoxLogicalWidth(logicalWidth.calcValue(containerLogicalWidth));
2789         }
2790     }
2791
2792     // Use computed values to calculate the horizontal position.
2793
2794     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
2795     // positioned, inline because right now, it is using the logical left position
2796     // of the first line box when really it should use the last line box.  When
2797     // this is fixed elsewhere, this block should be removed.
2798     if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2799         const RenderInline* flow = toRenderInline(containerBlock);
2800         InlineFlowBox* firstLine = flow->firstLineBox();
2801         InlineFlowBox* lastLine = flow->lastLineBox();
2802         if (firstLine && lastLine && firstLine != lastLine) {
2803             logicalLeftPos = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
2804             return;
2805         }
2806     }
2807
2808     logicalLeftPos = logicalLeftValue + marginLogicalLeftValue;
2809     computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidthValue, containerBlock, containerLogicalWidth);
2810 }
2811
2812 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
2813 {
2814     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
2815         return;
2816     
2817     // FIXME: The static distance computation has not been patched for mixed writing modes.
2818     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
2819     for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2820         if (curr->isBox() && !curr->isTableRow())
2821             staticLogicalTop += toRenderBox(curr)->logicalTop();
2822     }
2823     logicalTop.setValue(Fixed, staticLogicalTop);
2824 }
2825
2826 void RenderBox::computePositionedLogicalHeight()
2827 {
2828     if (isReplaced()) {
2829         computePositionedLogicalHeightReplaced();
2830         return;
2831     }
2832
2833     // The following is based off of the W3C Working Draft from April 11, 2006 of
2834     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
2835     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
2836     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
2837     // correspond to text from the spec)
2838
2839
2840     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
2841     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2842
2843     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
2844
2845     bool isHorizontal = isHorizontalWritingMode();
2846     bool isFlipped = style()->isFlippedBlocksWritingMode();
2847     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
2848     const Length marginBefore = style()->marginBefore();
2849     const Length marginAfter = style()->marginAfter();
2850     LayoutUnit& marginBeforeAlias = isHorizontal ? (isFlipped ? m_marginBottom : m_marginTop) : (isFlipped ? m_marginRight: m_marginLeft);
2851     LayoutUnit& marginAfterAlias = isHorizontal ? (isFlipped ? m_marginTop : m_marginBottom) : (isFlipped ? m_marginLeft: m_marginRight);
2852
2853     Length logicalTopLength = style()->logicalTop();
2854     Length logicalBottomLength = style()->logicalBottom();
2855         
2856     /*---------------------------------------------------------------------------*\
2857      * For the purposes of this section and the next, the term "static position"
2858      * (of an element) refers, roughly, to the position an element would have had
2859      * in the normal flow. More precisely, the static position for 'top' is the
2860      * distance from the top edge of the containing block to the top margin edge
2861      * of a hypothetical box that would have been the first box of the element if
2862      * its 'position' property had been 'static' and 'float' had been 'none'. The
2863      * value is negative if the hypothetical box is above the containing block.
2864      *
2865      * But rather than actually calculating the dimensions of that hypothetical
2866      * box, user agents are free to make a guess at its probable position.
2867      *
2868      * For the purposes of calculating the static position, the containing block
2869      * of fixed positioned elements is the initial containing block instead of
2870      * the viewport.
2871     \*---------------------------------------------------------------------------*/
2872
2873     // see FIXME 1
2874     // Calculate the static distance if needed.
2875     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
2876
2877     LayoutUnit logicalHeightResult; // Needed to compute overflow.
2878     LayoutUnit logicalTopPos;
2879
2880     // Calculate constraint equation values for 'height' case.
2881     computePositionedLogicalHeightUsing(style()->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2882                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2883                                         logicalHeightResult, marginBeforeAlias, marginAfterAlias, logicalTopPos);
2884     setLogicalTop(logicalTopPos);
2885
2886     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
2887     // see FIXME 2
2888
2889     // Calculate constraint equation values for 'max-height' case.
2890     if (!style()->logicalMaxHeight().isUndefined()) {
2891         LayoutUnit maxLogicalHeight;
2892         LayoutUnit maxMarginBefore;
2893         LayoutUnit maxMarginAfter;
2894         LayoutUnit maxLogicalTopPos;
2895
2896         computePositionedLogicalHeightUsing(style()->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2897                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2898                                             maxLogicalHeight, maxMarginBefore, maxMarginAfter, maxLogicalTopPos);
2899
2900         if (logicalHeightResult > maxLogicalHeight) {
2901             logicalHeightResult = maxLogicalHeight;
2902             marginBeforeAlias = maxMarginBefore;
2903             marginAfterAlias = maxMarginAfter;
2904             setLogicalTop(maxLogicalTopPos);
2905         }
2906     }
2907
2908     // Calculate constraint equation values for 'min-height' case.
2909     if (!style()->logicalMinHeight().isZero()) {
2910         LayoutUnit minLogicalHeight;
2911         LayoutUnit minMarginBefore;
2912         LayoutUnit minMarginAfter;
2913         LayoutUnit minLogicalTopPos;
2914
2915         computePositionedLogicalHeightUsing(style()->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2916                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2917                                             minLogicalHeight, minMarginBefore, minMarginAfter, minLogicalTopPos);
2918
2919         if (logicalHeightResult < minLogicalHeight) {
2920             logicalHeightResult = minLogicalHeight;
2921             marginBeforeAlias = minMarginBefore;
2922             marginAfterAlias = minMarginAfter;
2923             setLogicalTop(minLogicalTopPos);
2924         }
2925     }
2926
2927     // Set final height value.
2928     setLogicalHeight(logicalHeightResult + bordersPlusPadding);
2929     
2930     // Adjust logicalTop if we need to for perpendicular writing modes in regions.
2931     if (inRenderFlowThread() && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode()) {
2932         LayoutUnit logicalTopPos = logicalTop();
2933         const RenderBlock* cb = toRenderBlock(containerBlock);
2934         LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage() - logicalLeft();
2935         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2936         cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2937         RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2938         if (boxInfo) {
2939             logicalTopPos += boxInfo->logicalLeft();
2940             setLogicalTop(logicalTopPos);
2941         }
2942     }
2943 }
2944
2945 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
2946 {
2947     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2948     // 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.
2949     if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
2950         || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
2951         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
2952
2953     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
2954     if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2955         if (child->isHorizontalWritingMode())
2956             logicalTopPos += containerBlock->borderBottom();
2957         else
2958             logicalTopPos += containerBlock->borderRight();
2959     } else {
2960         if (child->isHorizontalWritingMode())
2961             logicalTopPos += containerBlock->borderTop();
2962         else
2963             logicalTopPos += containerBlock->borderLeft();
2964     }
2965 }
2966
2967 void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
2968                                                     LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding,
2969                                                     Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
2970                                                     LayoutUnit& logicalHeightValue, LayoutUnit& marginBeforeValue, LayoutUnit& marginAfterValue, LayoutUnit& logicalTopPos)
2971 {
2972     // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
2973     // converted to the static position in computePositionedLogicalHeight()
2974     ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
2975
2976     LayoutUnit contentLogicalHeight = logicalHeight() - bordersPlusPadding;
2977
2978     LayoutUnit logicalTopValue = 0;
2979
2980     bool logicalHeightIsAuto = logicalHeightLength.isAuto();
2981     bool logicalTopIsAuto = logicalTop.isAuto();
2982     bool logicalBottomIsAuto = logicalBottom.isAuto();
2983
2984     // Height is never unsolved for tables.
2985     if (isTable()) {
2986         logicalHeightLength.setValue(Fixed, contentLogicalHeight);
2987         logicalHeightIsAuto = false;
2988     }
2989
2990     if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
2991         /*-----------------------------------------------------------------------*\
2992          * If none of the three are 'auto': If both 'margin-top' and 'margin-
2993          * bottom' are 'auto', solve the equation under the extra constraint that
2994          * the two margins get equal values. If one of 'margin-top' or 'margin-
2995          * bottom' is 'auto', solve the equation for that value. If the values
2996          * are over-constrained, ignore the value for 'bottom' and solve for that
2997          * value.
2998         \*-----------------------------------------------------------------------*/
2999         // NOTE:  It is not necessary to solve for 'bottom' in the over constrained
3000         // case because the value is not used for any further calculations.
3001
3002         logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
3003         logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3004
3005         const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight) + bordersPlusPadding);
3006
3007         // Margins are now the only unknown
3008         if (marginBefore.isAuto() && marginAfter.isAuto()) {
3009             // Both margins auto, solve for equality
3010             // NOTE: This may result in negative values.
3011             marginBeforeValue = availableSpace / 2; // split the difference
3012             marginAfterValue = availableSpace - marginBeforeValue; // account for odd valued differences
3013         } else if (marginBefore.isAuto()) {
3014             // Solve for top margin
3015             marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
3016             marginBeforeValue = availableSpace - marginAfterValue;
3017         } else if (marginAfter.isAuto()) {
3018             // Solve for bottom margin
3019             marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
3020             marginAfterValue = availableSpace - marginBeforeValue;
3021         } else {
3022             // Over-constrained, (no need solve for bottom)
3023             marginBeforeValue = marginBefore.calcValue(containerLogicalHeight);
3024             marginAfterValue = marginAfter.calcValue(containerLogicalHeight);
3025         }
3026     } else {
3027         /*--------------------------------------------------------------------*\
3028          * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3029          * to 0, and pick the one of the following six rules that applies.
3030          *
3031          * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3032          *    the height is based on the content, and solve for 'top'.
3033          *
3034          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3035          * ------------------------------------------------------------------
3036          * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3037          *    set 'top' to the static position, and solve for 'bottom'.
3038          * ------------------------------------------------------------------
3039          *
3040          * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3041          *    the height is based on the content, and solve for 'bottom'.
3042          * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3043          *    solve for 'top'.
3044          * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3045          *    solve for 'height'.
3046          * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3047          *    solve for 'bottom'.
3048         \*--------------------------------------------------------------------*/
3049         // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3050         // because the value is not used for any further calculations.
3051
3052         // Calculate margins, 'auto' margins are ignored.
3053         marginBeforeValue = marginBefore.calcMinValue(containerLogicalHeight);
3054         marginAfterValue = marginAfter.calcMinValue(containerLogicalHeight);
3055
3056         const LayoutUnit availableSpace = containerLogicalHeight - (marginBeforeValue + marginAfterValue + bordersPlusPadding);
3057
3058         // Use rule/case that applies.
3059         if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3060             // RULE 1: (height is content based, solve of top)
3061             logicalHeightValue = contentLogicalHeight;
3062             logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
3063         } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
3064             // RULE 3: (height is content based, no need solve of bottom)
3065             logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3066             logicalHeightValue = contentLogicalHeight;
3067         } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3068             // RULE 4: (solve of top)
3069             logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
3070             logicalTopValue = availableSpace - (logicalHeightValue + logicalBottom.calcValue(containerLogicalHeight));
3071         } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3072             // RULE 5: (solve of height)
3073             logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3074             logicalHeightValue = max<LayoutUnit>(0, availableSpace - (logicalTopValue + logicalBottom.calcValue(containerLogicalHeight)));
3075         } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
3076             // RULE 6: (no need solve of bottom)
3077             logicalHeightValue = computeContentBoxLogicalHeight(logicalHeightLength.calcValue(containerLogicalHeight));
3078             logicalTopValue = logicalTop.calcValue(containerLogicalHeight);
3079         }
3080     }
3081
3082     // Use computed values to calculate the vertical position.
3083     logicalTopPos = logicalTopValue + marginBeforeValue;
3084     computeLogicalTopPositionedOffset(logicalTopPos, this, logicalHeightValue, containerBlock, containerLogicalHeight);
3085 }
3086
3087 void RenderBox::computePositionedLogicalWidthReplaced()
3088 {
3089     // The following is based off of the W3C Working Draft from April 11, 2006 of
3090     // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
3091     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
3092     // (block-style-comments in this function correspond to text from the spec and
3093     // the numbers correspond to numbers in spec)
3094
3095     // We don't use containingBlock(), since we may be positioned by an enclosing
3096     // relative positioned inline.
3097     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3098
3099     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
3100
3101     // To match WinIE, in quirks mode use the parent's 'direction' property
3102     // instead of the the container block's.
3103     TextDirection containerDirection = containerBlock->style()->direction();
3104
3105     // Variables to solve.
3106     bool isHorizontal = isHorizontalWritingMode();
3107     Length logicalLeft = style()->logicalLeft();
3108     Length logicalRight = style()->logicalRight();
3109     Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3110     Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3111     LayoutUnit& marginLogicalLeftAlias = isHorizontal ? m_marginLeft : m_marginTop;
3112     LayoutUnit& marginLogicalRightAlias = isHorizontal ? m_marginRight : m_marginBottom;
3113
3114     /*-----------------------------------------------------------------------*\
3115      * 1. The used value of 'width' is determined as for inline replaced
3116      *    elements.
3117     \*-----------------------------------------------------------------------*/
3118     // NOTE: This value of width is FINAL in that the min/max width calculations
3119     // are dealt with in computeReplacedWidth().  This means that the steps to produce
3120     // correct max/min in the non-replaced version, are not necessary.
3121     setLogicalWidth(computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth());
3122
3123     const LayoutUnit availableSpace = containerLogicalWidth - logicalWidth();
3124
3125     /*-----------------------------------------------------------------------*\
3126      * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
3127      *    of the containing block is 'ltr', set 'left' to the static position;
3128      *    else if 'direction' is 'rtl', set 'right' to the static position.
3129     \*-----------------------------------------------------------------------*/
3130     // see FIXME 1
3131     computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, 0); // FIXME: Pass the region.
3132
3133     /*-----------------------------------------------------------------------*\
3134      * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
3135      *    or 'margin-right' with '0'.
3136     \*-----------------------------------------------------------------------*/
3137     if (logicalLeft.isAuto() || logicalRight.isAuto()) {
3138         if (marginLogicalLeft.isAuto())
3139             marginLogicalLeft.setValue(Fixed, 0);
3140         if (marginLogicalRight.isAuto())
3141             marginLogicalRight.setValue(Fixed, 0);
3142     }
3143
3144     /*-----------------------------------------------------------------------*\
3145      * 4. If at this point both 'margin-left' and 'margin-right' are still
3146      *    'auto', solve the equation under the extra constraint that the two
3147      *    margins must get equal values, unless this would make them negative,
3148      *    in which case when the direction of the containing block is 'ltr'
3149      *    ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
3150      *    'margin-right' ('margin-left').
3151     \*-----------------------------------------------------------------------*/
3152     LayoutUnit logicalLeftValue = 0;
3153     LayoutUnit logicalRightValue = 0;
3154
3155     if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3156         // 'left' and 'right' cannot be 'auto' due to step 3
3157         ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3158
3159         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3160         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3161
3162         LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
3163         if (difference > 0) {
3164             marginLogicalLeftAlias = difference / 2; // split the difference
3165             marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
3166         } else {
3167             // Use the containing block's direction rather than the parent block's
3168             // per CSS 2.1 reference test abspos-replaced-width-margin-000.
3169             if (containerDirection == LTR) {
3170                 marginLogicalLeftAlias = 0;
3171                 marginLogicalRightAlias = difference; // will be negative
3172             } else {
3173                 marginLogicalLeftAlias = difference; // will be negative
3174                 marginLogicalRightAlias = 0;
3175             }
3176         }
3177
3178     /*-----------------------------------------------------------------------*\
3179      * 5. If at this point there is an 'auto' left, solve the equation for
3180      *    that value.
3181     \*-----------------------------------------------------------------------*/
3182     } else if (logicalLeft.isAuto()) {
3183         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3184         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3185         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3186
3187         // Solve for 'left'
3188         logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3189     } else if (logicalRight.isAuto()) {
3190         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3191         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3192         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3193
3194         // Solve for 'right'
3195         logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3196     } else if (marginLogicalLeft.isAuto()) {
3197         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3198         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3199         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3200
3201         // Solve for 'margin-left'
3202         marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
3203     } else if (marginLogicalRight.isAuto()) {
3204         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3205         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3206         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3207
3208         // Solve for 'margin-right'
3209         marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
3210     } else {
3211         // Nothing is 'auto', just calculate the values.
3212         marginLogicalLeftAlias = marginLogicalLeft.calcValue(containerLogicalWidth);
3213         marginLogicalRightAlias = marginLogicalRight.calcValue(containerLogicalWidth);
3214         logicalRightValue = logicalRight.calcValue(containerLogicalWidth);
3215         logicalLeftValue = logicalLeft.calcValue(containerLogicalWidth);
3216         // If the containing block is right-to-left, then push the left position as far to the right as possible
3217         if (containerDirection == RTL) {
3218             int totalLogicalWidth = logicalWidth() + logicalLeftValue + logicalRightValue +  marginLogicalLeftAlias + marginLogicalRightAlias;
3219             logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
3220         }
3221     }
3222
3223     /*-----------------------------------------------------------------------*\
3224      * 6. If at this point the values are over-constrained, ignore the value
3225      * &nbs