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