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