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