Make computeBlockDirectionMargins const
[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             ComputedMarginValues marginValues;
1989             bool shouldFlipBeforeAfter = cb->style()->writingMode() != style()->writingMode();
1990             computeBlockDirectionMargins(cb,
1991                 shouldFlipBeforeAfter ? marginValues.m_after : marginValues.m_before,
1992                 shouldFlipBeforeAfter ? marginValues.m_before : marginValues.m_after);
1993             setMarginBefore(marginValues.m_before);
1994             setMarginAfter(marginValues.m_after);
1995         }
1996
1997         // For tables, calculate margins only.
1998         if (isTable()) {
1999             if (hasPerpendicularContainingBlock) {
2000                 ComputedMarginValues marginValues;
2001                 bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), style());
2002                 computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), logicalHeight(),
2003                     shouldFlipBeforeAfter ? marginValues.m_after : marginValues.m_before,
2004                     shouldFlipBeforeAfter ? marginValues.m_before : marginValues.m_after);
2005                 setMarginBefore(marginValues.m_before);
2006                 setMarginAfter(marginValues.m_after);
2007             }
2008             return;
2009         }
2010
2011         // FIXME: Account for block-flow in flexible boxes.
2012         // https://bugs.webkit.org/show_bug.cgi?id=46418
2013         bool inHorizontalBox = parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL;
2014         bool stretching = parent()->style()->boxAlign() == BSTRETCH;
2015         bool treatAsReplaced = shouldComputeSizeAsReplaced() && (!inHorizontalBox || !stretching);
2016         bool checkMinMaxHeight = false;
2017
2018         // The parent box is flexing us, so it has increased or decreased our height.  We have to
2019         // grab our cached flexible height.
2020         // FIXME: Account for block-flow in flexible boxes.
2021         // https://bugs.webkit.org/show_bug.cgi?id=46418
2022         if (hasOverrideHeight() && parent()->isFlexibleBoxIncludingDeprecated())
2023             h = Length(overrideLogicalContentHeight(), Fixed);
2024         else if (treatAsReplaced)
2025             h = Length(computeReplacedLogicalHeight(), Fixed);
2026         else {
2027             h = style()->logicalHeight();
2028             checkMinMaxHeight = true;
2029         }
2030
2031         // Block children of horizontal flexible boxes fill the height of the box.
2032         // FIXME: Account for block-flow in flexible boxes.
2033         // https://bugs.webkit.org/show_bug.cgi?id=46418
2034         if (h.isAuto() && parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == HORIZONTAL
2035                 && parent()->isStretchingChildren()) {
2036             h = Length(parentBox()->contentLogicalHeight() - marginBefore() - marginAfter() - borderAndPaddingLogicalHeight(), Fixed);
2037             checkMinMaxHeight = false;
2038         }
2039
2040         LayoutUnit heightResult;
2041         if (checkMinMaxHeight) {
2042             heightResult = computeLogicalHeightUsing(MainOrPreferredSize, style()->logicalHeight());
2043             if (heightResult == -1)
2044                 heightResult = logicalHeight();
2045             heightResult = constrainLogicalHeightByMinMax(heightResult);
2046         } else {
2047             // The only times we don't check min/max height are when a fixed length has
2048             // been given as an override.  Just use that.  The value has already been adjusted
2049             // for box-sizing.
2050             heightResult = h.value() + borderAndPaddingLogicalHeight();
2051         }
2052
2053         setLogicalHeight(heightResult);
2054         
2055         if (hasPerpendicularContainingBlock) {
2056             ComputedMarginValues marginValues;
2057             bool shouldFlipBeforeAfter = shouldFlipBeforeAfterMargins(cb->style(), style());
2058             computeInlineDirectionMargins(cb, containingBlockLogicalWidthForContent(), heightResult,
2059                     shouldFlipBeforeAfter ? marginValues.m_after : marginValues.m_before,
2060                     shouldFlipBeforeAfter ? marginValues.m_before : marginValues.m_after);
2061             setMarginBefore(marginValues.m_before);
2062             setMarginAfter(marginValues.m_after);
2063         }
2064     }
2065
2066     // WinIE quirk: The <html> block always fills the entire canvas in quirks mode.  The <body> always fills the
2067     // <html> block in quirks mode.  Only apply this quirk if the block is normal flow and no height
2068     // is specified. When we're printing, we also need this quirk if the body or root has a percentage 
2069     // height since we don't set a height in RenderView when we're printing. So without this quirk, the 
2070     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
2071     bool paginatedContentNeedsBaseHeight = document()->printing() && h.isPercent()
2072         && (isRoot() || (isBody() && document()->documentElement()->renderer()->style()->logicalHeight().isPercent()));
2073     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
2074         // FIXME: Finish accounting for block flow here.
2075         // https://bugs.webkit.org/show_bug.cgi?id=46603
2076         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
2077         LayoutUnit visHeight;
2078         if (document()->printing())
2079             visHeight = static_cast<LayoutUnit>(view()->pageLogicalHeight());
2080         else  {
2081             if (isHorizontalWritingMode())
2082                 visHeight = view()->viewHeight();
2083             else
2084                 visHeight = view()->viewWidth();
2085         }
2086         if (isRoot())
2087             setLogicalHeight(max(logicalHeight(), visHeight - margins));
2088         else {
2089             LayoutUnit marginsBordersPadding = margins + parentBox()->marginBefore() + parentBox()->marginAfter() + parentBox()->borderAndPaddingLogicalHeight();
2090             setLogicalHeight(max(logicalHeight(), visHeight - marginsBordersPadding));
2091         }
2092     }
2093 }
2094
2095 LayoutUnit RenderBox::computeLogicalHeightUsing(SizeType heightType, const Length& height)
2096 {
2097     LayoutUnit logicalHeight = computeContentLogicalHeightUsing(heightType, height);
2098     if (logicalHeight != -1)
2099         logicalHeight = computeBorderBoxLogicalHeight(logicalHeight);
2100     return logicalHeight;
2101 }
2102
2103 LayoutUnit RenderBox::computeLogicalClientHeight(SizeType heightType, const Length& height)
2104 {
2105     LayoutUnit heightIncludingScrollbar = computeContentLogicalHeightUsing(heightType, height);
2106     if (heightIncludingScrollbar == -1)
2107         return -1;
2108     return std::max(LayoutUnit(0), computeContentBoxLogicalHeight(heightIncludingScrollbar) - scrollbarLogicalHeight());
2109 }
2110
2111 LayoutUnit RenderBox::computeContentLogicalHeightUsing(SizeType heightType, const Length& height)
2112 {
2113     if (height.isAuto())
2114         return heightType == MinSize ? 0 : -1;
2115     if (height.isFixed())
2116         return height.value();
2117     if (height.isPercent())
2118         return computePercentageLogicalHeight(height);
2119     if (height.isViewportPercentage())
2120         return valueForLength(height, 0, view());
2121     return -1;
2122 }
2123
2124 LayoutUnit RenderBox::computePercentageLogicalHeight(const Length& height)
2125 {
2126     LayoutUnit result = -1;
2127     
2128     // In quirks mode, blocks with auto height are skipped, and we keep looking for an enclosing
2129     // block that may have a specified height and then use it. In strict mode, this violates the
2130     // specification, which states that percentage heights just revert to auto if the containing
2131     // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
2132     // only at explicit containers.
2133     bool skippedAutoHeightContainingBlock = false;
2134     RenderBlock* cb = containingBlock();
2135     while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style()->logicalHeight().isAuto()) {
2136         if (!document()->inQuirksMode() && !cb->isAnonymousBlock())
2137             break;
2138         skippedAutoHeightContainingBlock = true;
2139         cb = cb->containingBlock();
2140         cb->addPercentHeightDescendant(this);
2141     }
2142
2143     RenderStyle* cbstyle = cb->style();
2144
2145     // A positioned element that specified both top/bottom or that specifies height should be treated as though it has a height
2146     // explicitly specified that can be used for any percentage computations.
2147     // FIXME: We can't just check top/bottom here.
2148     // https://bugs.webkit.org/show_bug.cgi?id=46500
2149     bool isOutOfFlowPositionedWithSpecifiedHeight = cb->isOutOfFlowPositioned() && (!cbstyle->logicalHeight().isAuto() || (!cbstyle->top().isAuto() && !cbstyle->bottom().isAuto()));
2150
2151     bool includeBorderPadding = isTable();
2152
2153     // Table cells violate what the CSS spec says to do with heights.  Basically we
2154     // don't care if the cell specified a height or not.  We just always make ourselves
2155     // be a percentage of the cell's current content height.
2156     if (cb->isTableCell()) {
2157         if (!skippedAutoHeightContainingBlock) {
2158             if (!cb->hasOverrideHeight()) {
2159                 // Normally we would let the cell size intrinsically, but scrolling overflow has to be
2160                 // treated differently, since WinIE lets scrolled overflow regions shrink as needed.
2161                 // While we can't get all cases right, we can at least detect when the cell has a specified
2162                 // height or when the table has a specified height.  In these cases we want to initially have
2163                 // no size and allow the flexing of the table or the cell to its specified height to cause us
2164                 // to grow to fill the space.  This could end up being wrong in some cases, but it is
2165                 // preferable to the alternative (sizing intrinsically and making the row end up too big).
2166                 RenderTableCell* cell = toRenderTableCell(cb);
2167                 if (scrollsOverflowY() && (!cell->style()->logicalHeight().isAuto() || !cell->table()->style()->logicalHeight().isAuto()))
2168                     return 0;
2169                 return -1;
2170             }
2171             result = cb->overrideLogicalContentHeight();
2172             includeBorderPadding = true;
2173         }
2174     } else if (cbstyle->logicalHeight().isFixed()) {
2175         // Otherwise we only use our percentage height if our containing block had a specified height.
2176         LayoutUnit contentBoxHeightWithScrollbar = cb->computeContentBoxLogicalHeight(cbstyle->logicalHeight().value());
2177         result = max<LayoutUnit>(0, contentBoxHeightWithScrollbar - cb->scrollbarLogicalHeight());
2178     } else if (cbstyle->logicalHeight().isPercent() && !isOutOfFlowPositionedWithSpecifiedHeight) {
2179         // We need to recur and compute the percentage height for our containing block.
2180         result = cb->computePercentageLogicalHeight(cbstyle->logicalHeight());
2181         if (result != -1)
2182             result = cb->computeContentBoxLogicalHeight(result);
2183     } else if (cb->isRenderView() || (cb->isBody() && document()->inQuirksMode()) || isOutOfFlowPositionedWithSpecifiedHeight) {
2184         // Don't allow this to affect the block' height() member variable, since this
2185         // can get called while the block is still laying out its kids.
2186         LayoutUnit oldHeight = cb->logicalHeight();
2187         cb->computeLogicalHeight();
2188         result = cb->contentLogicalHeight();
2189         cb->setLogicalHeight(oldHeight);
2190     }
2191
2192     if (result != -1) {
2193         result = valueForLength(height, result);
2194         if (includeBorderPadding) {
2195             // It is necessary to use the border-box to match WinIE's broken
2196             // box model.  This is essential for sizing inside
2197             // table cells using percentage heights.
2198             result -= borderAndPaddingLogicalHeight();
2199             result = max<LayoutUnit>(0, result);
2200         }
2201     }
2202     return result;
2203 }
2204
2205 LayoutUnit RenderBox::computeReplacedLogicalWidth(bool includeMaxWidth) const
2206 {
2207     return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style()->logicalWidth()), includeMaxWidth);
2208 }
2209
2210 LayoutUnit RenderBox::computeReplacedLogicalWidthRespectingMinMaxWidth(LayoutUnit logicalWidth, bool includeMaxWidth) const
2211 {
2212     LayoutUnit minLogicalWidth = computeReplacedLogicalWidthUsing(MinSize, style()->logicalMinWidth());
2213     LayoutUnit maxLogicalWidth = !includeMaxWidth || style()->logicalMaxWidth().isUndefined() ? logicalWidth : computeReplacedLogicalWidthUsing(MaxSize, style()->logicalMaxWidth());
2214     return max(minLogicalWidth, min(logicalWidth, maxLogicalWidth));
2215 }
2216
2217 LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(SizeType sizeType, Length logicalWidth) const
2218 {
2219     if (sizeType == MinSize && logicalWidth.isAuto())
2220         return computeContentBoxLogicalWidth(0);
2221
2222     switch (logicalWidth.type()) {
2223         case Fixed:
2224             return computeContentBoxLogicalWidth(logicalWidth.value());
2225         case ViewportPercentageWidth:
2226         case ViewportPercentageHeight:
2227         case ViewportPercentageMin:
2228             return computeContentBoxLogicalWidth(valueForLength(logicalWidth, 0, view()));
2229         case Percent: 
2230         case Calculated: {
2231             // FIXME: containingBlockLogicalWidthForContent() is wrong if the replaced element's block-flow is perpendicular to the
2232             // containing block's block-flow.
2233             // https://bugs.webkit.org/show_bug.cgi?id=46496
2234             const LayoutUnit cw = isOutOfFlowPositioned() ? containingBlockLogicalWidthForPositioned(toRenderBoxModelObject(container())) : containingBlockLogicalWidthForContent();
2235             Length containerLogicalWidth = containingBlock()->style()->logicalWidth();
2236             // FIXME: Handle cases when containing block width is calculated or viewport percent.
2237             // https://bugs.webkit.org/show_bug.cgi?id=91071
2238             if (cw > 0 || (!cw && (containerLogicalWidth.isFixed() || containerLogicalWidth.isPercent())))
2239                 return computeContentBoxLogicalWidth(minimumValueForLength(logicalWidth, cw));
2240         }
2241         // fall through
2242         default:
2243             return intrinsicLogicalWidth();
2244      }
2245 }
2246
2247 LayoutUnit RenderBox::computeReplacedLogicalHeight() const
2248 {
2249     return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style()->logicalHeight()));
2250 }
2251
2252 LayoutUnit RenderBox::computeReplacedLogicalHeightRespectingMinMaxHeight(LayoutUnit logicalHeight) const
2253 {
2254     LayoutUnit minLogicalHeight = computeReplacedLogicalHeightUsing(MinSize, style()->logicalMinHeight());
2255     LayoutUnit maxLogicalHeight = style()->logicalMaxHeight().isUndefined() ? logicalHeight : computeReplacedLogicalHeightUsing(MaxSize, style()->logicalMaxHeight());
2256     return max(minLogicalHeight, min(logicalHeight, maxLogicalHeight));
2257 }
2258
2259 LayoutUnit RenderBox::computeReplacedLogicalHeightUsing(SizeType sizeType, Length logicalHeight) const
2260 {
2261     if (sizeType == MinSize && logicalHeight.isAuto())
2262         return computeContentBoxLogicalHeight(0);
2263
2264     switch (logicalHeight.type()) {
2265         case Fixed:
2266             return computeContentBoxLogicalHeight(logicalHeight.value());
2267         case Percent:
2268         case Calculated:
2269         {
2270             RenderObject* cb = isOutOfFlowPositioned() ? container() : containingBlock();
2271             while (cb->isAnonymous()) {
2272                 cb = cb->containingBlock();
2273                 toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2274             }
2275
2276             // FIXME: This calculation is not patched for block-flow yet.
2277             // https://bugs.webkit.org/show_bug.cgi?id=46500
2278             if (cb->isOutOfFlowPositioned() && cb->style()->height().isAuto() && !(cb->style()->top().isAuto() || cb->style()->bottom().isAuto())) {
2279                 ASSERT(cb->isRenderBlock());
2280                 RenderBlock* block = toRenderBlock(cb);
2281                 LayoutUnit oldHeight = block->height();
2282                 block->computeLogicalHeight();
2283                 LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentHeight());
2284                 block->setHeight(oldHeight);
2285                 return computeContentBoxLogicalHeight(valueForLength(logicalHeight, newHeight));
2286             }
2287             
2288             // FIXME: availableLogicalHeight() is wrong if the replaced element's block-flow is perpendicular to the
2289             // containing block's block-flow.
2290             // https://bugs.webkit.org/show_bug.cgi?id=46496
2291             LayoutUnit availableHeight;
2292             if (isOutOfFlowPositioned())
2293                 availableHeight = containingBlockLogicalHeightForPositioned(toRenderBoxModelObject(cb));
2294             else {
2295                 availableHeight =  toRenderBox(cb)->availableLogicalHeight();
2296                 // It is necessary to use the border-box to match WinIE's broken
2297                 // box model.  This is essential for sizing inside
2298                 // table cells using percentage heights.
2299                 // FIXME: This needs to be made block-flow-aware.  If the cell and image are perpendicular block-flows, this isn't right.
2300                 // https://bugs.webkit.org/show_bug.cgi?id=46997
2301                 while (cb && !cb->isRenderView() && (cb->style()->logicalHeight().isAuto() || cb->style()->logicalHeight().isPercent())) {
2302                     if (cb->isTableCell()) {
2303                         // Don't let table cells squeeze percent-height replaced elements
2304                         // <http://bugs.webkit.org/show_bug.cgi?id=15359>
2305                         availableHeight = max(availableHeight, intrinsicLogicalHeight());
2306                         return valueForLength(logicalHeight, availableHeight - borderAndPaddingLogicalHeight());
2307                     }
2308                     toRenderBlock(cb)->addPercentHeightDescendant(const_cast<RenderBox*>(this));
2309                     cb = cb->containingBlock();
2310                 }
2311             }
2312             availableHeight = computeContentBoxLogicalHeight(valueForLength(logicalHeight, availableHeight));
2313             if (cb->isBox() && cb->style()->logicalHeight().isFixed())
2314                 availableHeight = max<LayoutUnit>(0, availableHeight - toRenderBox(cb)->scrollbarLogicalHeight());
2315             return availableHeight;
2316         }
2317         case ViewportPercentageWidth:
2318         case ViewportPercentageHeight:
2319         case ViewportPercentageMin:
2320             return computeContentBoxLogicalHeight(valueForLength(logicalHeight, 0, view()));
2321         default:
2322             return intrinsicLogicalHeight();
2323     }
2324 }
2325
2326 LayoutUnit RenderBox::availableLogicalHeight() const
2327 {
2328     return availableLogicalHeightUsing(style()->logicalHeight());
2329 }
2330
2331 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const
2332 {
2333     if (h.isFixed())
2334         return computeContentBoxLogicalHeight(h.value());
2335
2336     if (isRenderView())
2337         return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
2338
2339     // We need to stop here, since we don't want to increase the height of the table
2340     // artificially.  We're going to rely on this cell getting expanded to some new
2341     // height, and then when we lay out again we'll use the calculation below.
2342     if (isTableCell() && (h.isAuto() || h.isPercent()))
2343         return overrideLogicalContentHeight();
2344
2345     if (h.isPercent()) {
2346         LayoutUnit availableHeight;
2347         // https://bugs.webkit.org/show_bug.cgi?id=64046
2348         // For absolutely positioned elements whose containing block is based on a block-level element,
2349         // the percentage is calculated with respect to the height of the padding box of that element
2350         if (isOutOfFlowPositioned())
2351             availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
2352         else
2353             availableHeight = containingBlock()->availableLogicalHeight();
2354         return computeContentBoxLogicalHeight(valueForLength(h, availableHeight));
2355     }
2356
2357     // FIXME: We can't just check top/bottom here.
2358     // https://bugs.webkit.org/show_bug.cgi?id=46500
2359     if (isRenderBlock() && isOutOfFlowPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
2360         RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
2361         LayoutUnit oldHeight = block->logicalHeight();
2362         block->computeLogicalHeight();
2363         LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
2364         block->setLogicalHeight(oldHeight);
2365         return computeContentBoxLogicalHeight(newHeight);
2366     }
2367
2368     return containingBlock()->availableLogicalHeight();
2369 }
2370
2371 void RenderBox::computeBlockDirectionMargins(const RenderBlock* containingBlock, LayoutUnit& marginBefore, LayoutUnit& marginAfter) const
2372 {
2373     if (isTableCell()) {
2374         // FIXME: Not right if we allow cells to have different directionality than the table.  If we do allow this, though,
2375         // we may just do it with an extra anonymous block inside the cell.
2376         marginBefore = 0;
2377         marginAfter = 0;
2378         return;
2379     }
2380
2381     // Margins are calculated with respect to the logical width of
2382     // the containing block (8.3)
2383     LayoutUnit cw = containingBlockLogicalWidthForContent();
2384     RenderView* renderView = view();
2385     RenderStyle* containingBlockStyle = containingBlock->style();
2386     marginBefore = minimumValueForLength(style()->marginBeforeUsing(containingBlockStyle), cw, renderView);
2387     marginAfter = minimumValueForLength(style()->marginAfterUsing(containingBlockStyle), cw, renderView);
2388 }
2389
2390 void RenderBox::computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock)
2391 {
2392     LayoutUnit marginBefore;
2393     LayoutUnit marginAfter;
2394     computeBlockDirectionMargins(containingBlock, marginBefore, marginAfter);
2395     containingBlock->setMarginBeforeForChild(this, marginBefore);
2396     containingBlock->setMarginAfterForChild(this, marginAfter);
2397 }
2398
2399 LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region,
2400     LayoutUnit offsetFromLogicalTopOfFirstPage, bool checkForPerpendicularWritingMode) const
2401 {
2402     // Container for position:fixed is the frame.
2403     Frame* frame = view() ? view()->frame(): 0;
2404     FrameView* frameView = view() ? view()->frameView() : 0;
2405     if (fixedElementLaysOutRelativeToFrame(frame, frameView))
2406         return (view()->isHorizontalWritingMode() ? frameView->visibleWidth() : frameView->visibleHeight()) / frame->frameScaleFactor();
2407
2408     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2409         return containingBlockLogicalHeightForPositioned(containingBlock, false);
2410
2411     if (containingBlock->isBox()) {
2412         const RenderBlock* cb = toRenderBlock(containingBlock);
2413         LayoutUnit result = cb->clientLogicalWidth();
2414         if (inRenderFlowThread()) {
2415             RenderBoxRegionInfo* boxInfo = 0;
2416             if (!region) {
2417                 if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
2418                     return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
2419                 if (isWritingModeRoot()) {
2420                     LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2421                     RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2422                     if (cbRegion) {
2423                         cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2424                         boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2425                     }
2426                 }
2427             } else if (region && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
2428                 RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
2429                 boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
2430             }
2431             if (boxInfo)
2432                 return max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
2433         }
2434         return result;
2435     }
2436
2437     ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
2438
2439     const RenderInline* flow = toRenderInline(containingBlock);
2440     InlineFlowBox* first = flow->firstLineBox();
2441     InlineFlowBox* last = flow->lastLineBox();
2442
2443     // If the containing block is empty, return a width of 0.
2444     if (!first || !last)
2445         return 0;
2446
2447     LayoutUnit fromLeft;
2448     LayoutUnit fromRight;
2449     if (containingBlock->style()->isLeftToRightDirection()) {
2450         fromLeft = first->logicalLeft() + first->borderLogicalLeft();
2451         fromRight = last->logicalLeft() + last->logicalWidth() - last->borderLogicalRight();
2452     } else {
2453         fromRight = first->logicalLeft() + first->logicalWidth() - first->borderLogicalRight();
2454         fromLeft = last->logicalLeft() + last->borderLogicalLeft();
2455     }
2456
2457     return max<LayoutUnit>(0, fromRight - fromLeft);
2458 }
2459
2460 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
2461 {
2462     Frame* frame = view() ? view()->frame(): 0;
2463     FrameView* frameView = view() ? view()->frameView() : 0;
2464     if (fixedElementLaysOutRelativeToFrame(frame, frameView))
2465         return (view()->isHorizontalWritingMode() ? frameView->visibleHeight() : frameView->visibleWidth()) / frame->frameScaleFactor();
2466
2467     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
2468         return containingBlockLogicalWidthForPositioned(containingBlock, 0, 0, false);
2469
2470     if (containingBlock->isBox()) {
2471         const RenderBlock* cb = toRenderBlock(containingBlock);
2472         LayoutUnit result = cb->clientLogicalHeight();
2473         if (inRenderFlowThread() && containingBlock->isRenderFlowThread() && enclosingRenderFlowThread()->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode())
2474             return toRenderFlowThread(containingBlock)->contentLogicalHeightOfFirstRegion();
2475         return result;
2476     }
2477         
2478     ASSERT(containingBlock->isRenderInline() && containingBlock->isInFlowPositioned());
2479
2480     const RenderInline* flow = toRenderInline(containingBlock);
2481     InlineFlowBox* first = flow->firstLineBox();
2482     InlineFlowBox* last = flow->lastLineBox();
2483
2484     // If the containing block is empty, return a height of 0.
2485     if (!first || !last)
2486         return 0;
2487
2488     LayoutUnit heightResult;
2489     LayoutRect boundingBox = flow->linesBoundingBox();
2490     if (containingBlock->isHorizontalWritingMode())
2491         heightResult = boundingBox.height();
2492     else
2493         heightResult = boundingBox.width();
2494     heightResult -= (containingBlock->borderBefore() + containingBlock->borderAfter());
2495     return heightResult;
2496 }
2497
2498 static void computeInlineStaticDistance(Length& logicalLeft, Length& logicalRight, const RenderBox* child, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth, RenderRegion* region)
2499 {
2500     if (!logicalLeft.isAuto() || !logicalRight.isAuto())
2501         return;
2502
2503     // FIXME: The static distance computation has not been patched for mixed writing modes yet.
2504     if (child->parent()->style()->direction() == LTR) {
2505         LayoutUnit staticPosition = child->layer()->staticInlinePosition() - containerBlock->borderLogicalLeft();
2506         for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2507             if (curr->isBox()) {
2508                 staticPosition += toRenderBox(curr)->logicalLeft();
2509                 if (region && curr->isRenderBlock()) {
2510                     const RenderBlock* cb = toRenderBlock(curr);
2511                     region = cb->clampToStartAndEndRegions(region);
2512                     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2513                     if (boxInfo)
2514                         staticPosition += boxInfo->logicalLeft();
2515                 }
2516             }
2517         }
2518         logicalLeft.setValue(Fixed, staticPosition);
2519     } else {
2520         RenderBox* enclosingBox = child->parent()->enclosingBox();
2521         LayoutUnit staticPosition = child->layer()->staticInlinePosition() + containerLogicalWidth + containerBlock->borderLogicalLeft();
2522         for (RenderObject* curr = enclosingBox; curr; curr = curr->container()) {
2523             if (curr->isBox()) {
2524                 if (curr != containerBlock)
2525                     staticPosition -= toRenderBox(curr)->logicalLeft();
2526                 if (curr == enclosingBox)
2527                     staticPosition -= enclosingBox->logicalWidth();
2528                 if (region && curr->isRenderBlock()) {
2529                      const RenderBlock* cb = toRenderBlock(curr);
2530                      region = cb->clampToStartAndEndRegions(region);
2531                      RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->offsetFromLogicalTopOfFirstPage());
2532                      if (boxInfo) {
2533                         if (curr != containerBlock)
2534                             staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
2535                         if (curr == enclosingBox)
2536                             staticPosition += enclosingBox->logicalWidth() - boxInfo->logicalWidth();
2537                     }
2538                 }
2539             }
2540             if (curr == containerBlock)
2541                 break;
2542         }
2543         logicalRight.setValue(Fixed, staticPosition);
2544     }
2545 }
2546
2547 void RenderBox::computePositionedLogicalWidth(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
2548 {
2549     if (isReplaced()) {
2550         computePositionedLogicalWidthReplaced(); // FIXME: Patch for regions when we add replaced element support.
2551         return;
2552     }
2553
2554     // QUESTIONS
2555     // FIXME 1: Should we still deal with these the cases of 'left' or 'right' having
2556     // the type 'static' in determining whether to calculate the static distance?
2557     // NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
2558
2559     // FIXME 2: Can perhaps optimize out cases when max-width/min-width are greater
2560     // than or less than the computed width().  Be careful of box-sizing and
2561     // percentage issues.
2562
2563     // The following is based off of the W3C Working Draft from April 11, 2006 of
2564     // CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
2565     // <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
2566     // (block-style-comments in this function and in computePositionedLogicalWidthUsing()
2567     // correspond to text from the spec)
2568
2569
2570     // We don't use containingBlock(), since we may be positioned by an enclosing
2571     // relative positioned inline.
2572     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2573     
2574     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region, offsetFromLogicalTopOfFirstPage);
2575
2576     // Use the container block's direction except when calculating the static distance
2577     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
2578     // of the CSS 2.1 test suite
2579     TextDirection containerDirection = containerBlock->style()->direction();
2580
2581     bool isHorizontal = isHorizontalWritingMode();
2582     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth();
2583     const Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
2584     const Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
2585     LayoutUnit& marginLogicalLeftAlias = m_marginBox.mutableLogicalLeft(style()->writingMode());
2586     LayoutUnit& marginLogicalRightAlias = m_marginBox.mutableLogicalRight(style()->writingMode());
2587
2588     Length logicalLeftLength = style()->logicalLeft();
2589     Length logicalRightLength = style()->logicalRight();
2590
2591     /*---------------------------------------------------------------------------*\
2592      * For the purposes of this section and the next, the term "static position"
2593      * (of an element) refers, roughly, to the position an element would have had
2594      * in the normal flow. More precisely:
2595      *
2596      * * The static position for 'left' is the distance from the left edge of the
2597      *   containing block to the left margin edge of a hypothetical box that would
2598      *   have been the first box of the element if its 'position' property had
2599      *   been 'static' and 'float' had been 'none'. The value is negative if the
2600      *   hypothetical box is to the left of the containing block.
2601      * * The static position for 'right' is the distance from the right edge of the
2602      *   containing block to the right margin edge of the same hypothetical box as
2603      *   above. The value is positive if the hypothetical box is to the left of the
2604      *   containing block's edge.
2605      *
2606      * But rather than actually calculating the dimensions of that hypothetical box,
2607      * user agents are free to make a guess at its probable position.
2608      *
2609      * For the purposes of calculating the static position, the containing block of
2610      * fixed positioned elements is the initial containing block instead of the
2611      * viewport, and all scrollable boxes should be assumed to be scrolled to their
2612      * origin.
2613     \*---------------------------------------------------------------------------*/
2614
2615     // see FIXME 1
2616     // Calculate the static distance if needed.
2617     computeInlineStaticDistance(logicalLeftLength, logicalRightLength, this, containerBlock, containerLogicalWidth, region);
2618     
2619     // Calculate constraint equation values for 'width' case.
2620     LayoutUnit logicalWidthResult;
2621     LayoutUnit logicalLeftResult;
2622     computePositionedLogicalWidthUsing(MainOrPreferredSize, style()->logicalWidth(), containerBlock, containerDirection,
2623                                        containerLogicalWidth, bordersPlusPadding,
2624                                        logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2625                                        logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2626     setLogicalWidth(logicalWidthResult);
2627     setLogicalLeft(logicalLeftResult);
2628
2629     // Calculate constraint equation values for 'max-width' case.
2630     if (!style()->logicalMaxWidth().isUndefined()) {
2631         LayoutUnit maxLogicalWidth;
2632         LayoutUnit maxMarginLogicalLeft;
2633         LayoutUnit maxMarginLogicalRight;
2634         LayoutUnit maxLogicalLeftPos;
2635
2636         computePositionedLogicalWidthUsing(MaxSize, style()->logicalMaxWidth(), containerBlock, containerDirection,
2637                                            containerLogicalWidth, bordersPlusPadding,
2638                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2639                                            maxLogicalWidth, maxMarginLogicalLeft, maxMarginLogicalRight, maxLogicalLeftPos);
2640
2641         if (logicalWidth() > maxLogicalWidth) {
2642             setLogicalWidth(maxLogicalWidth);
2643             marginLogicalLeftAlias = maxMarginLogicalLeft;
2644             marginLogicalRightAlias = maxMarginLogicalRight;
2645             setLogicalLeft(maxLogicalLeftPos);
2646         }
2647     }
2648
2649     // Calculate constraint equation values for 'min-width' case.
2650     if (!style()->logicalMinWidth().isZero()) {
2651         LayoutUnit minLogicalWidth;
2652         LayoutUnit minMarginLogicalLeft;
2653         LayoutUnit minMarginLogicalRight;
2654         LayoutUnit minLogicalLeftPos;
2655
2656         computePositionedLogicalWidthUsing(MinSize, style()->logicalMinWidth(), containerBlock, containerDirection,
2657                                            containerLogicalWidth, bordersPlusPadding,
2658                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2659                                            minLogicalWidth, minMarginLogicalLeft, minMarginLogicalRight, minLogicalLeftPos);
2660
2661         if (logicalWidth() < minLogicalWidth) {
2662             setLogicalWidth(minLogicalWidth);
2663             marginLogicalLeftAlias = minMarginLogicalLeft;
2664             marginLogicalRightAlias = minMarginLogicalRight;
2665             setLogicalLeft(minLogicalLeftPos);
2666         }
2667     }
2668
2669     if (stretchesToMinIntrinsicLogicalWidth() && logicalWidth() < minPreferredLogicalWidth() - bordersPlusPadding) {
2670         computePositionedLogicalWidthUsing(MainOrPreferredSize, Length(minPreferredLogicalWidth() - bordersPlusPadding, Fixed), containerBlock, containerDirection,
2671                                            containerLogicalWidth, bordersPlusPadding,
2672                                            logicalLeftLength, logicalRightLength, marginLogicalLeft, marginLogicalRight,
2673                                            logicalWidthResult, marginLogicalLeftAlias, marginLogicalRightAlias, logicalLeftResult);
2674         setLogicalWidth(logicalWidthResult);
2675         setLogicalLeft(logicalLeftResult);
2676     }
2677
2678     // Put logicalWidth() into correct form.
2679     setLogicalWidth(logicalWidth() + bordersPlusPadding);
2680     
2681     // Adjust logicalLeft if we need to for the flipped version of our writing mode in regions.
2682     if (inRenderFlowThread() && !region && isWritingModeRoot() && isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
2683         LayoutUnit logicalLeftPos = logicalLeft();
2684         const RenderBlock* cb = toRenderBlock(containerBlock);
2685         LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
2686         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2687         if (cbRegion) {
2688             cbRegion = cb->clampToStartAndEndRegions(cbRegion);
2689             RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
2690             if (boxInfo) {
2691                 logicalLeftPos += boxInfo->logicalLeft();
2692                 setLogicalLeft(logicalLeftPos);
2693             }
2694         }
2695     }
2696 }
2697
2698 static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const RenderBox* child, LayoutUnit logicalWidthValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalWidth)
2699 {
2700     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
2701     // 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.
2702     if (containerBlock->isHorizontalWritingMode() != child->isHorizontalWritingMode() && containerBlock->style()->isFlippedBlocksWritingMode()) {
2703         logicalLeftPos = containerLogicalWidth - logicalWidthValue - logicalLeftPos;
2704         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderRight() : containerBlock->borderBottom());
2705     } else
2706         logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
2707 }
2708
2709 void RenderBox::computePositionedLogicalWidthUsing(SizeType widthSizeType, Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
2710                                                    LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
2711                                                    Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
2712                                                    LayoutUnit& logicalWidthValue, LayoutUnit& marginLogicalLeftValue, LayoutUnit& marginLogicalRightValue, LayoutUnit& logicalLeftPos)
2713 {
2714     if (widthSizeType == MinSize && logicalWidth.isAuto())
2715         logicalWidth = Length(0, Fixed);
2716
2717     // 'left' and 'right' cannot both be 'auto' because one would of been
2718     // converted to the static position already
2719     ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
2720
2721     LayoutUnit logicalLeftValue = 0;
2722
2723     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
2724     bool logicalLeftIsAuto = logicalLeft.isAuto();
2725     bool logicalRightIsAuto = logicalRight.isAuto();
2726     RenderView* renderView = view();
2727
2728     if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2729         /*-----------------------------------------------------------------------*\
2730          * If none of the three is 'auto': If both 'margin-left' and 'margin-
2731          * right' are 'auto', solve the equation under the extra constraint that
2732          * the two margins get equal values, unless this would make them negative,
2733          * in which case when direction of the containing block is 'ltr' ('rtl'),
2734          * set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
2735          * ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
2736          * solve the equation for that value. If the values are over-constrained,
2737          * ignore the value for 'left' (in case the 'direction' property of the
2738          * containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
2739          * and solve for that value.
2740         \*-----------------------------------------------------------------------*/
2741         // NOTE:  It is not necessary to solve for 'right' in the over constrained
2742         // case because the value is not used for any further calculations.
2743
2744         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
2745         logicalWidthValue = computeContentBoxLogicalWidth(valueForLength(logicalWidth, containerLogicalWidth, renderView));
2746
2747         const LayoutUnit availableSpace = containerLogicalWidth - (logicalLeftValue + logicalWidthValue + valueForLength(logicalRight, containerLogicalWidth, renderView) + bordersPlusPadding);
2748
2749         // Margins are now the only unknown
2750         if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
2751             // Both margins auto, solve for equality
2752             if (availableSpace >= 0) {
2753                 marginLogicalLeftValue = availableSpace / 2; // split the difference
2754                 marginLogicalRightValue = availableSpace - marginLogicalLeftValue; // account for odd valued differences
2755             } else {
2756                 // Use the containing block's direction rather than the parent block's
2757                 // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2758                 if (containerDirection == LTR) {
2759                     marginLogicalLeftValue = 0;
2760                     marginLogicalRightValue = availableSpace; // will be negative
2761                 } else {
2762                     marginLogicalLeftValue = availableSpace; // will be negative
2763                     marginLogicalRightValue = 0;
2764                 }
2765             }
2766         } else if (marginLogicalLeft.isAuto()) {
2767             // Solve for left margin
2768             marginLogicalRightValue = valueForLength(marginLogicalRight, containerLogicalWidth, renderView);
2769             marginLogicalLeftValue = availableSpace - marginLogicalRightValue;
2770         } else if (marginLogicalRight.isAuto()) {
2771             // Solve for right margin
2772             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerLogicalWidth, renderView);
2773             marginLogicalRightValue = availableSpace - marginLogicalLeftValue;
2774         } else {
2775             // Over-constrained, solve for left if direction is RTL
2776             marginLogicalLeftValue = valueForLength(marginLogicalLeft, containerLogicalWidth, renderView);
2777             marginLogicalRightValue = valueForLength(marginLogicalRight, containerLogicalWidth, renderView);
2778
2779             // Use the containing block's direction rather than the parent block's
2780             // per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
2781             if (containerDirection == RTL)
2782                 logicalLeftValue = (availableSpace + logicalLeftValue) - marginLogicalLeftValue - marginLogicalRightValue;
2783         }
2784     } else {
2785         /*--------------------------------------------------------------------*\
2786          * Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
2787          * to 0, and pick the one of the following six rules that applies.
2788          *
2789          * 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
2790          *    width is shrink-to-fit. Then solve for 'left'
2791          *
2792          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
2793          * ------------------------------------------------------------------
2794          * 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
2795          *    the 'direction' property of the containing block is 'ltr' set
2796          *    'left' to the static position, otherwise set 'right' to the
2797          *    static position. Then solve for 'left' (if 'direction is 'rtl')
2798          *    or 'right' (if 'direction' is 'ltr').
2799          * ------------------------------------------------------------------
2800          *
2801          * 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
2802          *    width is shrink-to-fit . Then solve for 'right'
2803          * 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
2804          *    for 'left'
2805          * 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
2806          *    for 'width'
2807          * 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
2808          *    for 'right'
2809          *
2810          * Calculation of the shrink-to-fit width is similar to calculating the
2811          * width of a table cell using the automatic table layout algorithm.
2812          * Roughly: calculate the preferred width by formatting the content
2813          * without breaking lines other than where explicit line breaks occur,
2814          * and also calculate the preferred minimum width, e.g., by trying all
2815          * possible line breaks. CSS 2.1 does not define the exact algorithm.
2816          * Thirdly, calculate the available width: this is found by solving
2817          * for 'width' after setting 'left' (in case 1) or 'right' (in case 3)
2818          * to 0.
2819          *
2820          * Then the shrink-to-fit width is:
2821          * min(max(preferred minimum width, available width), preferred width).
2822         \*--------------------------------------------------------------------*/
2823         // NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
2824         // because the value is not used for any further calculations.
2825
2826         // Calculate margins, 'auto' margins are ignored.
2827         marginLogicalLeftValue = minimumValueForLength(marginLogicalLeft, containerLogicalWidth, renderView);
2828         marginLogicalRightValue = minimumValueForLength(marginLogicalRight, containerLogicalWidth, renderView);
2829
2830         const LayoutUnit availableSpace = containerLogicalWidth - (marginLogicalLeftValue + marginLogicalRightValue + bordersPlusPadding);
2831
2832         // FIXME: Is there a faster way to find the correct case?
2833         // Use rule/case that applies.
2834         if (logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2835             // RULE 1: (use shrink-to-fit for width, and solve of left)
2836             LayoutUnit logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
2837
2838             // FIXME: would it be better to have shrink-to-fit in one step?
2839             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2840             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2841             LayoutUnit availableWidth = availableSpace - logicalRightValue;
2842             logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2843             logicalLeftValue = availableSpace - (logicalWidthValue + logicalRightValue);
2844         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && logicalRightIsAuto) {
2845             // RULE 3: (use shrink-to-fit for width, and no need solve of right)
2846             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
2847
2848             // FIXME: would it be better to have shrink-to-fit in one step?
2849             LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
2850             LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
2851             LayoutUnit availableWidth = availableSpace - logicalLeftValue;
2852             logicalWidthValue = min(max(preferredMinWidth, availableWidth), preferredWidth);
2853         } else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
2854             // RULE 4: (solve for left)
2855             logicalWidthValue = computeContentBoxLogicalWidth(valueForLength(logicalWidth, containerLogicalWidth, renderView));
2856             logicalLeftValue = availableSpace - (logicalWidthValue + valueForLength(logicalRight, containerLogicalWidth, renderView));
2857         } else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
2858             // RULE 5: (solve for width)
2859             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
2860             logicalWidthValue = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth, renderView));
2861         } else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
2862             // RULE 6: (no need solve for right)
2863             logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
2864             logicalWidthValue = computeContentBoxLogicalWidth(valueForLength(logicalWidth, containerLogicalWidth, renderView));
2865         }
2866     }
2867
2868     // Use computed values to calculate the horizontal position.
2869
2870     // FIXME: This hack is needed to calculate the  logical left position for a 'rtl' relatively
2871     // positioned, inline because right now, it is using the logical left position
2872     // of the first line box when really it should use the last line box.  When
2873     // this is fixed elsewhere, this block should be removed.
2874     if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
2875         const RenderInline* flow = toRenderInline(containerBlock);
2876         InlineFlowBox* firstLine = flow->firstLineBox();
2877         InlineFlowBox* lastLine = flow->lastLineBox();
2878         if (firstLine && lastLine && firstLine != lastLine) {
2879             logicalLeftPos = logicalLeftValue + marginLogicalLeftValue + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft());
2880             return;
2881         }
2882     }
2883
2884     logicalLeftPos = logicalLeftValue + marginLogicalLeftValue;
2885     computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidthValue, containerBlock, containerLogicalWidth);
2886 }
2887
2888 static void computeBlockStaticDistance(Length& logicalTop, Length& logicalBottom, const RenderBox* child, const RenderBoxModelObject* containerBlock)
2889 {
2890     if (!logicalTop.isAuto() || !logicalBottom.isAuto())
2891         return;
2892     
2893     // FIXME: The static distance computation has not been patched for mixed writing modes.
2894     LayoutUnit staticLogicalTop = child->layer()->staticBlockPosition() - containerBlock->borderBefore();
2895     for (RenderObject* curr = child->parent(); curr && curr != containerBlock; curr = curr->container()) {
2896         if (curr->isBox() && !curr->isTableRow())
2897             staticLogicalTop += toRenderBox(curr)->logicalTop();
2898     }
2899     logicalTop.setValue(Fixed, staticLogicalTop);
2900 }
2901
2902 void RenderBox::computePositionedLogicalHeight(LogicalExtentComputedValues& computedValues) const
2903 {
2904     if (isReplaced()) {
2905         computePositionedLogicalHeightReplaced(computedValues);
2906         return;
2907     }
2908
2909     // The following is based off of the W3C Working Draft from April 11, 2006 of
2910     // CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
2911     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
2912     // (block-style-comments in this function and in computePositionedLogicalHeightUsing()
2913     // correspond to text from the spec)
2914
2915
2916     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
2917     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
2918
2919     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
2920
2921     RenderStyle* styleToUse = style();
2922     const LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight();
2923     const Length marginBefore = styleToUse->marginBefore();
2924     const Length marginAfter = styleToUse->marginAfter();
2925     Length logicalTopLength = styleToUse->logicalTop();
2926     Length logicalBottomLength = styleToUse->logicalBottom();
2927
2928     /*---------------------------------------------------------------------------*\
2929      * For the purposes of this section and the next, the term "static position"
2930      * (of an element) refers, roughly, to the position an element would have had
2931      * in the normal flow. More precisely, the static position for 'top' is the
2932      * distance from the top edge of the containing block to the top margin edge
2933      * of a hypothetical box that would have been the first box of the element if
2934      * its 'position' property had been 'static' and 'float' had been 'none'. The
2935      * value is negative if the hypothetical box is above the containing block.
2936      *
2937      * But rather than actually calculating the dimensions of that hypothetical
2938      * box, user agents are free to make a guess at its probable position.
2939      *
2940      * For the purposes of calculating the static position, the containing block
2941      * of fixed positioned elements is the initial containing block instead of
2942      * the viewport.
2943     \*---------------------------------------------------------------------------*/
2944
2945     // see FIXME 1
2946     // Calculate the static distance if needed.
2947     computeBlockStaticDistance(logicalTopLength, logicalBottomLength, this, containerBlock);
2948
2949     // Calculate constraint equation values for 'height' case.
2950     computePositionedLogicalHeightUsing(MainOrPreferredSize, styleToUse->logicalHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2951                                         logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2952                                         computedValues);
2953
2954     // Avoid doing any work in the common case (where the values of min-height and max-height are their defaults).
2955     // see FIXME 2
2956
2957     // Calculate constraint equation values for 'max-height' case.
2958     if (!styleToUse->logicalMaxHeight().isUndefined()) {
2959         LogicalExtentComputedValues maxValues;
2960
2961         computePositionedLogicalHeightUsing(MaxSize, styleToUse->logicalMaxHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2962                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2963                                             maxValues);
2964
2965         if (computedValues.m_extent > maxValues.m_extent) {
2966             computedValues.m_extent = maxValues.m_extent;
2967             computedValues.m_position = maxValues.m_position;
2968             computedValues.m_margins.m_before = maxValues.m_margins.m_before;
2969             computedValues.m_margins.m_after = maxValues.m_margins.m_after;
2970         }
2971     }
2972
2973     // Calculate constraint equation values for 'min-height' case.
2974     if (!styleToUse->logicalMinHeight().isZero()) {
2975         LogicalExtentComputedValues minValues;
2976
2977         computePositionedLogicalHeightUsing(MinSize, styleToUse->logicalMinHeight(), containerBlock, containerLogicalHeight, bordersPlusPadding,
2978                                             logicalTopLength, logicalBottomLength, marginBefore, marginAfter,
2979                                             minValues);
2980
2981         if (computedValues.m_extent < minValues.m_extent) {
2982             computedValues.m_extent = minValues.m_extent;
2983             computedValues.m_position = minValues.m_position;
2984             computedValues.m_margins.m_before = minValues.m_margins.m_before;
2985             computedValues.m_margins.m_after = minValues.m_margins.m_after;
2986         }
2987     }
2988
2989     // Set final height value.
2990     computedValues.m_extent += bordersPlusPadding;
2991     
2992     // Adjust logicalTop if we need to for perpendicular writing modes in regions.
2993     if (inRenderFlowThread() && isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode()) {
2994         LayoutUnit logicalTopPos = computedValues.m_position;
2995         const RenderBlock* cb = toRenderBlock(containerBlock);
2996         LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage() - logicalLeft();
2997         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
2998         if (cbRegion) {
2999             cbRegion = cb->clampToStartAndEndRegions(cbRegion);
3000             RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
3001             if (boxInfo) {
3002                 logicalTopPos += boxInfo->logicalLeft();
3003                 computedValues.m_position = logicalTopPos;
3004             }
3005         }
3006     }
3007 }
3008
3009 static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
3010 {
3011     // Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space. If the containing block is flipped
3012     // 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.
3013     if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
3014         || (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
3015         logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
3016
3017     // Our offset is from the logical bottom edge in a flipped environment, e.g., right for vertical-rl and bottom for horizontal-bt.
3018     if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
3019         if (child->isHorizontalWritingMode())
3020             logicalTopPos += containerBlock->borderBottom();
3021         else
3022             logicalTopPos += containerBlock->borderRight();
3023     } else {
3024         if (child->isHorizontalWritingMode())
3025             logicalTopPos += containerBlock->borderTop();
3026         else
3027             logicalTopPos += containerBlock->borderLeft();
3028     }
3029 }
3030
3031 void RenderBox::computePositionedLogicalHeightUsing(SizeType heightSizeType, Length logicalHeightLength, const RenderBoxModelObject* containerBlock,
3032                                                     LayoutUnit containerLogicalHeight, LayoutUnit bordersPlusPadding,
3033                                                     Length logicalTop, Length logicalBottom, Length marginBefore, Length marginAfter,
3034                                                     LogicalExtentComputedValues& computedValues) const
3035 {
3036     if (heightSizeType == MinSize && logicalHeightLength.isAuto())
3037         logicalHeightLength = Length(0, Fixed);
3038
3039     // 'top' and 'bottom' cannot both be 'auto' because 'top would of been
3040     // converted to the static position in computePositionedLogicalHeight()
3041     ASSERT(!(logicalTop.isAuto() && logicalBottom.isAuto()));
3042
3043     LayoutUnit logicalHeightValue;
3044     LayoutUnit contentLogicalHeight = logicalHeight() - bordersPlusPadding;
3045
3046     LayoutUnit logicalTopValue = 0;
3047
3048     bool logicalHeightIsAuto = logicalHeightLength.isAuto();
3049     bool logicalTopIsAuto = logicalTop.isAuto();
3050     bool logicalBottomIsAuto = logicalBottom.isAuto();
3051     RenderView* renderView = view();
3052
3053     // Height is never unsolved for tables.
3054     if (isTable()) {
3055         logicalHeightLength.setValue(Fixed, contentLogicalHeight);
3056         logicalHeightIsAuto = false;
3057     }
3058
3059     if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3060         /*-----------------------------------------------------------------------*\
3061          * If none of the three are 'auto': If both 'margin-top' and 'margin-
3062          * bottom' are 'auto', solve the equation under the extra constraint that
3063          * the two margins get equal values. If one of 'margin-top' or 'margin-
3064          * bottom' is 'auto', solve the equation for that value. If the values
3065          * are over-constrained, ignore the value for 'bottom' and solve for that
3066          * value.
3067         \*-----------------------------------------------------------------------*/
3068         // NOTE:  It is not necessary to solve for 'bottom' in the over constrained
3069         // case because the value is not used for any further calculations.
3070
3071         logicalHeightValue = computeContentBoxLogicalHeight(valueForLength(logicalHeightLength, containerLogicalHeight, renderView));
3072         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3073
3074         const LayoutUnit availableSpace = containerLogicalHeight - (logicalTopValue + logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight, renderView) + bordersPlusPadding);
3075
3076         // Margins are now the only unknown
3077         if (marginBefore.isAuto() && marginAfter.isAuto()) {
3078             // Both margins auto, solve for equality
3079             // NOTE: This may result in negative values.
3080             computedValues.m_margins.m_before = availableSpace / 2; // split the difference
3081             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before; // account for odd valued differences
3082         } else if (marginBefore.isAuto()) {
3083             // Solve for top margin
3084             computedValues.m_margins.m_after = valueForLength(marginAfter, containerLogicalHeight, renderView);
3085             computedValues.m_margins.m_before = availableSpace - computedValues.m_margins.m_after;
3086         } else if (marginAfter.isAuto()) {
3087             // Solve for bottom margin
3088             computedValues.m_margins.m_before = valueForLength(marginBefore, containerLogicalHeight, renderView);
3089             computedValues.m_margins.m_after = availableSpace - computedValues.m_margins.m_before;
3090         } else {
3091             // Over-constrained, (no need solve for bottom)
3092             computedValues.m_margins.m_before = valueForLength(marginBefore, containerLogicalHeight, renderView);
3093             computedValues.m_margins.m_after = valueForLength(marginAfter, containerLogicalHeight, renderView);
3094         }
3095     } else {
3096         /*--------------------------------------------------------------------*\
3097          * Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
3098          * to 0, and pick the one of the following six rules that applies.
3099          *
3100          * 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
3101          *    the height is based on the content, and solve for 'top'.
3102          *
3103          *              OMIT RULE 2 AS IT SHOULD NEVER BE HIT
3104          * ------------------------------------------------------------------
3105          * 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
3106          *    set 'top' to the static position, and solve for 'bottom'.
3107          * ------------------------------------------------------------------
3108          *
3109          * 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
3110          *    the height is based on the content, and solve for 'bottom'.
3111          * 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
3112          *    solve for 'top'.
3113          * 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
3114          *    solve for 'height'.
3115          * 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
3116          *    solve for 'bottom'.
3117         \*--------------------------------------------------------------------*/
3118         // NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
3119         // because the value is not used for any further calculations.
3120
3121         // Calculate margins, 'auto' margins are ignored.
3122         computedValues.m_margins.m_before = minimumValueForLength(marginBefore, containerLogicalHeight, renderView);
3123         computedValues.m_margins.m_after = minimumValueForLength(marginAfter, containerLogicalHeight, renderView);
3124
3125         const LayoutUnit availableSpace = containerLogicalHeight - (computedValues.m_margins.m_before + computedValues.m_margins.m_after + bordersPlusPadding);
3126
3127         // Use rule/case that applies.
3128         if (logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3129             // RULE 1: (height is content based, solve of top)
3130             logicalHeightValue = contentLogicalHeight;
3131             logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight, renderView));
3132         } else if (!logicalTopIsAuto && logicalHeightIsAuto && logicalBottomIsAuto) {
3133             // RULE 3: (height is content based, no need solve of bottom)
3134             logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3135             logicalHeightValue = contentLogicalHeight;
3136         } else if (logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
3137             // RULE 4: (solve of top)
3138             logicalHeightValue = computeContentBoxLogicalHeight(valueForLength(logicalHeightLength, containerLogicalHeight, renderView));
3139             logicalTopValue = availableSpace - (logicalHeightValue + valueForLength(logicalBottom, containerLogicalHeight, renderView));
3140         } else if (!logicalTopIsAuto && logicalHeightIsAuto && !logicalBottomIsAuto) {
3141             // RULE 5: (solve of height)
3142             logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3143             logicalHeightValue = max<LayoutUnit>(0, availableSpace - (logicalTopValue + valueForLength(logicalBottom, containerLogicalHeight, renderView)));
3144         } else if (!logicalTopIsAuto && !logicalHeightIsAuto && logicalBottomIsAuto) {
3145             // RULE 6: (no need solve of bottom)
3146             logicalHeightValue = computeContentBoxLogicalHeight(valueForLength(logicalHeightLength, containerLogicalHeight, renderView));
3147             logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3148         }
3149     }
3150     computedValues.m_extent = logicalHeightValue;
3151
3152     // Use computed values to calculate the vertical position.
3153     computedValues.m_position = logicalTopValue + computedValues.m_margins.m_before;
3154     computeLogicalTopPositionedOffset(computedValues.m_position, this, logicalHeightValue, containerBlock, containerLogicalHeight);
3155 }
3156
3157 void RenderBox::computePositionedLogicalWidthReplaced()
3158 {
3159     // The following is based off of the W3C Working Draft from April 11, 2006 of
3160     // CSS 2.1: Section 10.3.8 "Absolutely positioned, replaced elements"
3161     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-width>
3162     // (block-style-comments in this function correspond to text from the spec and
3163     // the numbers correspond to numbers in spec)
3164
3165     // We don't use containingBlock(), since we may be positioned by an enclosing
3166     // relative positioned inline.
3167     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3168
3169     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
3170
3171     // To match WinIE, in quirks mode use the parent's 'direction' property
3172     // instead of the the container block's.
3173     TextDirection containerDirection = containerBlock->style()->direction();
3174
3175     // Variables to solve.
3176     bool isHorizontal = isHorizontalWritingMode();
3177     Length logicalLeft = style()->logicalLeft();
3178     Length logicalRight = style()->logicalRight();
3179     Length marginLogicalLeft = isHorizontal ? style()->marginLeft() : style()->marginTop();
3180     Length marginLogicalRight = isHorizontal ? style()->marginRight() : style()->marginBottom();
3181     LayoutUnit& marginLogicalLeftAlias = m_marginBox.mutableLogicalLeft(style()->writingMode());
3182     LayoutUnit& marginLogicalRightAlias = m_marginBox.mutableLogicalRight(style()->writingMode());
3183
3184     /*-----------------------------------------------------------------------*\
3185      * 1. The used value of 'width' is determined as for inline replaced
3186      *    elements.
3187     \*-----------------------------------------------------------------------*/
3188     // NOTE: This value of width is FINAL in that the min/max width calculations
3189     // are dealt with in computeReplacedWidth().  This means that the steps to produce
3190     // correct max/min in the non-replaced version, are not necessary.
3191     setLogicalWidth(computeReplacedLogicalWidth() + borderAndPaddingLogicalWidth());
3192
3193     const LayoutUnit availableSpace = containerLogicalWidth - logicalWidth();
3194
3195     /*-----------------------------------------------------------------------*\
3196      * 2. If both 'left' and 'right' have the value 'auto', then if 'direction'
3197      *    of the containing block is 'ltr', set 'left' to the static position;
3198      *    else if 'direction' is 'rtl', set 'right' to the static position.
3199     \*-----------------------------------------------------------------------*/
3200     // see FIXME 1
3201     computeInlineStaticDistance(logicalLeft, logicalRight, this, containerBlock, containerLogicalWidth, 0); // FIXME: Pass the region.
3202
3203     /*-----------------------------------------------------------------------*\
3204      * 3. If 'left' or 'right' are 'auto', replace any 'auto' on 'margin-left'
3205      *    or 'margin-right' with '0'.
3206     \*-----------------------------------------------------------------------*/
3207     if (logicalLeft.isAuto() || logicalRight.isAuto()) {
3208         if (marginLogicalLeft.isAuto())
3209             marginLogicalLeft.setValue(Fixed, 0);
3210         if (marginLogicalRight.isAuto())
3211             marginLogicalRight.setValue(Fixed, 0);
3212     }
3213
3214     /*-----------------------------------------------------------------------*\
3215      * 4. If at this point both 'margin-left' and 'margin-right' are still
3216      *    'auto', solve the equation under the extra constraint that the two
3217      *    margins must get equal values, unless this would make them negative,
3218      *    in which case when the direction of the containing block is 'ltr'
3219      *    ('rtl'), set 'margin-left' ('margin-right') to zero and solve for
3220      *    'margin-right' ('margin-left').
3221     \*-----------------------------------------------------------------------*/
3222     LayoutUnit logicalLeftValue = 0;
3223     LayoutUnit logicalRightValue = 0;
3224     RenderView* renderView = view();
3225
3226     if (marginLogicalLeft.isAuto() && marginLogicalRight.isAuto()) {
3227         // 'left' and 'right' cannot be 'auto' due to step 3
3228         ASSERT(!(logicalLeft.isAuto() && logicalRight.isAuto()));
3229
3230         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
3231         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
3232
3233         LayoutUnit difference = availableSpace - (logicalLeftValue + logicalRightValue);
3234         if (difference > 0) {
3235             marginLogicalLeftAlias = difference / 2; // split the difference
3236             marginLogicalRightAlias = difference - marginLogicalLeftAlias; // account for odd valued differences
3237         } else {
3238             // Use the containing block's direction rather than the parent block's
3239             // per CSS 2.1 reference test abspos-replaced-width-margin-000.
3240             if (containerDirection == LTR) {
3241                 marginLogicalLeftAlias = 0;
3242                 marginLogicalRightAlias = difference; // will be negative
3243             } else {
3244                 marginLogicalLeftAlias = difference; // will be negative
3245                 marginLogicalRightAlias = 0;
3246             }
3247         }
3248
3249     /*-----------------------------------------------------------------------*\
3250      * 5. If at this point there is an 'auto' left, solve the equation for
3251      *    that value.
3252     \*-----------------------------------------------------------------------*/
3253     } else if (logicalLeft.isAuto()) {
3254         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerLogicalWidth, renderView);
3255         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerLogicalWidth, renderView);
3256         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
3257
3258         // Solve for 'left'
3259         logicalLeftValue = availableSpace - (logicalRightValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3260     } else if (logicalRight.isAuto()) {
3261         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerLogicalWidth, renderView);
3262         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerLogicalWidth, renderView);
3263         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
3264
3265         // Solve for 'right'
3266         logicalRightValue = availableSpace - (logicalLeftValue + marginLogicalLeftAlias + marginLogicalRightAlias);
3267     } else if (marginLogicalLeft.isAuto()) {
3268         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerLogicalWidth, renderView);
3269         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
3270         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
3271
3272         // Solve for 'margin-left'
3273         marginLogicalLeftAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalRightAlias);
3274     } else if (marginLogicalRight.isAuto()) {
3275         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerLogicalWidth, renderView);
3276         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
3277         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
3278
3279         // Solve for 'margin-right'
3280         marginLogicalRightAlias = availableSpace - (logicalLeftValue + logicalRightValue + marginLogicalLeftAlias);
3281     } else {
3282         // Nothing is 'auto', just calculate the values.
3283         marginLogicalLeftAlias = valueForLength(marginLogicalLeft, containerLogicalWidth, renderView);
3284         marginLogicalRightAlias = valueForLength(marginLogicalRight, containerLogicalWidth, renderView);
3285         logicalRightValue = valueForLength(logicalRight, containerLogicalWidth, renderView);
3286         logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
3287         // If the containing block is right-to-left, then push the left position as far to the right as possible
3288         if (containerDirection == RTL) {
3289             int totalLogicalWidth = logicalWidth() + logicalLeftValue + logicalRightValue +  marginLogicalLeftAlias + marginLogicalRightAlias;
3290             logicalLeftValue = containerLogicalWidth - (totalLogicalWidth - logicalLeftValue);
3291         }
3292     }
3293
3294     /*-----------------------------------------------------------------------*\
3295      * 6. If at this point the values are over-constrained, ignore the value
3296      *    for either 'left' (in case the 'direction' property of the
3297      *    containing block is 'rtl') or 'right' (in case 'direction' is
3298      *    'ltr') and solve for that value.
3299     \*-----------------------------------------------------------------------*/
3300     // NOTE: Constraints imposed by the width of the containing block and its content have already been accounted for above.
3301
3302     // FIXME: Deal with differing writing modes here.  Our offset needs to be in the containing block's coordinate space, so that
3303     // can make the result here rather complicated to compute.
3304
3305     // Use computed values to calculate the horizontal position.
3306
3307     // FIXME: This hack is needed to calculate the logical left position for a 'rtl' relatively
3308     // positioned, inline containing block because right now, it is using the logical left position
3309     // of the first line box when really it should use the last line box.  When
3310     // this is fixed elsewhere, this block should be removed.
3311     if (containerBlock->isRenderInline() && !containerBlock->style()->isLeftToRightDirection()) {
3312         const RenderInline* flow = toRenderInline(containerBlock);
3313         InlineFlowBox* firstLine = flow->firstLineBox();
3314         InlineFlowBox* lastLine = flow->lastLineBox();
3315         if (firstLine && lastLine && firstLine != lastLine) {
3316             setLogicalLeft(logicalLeftValue + marginLogicalLeftAlias + lastLine->borderLogicalLeft() + (lastLine->logicalLeft() - firstLine->logicalLeft()));
3317             return;
3318         }
3319     }
3320
3321     LayoutUnit logicalLeftPos = logicalLeftValue + marginLogicalLeftAlias;
3322     computeLogicalLeftPositionedOffset(logicalLeftPos, this, logicalWidth(), containerBlock, containerLogicalWidth);
3323     setLogicalLeft(logicalLeftPos.round());
3324 }
3325
3326 void RenderBox::computePositionedLogicalHeightReplaced(LogicalExtentComputedValues& computedValues) const
3327 {
3328     // The following is based off of the W3C Working Draft from April 11, 2006 of
3329     // CSS 2.1: Section 10.6.5 "Absolutely positioned, replaced elements"
3330     // <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-replaced-height>
3331     // (block-style-comments in this function correspond to text from the spec and
3332     // the numbers correspond to numbers in spec)
3333
3334     // We don't use containingBlock(), since we may be positioned by an enclosing relpositioned inline.
3335     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
3336
3337     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
3338
3339     // Variables to solve.
3340     Length marginBefore = style()->marginBefore();
3341     Length marginAfter = style()->marginAfter();
3342     LayoutUnit& marginBeforeAlias = computedValues.m_margins.m_before;
3343     LayoutUnit& marginAfterAlias = computedValues.m_margins.m_after;
3344
3345     Length logicalTop = style()->logicalTop();
3346     Length logicalBottom = style()->logicalBottom();
3347     RenderView* renderView = view();
3348
3349     /*-----------------------------------------------------------------------*\
3350      * 1. The used value of 'height' is determined as for inline replaced
3351      *    elements.
3352     \*-----------------------------------------------------------------------*/
3353     // NOTE: This value of height is FINAL in that the min/max height calculations
3354     // are dealt with in computeReplacedHeight().  This means that the steps to produce
3355     // correct max/min in the non-replaced version, are not necessary.
3356     computedValues.m_extent = computeReplacedLogicalHeight() + borderAndPaddingLogicalHeight();
3357     const LayoutUnit availableSpace = containerLogicalHeight - computedValues.m_extent;
3358
3359     /*-----------------------------------------------------------------------*\
3360      * 2. If both 'top' and 'bottom' have the value 'auto', replace 'top'
3361      *    with the element's static position.
3362     \*-----------------------------------------------------------------------*/
3363     // see FIXME 1
3364     computeBlockStaticDistance(logicalTop, logicalBottom, this, containerBlock);
3365
3366     /*-----------------------------------------------------------------------*\
3367      * 3. If 'bottom' is 'auto', replace any 'auto' on 'margin-top' or
3368      *    'margin-bottom' with '0'.
3369     \*-----------------------------------------------------------------------*/
3370     // FIXME: The spec. says that this step should only be taken when bottom is
3371     // auto, but if only top is auto, this makes step 4 impossible.
3372     if (logicalTop.isAuto() || logicalBottom.isAuto()) {
3373         if (marginBefore.isAuto())
3374             marginBefore.setValue(Fixed, 0);
3375         if (marginAfter.isAuto())
3376             marginAfter.setValue(Fixed, 0);
3377     }
3378
3379     /*-----------------------------------------------------------------------*\
3380      * 4. If at this point both 'margin-top' and 'margin-bottom' are still
3381      *    'auto', solve the equation under the extra constraint that the two
3382      *    margins must get equal values.
3383     \*-----------------------------------------------------------------------*/
3384     LayoutUnit logicalTopValue = 0;
3385     LayoutUnit logicalBottomValue = 0;
3386
3387     if (marginBefore.isAuto() && marginAfter.isAuto()) {
3388         // 'top' and 'bottom' cannot be 'auto' due to step 2 and 3 combined.
3389         ASSERT(!(logicalTop.isAuto() || logicalBottom.isAuto()));
3390
3391         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3392         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
3393
3394         LayoutUnit difference = availableSpace - (logicalTopValue + logicalBottomValue);
3395         // NOTE: This may result in negative values.
3396         marginBeforeAlias =  difference / 2; // split the difference
3397         marginAfterAlias = difference - marginBeforeAlias; // account for odd valued differences
3398
3399     /*-----------------------------------------------------------------------*\
3400      * 5. If at this point there is only one 'auto' left, solve the equation
3401      *    for that value.
3402     \*-----------------------------------------------------------------------*/
3403     } else if (logicalTop.isAuto()) {
3404         marginBeforeAlias = valueForLength(marginBefore, containerLogicalHeight, renderView);
3405         marginAfterAlias = valueForLength(marginAfter, containerLogicalHeight, renderView);
3406         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
3407
3408         // Solve for 'top'
3409         logicalTopValue = availableSpace - (logicalBottomValue + marginBeforeAlias + marginAfterAlias);
3410     } else if (logicalBottom.isAuto()) {
3411         marginBeforeAlias = valueForLength(marginBefore, containerLogicalHeight, renderView);
3412         marginAfterAlias = valueForLength(marginAfter, containerLogicalHeight, renderView);
3413         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3414
3415         // Solve for 'bottom'
3416         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3417         // use the value.
3418     } else if (marginBefore.isAuto()) {
3419         marginAfterAlias = valueForLength(marginAfter, containerLogicalHeight, renderView);
3420         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3421         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
3422
3423         // Solve for 'margin-top'
3424         marginBeforeAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginAfterAlias);
3425     } else if (marginAfter.isAuto()) {
3426         marginBeforeAlias = valueForLength(marginBefore, containerLogicalHeight, renderView);
3427         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3428         logicalBottomValue = valueForLength(logicalBottom, containerLogicalHeight, renderView);
3429
3430         // Solve for 'margin-bottom'
3431         marginAfterAlias = availableSpace - (logicalTopValue + logicalBottomValue + marginBeforeAlias);
3432     } else {
3433         // Nothing is 'auto', just calculate the values.
3434         marginBeforeAlias = valueForLength(marginBefore, containerLogicalHeight, renderView);
3435         marginAfterAlias = valueForLength(marginAfter, containerLogicalHeight, renderView);
3436         logicalTopValue = valueForLength(logicalTop, containerLogicalHeight, renderView);
3437         // NOTE: It is not necessary to solve for 'bottom' because we don't ever
3438         // use the value.
3439      }
3440
3441     /*-----------------------------------------------------------------------*\
3442      * 6. If at this point the values are over-constrained, ignore the value
3443      *    for 'bottom' and solve for that value.
3444     \*-----------------------------------------------------------------------*/
3445     // NOTE: It is not necessary to do this step because we don't end up using
3446     // the value of 'bottom' regardless of whether the values are over-constrained
3447     // or not.
3448
3449     // Use computed values to calculate the vertical position.
3450     LayoutUnit logicalTopPos = logicalTopValue + marginBeforeAlias;
3451     computeLogicalTopPositionedOffset(logicalTopPos, this, computedValues.m_extent, containerBlock, containerLogicalHeight);
3452     computedValues.m_position = logicalTopPos.round();
3453 }
3454
3455 LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
3456 {
3457     // VisiblePositions at offsets inside containers either a) refer to the positions before/after
3458     // those containers (tables and select elements) or b) refer to the position inside an empty block.
3459     // They never refer to children.
3460     // FIXME: Paint the carets inside empty blocks differently than the carets before/after elements.
3461
3462     // FIXME: What about border and padding?
3463     LayoutRect rect(location(), LayoutSize(caretWidth, height()));
3464     bool ltr = box ? box->isLeftToRightDirection() : style()->isLeftToRightDirection();
3465
3466     if ((!caretOffset) ^ ltr)
3467         rect.move(LayoutSize(width() - caretWidth, 0));
3468
3469     if (box) {
3470         RootInlineBox* rootBox = box->root();
3471         LayoutUnit top = rootBox->lineTop();
3472         rect.setY(top);
3473         rect.setHeight(rootBox->lineBottom() - top);
3474     }
3475
3476     // If height of box is smaller than font height, use the latter one,
3477     // otherwise the caret might become invisible.
3478     //
3479     // Also, if the box is not a replaced element, always use the font height.
3480     // This prevents the "big caret" bug described in:
3481     // <rdar://problem/3777804> Deleting all content in a document can result in giant tall-as-window insertion point
3482     //
3483     // FIXME: ignoring :first-line, missing good reason to take care of
3484     LayoutUnit fontHeight = style()->fontMetrics().height();
3485     if (fontHeight > rect.height() || (!isReplaced() && !isTable()))
3486         rect.setHeight(fontHeight);
3487
3488     if (extraWidthToEndOfLine)
3489         *extraWidthToEndOfLine = x() + width() - rect.maxX();
3490
3491     // Move to local coords
3492     rect.moveBy(-location());
3493     return rect;
3494 }
3495
3496 VisiblePosition RenderBox::positionForPoint(const LayoutPoint& point)
3497 {
3498     // no children...return this render object's element, if there is one, and offset 0
3499     if (!firstChild())
3500         return createVisiblePosition(node() ? firstPositionInOrBeforeNode(node()) : Position());
3501
3502     if (isTable() && node()) {
3503         LayoutUnit right = contentWidth() + borderAndPaddingWidth();
3504         LayoutUnit bottom = contentHeight() + borderAndPaddingHeight();
3505         
3506         if (point.x() < 0 || point.x() > right || point.y() < 0 || point.y() > bottom) {
3507             if (point.x() <= right / 2)
3508                 return createVisiblePosition(firstPositionInOrBeforeNode(node()));
3509             return createVisiblePosition(lastPositionInOrAfterNode(node()));
3510         }
3511     }
3512
3513     // Pass off to the closest child.
3514     LayoutUnit minDist = MAX_LAYOUT_UNIT;
3515     RenderBox* closestRenderer = 0;
3516     LayoutPoint adjustedPoint = point;
3517     if (isTableRow())
3518         adjustedPoint.moveBy(location());
3519
3520     for (RenderObject* renderObject = firstChild(); renderObject; renderObject = renderObject->nextSibling()) {
3521         if ((!renderObject->firstChild() && !renderObject->isInline() && !renderObject->isBlockFlow() )
3522             || renderObject->style()->visibility() != VISIBLE)
3523             continue;
3524         
3525         if (!renderObject->isBox())
3526             continue;
3527         
3528         RenderBox* renderer = toRenderBox(renderObject);
3529
3530         LayoutUnit top = renderer->borderTop() + renderer->paddingTop() + (isTableRow() ? ZERO_LAYOUT_UNIT : renderer->y());
3531         LayoutUnit bottom = top + renderer->contentHeight();
3532         LayoutUnit left = renderer->borderLeft() + renderer->paddingLeft() + (isTableRow() ? ZERO_LAYOUT_UNIT : renderer->x());
3533         LayoutUnit right = left + renderer->contentWidth();
3534         
3535         if (point.x() <= right && point.x() >= left && point.y() <= top && point.y() >= bottom) {
3536             if (renderer->isTableRow())
3537                 return renderer->positionForPoint(point + adjustedPoint - renderer->locationOffset());
3538             return renderer->positionForPoint(point - renderer->locationOffset());
3539         }
3540
3541         // Find the distance from (x, y) to the box.  Split the space around the box into 8 pieces
3542         // and use a different compare depending on which piece (x, y) is in.
3543         LayoutPoint cmp;
3544         if (point.x() > right) {
3545             if (point.y() < top)
3546                 cmp = LayoutPoint(right, top);
3547             else if (point.y() > bottom)
3548                 cmp = LayoutPoint(right, bottom);
3549             else
3550                 cmp = LayoutPoint(right, point.y());
3551         } else if (point.x() < left) {
3552             if (point.y() < top)
3553                 cmp = LayoutPoint(left, top);
3554             else if (point.y() > bottom)
3555                 cmp = LayoutPoint(left, bottom);
3556             else
3557                 cmp = LayoutPoint(left, point.y());
3558         } else {
3559             if (point.y() < top)
3560                 cmp = LayoutPoint(point.x(), top);
3561             else
3562                 cmp = LayoutPoint(point.x(), bottom);
3563         }
3564
3565         LayoutSize difference = cmp - point;
3566
3567         LayoutUnit dist = difference.width() * difference.width() + difference.height() * difference.height();
3568         if (dist < minDist) {
3569             closestRenderer = renderer;
3570             minDist = dist;
3571         }
3572     }
3573     
3574     if (closestRenderer)
3575         return closestRenderer->positionForPoint(adjustedPoint - closestRenderer->locationOffset());
3576     
3577     return createVisiblePosition(firstPositionInOrBeforeNode(node()));
3578 }
3579
3580 bool RenderBox::shrinkToAvoidFloats() const
3581 {
3582     // Floating objects don't shrink.  Objects that don't avoid floats don't shrink.  Marquees don't shrink.
3583     if ((isInline() && !isHTMLMarquee()) || !avoidsFloats() || isFloating())
3584         return false;
3585     
3586     // Only auto width objects can possibly shrink to avoid floats.
3587     return style()->width().isAuto();
3588 }
3589
3590 bool RenderBox::avoidsFloats() const
3591 {
3592     return isReplaced() || hasOverflowClip() || isHR() || isLegend() || isWritingModeRoot() || isDeprecatedFlexItem();
3593 }
3594
3595 void RenderBox::addVisualEffectOverflow()
3596 {
3597     if (!style()->boxShadow() && !style()->hasBorderImageOutsets())
3598         return;
3599
3600     bool isFlipped = style()->isFlippedBlocksWritingMode();
3601     bool isHorizontal = isHorizontalWritingMode();
3602     
3603     LayoutRect borderBox = borderBoxRect();
3604     LayoutUnit overflowMinX = borderBox.x();
3605     LayoutUnit overflowMaxX = borderBox.maxX();
3606     LayoutUnit overflowMinY = borderBox.y();
3607     LayoutUnit overflowMaxY = borderBox.maxY();
3608     
3609     // Compute box-shadow overflow first.
3610     if (style()->boxShadow()) {
3611         LayoutUnit shadowLeft;
3612         LayoutUnit shadowRight;
3613         LayoutUnit shadowTop;
3614         LayoutUnit shadowBottom;
3615         style()->getBoxShadowExtent(shadowTop, shadowRight, shadowBottom, shadowLeft);
3616
3617         // In flipped blocks writing modes such as vertical-rl, the physical right shadow value is actually at the lower x-coordinate.
3618         overflowMinX = borderBox.x() + ((!isFlipped || isHorizontal) ? shadowLeft : -shadowRight);
3619         overflowMaxX = borderBox.maxX() + ((!isFlipped || isHorizontal) ? shadowRight : -shadowLeft);
3620         overflowMinY = borderBox.y() + ((!isFlipped || !isHorizontal) ? shadowTop : -shadowBottom);
3621         overflowMaxY = borderBox.maxY() + ((!isFlipped || !isHorizontal) ? shadowBottom : -shadowTop);
3622     }
3623
3624     // Now compute border-image-outset overflow.
3625     if (style()->hasBorderImageOutsets()) {
3626         LayoutBoxExtent borderOutsets = style()->borderImageOutsets();
3627         
3628         // In flipped blocks writing modes, the physical sides are inverted. For example in vertical-rl, the right
3629         // border is at the lower x coordinate value.
3630         overflowMinX = min(overflowMinX, borderBox.x() - ((!isFlipped || isHorizontal) ? borderOutsets.left() : borderOutsets.right()));
3631         overflowMaxX = max(overflowMaxX, borderBox.maxX() + ((!isFlipped || isHorizontal) ? borderOutsets.right() : borderOutsets.left()));
3632         overflowMinY = min(overflowMinY, borderBox.y() - ((!isFlipped || !isHorizontal) ? borderOutsets.top() : borderOutsets.bottom()));
3633         overflowMaxY = max(overflowMaxY, borderBox.maxY() + ((!isFlipped || !isHorizontal) ? borderOutsets.bottom() : borderOutsets.top()));
3634     }
3635
3636     // Add in the final overflow with shadows and outsets combined.
3637     addVisualOverflow(LayoutRect(overflowMinX, overflowMinY, overflowMaxX - overflowMinX, overflowMaxY - overflowMinY));
3638 }
3639
3640 void RenderBox::addOverflowFromChild(RenderBox* child, const LayoutSize& delta)
3641 {
3642     // Only propagate layout overflow from the child if the child isn't clipping its overflow.  If it is, then
3643     // its overflow is internal to it, and we don't care about it.  layoutOverflowRectForPropagation takes care of this
3644     // and just propagates the border box rect instead.
3645     LayoutRect childLayoutOverflowRect = child->layoutOverflowRectForPropagation(style());
3646     childLayoutOverflowRect.move(delta);
3647     addLayoutOverflow(childLayoutOverflowRect);
3648             
3649     // Add in visual overflow from the child.  Even if the child clips its overflow, it may still
3650     // have visual overflow of its own set from box shadows or reflections.  It is unnecessary to propagate this
3651     // overflow if we are clipping our own overflow.
3652     if (child->hasSelfPaintingLayer() || hasOverflowClip())
3653         return;
3654     LayoutRect childVisualOverflowRect = child->visualOverflowRectForPropagation(style());
3655     childVisualOverflowRect.move(delta);
3656     addVisualOverflow(childVisualOverflowRect);
3657 }
3658
3659 void RenderBox::addLayoutOverflow(const LayoutRect& rect)
3660 {
3661     LayoutRect clientBox = clientBoxRect();
3662     if (clientBox.contains(rect) || rect.isEmpty())
3663         return;
3664     
3665     // For overflow clip objects, we don't want to propagate overflow into unreachable areas.
3666     LayoutRect overflowRect(rect);
3667     if (hasOverflowClip() || isRenderView()) {
3668         // Overflow is in the block's coordinate space and thus is flipped for horizontal-bt and vertical-rl 
3669         // writing modes.  At this stage that is actually a simplification, since we can treat horizontal-tb/bt as the same
3670         // and vertical-lr/rl as the same.
3671         bool hasTopOverflow = !style()->isLeftToRightDirection() && !isHorizontalWritingMode();
3672         bool hasLeftOverflow = !style()->isLeftToRightDirection() && isHorizontalWritingMode();
3673         if (isFlexibleBox() && style()->isReverseFlexDirection()) {
3674             RenderFlexibleBox* flexibleBox = static_cast<RenderFlexibleBox*>(this);
3675             if (flexibleBox->isHorizontalFlow())
3676                 hasLeftOverflow = true;
3677             else
3678                 hasTopOverflow = true;
3679         }
3680
3681         if (hasColumns() && style()->columnProgression() == ReverseColumnProgression) {
3682             if (isHorizontalWritingMode() ^ !style()->hasInlineColumnAxis())
3683                 hasLeftOverflow = !hasLeftOverflow;
3684             else
3685                 hasTopOverflow = !hasTopOverflow;
3686         }
3687
3688         if (!hasTopOverflow)
3689             overflowRect.shiftYEdgeTo(max(overflowRect.y(), clientBox.y()));
3690         else
3691             overflowRect.shiftMaxYEdgeTo(min(overflowRect.maxY(), clientBox.maxY()));
3692         if (!hasLeftOverflow)
3693             overflowRect.shiftXEdgeTo(max(overflowRect.x(), clientBox.x()));
3694         else
3695             overflowRect.shiftMaxXEdgeTo(min(overflowRect.maxX(), clientBox.maxX()));
3696