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