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