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