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