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