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