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