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