3b092bb17ec2fdef415046508dde89275214e39b
[WebKit-https.git] / Source / WebCore / rendering / RenderBlock.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2007 David Smith (catfish.man@gmail.com)
5  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6  * Copyright (C) Research In Motion Limited 2010. 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 #include "config.h"
25 #include "RenderBlock.h"
26
27 #include "AXObjectCache.h"
28 #include "ColumnInfo.h"
29 #include "Document.h"
30 #include "Editor.h"
31 #include "Element.h"
32 #include "FloatQuad.h"
33 #include "Frame.h"
34 #include "FrameSelection.h"
35 #include "FrameView.h"
36 #include "GraphicsContext.h"
37 #include "HTMLFormElement.h"
38 #include "HTMLNames.h"
39 #include "HitTestLocation.h"
40 #include "HitTestResult.h"
41 #include "InlineIterator.h"
42 #include "InlineTextBox.h"
43 #include "LayoutRepainter.h"
44 #include "OverflowEvent.h"
45 #include "PODFreeListArena.h"
46 #include "Page.h"
47 #include "PaintInfo.h"
48 #include "RenderBoxRegionInfo.h"
49 #include "RenderCombineText.h"
50 #include "RenderDeprecatedFlexibleBox.h"
51 #include "RenderFlexibleBox.h"
52 #include "RenderImage.h"
53 #include "RenderInline.h"
54 #include "RenderLayer.h"
55 #include "RenderMarquee.h"
56 #include "RenderNamedFlowThread.h"
57 #include "RenderRegion.h"
58 #include "RenderReplica.h"
59 #include "RenderTableCell.h"
60 #include "RenderTextFragment.h"
61 #include "RenderTheme.h"
62 #include "RenderView.h"
63 #include "SVGTextRunRenderingContext.h"
64 #include "Settings.h"
65 #include "ShadowRoot.h"
66 #include "TransformState.h"
67 #include <wtf/StdLibExtras.h>
68 #if ENABLE(CSS_EXCLUSIONS)
69 #include "ExclusionShapeInsideInfo.h"
70 #include "ExclusionShapeOutsideInfo.h"
71 #endif
72 #include <wtf/StackStats.h>
73 #include <wtf/TemporaryChange.h>
74
75 using namespace std;
76 using namespace WTF;
77 using namespace Unicode;
78
79 namespace WebCore {
80
81 using namespace HTMLNames;
82
83 struct SameSizeAsRenderBlock : public RenderBox {
84     void* pointers[2];
85     RenderObjectChildList children;
86     RenderLineBoxList lineBoxes;
87     uint32_t bitfields;
88 };
89
90 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
91
92 struct SameSizeAsFloatingObject {
93     void* pointers[2];
94     LayoutRect rect;
95     int paginationStrut;
96     uint32_t bitfields : 8;
97 };
98
99 COMPILE_ASSERT(sizeof(RenderBlock::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
100
101 struct SameSizeAsMarginInfo {
102     uint32_t bitfields : 16;
103     LayoutUnit margins[2];
104 };
105
106 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
107 static ColumnInfoMap* gColumnInfoMap = 0;
108
109 static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
110 static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
111
112 static TrackedContainerMap* gPositionedContainerMap = 0;
113 static TrackedContainerMap* gPercentHeightContainerMap = 0;
114     
115 typedef WTF::HashMap<RenderBlock*, OwnPtr<ListHashSet<RenderInline*> > > ContinuationOutlineTableMap;
116
117 typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
118 static int gDelayUpdateScrollInfo = 0;
119 static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
120
121 static bool gColumnFlowSplitEnabled = true;
122
123 bool RenderBlock::s_canPropagateFloatIntoSibling = false;
124
125 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
126 // only works on RenderBlocks. If this change, this class should be shared with other RenderBoxes.
127 class OverflowEventDispatcher {
128     WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
129 public:
130     OverflowEventDispatcher(const RenderBlock* block)
131         : m_block(block)
132         , m_hadHorizontalLayoutOverflow(false)
133         , m_hadVerticalLayoutOverflow(false)
134     {
135         m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document()->hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
136         if (m_shouldDispatchEvent) {
137             m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
138             m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
139         }
140     }
141
142     ~OverflowEventDispatcher()
143     {
144         if (!m_shouldDispatchEvent)
145             return;
146
147         bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
148         bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
149
150         bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
151         bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
152         if (horizontalLayoutOverflowChanged || verticalLayoutOverflowChanged) {
153             if (FrameView* frameView = m_block->document()->view())
154                 frameView->scheduleEvent(OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow), m_block->node());
155         }
156     }
157
158 private:
159     const RenderBlock* m_block;
160     bool m_shouldDispatchEvent;
161     bool m_hadHorizontalLayoutOverflow;
162     bool m_hadVerticalLayoutOverflow;
163 };
164
165 // Our MarginInfo state used when laying out block children.
166 RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
167     : m_atBeforeSideOfBlock(true)
168     , m_atAfterSideOfBlock(false)
169     , m_hasMarginBeforeQuirk(false)
170     , m_hasMarginAfterQuirk(false)
171     , m_determinedMarginBeforeQuirk(false)
172     , m_discardMargin(false)
173 {
174     RenderStyle* blockStyle = block->style();
175     ASSERT(block->isRenderView() || block->parent());
176     m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isOutOfFlowPositioned()
177         && !block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable()
178         && !block->isRenderFlowThread() && !block->isWritingModeRoot() && !block->parent()->isFlexibleBox()
179         && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth() && !blockStyle->columnSpan();
180
181     m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
182
183     // If any height other than auto is specified in CSS, then we don't collapse our bottom
184     // margins with our children's margins.  To do otherwise would be to risk odd visual
185     // effects when the children overflow out of the parent block and yet still collapse
186     // with it.  We also don't collapse if we have any bottom border/padding.
187     m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && (afterBorderPadding == 0) &&
188         (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
189     
190     m_quirkContainer = block->isTableCell() || block->isBody();
191
192     m_discardMargin = m_canCollapseMarginBeforeWithChildren && block->mustDiscardMarginBefore();
193
194     m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxPositiveMarginBefore() : LayoutUnit();
195     m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxNegativeMarginBefore() : LayoutUnit();
196 }
197
198 // -------------------------------------------------------------------------------------------------------
199
200 RenderBlock::RenderBlock(ContainerNode* node)
201     : RenderBox(node)
202     , m_lineHeight(-1)
203     , m_hasMarginBeforeQuirk(false)
204     , m_hasMarginAfterQuirk(false)
205     , m_beingDestroyed(false)
206     , m_hasMarkupTruncation(false)
207     , m_hasBorderOrPaddingLogicalWidthChanged(false)
208 {
209     setChildrenInline(true);
210     COMPILE_ASSERT(sizeof(RenderBlock::FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
211     COMPILE_ASSERT(sizeof(RenderBlock::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
212 }
213
214 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
215 {
216     if (OwnPtr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
217         TrackedRendererListHashSet::iterator end = descendantSet->end();
218         for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
219             TrackedContainerMap::iterator it = containerMap->find(*descendant);
220             ASSERT(it != containerMap->end());
221             if (it == containerMap->end())
222                 continue;
223             HashSet<RenderBlock*>* containerSet = it->value.get();
224             ASSERT(containerSet->contains(block));
225             containerSet->remove(block);
226             if (containerSet->isEmpty())
227                 containerMap->remove(it);
228         }
229     }
230 }
231
232 RenderBlock::~RenderBlock()
233 {
234     if (m_floatingObjects)
235         deleteAllValues(m_floatingObjects->set());
236     
237     if (hasColumns())
238         gColumnInfoMap->take(this);
239
240     if (gPercentHeightDescendantsMap)
241         removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
242     if (gPositionedDescendantsMap)
243         removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
244 }
245
246 RenderBlock* RenderBlock::createAnonymous(Document* document)
247 {
248     RenderBlock* renderer = new (document->renderArena()) RenderBlock(0);
249     renderer->setDocumentForAnonymous(document);
250     return renderer;
251 }
252
253 void RenderBlock::willBeDestroyed()
254 {
255     // Mark as being destroyed to avoid trouble with merges in removeChild().
256     m_beingDestroyed = true;
257
258     // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
259     // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
260     children()->destroyLeftoverChildren();
261
262     // Destroy our continuation before anything other than anonymous children.
263     // The reason we don't destroy it before anonymous children is that they may
264     // have continuations of their own that are anonymous children of our continuation.
265     RenderBoxModelObject* continuation = this->continuation();
266     if (continuation) {
267         continuation->destroy();
268         setContinuation(0);
269     }
270     
271     if (!documentBeingDestroyed()) {
272         if (firstLineBox()) {
273             // We can't wait for RenderBox::destroy to clear the selection,
274             // because by then we will have nuked the line boxes.
275             // FIXME: The FrameSelection should be responsible for this when it
276             // is notified of DOM mutations.
277             if (isSelectionBorder())
278                 view()->clearSelection();
279
280             // If we are an anonymous block, then our line boxes might have children
281             // that will outlast this block. In the non-anonymous block case those
282             // children will be destroyed by the time we return from this function.
283             if (isAnonymousBlock()) {
284                 for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
285                     while (InlineBox* childBox = box->firstChild())
286                         childBox->remove();
287                 }
288             }
289         } else if (parent())
290             parent()->dirtyLinesFromChangedChild(this);
291     }
292
293     m_lineBoxes.deleteLineBoxes(renderArena());
294
295     if (lineGridBox())
296         lineGridBox()->destroy(renderArena());
297
298     if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
299         gDelayedUpdateScrollInfoSet->remove(this);
300
301     RenderBox::willBeDestroyed();
302 }
303
304 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
305 {
306     RenderStyle* oldStyle = style();
307     s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
308
309     setReplaced(newStyle->isDisplayInlineType());
310     
311     if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()) {
312         if (newStyle->position() == StaticPosition)
313             // Clear our positioned objects list. Our absolutely positioned descendants will be
314             // inserted into our containing block's positioned objects list during layout.
315             removePositionedObjects(0, NewContainingBlock);
316         else if (oldStyle->position() == StaticPosition) {
317             // Remove our absolutely positioned descendants from their current containing block.
318             // They will be inserted into our positioned objects list during layout.
319             RenderObject* cb = parent();
320             while (cb && (cb->style()->position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
321                 if (cb->style()->position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
322                     cb = cb->containingBlock();
323                     break;
324                 }
325                 cb = cb->parent();
326             }
327             
328             if (cb->isRenderBlock())
329                 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
330         }
331
332         if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
333             markAllDescendantsWithFloatsForLayout();
334     }
335
336     RenderBox::styleWillChange(diff, newStyle);
337 }
338
339 static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
340 {
341     if (newStyle->isHorizontalWritingMode())
342         return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
343             || oldStyle->borderRightWidth() != newStyle->borderRightWidth()
344             || oldStyle->paddingLeft() != newStyle->paddingLeft()
345             || oldStyle->paddingRight() != newStyle->paddingRight();
346
347     return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
348         || oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
349         || oldStyle->paddingTop() != newStyle->paddingTop()
350         || oldStyle->paddingBottom() != newStyle->paddingBottom();
351 }
352
353 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
354 {
355     RenderBox::styleDidChange(diff, oldStyle);
356     
357     RenderStyle* newStyle = style();
358     
359 #if ENABLE(CSS_EXCLUSIONS)
360     // FIXME: Bug 89993: Style changes should affect the ExclusionShapeInsideInfos for other render blocks that
361     // share the same ExclusionShapeInsideInfo
362     updateExclusionShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : 0);
363 #endif
364
365     if (!isAnonymousBlock()) {
366         // Ensure that all of our continuation blocks pick up the new style.
367         for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
368             RenderBoxModelObject* nextCont = currCont->continuation();
369             currCont->setContinuation(0);
370             currCont->setStyle(newStyle);
371             currCont->setContinuation(nextCont);
372         }
373     }
374
375     propagateStyleToAnonymousChildren(true);    
376     m_lineHeight = -1;
377
378     // After our style changed, if we lose our ability to propagate floats into next sibling
379     // blocks, then we need to find the top most parent containing that overhanging float and
380     // then mark its descendants with floats for layout and clear all floats from its next
381     // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
382     bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
383     if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
384         RenderBlock* parentBlock = this;
385         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
386         FloatingObjectSetIterator end = floatingObjectSet.end();
387
388         for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
389             if (curr->isRenderBlock()) {
390                 RenderBlock* currBlock = toRenderBlock(curr);
391
392                 if (currBlock->hasOverhangingFloats()) {
393                     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
394                         RenderBox* renderer = (*it)->renderer();
395                         if (currBlock->hasOverhangingFloat(renderer)) {
396                             parentBlock = currBlock;
397                             break;
398                         }
399                     }
400                 }
401             }
402         }
403               
404         parentBlock->markAllDescendantsWithFloatsForLayout();
405         parentBlock->markSiblingsWithFloatsForLayout();
406     }
407     
408     // It's possible for our border/padding to change, but for the overall logical width of the block to
409     // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
410     m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
411 }
412
413 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
414 {
415     if (beforeChild && beforeChild->parent() == this)
416         return this;
417
418     RenderBlock* curr = toRenderBlock(continuation());
419     RenderBlock* nextToLast = this;
420     RenderBlock* last = this;
421     while (curr) {
422         if (beforeChild && beforeChild->parent() == curr) {
423             if (curr->firstChild() == beforeChild)
424                 return last;
425             return curr;
426         }
427
428         nextToLast = last;
429         last = curr;
430         curr = toRenderBlock(curr->continuation());
431     }
432
433     if (!beforeChild && !last->firstChild())
434         return nextToLast;
435     return last;
436 }
437
438 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
439 {
440     RenderBlock* flow = continuationBefore(beforeChild);
441     ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
442     RenderBoxModelObject* beforeChildParent = 0;
443     if (beforeChild)
444         beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
445     else {
446         RenderBoxModelObject* cont = flow->continuation();
447         if (cont)
448             beforeChildParent = cont;
449         else
450             beforeChildParent = flow;
451     }
452
453     if (newChild->isFloatingOrOutOfFlowPositioned()) {
454         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
455         return;
456     }
457
458     // A continuation always consists of two potential candidates: a block or an anonymous
459     // column span box holding column span children.
460     bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
461     bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
462     bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
463
464     if (flow == beforeChildParent) {
465         flow->addChildIgnoringContinuation(newChild, beforeChild);
466         return;
467     }
468     
469     // The goal here is to match up if we can, so that we can coalesce and create the
470     // minimal # of continuations needed for the inline.
471     if (childIsNormal == bcpIsNormal) {
472         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
473         return;
474     }
475     if (flowIsNormal == childIsNormal) {
476         flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
477         return;
478     }
479     beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
480 }
481
482
483 void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
484 {
485     ASSERT(!continuation()); // We don't yet support column spans that aren't immediate children of the multi-column block.
486         
487     // The goal is to locate a suitable box in which to place our child.
488     RenderBlock* beforeChildParent = 0;
489     if (beforeChild) {
490         RenderObject* curr = beforeChild;
491         while (curr && curr->parent() != this)
492             curr = curr->parent();
493         beforeChildParent = toRenderBlock(curr);
494         ASSERT(beforeChildParent);
495         ASSERT(beforeChildParent->isAnonymousColumnsBlock() || beforeChildParent->isAnonymousColumnSpanBlock());
496     } else
497         beforeChildParent = toRenderBlock(lastChild());
498
499     // If the new child is floating or positioned it can just go in that block.
500     if (newChild->isFloatingOrOutOfFlowPositioned()) {
501         beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
502         return;
503     }
504
505     // See if the child can be placed in the box.
506     bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
507     bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
508
509     if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans) {
510         beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
511         return;
512     }
513
514     if (!beforeChild) {
515         // Create a new block of the correct type.
516         RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
517         children()->appendChildNode(this, newBox);
518         newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
519         return;
520     }
521
522     RenderObject* immediateChild = beforeChild;
523     bool isPreviousBlockViable = true;
524     while (immediateChild->parent() != this) {
525         if (isPreviousBlockViable)
526             isPreviousBlockViable = !immediateChild->previousSibling();
527         immediateChild = immediateChild->parent();
528     }
529     if (isPreviousBlockViable && immediateChild->previousSibling()) {
530         toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); // Treat like an append.
531         return;
532     }
533         
534     // Split our anonymous blocks.
535     RenderObject* newBeforeChild = splitAnonymousBoxesAroundChild(beforeChild);
536
537     
538     // Create a new anonymous box of the appropriate type.
539     RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
540     children()->insertChildNode(this, newBox, newBeforeChild);
541     newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
542     return;
543 }
544
545 RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
546 {
547     RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
548     for (RenderObject* curr = this; curr; curr = curr->parent()) {
549         if (!curr->isRenderBlock() || curr->isFloatingOrOutOfFlowPositioned() || curr->isTableCell() || curr->isRoot() || curr->isRenderView() || curr->hasOverflowClip()
550             || curr->isInlineBlockOrInlineTable())
551             return 0;
552
553         // FIXME: Tables, RenderButtons, and RenderListItems all do special management
554         // of their children that breaks when the flow is split through them. Disabling
555         // multi-column for them to avoid this problem.
556         if (curr->isTable() || curr->isRenderButton() || curr->isListItem())
557             return 0;
558         
559         RenderBlock* currBlock = toRenderBlock(curr);
560         if (!currBlock->createsAnonymousWrapper())
561             firstChildIgnoringAnonymousWrappers = currBlock;
562
563         if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
564             return firstChildIgnoringAnonymousWrappers;
565             
566         if (currBlock->isAnonymousColumnSpanBlock())
567             return 0;
568     }
569     return 0;
570 }
571
572 RenderBlock* RenderBlock::clone() const
573 {
574     RenderBlock* cloneBlock;
575     if (isAnonymousBlock()) {
576         cloneBlock = createAnonymousBlock();
577         cloneBlock->setChildrenInline(childrenInline());
578     }
579     else {
580         RenderObject* cloneRenderer = toElement(node())->createRenderer(renderArena(), style());
581         cloneBlock = toRenderBlock(cloneRenderer);
582         cloneBlock->setStyle(style());
583
584         // This takes care of setting the right value of childrenInline in case
585         // generated content is added to cloneBlock and 'this' does not have
586         // generated content added yet.
587         cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
588     }
589     cloneBlock->setFlowThreadState(flowThreadState());
590     return cloneBlock;
591 }
592
593 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
594                               RenderBlock* middleBlock,
595                               RenderObject* beforeChild, RenderBoxModelObject* oldCont)
596 {
597     // Create a clone of this inline.
598     RenderBlock* cloneBlock = clone();
599     if (!isAnonymousBlock())
600         cloneBlock->setContinuation(oldCont);
601
602     if (!beforeChild && isAfterContent(lastChild()))
603         beforeChild = lastChild();
604
605     // If we are moving inline children from |this| to cloneBlock, then we need
606     // to clear our line box tree.
607     if (beforeChild && childrenInline())
608         deleteLineBoxTree();
609
610     // Now take all of the children from beforeChild to the end and remove
611     // them from |this| and place them in the clone.
612     moveChildrenTo(cloneBlock, beforeChild, 0, true);
613     
614     // Hook |clone| up as the continuation of the middle block.
615     if (!cloneBlock->isAnonymousBlock())
616         middleBlock->setContinuation(cloneBlock);
617
618     // We have been reparented and are now under the fromBlock.  We need
619     // to walk up our block parent chain until we hit the containing anonymous columns block.
620     // Once we hit the anonymous columns block we're done.
621     RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
622     RenderBoxModelObject* currChild = this;
623     RenderObject* currChildNextSibling = currChild->nextSibling();
624
625     while (curr && curr != fromBlock) {
626         ASSERT_WITH_SECURITY_IMPLICATION(curr->isRenderBlock());
627         
628         RenderBlock* blockCurr = toRenderBlock(curr);
629         
630         // Create a new clone.
631         RenderBlock* cloneChild = cloneBlock;
632         cloneBlock = blockCurr->clone();
633
634         // Insert our child clone as the first child.
635         cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
636
637         // Hook the clone up as a continuation of |curr|.  Note we do encounter
638         // anonymous blocks possibly as we walk up the block chain.  When we split an
639         // anonymous block, there's no need to do any continuation hookup, since we haven't
640         // actually split a real element.
641         if (!blockCurr->isAnonymousBlock()) {
642             oldCont = blockCurr->continuation();
643             blockCurr->setContinuation(cloneBlock);
644             cloneBlock->setContinuation(oldCont);
645         }
646
647         // Now we need to take all of the children starting from the first child
648         // *after* currChild and append them all to the clone.
649         blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
650
651         // Keep walking up the chain.
652         currChild = curr;
653         currChildNextSibling = currChild->nextSibling();
654         curr = toRenderBoxModelObject(curr->parent());
655     }
656
657     // Now we are at the columns block level. We need to put the clone into the toBlock.
658     toBlock->children()->appendChildNode(toBlock, cloneBlock);
659
660     // Now take all the children after currChild and remove them from the fromBlock
661     // and put them in the toBlock.
662     fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
663 }
664
665 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
666                             RenderObject* newChild, RenderBoxModelObject* oldCont)
667 {
668     RenderBlock* pre = 0;
669     RenderBlock* block = containingColumnsBlock();
670     
671     // Delete our line boxes before we do the inline split into continuations.
672     block->deleteLineBoxTree();
673     
674     bool madeNewBeforeBlock = false;
675     if (block->isAnonymousColumnsBlock()) {
676         // We can reuse this block and make it the preBlock of the next continuation.
677         pre = block;
678         pre->removePositionedObjects(0);
679         pre->removeFloatingObjects();
680         block = toRenderBlock(block->parent());
681     } else {
682         // No anonymous block available for use.  Make one.
683         pre = block->createAnonymousColumnsBlock();
684         pre->setChildrenInline(false);
685         madeNewBeforeBlock = true;
686     }
687
688     RenderBlock* post = block->createAnonymousColumnsBlock();
689     post->setChildrenInline(false);
690
691     RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
692     if (madeNewBeforeBlock)
693         block->children()->insertChildNode(block, pre, boxFirst);
694     block->children()->insertChildNode(block, newBlockBox, boxFirst);
695     block->children()->insertChildNode(block, post, boxFirst);
696     block->setChildrenInline(false);
697     
698     if (madeNewBeforeBlock)
699         block->moveChildrenTo(pre, boxFirst, 0, true);
700
701     splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
702
703     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
704     // time in makeChildrenNonInline by just setting this explicitly up front.
705     newBlockBox->setChildrenInline(false);
706
707     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
708     // connected, thus allowing newChild access to a renderArena should it need
709     // to wrap itself in additional boxes (e.g., table construction).
710     newBlockBox->addChild(newChild);
711
712     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
713     // get deleted properly.  Because objects moves from the pre block into the post block, we want to
714     // make new line boxes instead of leaving the old line boxes around.
715     pre->setNeedsLayoutAndPrefWidthsRecalc();
716     block->setNeedsLayoutAndPrefWidthsRecalc();
717     post->setNeedsLayoutAndPrefWidthsRecalc();
718 }
719
720 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
721 {
722     RenderBlock* pre = 0;
723     RenderBlock* post = 0;
724     RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|.  Assign to a variable
725                                // so that we don't have to patch all of the rest of the code later on.
726     
727     // Delete the block's line boxes before we do the split.
728     block->deleteLineBoxTree();
729
730     if (beforeChild && beforeChild->parent() != this)
731         beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
732
733     if (beforeChild != firstChild()) {
734         pre = block->createAnonymousColumnsBlock();
735         pre->setChildrenInline(block->childrenInline());
736     }
737
738     if (beforeChild) {
739         post = block->createAnonymousColumnsBlock();
740         post->setChildrenInline(block->childrenInline());
741     }
742
743     RenderObject* boxFirst = block->firstChild();
744     if (pre)
745         block->children()->insertChildNode(block, pre, boxFirst);
746     block->children()->insertChildNode(block, newBlockBox, boxFirst);
747     if (post)
748         block->children()->insertChildNode(block, post, boxFirst);
749     block->setChildrenInline(false);
750     
751     // The pre/post blocks always have layers, so we know to always do a full insert/remove (so we pass true as the last argument).
752     block->moveChildrenTo(pre, boxFirst, beforeChild, true);
753     block->moveChildrenTo(post, beforeChild, 0, true);
754
755     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
756     // time in makeChildrenNonInline by just setting this explicitly up front.
757     newBlockBox->setChildrenInline(false);
758
759     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
760     // connected, thus allowing newChild access to a renderArena should it need
761     // to wrap itself in additional boxes (e.g., table construction).
762     newBlockBox->addChild(newChild);
763
764     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
765     // get deleted properly.  Because objects moved from the pre block into the post block, we want to
766     // make new line boxes instead of leaving the old line boxes around.
767     if (pre)
768         pre->setNeedsLayoutAndPrefWidthsRecalc();
769     block->setNeedsLayoutAndPrefWidthsRecalc();
770     if (post)
771         post->setNeedsLayoutAndPrefWidthsRecalc();
772 }
773
774 RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
775 {
776     // FIXME: This function is the gateway for the addition of column-span support.  It will
777     // be added to in three stages:
778     // (1) Immediate children of a multi-column block can span.
779     // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
780     // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
781     // cross the streams and have to cope with both types of continuations mixed together).
782     // This function currently supports (1) and (2).
783     RenderBlock* columnsBlockAncestor = 0;
784     if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
785         && !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
786         columnsBlockAncestor = containingColumnsBlock(false);
787         if (columnsBlockAncestor) {
788             // Make sure that none of the parent ancestors have a continuation.
789             // If yes, we do not want split the block into continuations.
790             RenderObject* curr = this;
791             while (curr && curr != columnsBlockAncestor) {
792                 if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
793                     columnsBlockAncestor = 0;
794                     break;
795                 }
796                 curr = curr->parent();
797             }
798         }
799     }
800     return columnsBlockAncestor;
801 }
802
803 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
804 {
805     if (beforeChild && beforeChild->parent() != this) {
806         RenderObject* beforeChildContainer = beforeChild->parent();
807         while (beforeChildContainer->parent() != this)
808             beforeChildContainer = beforeChildContainer->parent();
809         ASSERT(beforeChildContainer);
810
811         if (beforeChildContainer->isAnonymous()) {
812             // If the requested beforeChild is not one of our children, then this is because
813             // there is an anonymous container within this object that contains the beforeChild.
814             RenderObject* beforeChildAnonymousContainer = beforeChildContainer;
815             if (beforeChildAnonymousContainer->isAnonymousBlock()
816 #if ENABLE(FULLSCREEN_API)
817                 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
818                 || beforeChildAnonymousContainer->isRenderFullScreen()
819                 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
820 #endif
821                 ) {
822                 // Insert the child into the anonymous block box instead of here.
823                 if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
824                     beforeChild->parent()->addChild(newChild, beforeChild);
825                 else
826                     addChild(newChild, beforeChild->parent());
827                 return;
828             }
829
830             ASSERT(beforeChildAnonymousContainer->isTable());
831             if (newChild->isTablePart()) {
832                 // Insert into the anonymous table.
833                 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
834                 return;
835             }
836
837             beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
838
839             ASSERT(beforeChild->parent() == this);
840             if (beforeChild->parent() != this) {
841                 // We should never reach here. If we do, we need to use the
842                 // safe fallback to use the topmost beforeChild container.
843                 beforeChild = beforeChildContainer;
844             }
845         } else {
846             // We will reach here when beforeChild is a run-in element.
847             // If run-in element precedes a block-level element, it becomes the
848             // the first inline child of that block level element. The insertion
849             // point will be before that block-level element.
850             ASSERT(beforeChild->isRunIn());
851             beforeChild = beforeChildContainer;
852         }
853     }
854
855     // Nothing goes before the intruded run-in.
856     if (beforeChild && beforeChild->isRunIn() && runInIsPlacedIntoSiblingBlock(beforeChild))
857         beforeChild = beforeChild->nextSibling();
858
859     // Check for a spanning element in columns.
860     if (gColumnFlowSplitEnabled) {
861         RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
862         if (columnsBlockAncestor) {
863             TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
864             // We are placing a column-span element inside a block.
865             RenderBlock* newBox = createAnonymousColumnSpanBlock();
866         
867             if (columnsBlockAncestor != this) {
868                 // We are nested inside a multi-column element and are being split by the span. We have to break up
869                 // our block into continuations.
870                 RenderBoxModelObject* oldContinuation = continuation();
871
872                 // When we split an anonymous block, there's no need to do any continuation hookup,
873                 // since we haven't actually split a real element.
874                 if (!isAnonymousBlock())
875                     setContinuation(newBox);
876
877                 splitFlow(beforeChild, newBox, newChild, oldContinuation);
878                 return;
879             }
880
881             // We have to perform a split of this block's children. This involves creating an anonymous block box to hold
882             // the column-spanning |newChild|. We take all of the children from before |newChild| and put them into
883             // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
884             makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
885             return;
886         }
887     }
888
889     bool madeBoxesNonInline = false;
890
891     // A block has to either have all of its children inline, or all of its children as blocks.
892     // So, if our children are currently inline and a block child has to be inserted, we move all our
893     // inline children into anonymous block boxes.
894     if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
895         // This is a block with inline content. Wrap the inline content in anonymous blocks.
896         makeChildrenNonInline(beforeChild);
897         madeBoxesNonInline = true;
898
899         if (beforeChild && beforeChild->parent() != this) {
900             beforeChild = beforeChild->parent();
901             ASSERT(beforeChild->isAnonymousBlock());
902             ASSERT(beforeChild->parent() == this);
903         }
904     } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
905         // If we're inserting an inline child but all of our children are blocks, then we have to make sure
906         // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
907         // a new one is created and inserted into our list of children in the appropriate position.
908         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
909
910         if (afterChild && afterChild->isAnonymousBlock()) {
911             afterChild->addChild(newChild);
912             return;
913         }
914
915         if (newChild->isInline()) {
916             // No suitable existing anonymous box - create a new one.
917             RenderBlock* newBox = createAnonymousBlock();
918             RenderBox::addChild(newBox, beforeChild);
919             newBox->addChild(newChild);
920             return;
921         }
922     }
923
924     RenderBox::addChild(newChild, beforeChild);
925  
926     // Handle placement of run-ins.
927     placeRunInIfNeeded(newChild);
928
929     if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
930         toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
931     // this object may be dead here
932 }
933
934 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
935 {
936     if (continuation() && !isAnonymousBlock())
937         addChildToContinuation(newChild, beforeChild);
938     else
939         addChildIgnoringContinuation(newChild, beforeChild);
940 }
941
942 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
943 {
944     if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
945         addChildToAnonymousColumnBlocks(newChild, beforeChild);
946     else
947         addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
948 }
949
950 static void getInlineRun(RenderObject* start, RenderObject* boundary,
951                          RenderObject*& inlineRunStart,
952                          RenderObject*& inlineRunEnd)
953 {
954     // Beginning at |start| we find the largest contiguous run of inlines that
955     // we can.  We denote the run with start and end points, |inlineRunStart|
956     // and |inlineRunEnd|.  Note that these two values may be the same if
957     // we encounter only one inline.
958     //
959     // We skip any non-inlines we encounter as long as we haven't found any
960     // inlines yet.
961     //
962     // |boundary| indicates a non-inclusive boundary point.  Regardless of whether |boundary|
963     // is inline or not, we will not include it in a run with inlines before it.  It's as though we encountered
964     // a non-inline.
965     
966     // Start by skipping as many non-inlines as we can.
967     RenderObject * curr = start;
968     bool sawInline;
969     do {
970         while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
971             curr = curr->nextSibling();
972         
973         inlineRunStart = inlineRunEnd = curr;
974         
975         if (!curr)
976             return; // No more inline children to be found.
977         
978         sawInline = curr->isInline();
979         
980         curr = curr->nextSibling();
981         while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
982             inlineRunEnd = curr;
983             if (curr->isInline())
984                 sawInline = true;
985             curr = curr->nextSibling();
986         }
987     } while (!sawInline);
988 }
989
990 void RenderBlock::deleteLineBoxTree()
991 {
992     if (containsFloats()) {
993         // Clear references to originating lines, since the lines are being deleted
994         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
995         FloatingObjectSetIterator end = floatingObjectSet.end();
996         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
997             ASSERT(!((*it)->m_originatingLine) || (*it)->m_originatingLine->renderer() == this);
998             (*it)->m_originatingLine = 0;
999         }
1000     }
1001     m_lineBoxes.deleteLineBoxTree(renderArena());
1002
1003     if (AXObjectCache* cache = document()->existingAXObjectCache())
1004         cache->recomputeIsIgnored(this);
1005 }
1006
1007 RootInlineBox* RenderBlock::createRootInlineBox()
1008 {
1009     return new (renderArena()) RootInlineBox(this);
1010 }
1011
1012 RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
1013 {
1014     RootInlineBox* rootBox = createRootInlineBox();
1015     m_lineBoxes.appendLineBox(rootBox);
1016
1017     if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
1018         if (AXObjectCache* cache = document()->existingAXObjectCache())
1019             cache->recomputeIsIgnored(this);
1020     }
1021
1022     return rootBox;
1023 }
1024
1025 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
1026 {    
1027     // makeChildrenNonInline takes a block whose children are *all* inline and it
1028     // makes sure that inline children are coalesced under anonymous
1029     // blocks.  If |insertionPoint| is defined, then it represents the insertion point for
1030     // the new block child that is causing us to have to wrap all the inlines.  This
1031     // means that we cannot coalesce inlines before |insertionPoint| with inlines following
1032     // |insertionPoint|, because the new child is going to be inserted in between the inlines,
1033     // splitting them.
1034     ASSERT(isInlineBlockOrInlineTable() || !isInline());
1035     ASSERT(!insertionPoint || insertionPoint->parent() == this);
1036
1037     setChildrenInline(false);
1038
1039     RenderObject *child = firstChild();
1040     if (!child)
1041         return;
1042
1043     deleteLineBoxTree();
1044
1045     // Since we are going to have block children, we have to move
1046     // back the run-in to its original place.
1047     if (child->isRunIn()) {
1048         moveRunInToOriginalPosition(child);
1049         child = firstChild();
1050     }
1051
1052     while (child) {
1053         RenderObject *inlineRunStart, *inlineRunEnd;
1054         getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
1055
1056         if (!inlineRunStart)
1057             break;
1058
1059         child = inlineRunEnd->nextSibling();
1060
1061         RenderBlock* block = createAnonymousBlock();
1062         children()->insertChildNode(this, block, inlineRunStart);
1063         moveChildrenTo(block, inlineRunStart, child);
1064     }
1065
1066 #ifndef NDEBUG
1067     for (RenderObject *c = firstChild(); c; c = c->nextSibling())
1068         ASSERT(!c->isInline());
1069 #endif
1070
1071     repaint();
1072 }
1073
1074 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
1075 {
1076     ASSERT(child->isAnonymousBlock());
1077     ASSERT(!child->childrenInline());
1078     
1079     if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
1080         return;
1081     
1082     RenderObject* firstAnChild = child->m_children.firstChild();
1083     RenderObject* lastAnChild = child->m_children.lastChild();
1084     if (firstAnChild) {
1085         RenderObject* o = firstAnChild;
1086         while (o) {
1087             o->setParent(this);
1088             o = o->nextSibling();
1089         }
1090         firstAnChild->setPreviousSibling(child->previousSibling());
1091         lastAnChild->setNextSibling(child->nextSibling());
1092         if (child->previousSibling())
1093             child->previousSibling()->setNextSibling(firstAnChild);
1094         if (child->nextSibling())
1095             child->nextSibling()->setPreviousSibling(lastAnChild);
1096             
1097         if (child == m_children.firstChild())
1098             m_children.setFirstChild(firstAnChild);
1099         if (child == m_children.lastChild())
1100             m_children.setLastChild(lastAnChild);
1101     } else {
1102         if (child == m_children.firstChild())
1103             m_children.setFirstChild(child->nextSibling());
1104         if (child == m_children.lastChild())
1105             m_children.setLastChild(child->previousSibling());
1106
1107         if (child->previousSibling())
1108             child->previousSibling()->setNextSibling(child->nextSibling());
1109         if (child->nextSibling())
1110             child->nextSibling()->setPreviousSibling(child->previousSibling());
1111     }
1112
1113     child->children()->setFirstChild(0);
1114     child->m_next = 0;
1115
1116     // Remove all the information in the flow thread associated with the leftover anonymous block.
1117     child->removeFromRenderFlowThread();
1118
1119     child->setParent(0);
1120     child->setPreviousSibling(0);
1121     child->setNextSibling(0);
1122
1123     child->destroy();
1124 }
1125
1126 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
1127 {
1128     if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
1129         return false;
1130
1131     if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
1132         || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
1133         return false;
1134
1135     // FIXME: This check isn't required when inline run-ins can't be split into continuations.
1136     if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
1137         return false;
1138
1139     if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
1140         || (next && (next->isRubyRun() || next->isRubyBase())))
1141         return false;
1142
1143     if (!prev || !next)
1144         return true;
1145
1146     // Make sure the types of the anonymous blocks match up.
1147     return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
1148            && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
1149 }
1150
1151 void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child)
1152 {
1153     parent->setNeedsLayoutAndPrefWidthsRecalc();
1154     parent->setChildrenInline(child->childrenInline());
1155     RenderObject* nextSibling = child->nextSibling();
1156
1157     RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
1158     CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
1159     
1160     RenderBlock* anonBlock = toRenderBlock(parent->children()->removeChildNode(parent, child, child->hasLayer()));
1161     anonBlock->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
1162     // Delete the now-empty block's lines and nuke it.
1163     anonBlock->deleteLineBoxTree();
1164     if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
1165         toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(anonBlock);
1166     anonBlock->destroy();
1167 }
1168
1169 void RenderBlock::removeChild(RenderObject* oldChild)
1170 {
1171     // No need to waste time in merging or removing empty anonymous blocks.
1172     // We can just bail out if our document is getting destroyed.
1173     if (documentBeingDestroyed()) {
1174         RenderBox::removeChild(oldChild);
1175         return;
1176     }
1177
1178     // This protects against column split flows when anonymous blocks are getting merged.
1179     TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
1180
1181     // If this child is a block, and if our previous and next siblings are
1182     // both anonymous blocks with inline content, then we can go ahead and
1183     // fold the inline content back together.
1184     RenderObject* prev = oldChild->previousSibling();
1185     RenderObject* next = oldChild->nextSibling();
1186     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1187     if (canMergeAnonymousBlocks && prev && next) {
1188         prev->setNeedsLayoutAndPrefWidthsRecalc();
1189         RenderBlock* nextBlock = toRenderBlock(next);
1190         RenderBlock* prevBlock = toRenderBlock(prev);
1191        
1192         if (prev->childrenInline() != next->childrenInline()) {
1193             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1194             RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1195             
1196             // Place the inline children block inside of the block children block instead of deleting it.
1197             // In order to reuse it, we have to reset it to just be a generic anonymous block.  Make sure
1198             // to clear out inherited column properties by just making a new style, and to also clear the
1199             // column span flag if it is set.
1200             ASSERT(!inlineChildrenBlock->continuation());
1201             RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
1202             // Cache this value as it might get changed in setStyle() call.
1203             bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
1204             inlineChildrenBlock->setStyle(newStyle);
1205             children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlockHasLayer);
1206             
1207             // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1208             blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1209                                                             inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer());
1210             next->setNeedsLayoutAndPrefWidthsRecalc();
1211             
1212             // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1213             // of "this". we null out prev or next so that is not used later in the function.
1214             if (inlineChildrenBlock == prevBlock)
1215                 prev = 0;
1216             else
1217                 next = 0;
1218         } else {
1219             // Take all the children out of the |next| block and put them in
1220             // the |prev| block.
1221             nextBlock->moveAllChildrenTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());        
1222             
1223             // Delete the now-empty block's lines and nuke it.
1224             nextBlock->deleteLineBoxTree();
1225             nextBlock->destroy();
1226             next = 0;
1227         }
1228     }
1229
1230     RenderBox::removeChild(oldChild);
1231
1232     RenderObject* child = prev ? prev : next;
1233     if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
1234         // The removal has knocked us down to containing only a single anonymous
1235         // box.  We can go ahead and pull the content right back up into our
1236         // box.
1237         collapseAnonymousBoxChild(this, child);
1238     } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
1239         // It's possible that the removal has knocked us down to a single anonymous
1240         // block with pseudo-style element siblings (e.g. first-letter). If these
1241         // are floating, then we need to pull the content up also.
1242         RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
1243         if ((anonBlock->previousSibling() || anonBlock->nextSibling())
1244             && (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
1245             && (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
1246             collapseAnonymousBoxChild(this, anonBlock);
1247         }
1248     }
1249
1250     if (!firstChild()) {
1251         // If this was our last child be sure to clear out our line boxes.
1252         if (childrenInline())
1253             deleteLineBoxTree();
1254
1255         // If we are an empty anonymous block in the continuation chain,
1256         // we need to remove ourself and fix the continuation chain.
1257         if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild->isListMarker()) {
1258             RenderObject* containingBlockIgnoringAnonymous = containingBlock();
1259             while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymousBlock())
1260                 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
1261             for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
1262                 if (curr->virtualContinuation() != this)
1263                     continue;
1264
1265                 // Found our previous continuation. We just need to point it to
1266                 // |this|'s next continuation.
1267                 RenderBoxModelObject* nextContinuation = continuation();
1268                 if (curr->isRenderInline())
1269                     toRenderInline(curr)->setContinuation(nextContinuation);
1270                 else if (curr->isRenderBlock())
1271                     toRenderBlock(curr)->setContinuation(nextContinuation);
1272                 else
1273                     ASSERT_NOT_REACHED();
1274
1275                 break;
1276             }
1277             setContinuation(0);
1278             destroy();
1279         }
1280     }
1281 }
1282
1283 bool RenderBlock::isSelfCollapsingBlock() const
1284 {
1285     // We are not self-collapsing if we
1286     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1287     // (b) are a table,
1288     // (c) have border/padding,
1289     // (d) have a min-height
1290     // (e) have specified that one of our margins can't collapse using a CSS extension
1291     if (logicalHeight() > 0
1292         || isTable() || borderAndPaddingLogicalHeight()
1293         || style()->logicalMinHeight().isPositive()
1294         || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1295         return false;
1296
1297     Length logicalHeightLength = style()->logicalHeight();
1298     bool hasAutoHeight = logicalHeightLength.isAuto();
1299     if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
1300         hasAutoHeight = true;
1301         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1302             if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1303                 hasAutoHeight = false;
1304         }
1305     }
1306
1307     // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1308     // on whether we have content that is all self-collapsing or not.
1309     if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1310         // If the block has inline children, see if we generated any line boxes.  If we have any
1311         // line boxes, then we can't be self-collapsing, since we have content.
1312         if (childrenInline())
1313             return !firstLineBox();
1314         
1315         // Whether or not we collapse is dependent on whether all our normal flow children
1316         // are also self-collapsing.
1317         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1318             if (child->isFloatingOrOutOfFlowPositioned())
1319                 continue;
1320             if (!child->isSelfCollapsingBlock())
1321                 return false;
1322         }
1323         return true;
1324     }
1325     return false;
1326 }
1327
1328 void RenderBlock::startDelayUpdateScrollInfo()
1329 {
1330     if (gDelayUpdateScrollInfo == 0) {
1331         ASSERT(!gDelayedUpdateScrollInfoSet);
1332         gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1333     }
1334     ASSERT(gDelayedUpdateScrollInfoSet);
1335     ++gDelayUpdateScrollInfo;
1336 }
1337
1338 void RenderBlock::finishDelayUpdateScrollInfo()
1339 {
1340     --gDelayUpdateScrollInfo;
1341     ASSERT(gDelayUpdateScrollInfo >= 0);
1342     if (gDelayUpdateScrollInfo == 0) {
1343         ASSERT(gDelayedUpdateScrollInfoSet);
1344
1345         OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1346         gDelayedUpdateScrollInfoSet = 0;
1347
1348         for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1349             RenderBlock* block = *it;
1350             if (block->hasOverflowClip()) {
1351                 block->layer()->updateScrollInfoAfterLayout();
1352             }
1353         }
1354     }
1355 }
1356
1357 void RenderBlock::updateScrollInfoAfterLayout()
1358 {
1359     if (hasOverflowClip()) {
1360         if (style()->isFlippedBlocksWritingMode()) {
1361             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=97937
1362             // Workaround for now. We cannot delay the scroll info for overflow
1363             // for items with opposite writing directions, as the contents needs
1364             // to overflow in that direction
1365             layer()->updateScrollInfoAfterLayout();
1366             return;
1367         }
1368
1369         if (gDelayUpdateScrollInfo)
1370             gDelayedUpdateScrollInfoSet->add(this);
1371         else
1372             layer()->updateScrollInfoAfterLayout();
1373     }
1374 }
1375
1376 void RenderBlock::layout()
1377 {
1378     StackStats::LayoutCheckPoint layoutCheckPoint;
1379     OverflowEventDispatcher dispatcher(this);
1380
1381     // Update our first letter info now.
1382     updateFirstLetter();
1383
1384     // Table cells call layoutBlock directly, so don't add any logic here.  Put code into
1385     // layoutBlock().
1386     layoutBlock(false);
1387     
1388     // It's safe to check for control clip here, since controls can never be table cells.
1389     // If we have a lightweight clip, there can never be any overflow from children.
1390     if (hasControlClip() && m_overflow)
1391         clearLayoutOverflow();
1392
1393     invalidateBackgroundObscurationStatus();
1394 }
1395
1396 #if ENABLE(CSS_EXCLUSIONS)
1397 void RenderBlock::updateExclusionShapeInsideInfoAfterStyleChange(const ExclusionShapeValue* shapeInside, const ExclusionShapeValue* oldShapeInside)
1398 {
1399     // FIXME: A future optimization would do a deep comparison for equality.
1400     if (shapeInside == oldShapeInside)
1401         return;
1402
1403     ExclusionShapeInsideInfo* exclusionShapeInsideInfo;
1404     if (shapeInside) {
1405         exclusionShapeInsideInfo = ensureExclusionShapeInsideInfo();
1406         exclusionShapeInsideInfo->dirtyShapeSize();
1407         exclusionShapeInsideInfo->setNeedsRemoval(false);
1408     } else if ((exclusionShapeInsideInfo = this->exclusionShapeInsideInfo(ShapePresentOrRemoved)))
1409         exclusionShapeInsideInfo->setNeedsRemoval(true);
1410 }
1411 #endif
1412
1413 static inline bool exclusionInfoRequiresRelayout(const RenderBlock* block)
1414 {
1415 #if !ENABLE(CSS_EXCLUSIONS)
1416     return false;
1417 #else
1418     ExclusionShapeInsideInfo* info = block->exclusionShapeInsideInfo(RenderBlock::ShapePresentOrRemoved);
1419     if (info)
1420         info->setNeedsLayout(info->shapeSizeDirty() || info->needsRemoval());
1421     else
1422         info = block->layoutExclusionShapeInsideInfo(RenderBlock::ShapePresentOrRemoved);
1423     return info && info->needsLayout();
1424 #endif
1425 }
1426
1427 bool RenderBlock::updateRegionsAndExclusionsBeforeChildLayout(RenderFlowThread* flowThread)
1428 {
1429 #if ENABLE(CSS_EXCLUSIONS)
1430     if (!flowThread && !exclusionShapeInsideInfo())
1431 #else
1432     if (!flowThread)
1433 #endif
1434         return exclusionInfoRequiresRelayout(this);
1435
1436     LayoutUnit oldHeight = logicalHeight();
1437     LayoutUnit oldTop = logicalTop();
1438
1439     // Compute the maximum logical height content may cause this block to expand to
1440     // FIXME: These should eventually use the const computeLogicalHeight rather than updateLogicalHeight
1441     setLogicalHeight(LayoutUnit::max() / 2);
1442     updateLogicalHeight();
1443
1444 #if ENABLE(CSS_EXCLUSIONS)
1445     computeExclusionShapeSize();
1446 #endif
1447
1448     // Set our start and end regions. No regions above or below us will be considered by our children. They are
1449     // effectively clamped to our region range.
1450     computeRegionRangeForBlock(flowThread);
1451
1452     setLogicalHeight(oldHeight);
1453     setLogicalTop(oldTop);
1454     
1455     return exclusionInfoRequiresRelayout(this);
1456 }
1457
1458 #if ENABLE(CSS_EXCLUSIONS)
1459 void RenderBlock::computeExclusionShapeSize()
1460 {
1461     ExclusionShapeInsideInfo* exclusionShapeInsideInfo = this->exclusionShapeInsideInfo();
1462     if (exclusionShapeInsideInfo) {
1463         bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
1464         exclusionShapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
1465     }
1466 }
1467 #endif
1468
1469 void RenderBlock::updateRegionsAndExclusionsAfterChildLayout(RenderFlowThread* flowThread, bool heightChanged)
1470 {
1471 #if ENABLE(CSS_EXCLUSIONS)
1472     ExclusionShapeInsideInfo* exclusionShapeInsideInfo = this->exclusionShapeInsideInfo(ShapePresentOrRemoved);
1473     if (exclusionShapeInsideInfo && exclusionShapeInsideInfo->needsRemoval())
1474         setExclusionShapeInsideInfo(nullptr);
1475
1476     // A previous sibling has changed dimension, so we need to relayout the shape with the content
1477     ExclusionShapeInsideInfo* shapeInsideInfo = layoutExclusionShapeInsideInfo();
1478     if (heightChanged && shapeInsideInfo)
1479         shapeInsideInfo->dirtyShapeSize();
1480 #endif
1481     computeRegionRangeForBlock(flowThread);
1482 }
1483
1484 void RenderBlock::computeRegionRangeForBlock(RenderFlowThread* flowThread)
1485 {
1486     if (flowThread)
1487         flowThread->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
1488 }
1489
1490 bool RenderBlock::updateLogicalWidthAndColumnWidth()
1491 {
1492     LayoutUnit oldWidth = logicalWidth();
1493     LayoutUnit oldColumnWidth = desiredColumnWidth();
1494
1495     updateLogicalWidth();
1496     calcColumnWidth();
1497
1498     bool hasBorderOrPaddingLogicalWidthChanged = m_hasBorderOrPaddingLogicalWidthChanged;
1499     m_hasBorderOrPaddingLogicalWidthChanged = false;
1500
1501     return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth() || hasBorderOrPaddingLogicalWidthChanged;
1502 }
1503
1504 void RenderBlock::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
1505 {
1506     ColumnInfo* colInfo = columnInfo();
1507     if (hasColumns()) {
1508         if (!pageLogicalHeight) {
1509             // We need to go ahead and set our explicit page height if one exists, so that we can
1510             // avoid doing two layout passes.
1511             updateLogicalHeight();
1512             LayoutUnit columnHeight = contentLogicalHeight();
1513             if (columnHeight > 0) {
1514                 pageLogicalHeight = columnHeight;
1515                 hasSpecifiedPageLogicalHeight = true;
1516             }
1517             setLogicalHeight(0);
1518         }
1519         if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
1520             colInfo->setColumnHeight(pageLogicalHeight);
1521             pageLogicalHeightChanged = true;
1522         }
1523         
1524         if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
1525             colInfo->clearForcedBreaks();
1526
1527         colInfo->setPaginationUnit(paginationUnit());
1528     } else if (isRenderFlowThread()) {
1529         pageLogicalHeight = 1; // This is just a hack to always make sure we have a page logical height.
1530         pageLogicalHeightChanged = toRenderFlowThread(this)->pageLogicalSizeChanged();
1531     }
1532 }
1533
1534 void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
1535 {
1536     ASSERT(needsLayout());
1537
1538     if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
1539         return;                                      // cause us to come in here.  Just bail.
1540
1541     if (!relayoutChildren && simplifiedLayout())
1542         return;
1543
1544     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
1545
1546     if (updateLogicalWidthAndColumnWidth())
1547         relayoutChildren = true;
1548
1549     clearFloats();
1550
1551     LayoutUnit previousHeight = logicalHeight();
1552     // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
1553     // for consistency with other render classes?
1554     setLogicalHeight(0);
1555
1556     bool pageLogicalHeightChanged = false;
1557     bool hasSpecifiedPageLogicalHeight = false;
1558     checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
1559
1560     RenderView* renderView = view();
1561     RenderStyle* styleToUse = style();
1562     LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
1563
1564     // Regions changing widths can force us to relayout our children.
1565     RenderFlowThread* flowThread = flowThreadContainingBlock();
1566     if (logicalWidthChangedInRegions(flowThread))
1567         relayoutChildren = true;
1568     if (updateRegionsAndExclusionsBeforeChildLayout(flowThread))
1569         relayoutChildren = true;
1570
1571     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
1572     // our current maximal positive and negative margins.  These values are used when we
1573     // are collapsed with adjacent blocks, so for example, if you have block A and B
1574     // collapsing together, then you'd take the maximal positive margin from both A and B
1575     // and subtract it from the maximal negative margin from both A and B to get the
1576     // true collapsed margin.  This algorithm is recursive, so when we finish layout()
1577     // our block knows its current maximal positive/negative values.
1578     //
1579     // Start out by setting our margin values to our current margins.  Table cells have
1580     // no margins, so we don't fill in the values for table cells.
1581     bool isCell = isTableCell();
1582     if (!isCell) {
1583         initMaxMarginValues();
1584         
1585         setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
1586         setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
1587         setPaginationStrut(0);
1588     }
1589
1590     LayoutUnit repaintLogicalTop = 0;
1591     LayoutUnit repaintLogicalBottom = 0;
1592     LayoutUnit maxFloatLogicalBottom = 0;
1593     if (!firstChild() && !isAnonymousBlock())
1594         setChildrenInline(true);
1595     if (childrenInline())
1596         layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
1597     else
1598         layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
1599
1600     // Expand our intrinsic height to encompass floats.
1601     LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
1602     if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
1603         setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
1604     
1605     if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
1606         return;
1607
1608     // Calculate our new height.
1609     LayoutUnit oldHeight = logicalHeight();
1610     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
1611
1612     // Before updating the final size of the flow thread make sure a forced break is applied after the content.
1613     // This ensures the size information is correctly computed for the last auto-height region receiving content.
1614     if (isRenderFlowThread())
1615         toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
1616
1617     updateLogicalHeight();
1618     LayoutUnit newHeight = logicalHeight();
1619     if (oldHeight != newHeight) {
1620         if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
1621             // One of our children's floats may have become an overhanging float for us. We need to look for it.
1622             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1623                 if (child->isBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
1624                     RenderBlock* block = toRenderBlock(child);
1625                     if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
1626                         addOverhangingFloats(block, false);
1627                 }
1628             }
1629         }
1630     }
1631
1632     bool heightChanged = (previousHeight != newHeight);
1633     if (heightChanged)
1634         relayoutChildren = true;
1635
1636     layoutPositionedObjects(relayoutChildren || isRoot());
1637
1638     updateRegionsAndExclusionsAfterChildLayout(flowThread, heightChanged);
1639
1640     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
1641     computeOverflow(oldClientAfterEdge);
1642     
1643     statePusher.pop();
1644
1645     fitBorderToLinesIfNeeded();
1646
1647     if (renderView->layoutState()->m_pageLogicalHeight)
1648         setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
1649
1650     updateLayerTransform();
1651
1652     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
1653     // we overflow or not.
1654     updateScrollInfoAfterLayout();
1655
1656     // FIXME: This repaint logic should be moved into a separate helper function!
1657     // Repaint with our new bounds if they are different from our old bounds.
1658     bool didFullRepaint = repainter.repaintAfterLayout();
1659     if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
1660         // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1661         // it had to lay out.  We wouldn't need the hasOverflowClip() hack in that case either.
1662         LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1663         LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1664         if (hasOverflowClip()) {
1665             // If we have clipped overflow, we should use layout overflow as well, since visual overflow from lines didn't propagate to our block's overflow.
1666             // Note the old code did this as well but even for overflow:visible.  The addition of hasOverflowClip() at least tightens up the hack a bit.
1667             // layoutInlineChildren should be patched to compute the entire repaint rect.
1668             repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1669             repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1670         }
1671         
1672         LayoutRect repaintRect;
1673         if (isHorizontalWritingMode())
1674             repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
1675         else
1676             repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1677
1678         // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1679         adjustRectForColumns(repaintRect);
1680
1681         repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1682         
1683         if (hasOverflowClip()) {
1684             // Adjust repaint rect for scroll offset
1685             repaintRect.move(-scrolledContentOffset());
1686
1687             // Don't allow this rect to spill out of our overflow box.
1688             repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1689         }
1690
1691         // Make sure the rect is still non-empty after intersecting for overflow above
1692         if (!repaintRect.isEmpty()) {
1693             repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1694             if (hasReflection())
1695                 repaintRectangle(reflectedRect(repaintRect));
1696         }
1697     }
1698
1699     setNeedsLayout(false);
1700 }
1701
1702 void RenderBlock::addOverflowFromChildren()
1703 {
1704     if (!hasColumns()) {
1705         if (childrenInline())
1706             addOverflowFromInlineChildren();
1707         else
1708             addOverflowFromBlockChildren();
1709     } else {
1710         ColumnInfo* colInfo = columnInfo();
1711         if (columnCount(colInfo)) {
1712             LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1713             addLayoutOverflow(lastRect);
1714             if (!hasOverflowClip())
1715                 addVisualOverflow(lastRect);
1716         }
1717     }
1718 }
1719
1720 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1721 {
1722     m_overflow.clear();
1723
1724     // Add overflow from children.
1725     addOverflowFromChildren();
1726
1727     if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
1728         addOverflowFromFloats();
1729
1730     // Add in the overflow from positioned objects.
1731     addOverflowFromPositionedObjects();
1732
1733     if (hasOverflowClip()) {
1734         // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1735         // and bottom padding.  Set the axis we don't care about to be 1, since we want this overflow to always
1736         // be considered reachable.
1737         LayoutRect clientRect(clientBoxRect());
1738         LayoutRect rectToApply;
1739         if (isHorizontalWritingMode())
1740             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1741         else
1742             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1743         addLayoutOverflow(rectToApply);
1744         if (hasRenderOverflow())
1745             m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
1746     }
1747         
1748     // Allow our overflow to catch cases where the caret in an empty editable element with negative text indent needs to get painted.
1749     LayoutUnit textIndent = textIndentOffset();
1750     if (textIndent < 0) {
1751         LayoutRect clientRect(clientBoxRect());
1752         LayoutRect rectToApply = LayoutRect(clientRect.x() + min<LayoutUnit>(0, textIndent), clientRect.y(), clientRect.width() - min<LayoutUnit>(0, textIndent), clientRect.height());
1753         addVisualOverflow(rectToApply);
1754     }
1755
1756     // Add visual overflow from box-shadow and border-image-outset.
1757     addVisualEffectOverflow();
1758
1759     // Add visual overflow from theme.
1760     addVisualOverflowFromTheme();
1761
1762     if (isRenderFlowThread())
1763         toRenderFlowThread(this)->computeOverflowStateForRegions(oldClientAfterEdge);
1764 }
1765
1766 void RenderBlock::addOverflowFromBlockChildren()
1767 {
1768     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1769         if (!child->isFloatingOrOutOfFlowPositioned())
1770             addOverflowFromChild(child);
1771     }
1772 }
1773
1774 void RenderBlock::addOverflowFromFloats()
1775 {
1776     if (!m_floatingObjects)
1777         return;
1778
1779     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1780     FloatingObjectSetIterator end = floatingObjectSet.end();
1781     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1782         FloatingObject* r = *it;
1783         if (r->isDescendant())
1784             addOverflowFromChild(r->m_renderer, IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
1785     }
1786 }
1787
1788 void RenderBlock::addOverflowFromPositionedObjects()
1789 {
1790     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1791     if (!positionedDescendants)
1792         return;
1793
1794     RenderBox* positionedObject;
1795     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1796     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1797         positionedObject = *it;
1798         
1799         // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1800         if (positionedObject->style()->position() != FixedPosition) {
1801             LayoutUnit x = positionedObject->x();
1802             if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1803                 x -= verticalScrollbarWidth();
1804             addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
1805         }
1806     }
1807 }
1808
1809 void RenderBlock::addVisualOverflowFromTheme()
1810 {
1811     if (!style()->hasAppearance())
1812         return;
1813
1814     IntRect inflatedRect = pixelSnappedBorderBoxRect();
1815     theme()->adjustRepaintRect(this, inflatedRect);
1816     addVisualOverflow(inflatedRect);
1817 }
1818
1819 bool RenderBlock::expandsToEncloseOverhangingFloats() const
1820 {
1821     return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBoxIncludingDeprecated())
1822            || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
1823 }
1824
1825 void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1826 {
1827     bool isHorizontal = isHorizontalWritingMode();
1828     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1829     
1830     LayoutUnit logicalTop = logicalHeight();
1831     updateStaticInlinePositionForChild(child, logicalTop);
1832
1833     if (!marginInfo.canCollapseWithMarginBefore()) {
1834         // Positioned blocks don't collapse margins, so add the margin provided by
1835         // the container now. The child's own margin is added later when calculating its logical top.
1836         LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1837         LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1838         logicalTop += collapsedBeforePos - collapsedBeforeNeg;
1839     }
1840     
1841     RenderLayer* childLayer = child->layer();
1842     if (childLayer->staticBlockPosition() != logicalTop) {
1843         childLayer->setStaticBlockPosition(logicalTop);
1844         if (hasStaticBlockPosition)
1845             child->setChildNeedsLayout(true, MarkOnlyThis);
1846     }
1847 }
1848
1849 void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
1850 {
1851     // The float should be positioned taking into account the bottom margin
1852     // of the previous flow.  We add that margin into the height, get the
1853     // float positioned properly, and then subtract the margin out of the
1854     // height again.  In the case of self-collapsing blocks, we always just
1855     // use the top margins, since the self-collapsing block collapsed its
1856     // own bottom margin into its top margin.
1857     //
1858     // Note also that the previous flow may collapse its margin into the top of
1859     // our block.  If this is the case, then we do not add the margin in to our
1860     // height when computing the position of the float.   This condition can be tested
1861     // for by simply calling canCollapseWithMarginBefore.  See
1862     // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1863     // an example of this scenario.
1864     LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1865     setLogicalHeight(logicalHeight() + marginOffset);
1866     positionNewFloats();
1867     setLogicalHeight(logicalHeight() - marginOffset);
1868 }
1869
1870 static void destroyRunIn(RenderBoxModelObject* runIn)
1871 {
1872     ASSERT(runIn->isRunIn());
1873     ASSERT(!runIn->firstChild());
1874
1875     // Delete our line box tree. This is needed as our children got moved
1876     // and our line box tree is no longer valid.
1877     if (runIn->isRenderBlock())
1878         toRenderBlock(runIn)->deleteLineBoxTree();
1879     else if (runIn->isRenderInline())
1880         toRenderInline(runIn)->deleteLineBoxTree();
1881     else
1882         ASSERT_NOT_REACHED();
1883
1884     runIn->destroy();
1885 }
1886
1887 void RenderBlock::placeRunInIfNeeded(RenderObject* newChild)
1888 {
1889     if (newChild->isRunIn())
1890         moveRunInUnderSiblingBlockIfNeeded(newChild);
1891     else if (RenderObject* prevSibling = newChild->previousSibling()) {
1892         if (prevSibling->isRunIn())
1893             moveRunInUnderSiblingBlockIfNeeded(prevSibling);
1894     }
1895 }
1896
1897 RenderBoxModelObject* RenderBlock::createReplacementRunIn(RenderBoxModelObject* runIn)
1898 {
1899     ASSERT(runIn->isRunIn());
1900     ASSERT(runIn->node());
1901
1902     RenderBoxModelObject* newRunIn = 0;
1903     if (!runIn->isRenderBlock())
1904         newRunIn = new (renderArena()) RenderBlock(runIn->node());
1905     else
1906         newRunIn = new (renderArena()) RenderInline(toElement(runIn->node()));
1907
1908     runIn->node()->setRenderer(newRunIn);
1909     newRunIn->setStyle(runIn->style());
1910
1911     runIn->moveAllChildrenTo(newRunIn, true);
1912
1913     return newRunIn;
1914 }
1915
1916 void RenderBlock::moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn)
1917 {
1918     ASSERT(runIn->isRunIn());
1919
1920     // See if we have inline children. If the children aren't inline,
1921     // then just treat the run-in as a normal block.
1922     if (!runIn->childrenInline())
1923         return;
1924
1925     // FIXME: We don't handle non-block elements with run-in for now.
1926     if (!runIn->isRenderBlock())
1927         return;
1928
1929     // FIXME: We don't support run-ins with or as part of a continuation
1930     // as it makes the back-and-forth placing complex.
1931     if (runIn->isElementContinuation() || runIn->virtualContinuation())
1932         return;
1933
1934     // Check if this node is allowed to run-in. E.g. <select> expects its renderer to
1935     // be a RenderListBox or RenderMenuList, and hence cannot be a RenderInline run-in.
1936     if (!runIn->canBeReplacedWithInlineRunIn())
1937         return;
1938
1939     RenderObject* curr = runIn->nextSibling();
1940     if (!curr || !curr->isRenderBlock() || !curr->childrenInline())
1941         return;
1942
1943     // Per CSS3, "A run-in cannot run in to a block that already starts with a
1944     // run-in or that itself is a run-in".
1945     if (curr->isRunIn() || (curr->firstChild() && curr->firstChild()->isRunIn()))
1946         return;
1947
1948     if (curr->isAnonymous() || curr->isFloatingOrOutOfFlowPositioned())
1949         return;
1950
1951     RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
1952     RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
1953     destroyRunIn(oldRunIn);
1954
1955     // Now insert the new child under |curr| block. Use addChild instead of insertChildNode
1956     // since it handles correct placement of the children, especially where we cannot insert
1957     // anything before the first child. e.g. details tag. See https://bugs.webkit.org/show_bug.cgi?id=58228.
1958     curr->addChild(newRunIn, curr->firstChild());
1959
1960     // Make sure that |this| get a layout since its run-in child moved.
1961     curr->setNeedsLayoutAndPrefWidthsRecalc();
1962 }
1963
1964 bool RenderBlock::runInIsPlacedIntoSiblingBlock(RenderObject* runIn)
1965 {
1966     ASSERT(runIn->isRunIn());
1967
1968     // If we don't have a parent, we can't be moved into our sibling block.
1969     if (!parent())
1970         return false;
1971
1972     // An intruded run-in needs to be an inline.
1973     if (!runIn->isRenderInline())
1974         return false;
1975
1976     return true;
1977 }
1978
1979 void RenderBlock::moveRunInToOriginalPosition(RenderObject* runIn)
1980 {
1981     ASSERT(runIn->isRunIn());
1982
1983     if (!runInIsPlacedIntoSiblingBlock(runIn))
1984         return;
1985
1986     // FIXME: Run-in that are now placed in sibling block can break up into continuation
1987     // chains when new children are added to it. We cannot easily send them back to their
1988     // original place since that requires writing integration logic with RenderInline::addChild
1989     // and all other places that might cause continuations to be created (without blowing away
1990     // |this|). Disabling this feature for now to prevent crashes.
1991     if (runIn->isElementContinuation() || runIn->virtualContinuation())
1992         return;
1993
1994     RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
1995     RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
1996     destroyRunIn(oldRunIn);
1997
1998     // Add the run-in block as our previous sibling.
1999     parent()->addChild(newRunIn, this);
2000
2001     // Make sure that the parent holding the new run-in gets layout.
2002     parent()->setNeedsLayoutAndPrefWidthsRecalc();
2003 }
2004
2005 LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
2006 {
2007     bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
2008     bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
2009     bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
2010
2011     // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
2012     childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
2013
2014     // Get the four margin values for the child and cache them.
2015     const MarginValues childMargins = marginValuesForChild(child);
2016
2017     // Get our max pos and neg top margins.
2018     LayoutUnit posTop = childMargins.positiveMarginBefore();
2019     LayoutUnit negTop = childMargins.negativeMarginBefore();
2020
2021     // For self-collapsing blocks, collapse our bottom margins into our
2022     // top to get new posTop and negTop values.
2023     if (childIsSelfCollapsing) {
2024         posTop = max(posTop, childMargins.positiveMarginAfter());
2025         negTop = max(negTop, childMargins.negativeMarginAfter());
2026     }
2027     
2028     // See if the top margin is quirky. We only care if this child has
2029     // margins that will collapse with us.
2030     bool topQuirk = hasMarginBeforeQuirk(child);
2031
2032     if (marginInfo.canCollapseWithMarginBefore()) {
2033         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2034             // This child is collapsing with the top of the
2035             // block. If it has larger margin values, then we need to update
2036             // our own maximal values.
2037             if (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
2038                 setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
2039
2040             // The minute any of the margins involved isn't a quirk, don't
2041             // collapse it away, even if the margin is smaller (www.webreference.com
2042             // has an example of this, a <dt> with 0.8em author-specified inside
2043             // a <dl> inside a <td>.
2044             if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
2045                 setHasMarginBeforeQuirk(false);
2046                 marginInfo.setDeterminedMarginBeforeQuirk(true);
2047             }
2048
2049             if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
2050                 // We have no top margin and our top child has a quirky margin.
2051                 // We will pick up this quirky margin and pass it through.
2052                 // This deals with the <td><div><p> case.
2053                 // Don't do this for a block that split two inlines though. You do
2054                 // still apply margins in this case.
2055                 setHasMarginBeforeQuirk(true);
2056         } else
2057             // The before margin of the container will also discard all the margins it is collapsing with.
2058             setMustDiscardMarginBefore();
2059     }
2060
2061     // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard. 
2062     if (childDiscardMarginBefore) {
2063         marginInfo.setDiscardMargin(true);
2064         marginInfo.clearMargin();
2065     }
2066
2067     if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
2068         marginInfo.setHasMarginBeforeQuirk(topQuirk);
2069
2070     LayoutUnit beforeCollapseLogicalTop = logicalHeight();
2071     LayoutUnit logicalTop = beforeCollapseLogicalTop;
2072     if (childIsSelfCollapsing) {
2073         // For a self collapsing block both the before and after margins get discarded. The block doesn't contribute anything to the height of the block.
2074         // Also, the child's top position equals the logical height of the container.
2075         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2076             // This child has no height. We need to compute our
2077             // position before we collapse the child's margins together,
2078             // so that we can get an accurate position for the zero-height block.
2079             LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
2080             LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
2081             marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
2082             
2083             // Now collapse the child's margins together, which means examining our
2084             // bottom margin values as well. 
2085             marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
2086             marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
2087
2088             if (!marginInfo.canCollapseWithMarginBefore())
2089                 // We need to make sure that the position of the self-collapsing block
2090                 // is correct, since it could have overflowing content
2091                 // that needs to be positioned correctly (e.g., a block that
2092                 // had a specified height of 0 but that actually had subcontent).
2093                 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
2094         }
2095     } else {
2096         if (mustSeparateMarginBeforeForChild(child)) {
2097             ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
2098             // If we are at the before side of the block and we collapse, ignore the computed margin
2099             // and just add the child margin to the container height. This will correctly position
2100             // the child inside the container.
2101             LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
2102             setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
2103             logicalTop = logicalHeight();
2104         } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
2105             || (!marginInfo.canCollapseMarginBeforeWithChildren()
2106             && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
2107             // We're collapsing with a previous sibling's margins and not
2108             // with the top of the block.
2109             setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
2110             logicalTop = logicalHeight();
2111         }
2112
2113         marginInfo.setDiscardMargin(childDiscardMarginAfter);
2114         
2115         if (!marginInfo.discardMargin()) {
2116             marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
2117             marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
2118         } else
2119             marginInfo.clearMargin();
2120
2121         if (marginInfo.margin())
2122             marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
2123     }
2124     
2125     // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
2126     // collapsed into the page edge.
2127     LayoutState* layoutState = view()->layoutState();
2128     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
2129         && hasNextPage(beforeCollapseLogicalTop)) {
2130         LayoutUnit oldLogicalTop = logicalTop;
2131         logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
2132         setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
2133     }
2134
2135     // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
2136     // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
2137     // or clear it anyway, so don't worry about any floating children it may contain.
2138     LayoutUnit oldLogicalHeight = logicalHeight();
2139     setLogicalHeight(logicalTop);
2140     RenderObject* prev = child->previousSibling();
2141     if (prev && prev->isBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
2142         RenderBlock* block = toRenderBlock(prev);
2143         if (block->containsFloats() && !block->avoidsFloats() && (block->logicalTop() + block->lowestFloatLogicalBottom()) > logicalTop) 
2144             addOverhangingFloats(block, false);
2145     }
2146     setLogicalHeight(oldLogicalHeight);
2147
2148     return logicalTop;
2149 }
2150
2151 LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
2152 {
2153     LayoutUnit heightIncrease = getClearDelta(child, yPos);
2154     if (!heightIncrease)
2155         return yPos;
2156
2157     if (child->isSelfCollapsingBlock()) {
2158         bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
2159
2160         // For self-collapsing blocks that clear, they can still collapse their
2161         // margins with following siblings.  Reset the current margins to represent
2162         // the self-collapsing block's margins only.
2163         // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
2164         if (!childDiscardMargin) {
2165             MarginValues childMargins = marginValuesForChild(child);
2166             marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
2167             marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
2168         } else
2169             marginInfo.clearMargin();
2170         marginInfo.setDiscardMargin(childDiscardMargin);
2171
2172         // CSS2.1 states:
2173         // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with 
2174         // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
2175         // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
2176         // for a block with height - if none is found then don't allow the margins to collapse with the parent.
2177         bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
2178         for (RenderBox* curr = child->nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
2179             if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
2180                 wouldCollapseMarginsWithParent = false;
2181         }
2182         if (wouldCollapseMarginsWithParent)
2183             marginInfo.setCanCollapseMarginAfterWithChildren(false);
2184
2185         // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
2186         // Move the top of the child box to the bottom of the float ignoring the child's top margin.
2187         LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
2188         setLogicalHeight(child->logicalTop() - collapsedMargin);
2189         // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
2190         heightIncrease -= max(LayoutUnit(), collapsedMargin);
2191     } else
2192         // Increase our height by the amount we had to clear.
2193         setLogicalHeight(logicalHeight() + heightIncrease);
2194     
2195     if (marginInfo.canCollapseWithMarginBefore()) {
2196         // We can no longer collapse with the top of the block since a clear
2197         // occurred.  The empty blocks collapse into the cleared block.
2198         // FIXME: This isn't quite correct.  Need clarification for what to do
2199         // if the height the cleared block is offset by is smaller than the
2200         // margins involved.
2201         setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
2202         marginInfo.setAtBeforeSideOfBlock(false);
2203
2204         // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
2205         setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
2206     }
2207
2208     LayoutUnit logicalTop = yPos + heightIncrease;
2209     // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
2210     // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
2211     if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
2212         toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
2213
2214     return logicalTop;
2215 }
2216
2217 void RenderBlock::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
2218 {
2219     // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
2220     // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
2221     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2222     if ((document()->inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
2223         return;
2224
2225     // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
2226     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2227     if (child->style()->marginBeforeCollapse() == MDISCARD) {
2228         positiveMarginBefore = 0;
2229         negativeMarginBefore = 0;
2230         discardMarginBefore = true;
2231         return;
2232     }
2233
2234     LayoutUnit beforeChildMargin = marginBeforeForChild(child);
2235     positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
2236     negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
2237
2238     if (!child->isRenderBlock())
2239         return;
2240     
2241     RenderBlock* childBlock = toRenderBlock(child);
2242     if (childBlock->childrenInline() || childBlock->isWritingModeRoot())
2243         return;
2244
2245     MarginInfo childMarginInfo(childBlock, childBlock->borderBefore() + childBlock->paddingBefore(), childBlock->borderAfter() + childBlock->paddingAfter());
2246     if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
2247         return;
2248
2249     RenderBox* grandchildBox = childBlock->firstChildBox();
2250     for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
2251         if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
2252             break;
2253     }
2254     
2255     // Give up if there is clearance on the box, since it probably won't collapse into us.
2256     if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
2257         return;
2258
2259     // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
2260     if (grandchildBox->needsLayout()) {
2261         grandchildBox->computeAndSetBlockDirectionMargins(this);
2262         if (grandchildBox->isRenderBlock()) {
2263             RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
2264             grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
2265             grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
2266         }
2267     }
2268
2269     // Collapse the margin of the grandchild box with our own to produce an estimate.
2270     childBlock->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2271 }
2272
2273 LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
2274 {
2275     // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
2276     // relayout if there are intruding floats.
2277     LayoutUnit logicalTopEstimate = logicalHeight();
2278     if (!marginInfo.canCollapseWithMarginBefore()) {
2279         LayoutUnit positiveMarginBefore = 0;
2280         LayoutUnit negativeMarginBefore = 0;
2281         bool discardMarginBefore = false;
2282         if (child->selfNeedsLayout()) {
2283             // Try to do a basic estimation of how the collapse is going to go.
2284             marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2285         } else {
2286             // Use the cached collapsed margin values from a previous layout. Most of the time they
2287             // will be right.
2288             MarginValues marginValues = marginValuesForChild(child);
2289             positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
2290             negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
2291             discardMarginBefore = mustDiscardMarginBeforeForChild(child);
2292         }
2293
2294         // Collapse the result with our current margins.
2295         if (!discardMarginBefore)
2296             logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
2297     }
2298
2299     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
2300     // page.
2301     LayoutState* layoutState = view()->layoutState();
2302     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
2303         && hasNextPage(logicalHeight()))
2304         logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
2305
2306     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
2307     
2308     estimateWithoutPagination = logicalTopEstimate;
2309
2310     if (layoutState->isPaginated()) {
2311         // If the object has a page or column break value of "before", then we should shift to the top of the next page.
2312         logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
2313     
2314         // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
2315         logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
2316         
2317         if (!child->selfNeedsLayout() && child->isRenderBlock())
2318             logicalTopEstimate += toRenderBlock(child)->paginationStrut();
2319     }
2320
2321     return logicalTopEstimate;
2322 }
2323
2324 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart,
2325     RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
2326 {
2327     LayoutUnit startPosition = startOffsetForContent(region, offsetFromLogicalTopOfFirstPage);
2328
2329     // Add in our start margin.
2330     LayoutUnit oldPosition = startPosition + childMarginStart;
2331     LayoutUnit newPosition = oldPosition;
2332
2333     LayoutUnit blockOffset = logicalTopForChild(child);
2334     if (region)
2335         blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage));
2336
2337     LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, offsetFromLogicalTopOfFirstPage, logicalHeightForChild(child));
2338
2339     if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
2340         if (childMarginStart < 0)
2341             startOff += childMarginStart;
2342         newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
2343     } else if (startOff != startPosition)
2344         newPosition = startOff + childMarginStart;
2345
2346     return newPosition - oldPosition;
2347 }
2348
2349 void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode applyDelta)
2350 {
2351     LayoutUnit startPosition = borderStart() + paddingStart();
2352     if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2353         startPosition -= verticalScrollbarWidth();
2354     LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
2355
2356     // Add in our start margin.
2357     LayoutUnit childMarginStart = marginStartForChild(child);
2358     LayoutUnit newPosition = startPosition + childMarginStart;
2359         
2360     // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats.  They need
2361     // to shift over as necessary to dodge any floats that might get in the way.
2362     if (child->avoidsFloats() && containsFloats() && !flowThreadContainingBlock())
2363         newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
2364
2365     setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
2366 }
2367
2368 void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
2369 {
2370     if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
2371         // Update the after side margin of the container to discard if the after margin of the last child also discards and we collapse with it.
2372         // Don't update the max margin values because we won't need them anyway.
2373         if (marginInfo.discardMargin()) {
2374             setMustDiscardMarginAfter();
2375             return;
2376         }
2377
2378         // Update our max pos/neg bottom margins, since we collapsed our bottom margins
2379         // with our children.
2380         setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
2381
2382         if (!marginInfo.hasMarginAfterQuirk())
2383             setHasMarginAfterQuirk(false);
2384
2385         if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
2386             // We have no bottom margin and our last child has a quirky margin.
2387             // We will pick up this quirky margin and pass it through.
2388             // This deals with the <td><div><p> case.
2389             setHasMarginAfterQuirk(true);
2390     }
2391 }
2392
2393 void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
2394 {
2395     marginInfo.setAtAfterSideOfBlock(true);
2396
2397     // If we can't collapse with children then go ahead and add in the bottom margin.
2398     // Don't do this for ordinary anonymous blocks as only the enclosing box should add in
2399     // its margin.
2400     if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
2401         && (!isAnonymousBlock() || isAnonymousColumnsBlock() || isAnonymousColumnSpanBlock())
2402         && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
2403         setLogicalHeight(logicalHeight() + marginInfo.margin());
2404         
2405     // Now add in our bottom border/padding.
2406     setLogicalHeight(logicalHeight() + afterSide);
2407
2408     // Negative margins can cause our height to shrink below our minimal height (border/padding).
2409     // If this happens, ensure that the computed height is increased to the minimal height.
2410     setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
2411
2412     // Update our bottom collapsed margin info.
2413     setCollapsedBottomMargin(marginInfo);
2414 }
2415
2416 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
2417 {
2418     if (isHorizontalWritingMode()) {
2419         if (applyDelta == ApplyLayoutDelta)
2420             view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
2421         child->setX(logicalLeft);
2422     } else {
2423         if (applyDelta == ApplyLayoutDelta)
2424             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
2425         child->setY(logicalLeft);
2426     }
2427 }
2428
2429 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
2430 {
2431     if (isHorizontalWritingMode()) {
2432         if (applyDelta == ApplyLayoutDelta)
2433             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
2434         child->setY(logicalTop);
2435     } else {
2436         if (applyDelta == ApplyLayoutDelta)
2437             view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
2438         child->setX(logicalTop);
2439     }
2440 }
2441
2442 void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox* child)
2443 {
2444     // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
2445     // an auto value. Add a method to determine this, so that we can avoid the relayout.
2446     if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()) || child->hasViewportPercentageLogicalHeight())
2447         child->setChildNeedsLayout(true, MarkOnlyThis);
2448
2449     // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2450     if (relayoutChildren && child->needsPreferredWidthsRecalculation())
2451         child->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2452 }
2453
2454 void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
2455 {
2456     if (gPercentHeightDescendantsMap) {
2457         if (TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this)) {
2458             TrackedRendererListHashSet::iterator end = descendants->end();
2459             for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
2460                 RenderBox* box = *it;
2461                 while (box != this) {
2462                     if (box->normalChildNeedsLayout())
2463                         break;
2464                     box->setChildNeedsLayout(true, MarkOnlyThis);
2465                     box = box->containingBlock();
2466                     ASSERT(box);
2467                     if (!box)
2468                         break;
2469                 }
2470             }
2471         }
2472     }
2473
2474     LayoutUnit beforeEdge = borderBefore() + paddingBefore();
2475     LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
2476
2477     setLogicalHeight(beforeEdge);
2478     
2479     // Lay out our hypothetical grid line as though it occurs at the top of the block.
2480     if (view()->layoutState()->lineGrid() == this)
2481         layoutLineGridBox();
2482
2483     // The margin struct caches all our current margin collapsing state.  The compact struct caches state when we encounter compacts,
2484     MarginInfo marginInfo(this, beforeEdge, afterEdge);
2485
2486     // Fieldsets need to find their legend and position it inside the border of the object.
2487     // The legend then gets skipped during normal layout.  The same is true for ruby text.
2488     // It doesn't get included in the normal layout process but is instead skipped.
2489     RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
2490
2491     LayoutUnit previousFloatLogicalBottom = 0;
2492     maxFloatLogicalBottom = 0;
2493
2494     RenderBox* next = firstChildBox();
2495
2496     while (next) {
2497         RenderBox* child = next;
2498         next = child->nextSiblingBox();
2499
2500         if (childToExclude == child)
2501             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
2502
2503         updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
2504
2505         if (child->isOutOfFlowPositioned()) {
2506             child->containingBlock()->insertPositionedObject(child);
2507             adjustPositionedBlock(child, marginInfo);
2508             continue;
2509         }
2510         if (child->isFloating()) {
2511             insertFloatingObject(child);
2512             adjustFloatingBlock(marginInfo);
2513             continue;
2514         }
2515
2516         // Lay out the child.
2517         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
2518     }
2519     
2520     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
2521     // determining the correct collapsed bottom margin information.
2522     handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
2523 }
2524
2525 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
2526 {
2527     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
2528     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
2529
2530     // The child is a normal flow object.  Compute the margins we will use for collapsing now.
2531     child->computeAndSetBlockDirectionMargins(this);
2532
2533     // Try to guess our correct logical top position.  In most cases this guess will
2534     // be correct.  Only if we're wrong (when we compute the real logical top position)
2535     // will we have to potentially relayout.
2536     LayoutUnit estimateWithoutPagination;
2537     LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
2538
2539     // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
2540     LayoutRect oldRect = child->frameRect();
2541     LayoutUnit oldLogicalTop = logicalTopForChild(child);
2542
2543 #if !ASSERT_DISABLED
2544     LayoutSize oldLayoutDelta = view()->layoutDelta();
2545 #endif
2546     // Go ahead and position the child as though it didn't collapse with the top.
2547     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
2548
2549     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
2550     bool markDescendantsWithFloats = false;
2551     if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
2552         markDescendantsWithFloats = true;
2553     else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
2554         // If an element might be affected by the presence of floats, then always mark it for
2555         // layout.
2556         LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
2557         if (fb > logicalTopEstimate)
2558             markDescendantsWithFloats = true;
2559     }
2560
2561     if (childRenderBlock) {
2562         if (markDescendantsWithFloats)
2563             childRenderBlock->markAllDescendantsWithFloatsForLayout();
2564         if (!child->isWritingModeRoot())
2565             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
2566     }
2567
2568     if (!child->needsLayout())
2569         child->markForPaginationRelayoutIfNeeded();
2570
2571     bool childHadLayout = child->everHadLayout();
2572     bool childNeededLayout = child->needsLayout();
2573     if (childNeededLayout)
2574         child->layout();
2575
2576     // Cache if we are at the top of the block right now.
2577     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
2578
2579     // Now determine the correct ypos based off examination of collapsing margin
2580     // values.
2581     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
2582
2583     // Now check for clear.
2584     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
2585     
2586     bool paginated = view()->layoutState()->isPaginated();
2587     if (paginated)
2588         logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
2589             atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
2590
2591     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
2592
2593     // Now we have a final top position.  See if it really does end up being different from our estimate.
2594     // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
2595     // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
2596     if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
2597         if (child->shrinkToAvoidFloats()) {
2598             // The child's width depends on the line width.
2599             // When the child shifts to clear an item, its width can
2600             // change (because it has more available line width).
2601             // So go ahead and mark the item as dirty.
2602             child->setChildNeedsLayout(true, MarkOnlyThis);
2603         }
2604         
2605         if (childRenderBlock) {
2606             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
2607                 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2608             if (!child->needsLayout())
2609                 child->markForPaginationRelayoutIfNeeded();
2610         }
2611
2612         // Our guess was wrong. Make the child lay itself out again.
2613         child->layoutIfNeeded();
2614     }
2615
2616     // We are no longer at the top of the block if we encounter a non-empty child.  
2617     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
2618     if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
2619         marginInfo.setAtBeforeSideOfBlock(false);
2620
2621     // Now place the child in the correct left position
2622     determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
2623
2624     // Update our height now that the child has been placed in the correct position.
2625     setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
2626     if (mustSeparateMarginAfterForChild(child)) {
2627         setLogicalHeight(logicalHeight() + marginAfterForChild(child));
2628         marginInfo.clearMargin();
2629     }
2630     // If the child has overhanging floats that intrude into following siblings (or possibly out
2631     // of this block), then the parent gets notified of the floats now.
2632     if (childRenderBlock && childRenderBlock->containsFloats())
2633         maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
2634
2635     LayoutSize childOffset = child->location() - oldRect.location();
2636     if (childOffset.width() || childOffset.height()) {
2637         view()->addLayoutDelta(childOffset);
2638
2639         // If the child moved, we have to repaint it as well as any floating/positioned
2640         // descendants.  An exception is if we need a layout.  In this case, we know we're going to
2641         // repaint ourselves (and the child) anyway.
2642         if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
2643             child->repaintDuringLayoutIfMoved(oldRect);
2644     }
2645
2646     if (!childHadLayout && child->checkForRepaintDuringLayout()) {
2647         child->repaint();
2648         child->repaintOverhangingFloats(true);
2649     }
2650
2651     if (paginated) {
2652         // Check for an after page/column break.
2653         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
2654         if (newHeight != height())
2655             setLogicalHeight(newHeight);
2656     }
2657
2658     ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
2659 }
2660
2661 void RenderBlock::simplifiedNormalFlowLayout()
2662 {
2663     if (childrenInline()) {
2664         ListHashSet<RootInlineBox*> lineBoxes;
2665         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
2666             RenderObject* o = walker.current();
2667             if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
2668                 o->layoutIfNeeded();
2669                 if (toRenderBox(o)->inlineBoxWrapper()) {
2670                     RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
2671                     lineBoxes.add(box);
2672                 }
2673             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
2674                 o->setNeedsLayout(false);
2675         }
2676
2677         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
2678         GlyphOverflowAndFallbackFontsMap textBoxDataMap;                  
2679         for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
2680             RootInlineBox* box = *it;
2681             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
2682         }
2683     } else {
2684         for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
2685             if (!box->isOutOfFlowPositioned())
2686                 box->layoutIfNeeded();
2687         }
2688     }
2689 }
2690
2691 bool RenderBlock::simplifiedLayout()
2692 {
2693     if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
2694         return false;
2695
2696     LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
2697     
2698     if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
2699         return false;
2700
2701     // Lay out positioned descendants or objects that just need to recompute overflow.
2702     if (needsSimplifiedNormalFlowLayout())
2703         simplifiedNormalFlowLayout();
2704
2705     // Lay out our positioned objects if our positioned child bit is set.
2706     // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
2707     // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the 
2708     // relative positioned container. So if we can have fixed pos objects in our positioned objects list check if any of them
2709     // are statically positioned and thus need to move with their absolute ancestors.
2710     bool canContainFixedPosObjects = canContainFixedPositionObjects();
2711     if (posChildNeedsLayout() || canContainFixedPosObjects)
2712         layoutPositionedObjects(false, !posChildNeedsLayout() && canContainFixedPosObjects);
2713
2714     // Recompute our overflow information.
2715     // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
2716     // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
2717     // For now just always recompute overflow.  This is no worse performance-wise than the old code that called rightmostPosition and
2718     // lowestPosition on every relayout so it's not a regression.
2719     // computeOverflow expects the bottom edge before we clamp our height. Since this information isn't available during
2720     // simplifiedLayout, we cache the value in m_overflow.
2721     LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
2722     computeOverflow(oldClientAfterEdge, true);
2723
2724     statePusher.pop();
2725     
2726     updateLayerTransform();
2727
2728     updateScrollInfoAfterLayout();
2729
2730     setNeedsLayout(false);
2731     return true;
2732 }
2733
2734 void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child)
2735 {
2736     if (child->style()->position() != FixedPosition)
2737         return;
2738
2739     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode());
2740     bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode());
2741     if (!hasStaticBlockPosition && !hasStaticInlinePosition)
2742         return;
2743
2744     RenderObject* o = child->parent();
2745     while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition)
2746         o = o->parent();
2747     if (o->style()->position() != AbsolutePosition)
2748         return;
2749
2750     RenderBox* box = toRenderBox(child);
2751     if (hasStaticInlinePosition) {
2752         LayoutUnit oldLeft = box->logicalLeft();
2753         box->updateLogicalWidth();
2754         if (box->logicalLeft() != oldLeft)
2755             child->setChildNeedsLayout(true, MarkOnlyThis);
2756     } else if (hasStaticBlockPosition) {
2757         LayoutUnit oldTop = box->logicalTop();
2758         box->updateLogicalHeight();
2759         if (box->logicalTop() != oldTop)
2760             child->setChildNeedsLayout(true, MarkOnlyThis);
2761     }
2762 }
2763
2764 void RenderBlock::layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly)
2765 {
2766     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2767     if (!positionedDescendants)
2768         return;
2769         
2770     if (hasColumns())
2771         view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
2772
2773     RenderBox* r;
2774     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2775     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2776         r = *it;
2777
2778         // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
2779         // if this is a fixed position element, mark it for layout if it has an abspos ancestor and needs to move with that ancestor, i.e. 
2780         // it has static position.
2781         markFixedPositionObjectForLayoutIfNeeded(r);
2782         if (fixedPositionObjectsOnly) {
2783             r->layoutIfNeeded();
2784             continue;
2785         }
2786
2787         // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
2788         // non-positioned block.  Rather than trying to detect all of these movement cases, we just always lay out positioned
2789         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
2790         // positioned explicitly) this should not incur a performance penalty.
2791         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
2792             r->setChildNeedsLayout(true, MarkOnlyThis);
2793             
2794         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2795         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
2796             r->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2797         
2798         if (!r->needsLayout())
2799             r->markForPaginationRelayoutIfNeeded();
2800         
2801         // We don't have to do a full layout.  We just have to update our position. Try that first. If we have shrink-to-fit width
2802         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
2803         if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
2804             r->setNeedsLayout(false);
2805             
2806         // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
2807         // If it's wrong we'll lay out again.
2808         LayoutUnit oldLogicalTop = 0;
2809         bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout(); 
2810         if (needsBlockDirectionLocationSetBeforeLayout) {
2811             if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
2812                 r->updateLogicalHeight();
2813             else
2814                 r->updateLogicalWidth();
2815             oldLogicalTop = logicalTopForChild(r);
2816         }
2817         
2818         r->layoutIfNeeded();
2819
2820         // Lay out again if our estimate was wrong.
2821         if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
2822             r->setChildNeedsLayout(true, MarkOnlyThis);
2823             r->layoutIfNeeded();
2824         }
2825     }
2826     
2827     if (hasColumns())
2828         view()->layoutState()->m_columnInfo = columnInfo(); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
2829 }
2830
2831 void RenderBlock::markPositionedObjectsForLayout()
2832 {
2833     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2834     if (positionedDescendants) {
2835         RenderBox* r;
2836         TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2837         for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2838             r = *it;
2839             r->setChildNeedsLayout(true);
2840         }
2841     }
2842 }
2843
2844 void RenderBlock::markForPaginationRelayoutIfNeeded()
2845 {
2846     ASSERT(!needsLayout());
2847     if (needsLayout())
2848         return;
2849
2850     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()) || shouldBreakAtLineToAvoidWidow())
2851         setChildNeedsLayout(true, MarkOnlyThis);
2852 }
2853
2854 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
2855 {
2856     // Repaint any overhanging floats (if we know we're the one to paint them).
2857     // Otherwise, bail out.
2858     if (!hasOverhangingFloats())
2859         return;
2860
2861     // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2862     // in this block. Better yet would be to push extra state for the containers of other floats.
2863     LayoutStateDisabler layoutStateDisabler(view());
2864     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2865     FloatingObjectSetIterator end = floatingObjectSet.end();
2866     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2867         FloatingObject* r = *it;
2868         // Only repaint the object if it is overhanging, is not in its own layer, and
2869         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2870         // condition is replaced with being a descendant of us.
2871         if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->shouldPaint()) && !r->m_renderer->hasSelfPaintingLayer()) {
2872             r->m_renderer->repaint();
2873             r->m_renderer->repaintOverhangingFloats(false);
2874         }
2875     }
2876 }
2877  
2878 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2879 {
2880     LayoutPoint adjustedPaintOffset = paintOffset + location();
2881     
2882     PaintPhase phase = paintInfo.phase;
2883
2884     // Check if we need to do anything at all.
2885     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
2886     // paints the root's background.
2887     if (!isRoot()) {
2888         LayoutRect overflowBox = overflowRectForPaintRejection();
2889         flipForWritingMode(overflowBox);
2890         overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
2891         overflowBox.moveBy(adjustedPaintOffset);
2892         if (!overflowBox.intersects(paintInfo.rect))
2893             return;
2894     }
2895
2896     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
2897     paintObject(paintInfo, adjustedPaintOffset);
2898     if (pushedClip)
2899         popContentsClip(paintInfo, phase, adjustedPaintOffset);
2900
2901     // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
2902     // z-index.  We paint after we painted the background/border, so that the scrollbars will
2903     // sit above the background/border.
2904     if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this) && !paintInfo.paintRootBackgroundOnly())
2905         layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
2906 }
2907
2908 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2909 {
2910     if (paintInfo.context->paintingDisabled())
2911         return;
2912
2913     const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
2914     bool ruleTransparent = style()->columnRuleIsTransparent();
2915     EBorderStyle ruleStyle = style()->columnRuleStyle();
2916     LayoutUnit ruleThickness = style()->columnRuleWidth();
2917     LayoutUnit colGap = columnGap();
2918     bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent;
2919     if (!renderRule)
2920         return;
2921
2922     ColumnInfo* colInfo = columnInfo();
2923     unsigned colCount = columnCount(colInfo);
2924
2925     bool antialias = shouldAntialiasLines(paintInfo.context);
2926
2927     if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
2928         bool leftToRight = style()->isLeftToRightDirection() ^ colInfo->progressionIsReversed();
2929         LayoutUnit currLogicalLeftOffset = leftToRight ? LayoutUnit() : contentLogicalWidth();
2930         LayoutUnit ruleAdd = logicalLeftOffsetForContent();
2931         LayoutUnit ruleLogicalLeft = leftToRight ? LayoutUnit() : contentLogicalWidth();
2932         LayoutUnit inlineDirectionSize = colInfo->desiredColumnWidth();
2933         BoxSide boxSide = isHorizontalWritingMode()
2934             ? leftToRight ? BSLeft : BSRight
2935             : leftToRight ? BSTop : BSBottom;
2936
2937         for (unsigned i = 0; i < colCount; i++) {
2938             // Move to the next position.
2939             if (leftToRight) {
2940                 ruleLogicalLeft += inlineDirectionSize + colGap / 2;
2941                 currLogicalLeftOffset += inlineDirectionSize + colGap;
2942             } else {
2943                 ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
2944                 currLogicalLeftOffset -= (inlineDirectionSize + colGap);
2945             }
2946            
2947             // Now paint the column rule.
2948             if (i < colCount - 1) {
2949                 LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd : paintOffset.x() + borderLeft() + paddingLeft();
2950                 LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleThickness : ruleLeft + contentWidth();
2951                 LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd;
2952                 LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleThickness;
2953                 IntRect pixelSnappedRuleRect = pixelSnappedIntRectFromEdges(ruleLeft, ruleTop, ruleRight, ruleBottom);
2954                 drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
2955             }
2956             
2957             ruleLogicalLeft = currLogicalLeftOffset;
2958         }
2959     } else {
2960         bool topToBottom = !style()->isFlippedBlocksWritingMode() ^ colInfo->progressionIsReversed();
2961         LayoutUnit ruleLeft = isHorizontalWritingMode()
2962             ? borderLeft() + paddingLeft()
2963             : colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter());
2964         LayoutUnit ruleWidth = isHorizontalWritingMode() ? contentWidth() : ruleThickness;
2965         LayoutUnit ruleTop = isHorizontalWritingMode()
2966             ? colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter())
2967             : borderStart() + paddingStart();
2968         LayoutUnit ruleHeight = isHorizontalWritingMode() ? ruleThickness : contentHeight();
2969         LayoutRect ruleRect(ruleLeft, ruleTop, ruleWidth, ruleHeight);
2970
2971         if (!topToBottom) {
2972             if (isHorizontalWritingMode())
2973                 ruleRect.setY(height() - ruleRect.maxY());
2974             else
2975                 ruleRect.setX(width() - ruleRect.maxX());
2976         }
2977
2978         ruleRect.moveBy(paintOffset);
2979
2980         BoxSide boxSide = isHorizontalWritingMode()
2981             ? topToBottom ? BSTop : BSBottom
2982             : topToBottom ? BSLeft : BSRight;
2983
2984         LayoutSize step(0, topToBottom ? colInfo->columnHeight() + colGap : -(colInfo->columnHeight() + colGap));
2985         if (!isHorizontalWritingMode())
2986             step = step.transposedSize();
2987
2988         for (unsigned i = 1; i < colCount; i++) {
2989             ruleRect.move(step);
2990             IntRect pixelSnappedRuleRect = pixelSnappedIntRect(ruleRect);
2991             drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
2992         }
2993     }
2994 }
2995
2996 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
2997 {
2998     // We need to do multiple passes, breaking up our child painting into strips.
2999     GraphicsContext* context = paintInfo.context;
3000     ColumnInfo* colInfo = columnInfo();
3001     unsigned colCount = columnCount(colInfo);
3002     if (!colCount)
3003         return;
3004     LayoutUnit currLogicalTopOffset = 0;
3005     LayoutUnit colGap = columnGap();
3006     for (unsigned i = 0; i < colCount; i++) {
3007         // For each rect, we clip to the rect, and then we adjust our coords.
3008         LayoutRect colRect = columnRectAt(colInfo, i);
3009         flipForWritingMode(colRect);
3010         LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
3011         LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
3012         if (colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
3013             if (isHorizontalWritingMode())
3014                 offset.expand(0, colRect.y() - borderTop() - paddingTop());
3015             else
3016                 offset.expand(colRect.x() - borderLeft() - paddingLeft(), 0);
3017         }
3018         colRect.moveBy(paintOffset);
3019         PaintInfo info(paintInfo);
3020         info.rect.intersect(pixelSnappedIntRect(colRect));
3021         
3022         if (!info.rect.isEmpty()) {
3023             GraphicsContextStateSaver stateSaver(*context);
3024             LayoutRect clipRect(colRect);
3025             
3026             if (i < colCount - 1) {
3027                 if (isHorizontalWritingMode())
3028                     clipRect.expand(colGap / 2, 0);
3029                 else
3030                     clipRect.expand(0, colGap / 2);
3031             }
3032             // Each strip pushes a clip, since column boxes are specified as being
3033             // like overflow:hidden.
3034             // FIXME: Content and column rules that extend outside column boxes at the edges of the multi-column element
3035             // are clipped according to the 'overflow' property.
3036             context->clip(pixelSnappedIntRect(clipRect));
3037
3038             // Adjust our x and y when painting.
3039             LayoutPoint adjustedPaintOffset = paintOffset + offset;
3040             if (paintingFloats)
3041                 paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
3042             else
3043                 paintContents(info, adjustedPaintOffset);
3044         }
3045
3046         LayoutUnit blockDelta = (isHorizontalWritingMode() ? colRect.height() : colRect.width());
3047         if (style()->isFlippedBlocksWritingMode())
3048             currLogicalTopOffset += blockDelta;
3049         else
3050             currLogicalTopOffset -= blockDelta;
3051     }
3052 }
3053
3054 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3055 {
3056     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
3057     // It's ok not to draw, because later on, when all the stylesheets do load, styleResolverChanged() on the Document
3058     // will do a full repaint.
3059     if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
3060         return;
3061
3062     if (childrenInline())
3063         m_lineBoxes.paint(this, paintInfo, paintOffset);
3064     else {
3065         PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
3066         newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
3067
3068         // We don't paint our own background, but we do let the kids paint their backgrounds.
3069         PaintInfo paintInfoForChild(paintInfo);
3070         paintInfoForChild.phase = newPhase;
3071         paintInfoForChild.updatePaintingRootForChildren(this);
3072
3073         // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
3074         // NSViews. Do not add any more code for this.
3075         bool usePrintRect = !view()->printRect().isEmpty();
3076         paintChildren(paintInfo, paintOffset, paintInfoForChild, usePrintRect);
3077     }
3078 }
3079
3080 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3081 {
3082     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
3083         if (!paintChild(child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
3084             return;
3085     }
3086 }
3087
3088 bool RenderBlock::paintChild(RenderBox* child, PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3089 {
3090     // Check for page-break-before: always, and if it's set, break and bail.
3091     bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
3092     LayoutUnit absoluteChildY = paintOffset.y() + child->y();
3093     if (checkBeforeAlways
3094         && absoluteChildY > paintInfo.rect.y()
3095         && absoluteChildY < paintInfo.rect.maxY()) {
3096         view()->setBestTruncatedAt(absoluteChildY, this, true);
3097         return false;
3098     }
3099
3100     RenderView* renderView = view();
3101     if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
3102         // Paginate block-level replaced elements.
3103         if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
3104             if (absoluteChildY < renderView->truncatedAt())
3105                 renderView->setBestTruncatedAt(absoluteChildY, child);
3106             // If we were able to truncate, don't paint.
3107             if (absoluteChildY >= renderView->truncatedAt())
3108                 return false;
3109         }
3110     }
3111
3112     LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
3113     if (!child->hasSelfPaintingLayer() && !child->isFloating())
3114         child->paint(paintInfoForChild, childPoint);
3115
3116     // Check for page-break-after: always, and if it's set, break and bail.
3117     bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
3118     if (checkAfterAlways
3119         && (absoluteChildY + child->height()) > paintInfo.rect.y()
3120         && (absoluteChildY + child->height()) < paintInfo.rect.maxY()) {
3121         view()->setBestTruncatedAt(absoluteChildY + child->height() + max<LayoutUnit>(0, child->collapsedMarginAfter()), this, true);
3122         return false;
3123     }
3124     return true;
3125 }
3126
3127
3128 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
3129 {
3130     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
3131     bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
3132     RenderObject* caretPainter;
3133     bool isContentEditable;
3134     if (type == CursorCaret) {
3135         caretPainter = frame()->selection()->caretRenderer();
3136         isContentEditable = frame()->selection()->rendererIsEditable();
3137     } else {
3138         caretPainter = frame()->page()->dragCaretController()->caretRenderer();
3139         isContentEditable = frame()->page()->dragCaretController()->isContentEditable();
3140     }
3141
3142     if (caretPainter == this && (isContentEditable || caretBrowsing)) {
3143         if (type == CursorCaret)
3144             frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
3145         else
3146             frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
3147     }
3148 }
3149
3150 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3151 {
3152     PaintPhase paintPhase = paintInfo.phase;
3153
3154     // 1. paint background, borders etc
3155     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
3156         if (hasBoxDecorations())
3157             paintBoxDecorations(paintInfo, paintOffset);
3158         if (hasColumns() && !paintInfo.paintRootBackgroundOnly())
3159             paintColumnRules(paintInfo, paintOffset);
3160     }
3161
3162     if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
3163         paintMask(paintInfo, paintOffset);
3164         return;
3165     }
3166
3167     // We're done.  We don't bother painting any children.
3168     if (paintPhase == PaintPhaseBlockBackground || paintInfo.paintRootBackgroundOnly())
3169         return;
3170
3171     // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
3172     LayoutPoint scrolledOffset = paintOffset;
3173     if (hasOverflowClip())
3174         scrolledOffset.move(-scrolledContentOffset());
3175
3176     // 2. paint contents
3177     if (paintPhase != PaintPhaseSelfOutline) {
3178         if (hasColumns())
3179             paintColumnContents(paintInfo, scrolledOffset);
3180         else
3181             paintContents(paintInfo, scrolledOffset);
3182     }
3183
3184     // 3. paint selection
3185     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
3186     bool isPrinting = document()->printing();
3187     if (!isPrinting && !hasColumns())
3188         paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
3189
3190     // 4. paint floats.
3191     if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
3192         if (hasColumns())
3193             paintColumnContents(paintInfo, scrolledOffset, true);
3194         else
3195             paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
3196     }
3197
3198     // 5. paint outline.
3199     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
3200         paintOutline(paintInfo, LayoutRect(paintOffset, size()));
3201
3202     // 6. paint continuation outlines.
3203     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
3204         RenderInline* inlineCont = inlineElementContinuation();
3205         if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE) {
3206             RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->renderer());
3207             RenderBlock* cb = containingBlock();
3208
3209             bool inlineEnclosedInSelfPaintingLayer = false;
3210             for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = box->parent()->enclosingBoxModelObject()) {
3211                 if (box->hasSelfPaintingLayer()) {
3212                     inlineEnclosedInSelfPaintingLayer = true;
3213                     break;
3214                 }
3215             }
3216
3217             // Do not add continuations for outline painting by our containing block if we are a relative positioned
3218             // anonymous block (i.e. have our own layer), paint them straightaway instead. This is because a block depends on renderers in its continuation table being
3219             // in the same layer. 
3220             if (!inlineEnclosedInSelfPaintingLayer && !hasLayer())
3221                 cb->addContinuationWithOutline(inlineRenderer);
3222             else if (!inlineRenderer->firstLineBox() || (!inlineEnclosedInSelfPaintingLayer && hasLayer()))
3223                 inlineRenderer->paintOutline(paintInfo, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
3224         }
3225         paintContinuationOutlines(paintInfo, paintOffset);
3226     }
3227
3228     // 7. paint caret.
3229     // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
3230     // then paint the caret.
3231     if (paintPhase == PaintPhaseForeground) {        
3232         paintCaret(paintInfo, paintOffset, CursorCaret);
3233         paintCaret(paintInfo, paintOffset, DragCaret);
3234     }
3235 }
3236
3237 LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
3238 {
3239     if (!style()->isFlippedBlocksWritingMode())
3240         return point;
3241     
3242     // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
3243     // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
3244     // case.
3245     if (isHorizontalWritingMode())
3246         return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
3247     return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
3248 }
3249
3250 void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
3251 {
3252     if (!m_floatingObjects)
3253         return;
3254
3255     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3256     FloatingObjectSetIterator end = floatingObjectSet.end();
3257     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
3258         FloatingObject* r = *it;
3259         // Only paint the object if our m_shouldPaint flag is set.
3260         if (r->shouldPaint() && !r->m_renderer->hasSelfPaintingLayer()) {
3261             PaintInfo currentPaintInfo(paintInfo);
3262             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
3263             LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->m_renderer->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->m_renderer->y()));
3264             r->m_renderer->paint(currentPaintInfo, childPoint);
3265             if (!preservePhase) {
3266                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
3267                 r->m_renderer->paint(currentPaintInfo, childPoint);
3268                 currentPaintInfo.phase = PaintPhaseFloat;
3269                 r->m_renderer->paint(currentPaintInfo, childPoint);
3270                 currentPaintInfo.phase = PaintPhaseForeground;
3271                 r->m_renderer->paint(currentPaintInfo, childPoint);
3272                 currentPaintInfo.phase = PaintPhaseOutline;
3273                 r->m_renderer->paint(currentPaintInfo, childPoint);
3274             }
3275         }
3276     }
3277 }
3278
3279 RenderInline* RenderBlock::inlineElementContinuation() const
3280
3281     RenderBoxModelObject* continuation = this->continuation();
3282     return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
3283 }
3284
3285 RenderBlock* RenderBlock::blockElementContinuation() const
3286 {
3287     RenderBoxModelObject* currentContinuation = continuation();
3288     if (!currentContinuation || currentContinuation->isInline())
3289         return 0;
3290     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
3291     if (nextContinuation->isAnonymousBlock())
3292         return nextContinuation->blockElementContinuation();
3293     return nextContinuation;
3294 }
3295     
3296 static ContinuationOutlineTableMap* continuationOutlineTable()
3297 {
3298     DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
3299     return &table;
3300 }
3301
3302 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
3303 {
3304     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
3305     // way of painting.
3306     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
3307     
3308     ContinuationOutlineTableMap* table = continuationOutlineTable();
3309     ListHashSet<RenderInline*>* continuations = table->get(this);
3310     if (!continuations) {
3311         continuations = new ListHashSet<RenderInline*>;
3312         table->set(this, adoptPtr(continuations));
3313     }
3314     
3315     continuations->add(flow);
3316 }
3317
3318 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
3319 {
3320     ContinuationOutlineTableMap* table = continuationOutlineTable();
3321     if (table->isEmpty())
3322         return false;
3323         
3324     ListHashSet<RenderInline*>* continuations = table->get(this);
3325     if (!continuations)
3326         return false;
3327
3328     return continuations->contains(flow);
3329 }
3330
3331 void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
3332 {
3333     ContinuationOutlineTableMap* table = continuationOutlineTable();
3334     if (table->isEmpty())
3335         return;
3336         
3337     OwnPtr<ListHashSet<RenderInline*> > continuations = table->take(this);
3338     if (!continuations)
3339         return;
3340
3341     LayoutPoint accumulatedPaintOffset = paintOffset;
3342     // Paint each continuation outline.
3343     ListHashSet<RenderInline*>::iterator end = continuations->end();
3344     for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
3345         // Need to add in the coordinates of the intervening blocks.
3346         RenderInline* flow = *it;
3347         RenderBlock* block = flow->containingBlock();
3348         for ( ; block && block != this; block = block->containingBlock())
3349             accumulatedPaintOffset.moveBy(block->location());
3350         ASSERT(block);   
3351         flow->paintOutline(info, accumulatedPaintOffset);
3352     }
3353 }
3354
3355 bool RenderBlock::shouldPaintSelectionGaps() const
3356 {
3357     return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
3358 }
3359
3360 bool RenderBlock::isSelectionRoot() const
3361 {
3362     if (isPseudoElement())
3363         return false;
3364     ASSERT(node() || isAnonymous());
3365         
3366     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
3367     if (isTable())
3368         return false;
3369         
3370     if (isBody() || isRoot() || hasOverflowClip()
3371         || isPositioned() || isFloating()
3372         || isTableCell() || isInlineBlockOrInlineTable()
3373         || hasTransform() || hasReflection() || hasMask() || isWritingModeRoot()
3374         || isRenderFlowThread())
3375         return true;
3376     
3377     if (view() && view()->selectionStart()) {
3378         Node* startElement = view()->selectionStart()->node();
3379         if (startElement && startElement->rootEditableElement() == node())
3380             return true;
3381     }
3382     
3383     return false;
3384 }
3385
3386 GapRects RenderBlock::selectionGapRectsForRepaint(const RenderLayerModelObject* repaintContainer)
3387 {
3388     ASSERT(!needsLayout());
3389
3390     if (!shouldPaintSelectionGaps())
3391         return GapRects();
3392
3393     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
3394     mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip | UseTransforms);
3395     LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint());
3396
3397     if (hasOverflowClip())
3398         offsetFromRepaintContainer -= scrolledContentOffset();
3399
3400     LayoutUnit lastTop = 0;
3401     LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
3402     LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
3403     
3404     return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight);
3405 }
3406
3407 void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3408 {
3409     if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
3410         LayoutUnit lastTop = 0;
3411         LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
3412         LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
3413         GraphicsContextStateSaver stateSaver(*paintInfo.context);
3414
3415         LayoutRect gapRectsBounds = selectionGaps(this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, &paintInfo);
3416         if (!gapRectsBounds.isEmpty()) {
3417             if (RenderLayer* layer = enclosingLayer()) {
3418                 gapRectsBounds.moveBy(-paintOffset);
3419                 if (!hasLayer()) {
3420                     LayoutRect localBounds(gapRectsBounds);
3421                     flipForWritingMode(localBounds);
3422                     gapRectsBounds = localToContainerQuad(FloatRect(localBounds), layer->renderer()).enclosingBoundingBox();
3423                     if (layer->renderer()->hasOverflowClip())
3424                         gapRectsBounds.move(layer->renderBox()->scrolledContentOffset());
3425                 }
3426                 layer->addBlockSelectionGapsBounds(gapRectsBounds);
3427             }
3428         }
3429     }
3430 }
3431
3432 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, TrackedRendererListHashSet* positionedObjects)
3433 {
3434     if (!positionedObjects)
3435         return;
3436     
3437     TrackedRendererListHashSet::const_iterator end = positionedObjects->end();
3438     for (TrackedRendererListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
3439         RenderBox* r = *it;
3440         paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
3441     }
3442 }
3443
3444 static LayoutUnit blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3445 {
3446     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
3447 }
3448
3449 static LayoutUnit inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3450 {
3451     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
3452 }
3453
3454 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
3455 {
3456     LayoutRect result;
3457     if (isHorizontalWritingMode())
3458         result = logicalRect;
3459     else
3460         result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
3461     flipForWritingMode(result);
3462     result.moveBy(rootBlockPhysicalPosition);
3463     return result;
3464 }
3465
3466 GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3467                                     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
3468 {
3469     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
3470     // Clip out floating and positioned objects when painting selection gaps.
3471     if (paintInfo) {
3472         // Note that we don't clip out overflow for positioned objects.  We just stick to the border box.
3473         LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
3474         rootBlock->flipForWritingMode(flippedBlockRect);
3475         flippedBlockRect.moveBy(rootBlockPhysicalPosition);
3476         clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), positionedObjects());
3477         if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
3478             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
3479                 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
3480         if (m_floatingObjects) {
3481             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3482             FloatingObjectSetIterator end = floatingObjectSet.end();
3483             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
3484                 FloatingObject* r = *it;
3485                 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
3486                                     offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
3487                                     r->m_renderer->width(), r->m_renderer->height());
3488                 rootBlock->flipForWritingMode(floatBox);
3489                 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
3490                 paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
3491             }
3492         }
3493     }
3494
3495     // FIXME: overflow: auto/scroll regions need more math here, since painting in the border box is different from painting in the padding box (one is scrolled, the other is
3496     // fixed).
3497     GapRects result;
3498     if (!isBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
3499         return result;
3500
3501     if (hasColumns() || hasTransform() || style()->columnSpan()) {
3502         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
3503         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3504         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
3505         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
3506         return result;
3507     }
3508
3509     if (childrenInline())
3510         result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
3511     else
3512         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
3513
3514     // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
3515     if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
3516         result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
3517                                              logicalHeight(), paintInfo));
3518     return result;
3519 }
3520
3521 GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3522                                           LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
3523 {
3524     GapRects result;
3525
3526     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
3527
3528     if (!firstLineBox()) {
3529         if (containsStart) {
3530             // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
3531             // case.
3532             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3533             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
3534             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
3535         }
3536         return result;
3537     }
3538
3539     RootInlineBox* lastSelectedLine = 0;
3540     RootInlineBox* curr;
3541     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
3542
3543     // Now paint the gaps for the lines.
3544     for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
3545         LayoutUnit selTop =  curr->selectionTopAdjustedForPrecedingBlock();
3546         LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
3547
3548         if (!containsStart && !lastSelectedLine &&
3549             selectionState() != SelectionStart && selectionState() != SelectionBoth)
3550             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
3551                                                  selTop, paintInfo));
3552         
3553         LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
3554         logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
3555         LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
3556         if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
3557             || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
3558             result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
3559
3560         lastSelectedLine = curr;
3561     }
3562
3563     if (containsStart && !lastSelectedLine)
3564         // VisibleSelection must start just after our last line.
3565         lastSelectedLine = lastRootBox();
3566
3567     if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
3568         // Go ahead and update our lastY to be the bottom of the last selected line.
3569         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
3570         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
3571         lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
3572     }
3573     return result;
3574 }
3575
3576 GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3577                                          LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
3578 {
3579     GapRects result;
3580
3581     // Go ahead and jump right to the first block child that contains some selected objects.
3582     RenderBox* curr;
3583     for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
3584
3585     for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
3586         SelectionState childState = curr->selectionState();
3587         if (childState == SelectionBoth || childState == SelectionEnd)
3588             sawSelectionEnd = true;
3589
3590         if (curr->isFloatingOrOutOfFlowPositioned())
3591             continue; // We must be a normal flow object in order to even be considered.
3592
3593         if (curr->hasPaintOffset() && curr->hasLayer()) {
3594             // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
3595             // Just disregard it completely.
3596             LayoutSize relOffset = curr->layer()->paintOffset();
3597             if (relOffset.width() || relOffset.height())
3598                 continue;
3599         }
3600
3601         bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
3602         bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
3603         if (fillBlockGaps) {
3604             // We need to fill the vertical gap above this object.
3605             if (childState == SelectionEnd || childState == SelectionInside)
3606                 // Fill the gap above the object.
3607                 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
3608                                                      curr->logicalTop(), paintInfo));
3609
3610             // Only fill side gaps for objects that paint their own selection if we know for sure the selection is going to extend all the way *past*
3611             // our object.  We know this if the selection did not end inside our object.
3612             if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
3613                 childState = SelectionNone;
3614
3615             // Fill side gaps on this object based off its state.
3616             bool leftGap, rightGap;
3617             getSelectionGapInfo(childState, leftGap, rightGap);
3618
3619             if (leftGap)
3620                 result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
3621             if (rightGap)
3622                 result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
3623
3624             // Update lastLogicalTop to be just underneath the object.  lastLogicalLeft and lastLogicalRight extend as far as
3625             // they can without bumping into floating or positioned objects.  Ideally they will go right up
3626             // to the border of the root selection block.
3627             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
3628             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
3629             lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
3630         } else if (childState != SelectionNone)
3631             // We must be a block that has some selected object inside it.  Go ahead and recur.
3632             result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()), 
3633                                                             lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo));
3634     }
3635     return result;
3636 }
3637
3638 LayoutRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3639                                           LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo)
3640 {
3641     LayoutUnit logicalTop = lastLogicalTop;
3642     LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
3643     if (logicalHeight <= 0)
3644         return LayoutRect();
3645
3646     // Get the selection offsets for the bottom of the gap
3647     LayoutUnit logicalLeft = max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
3648     LayoutUnit logicalRight = min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
3649     LayoutUnit logicalWidth = logicalRight - logicalLeft;
3650     if (logicalWidth <= 0)
3651         return LayoutRect();
3652
3653     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
3654     if (paintInfo)
3655         paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selectionBackgroundColor(), style()->colorSpace());
3656     return gapRect;
3657 }
3658
3659 LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3660                                                 RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
3661 {
3662     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
3663     LayoutUnit rootBlockLogicalLeft = max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
3664     LayoutUnit rootBlockLogicalRight = min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + floorToInt(logicalLeft), min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
3665     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
3666     if (rootBlockLogicalWidth <= 0)
3667         return LayoutRect();
3668
3669     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
3670     if (paintInfo)
3671         paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
3672     return gapRect;
3673 }
3674
3675 LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3676                                                  RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
3677 {
3678     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
3679     LayoutUnit rootBlockLogicalLeft = max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + floorToInt(logicalRight), max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
3680     LayoutUnit rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
3681     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
3682     if (rootBlockLogicalWidth <= 0)
3683         return LayoutRect();
3684
3685     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
3686     if (paintInfo)
3687         paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
3688     return gapRect;
3689 }
3690
3691 void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap)
3692 {
3693     bool ltr = style()->isLeftToRightDirection();
3694     leftGap = (state == RenderObject::SelectionInside) ||
3695               (state == RenderObject::SelectionEnd && ltr) ||
3696               (state == RenderObject::SelectionStart && !ltr);
3697     rightGap = (state == RenderObject::SelectionInside) ||
3698                (state == RenderObject::SelectionStart && ltr) ||
3699                (state == RenderObject::SelectionEnd && !ltr);
3700 }
3701
3702 LayoutUnit RenderBlock::logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
3703 {
3704     LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
3705     if (logicalLeft == logicalLeftOffsetForContent()) {
3706         if (rootBlock != this)
3707             // The border can potentially be further extended by our containingBlock().
3708             return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
3709         return logicalLeft;
3710     } else {
3711         RenderBlock* cb = this;
3712         while (cb != rootBlock) {
3713             logicalLeft += cb->logicalLeft();
3714