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