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