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