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