Child not placed correctly when beforeChild (table part)
[WebKit.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::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
1864 {
1865     if (isHorizontalWritingMode()) {
1866         if (applyDelta == ApplyLayoutDelta)
1867             view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
1868         child->setX(logicalLeft);
1869     } else {
1870         if (applyDelta == ApplyLayoutDelta)
1871             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
1872         child->setY(logicalLeft);
1873     }
1874 }
1875
1876 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
1877 {
1878     if (isHorizontalWritingMode()) {
1879         if (applyDelta == ApplyLayoutDelta)
1880             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
1881         child->setY(logicalTop);
1882     } else {
1883         if (applyDelta == ApplyLayoutDelta)
1884             view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
1885         child->setX(logicalTop);
1886     }
1887 }
1888
1889 void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
1890 {
1891     if (gPercentHeightDescendantsMap) {
1892         if (HashSet<RenderBox*>* descendants = gPercentHeightDescendantsMap->get(this)) {
1893             HashSet<RenderBox*>::iterator end = descendants->end();
1894             for (HashSet<RenderBox*>::iterator it = descendants->begin(); it != end; ++it) {
1895                 RenderBox* box = *it;
1896                 while (box != this) {
1897                     if (box->normalChildNeedsLayout())
1898                         break;
1899                     box->setChildNeedsLayout(true, false);
1900                     box = box->containingBlock();
1901                     ASSERT(box);
1902                     if (!box)
1903                         break;
1904                 }
1905             }
1906         }
1907     }
1908
1909     LayoutUnit beforeEdge = borderBefore() + paddingBefore();
1910     LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
1911
1912     setLogicalHeight(beforeEdge);
1913
1914     // The margin struct caches all our current margin collapsing state.  The compact struct caches state when we encounter compacts,
1915     MarginInfo marginInfo(this, beforeEdge, afterEdge);
1916
1917     // Fieldsets need to find their legend and position it inside the border of the object.
1918     // The legend then gets skipped during normal layout.  The same is true for ruby text.
1919     // It doesn't get included in the normal layout process but is instead skipped.
1920     RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
1921
1922     LayoutUnit previousFloatLogicalBottom = 0;
1923     maxFloatLogicalBottom = 0;
1924
1925     RenderBox* next = firstChildBox();
1926
1927     while (next) {
1928         RenderBox* child = next;
1929         next = child->nextSiblingBox();
1930
1931         if (childToExclude == child)
1932             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
1933
1934         // Make sure we layout children if they need it.
1935         // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
1936         // an auto value.  Add a method to determine this, so that we can avoid the relayout.
1937         if (relayoutChildren || ((child->style()->logicalHeight().isPercent() || child->style()->logicalMinHeight().isPercent() || child->style()->logicalMaxHeight().isPercent()) && !isRenderView()))
1938             child->setChildNeedsLayout(true, false);
1939
1940         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1941         if (relayoutChildren && child->needsPreferredWidthsRecalculation())
1942             child->setPreferredLogicalWidthsDirty(true, false);
1943
1944         // Handle the four types of special elements first.  These include positioned content, floating content, compacts and
1945         // run-ins.  When we encounter these four types of objects, we don't actually lay them out as normal flow blocks.
1946         if (handleSpecialChild(child, marginInfo))
1947             continue;
1948
1949         // Lay out the child.
1950         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
1951     }
1952     
1953     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
1954     // determining the correct collapsed bottom margin information.
1955     handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
1956 }
1957
1958 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
1959 {
1960     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
1961     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
1962
1963     // The child is a normal flow object.  Compute the margins we will use for collapsing now.
1964     child->computeBlockDirectionMargins(this);
1965
1966     // Do not allow a collapse if the margin-before-collapse style is set to SEPARATE.
1967     if (child->style()->marginBeforeCollapse() == MSEPARATE) {
1968         marginInfo.setAtBeforeSideOfBlock(false);
1969         marginInfo.clearMargin();
1970     }
1971
1972     // Try to guess our correct logical top position.  In most cases this guess will
1973     // be correct.  Only if we're wrong (when we compute the real logical top position)
1974     // will we have to potentially relayout.
1975     LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo);
1976
1977     // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
1978     LayoutRect oldRect(child->x(), child->y() , child->width(), child->height());
1979     LayoutUnit oldLogicalTop = logicalTopForChild(child);
1980
1981 #ifndef NDEBUG
1982     LayoutSize oldLayoutDelta = view()->layoutDelta();
1983 #endif
1984     // Go ahead and position the child as though it didn't collapse with the top.
1985     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
1986
1987     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
1988     bool markDescendantsWithFloats = false;
1989     if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
1990         markDescendantsWithFloats = true;
1991     else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
1992         // If an element might be affected by the presence of floats, then always mark it for
1993         // layout.
1994         LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottomIncludingPositionedFloats());
1995         if (fb > logicalTopEstimate)
1996             markDescendantsWithFloats = true;
1997     }
1998
1999     if (childRenderBlock) {
2000         if (markDescendantsWithFloats)
2001             childRenderBlock->markAllDescendantsWithFloatsForLayout();
2002         if (!child->isWritingModeRoot())
2003             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottomIncludingPositionedFloats());
2004     }
2005
2006     if (!child->needsLayout())
2007         child->markForPaginationRelayoutIfNeeded();
2008
2009     bool childHadLayout = child->m_everHadLayout;
2010     bool childNeededLayout = child->needsLayout();
2011     if (childNeededLayout)
2012         child->layout();
2013
2014     // Cache if we are at the top of the block right now.
2015     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
2016
2017     // Now determine the correct ypos based off examination of collapsing margin
2018     // values.
2019     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
2020
2021     // Now check for clear.
2022     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
2023     
2024     bool paginated = view()->layoutState()->isPaginated();
2025     if (paginated) {
2026         LayoutUnit oldTop = logicalTopAfterClear;
2027         
2028         // If the object has a page or column break value of "before", then we should shift to the top of the next page.
2029         logicalTopAfterClear = applyBeforeBreak(child, logicalTopAfterClear);
2030     
2031         // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
2032         LayoutUnit logicalTopBeforeUnsplittableAdjustment = logicalTopAfterClear;
2033         LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, logicalTopAfterClear);
2034         
2035         LayoutUnit paginationStrut = 0;
2036         LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
2037         if (unsplittableAdjustmentDelta)
2038             paginationStrut = unsplittableAdjustmentDelta;
2039         else if (childRenderBlock && childRenderBlock->paginationStrut())
2040             paginationStrut = childRenderBlock->paginationStrut();
2041
2042         if (paginationStrut) {
2043             // We are willing to propagate out to our parent block as long as we were at the top of the block prior
2044             // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
2045             if (atBeforeSideOfBlock && oldTop == logicalTopBeforeClear && !isPositioned() && !isTableCell()) {
2046                 // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
2047                 // have all the information to do so (the strut only has the remaining amount to push).  Gecko gets this wrong too
2048                 // and pushes to the next page anyway, so not too concerned about it.
2049                 setPaginationStrut(logicalTopAfterClear + paginationStrut);
2050                 if (childRenderBlock)
2051                     childRenderBlock->setPaginationStrut(0);
2052             } else
2053                 logicalTopAfterClear += paginationStrut;
2054         }
2055
2056         // Similar to how we apply clearance.  Go ahead and boost height() to be the place where we're going to position the child.
2057         setLogicalHeight(logicalHeight() + (logicalTopAfterClear - oldTop));
2058     }
2059
2060     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
2061
2062     // Now we have a final top position.  See if it really does end up being different from our estimate.
2063     if (logicalTopAfterClear != logicalTopEstimate) {
2064         if (child->shrinkToAvoidFloats()) {
2065             // The child's width depends on the line width.
2066             // When the child shifts to clear an item, its width can
2067             // change (because it has more available line width).
2068             // So go ahead and mark the item as dirty.
2069             child->setChildNeedsLayout(true, false);
2070         }
2071         if (childRenderBlock) {
2072             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
2073                 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2074             if (!child->needsLayout())
2075                 child->markForPaginationRelayoutIfNeeded();
2076         }
2077
2078         // Our guess was wrong. Make the child lay itself out again.
2079         child->layoutIfNeeded();
2080     }
2081
2082     // We are no longer at the top of the block if we encounter a non-empty child.  
2083     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
2084     if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
2085         marginInfo.setAtBeforeSideOfBlock(false);
2086
2087     // Now place the child in the correct left position
2088     determineLogicalLeftPositionForChild(child);
2089
2090     // Update our height now that the child has been placed in the correct position.
2091     setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
2092     if (child->style()->marginAfterCollapse() == MSEPARATE) {
2093         setLogicalHeight(logicalHeight() + marginAfterForChild(child));
2094         marginInfo.clearMargin();
2095     }
2096     // If the child has overhanging floats that intrude into following siblings (or possibly out
2097     // of this block), then the parent gets notified of the floats now.
2098     if (childRenderBlock && childRenderBlock->containsFloats())
2099         maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
2100
2101     LayoutSize childOffset(child->x() - oldRect.x(), child->y() - oldRect.y());
2102     if (childOffset.width() || childOffset.height()) {
2103         view()->addLayoutDelta(childOffset);
2104
2105         // If the child moved, we have to repaint it as well as any floating/positioned
2106         // descendants.  An exception is if we need a layout.  In this case, we know we're going to
2107         // repaint ourselves (and the child) anyway.
2108         if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
2109             child->repaintDuringLayoutIfMoved(oldRect);
2110     }
2111
2112     if (!childHadLayout && child->checkForRepaintDuringLayout()) {
2113         child->repaint();
2114         child->repaintOverhangingFloats(true);
2115     }
2116
2117     if (paginated) {
2118         // Check for an after page/column break.
2119         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
2120         if (newHeight != height())
2121             setLogicalHeight(newHeight);
2122     }
2123
2124     // FIXME: Change to use roughlyEquals when we move to float.
2125     // See https://bugs.webkit.org/show_bug.cgi?id=66148
2126     ASSERT(oldLayoutDelta == view()->layoutDelta());
2127 }
2128
2129 void RenderBlock::simplifiedNormalFlowLayout()
2130 {
2131     if (childrenInline()) {
2132         ListHashSet<RootInlineBox*> lineBoxes;
2133         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
2134             RenderObject* o = walker.current();
2135             if (!o->isPositioned() && (o->isReplaced() || o->isFloating())) {
2136                 o->layoutIfNeeded();
2137                 if (toRenderBox(o)->inlineBoxWrapper()) {
2138                     RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
2139                     lineBoxes.add(box);
2140                 }
2141             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
2142                 o->setNeedsLayout(false);
2143         }
2144
2145         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
2146         GlyphOverflowAndFallbackFontsMap textBoxDataMap;                  
2147         for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
2148             RootInlineBox* box = *it;
2149             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
2150         }
2151     } else {
2152         for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
2153             if (!box->isPositioned())
2154                 box->layoutIfNeeded();
2155         }
2156     }
2157 }
2158
2159 bool RenderBlock::simplifiedLayout()
2160 {
2161     if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
2162         return false;
2163
2164     LayoutStateMaintainer statePusher(view(), this, IntSize(x(), y()), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
2165     
2166     if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
2167         return false;
2168
2169     // Lay out positioned descendants or objects that just need to recompute overflow.
2170     if (needsSimplifiedNormalFlowLayout())
2171         simplifiedNormalFlowLayout();
2172
2173     // Lay out our positioned objects if our positioned child bit is set.
2174     if (posChildNeedsLayout() && layoutPositionedObjects(false))
2175         return false; // If a positioned float is causing our normal flow to change, then we have to bail and do a full layout.
2176
2177     // Recompute our overflow information.
2178     // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
2179     // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
2180     // For now just always recompute overflow.  This is no worse performance-wise than the old code that called rightmostPosition and
2181     // lowestPosition on every relayout so it's not a regression.
2182     m_overflow.clear();
2183     computeOverflow(clientLogicalBottom(), true);
2184
2185     statePusher.pop();
2186     
2187     updateLayerTransform();
2188
2189     updateScrollInfoAfterLayout();
2190
2191     setNeedsLayout(false);
2192     return true;
2193 }
2194
2195 bool RenderBlock::positionedFloatsNeedRelayout()
2196 {
2197     if (!hasPositionedFloats())
2198         return false;
2199     
2200     RenderBox* positionedObject;
2201     Iterator end = m_positionedObjects->end();
2202     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2203         positionedObject = *it;
2204         if (!positionedObject->isFloating())
2205             continue;
2206
2207         if (positionedObject->needsLayout())
2208             return true;
2209
2210         if (positionedObject->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && positionedObject->parent() != this && positionedObject->parent()->isBlockFlow())
2211             return true;
2212         
2213         if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(logicalTop()) != pageLogicalOffset()))
2214             return true;
2215     }
2216     
2217     return false;
2218 }
2219
2220 bool RenderBlock::layoutPositionedObjects(bool relayoutChildren)
2221 {
2222     if (!m_positionedObjects)
2223         return false;
2224         
2225     if (hasColumns())
2226         view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
2227
2228     bool didFloatingBoxRelayout = false;
2229
2230     RenderBox* r;
2231     Iterator end = m_positionedObjects->end();
2232     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2233         r = *it;
2234         // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
2235         // non-positioned block.  Rather than trying to detect all of these movement cases, we just always lay out positioned
2236         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
2237         // positioned explicitly) this should not incur a performance penalty.
2238         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
2239             r->setChildNeedsLayout(true, false);
2240             
2241         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2242         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
2243             r->setPreferredLogicalWidthsDirty(true, false);
2244         
2245         if (!r->needsLayout())
2246             r->markForPaginationRelayoutIfNeeded();
2247         
2248         // FIXME: Technically we could check the old placement and the new placement of the box and only invalidate if
2249         // the margin box of the object actually changed.
2250         if (r->needsLayout() && r->isFloating())
2251             didFloatingBoxRelayout = true;
2252
2253         // 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
2254         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
2255         if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
2256             r->setNeedsLayout(false);
2257         r->layoutIfNeeded();
2258     }
2259     
2260     if (hasColumns())
2261         view()->layoutState()->m_columnInfo = columnInfo(); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
2262         
2263     return didFloatingBoxRelayout;
2264 }
2265
2266 void RenderBlock::markPositionedObjectsForLayout()
2267 {
2268     if (m_positionedObjects) {
2269         RenderBox* r;
2270         Iterator end = m_positionedObjects->end();
2271         for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2272             r = *it;
2273             r->setChildNeedsLayout(true);
2274         }
2275     }
2276 }
2277
2278 void RenderBlock::markForPaginationRelayoutIfNeeded()
2279 {
2280     ASSERT(!needsLayout());
2281     if (needsLayout())
2282         return;
2283
2284     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(logicalTop()) != pageLogicalOffset()))
2285         setChildNeedsLayout(true, false);
2286 }
2287
2288 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
2289 {
2290     // Repaint any overhanging floats (if we know we're the one to paint them).
2291     // Otherwise, bail out.
2292     if (!hasOverhangingFloats())
2293         return;
2294
2295     // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2296     // in this block. Better yet would be to push extra state for the containers of other floats.
2297     LayoutStateDisabler layoutStateDisabler(view());
2298     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2299     FloatingObjectSetIterator end = floatingObjectSet.end();
2300     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2301         FloatingObject* r = *it;
2302         // Only repaint the object if it is overhanging, is not in its own layer, and
2303         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2304         // condition is replaced with being a descendant of us.
2305         if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->m_shouldPaint) && !r->m_renderer->hasSelfPaintingLayer()) {
2306             r->m_renderer->repaint();
2307             r->m_renderer->repaintOverhangingFloats();
2308         }
2309     }
2310 }
2311  
2312 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2313 {
2314     LayoutPoint adjustedPaintOffset = paintOffset + location();
2315     
2316     PaintPhase phase = paintInfo.phase;
2317
2318     // Check if we need to do anything at all.
2319     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
2320     // paints the root's background.
2321     if (!isRoot()) {
2322         LayoutRect overflowBox = visualOverflowRect();
2323         flipForWritingMode(overflowBox);
2324         overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
2325         overflowBox.moveBy(adjustedPaintOffset);
2326         if (!overflowBox.intersects(paintInfo.rect))
2327             return;
2328     }
2329
2330     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
2331     paintObject(paintInfo, adjustedPaintOffset);
2332     if (pushedClip)
2333         popContentsClip(paintInfo, phase, adjustedPaintOffset);
2334
2335     // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
2336     // z-index.  We paint after we painted the background/border, so that the scrollbars will
2337     // sit above the background/border.
2338     if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this))
2339         layer()->paintOverflowControls(paintInfo.context, adjustedPaintOffset, paintInfo.rect);
2340 }
2341
2342 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2343 {
2344     if (paintInfo.context->paintingDisabled())
2345         return;
2346
2347     const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
2348     bool ruleTransparent = style()->columnRuleIsTransparent();
2349     EBorderStyle ruleStyle = style()->columnRuleStyle();
2350     LayoutUnit ruleWidth = style()->columnRuleWidth();
2351     LayoutUnit colGap = columnGap();
2352     bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent && ruleWidth <= colGap;
2353     if (!renderRule)
2354         return;
2355
2356     // We need to do multiple passes, breaking up our child painting into strips.
2357     ColumnInfo* colInfo = columnInfo();
2358     unsigned colCount = columnCount(colInfo);
2359     LayoutUnit currLogicalLeftOffset = style()->isLeftToRightDirection() ? 0 : contentLogicalWidth();
2360     LayoutUnit ruleAdd = logicalLeftOffsetForContent();
2361     LayoutUnit ruleLogicalLeft = style()->isLeftToRightDirection() ? 0 : contentLogicalWidth();
2362
2363     const AffineTransform& currentCTM = paintInfo.context->getCTM();
2364     bool antialias = !currentCTM.isIdentityOrTranslationOrFlipped();
2365
2366     for (unsigned i = 0; i < colCount; i++) {
2367         LayoutRect colRect = columnRectAt(colInfo, i);
2368
2369         LayoutUnit inlineDirectionSize = isHorizontalWritingMode() ? colRect.width() : colRect.height();
2370         
2371         // Move to the next position.
2372         if (style()->isLeftToRightDirection()) {
2373             ruleLogicalLeft += inlineDirectionSize + colGap / 2;
2374             currLogicalLeftOffset += inlineDirectionSize + colGap;
2375         } else {
2376             ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
2377             currLogicalLeftOffset -= (inlineDirectionSize + colGap);
2378         }
2379        
2380         // Now paint the column rule.
2381         if (i < colCount - 1) {
2382             LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleWidth / 2 + ruleAdd : paintOffset.x() + borderBefore() + paddingBefore();
2383             LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleWidth : ruleLeft + contentWidth();
2384             LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleWidth / 2 + ruleAdd;
2385             LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleWidth;
2386             drawLineForBoxSide(paintInfo.context, ruleLeft, ruleTop, ruleRight, ruleBottom,
2387                                style()->isLeftToRightDirection() ? BSLeft : BSRight, ruleColor, ruleStyle, 0, 0, antialias);
2388         }
2389         
2390         ruleLogicalLeft = currLogicalLeftOffset;
2391     }
2392 }
2393
2394 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
2395 {
2396     // We need to do multiple passes, breaking up our child painting into strips.
2397     GraphicsContext* context = paintInfo.context;
2398     ColumnInfo* colInfo = columnInfo();
2399     unsigned colCount = columnCount(colInfo);
2400     if (!colCount)
2401         return;
2402     LayoutUnit currLogicalTopOffset = 0;
2403     for (unsigned i = 0; i < colCount; i++) {
2404         // For each rect, we clip to the rect, and then we adjust our coords.
2405         LayoutRect colRect = columnRectAt(colInfo, i);
2406         flipForWritingMode(colRect);
2407         LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
2408         LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
2409         colRect.moveBy(paintOffset);
2410         PaintInfo info(paintInfo);
2411         info.rect.intersect(colRect);
2412         
2413         if (!info.rect.isEmpty()) {
2414             GraphicsContextStateSaver stateSaver(*context);
2415             
2416             // Each strip pushes a clip, since column boxes are specified as being
2417             // like overflow:hidden.
2418             context->clip(colRect);
2419
2420             // Adjust our x and y when painting.
2421             LayoutPoint adjustedPaintOffset = paintOffset + offset;
2422             if (paintingFloats)
2423                 paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
2424             else
2425                 paintContents(info, adjustedPaintOffset);
2426         }
2427
2428         LayoutUnit blockDelta = (isHorizontalWritingMode() ? colRect.height() : colRect.width());
2429         if (style()->isFlippedBlocksWritingMode())
2430             currLogicalTopOffset += blockDelta;
2431         else
2432             currLogicalTopOffset -= blockDelta;
2433     }
2434 }
2435
2436 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2437 {
2438     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
2439     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2440     // will do a full repaint().
2441     if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
2442         return;
2443
2444     if (childrenInline())
2445         m_lineBoxes.paint(this, paintInfo, paintOffset);
2446     else
2447         paintChildren(paintInfo, paintOffset);
2448 }
2449
2450 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2451 {
2452     PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
2453     newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
2454     
2455     // We don't paint our own background, but we do let the kids paint their backgrounds.
2456     PaintInfo info(paintInfo);
2457     info.phase = newPhase;
2458     info.updatePaintingRootForChildren(this);
2459     
2460     // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
2461     // NSViews.  Do not add any more code for this.
2462     RenderView* renderView = view();
2463     bool usePrintRect = !renderView->printRect().isEmpty();
2464     
2465     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {        
2466         // Check for page-break-before: always, and if it's set, break and bail.
2467         bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
2468         LayoutUnit absoluteChildY = paintOffset.y() + child->y();
2469         if (checkBeforeAlways
2470             && absoluteChildY > paintInfo.rect.y()
2471             && absoluteChildY < paintInfo.rect.maxY()) {
2472             view()->setBestTruncatedAt(absoluteChildY, this, true);
2473             return;
2474         }
2475
2476         if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
2477             // Paginate block-level replaced elements.
2478             if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
2479                 if (absoluteChildY < renderView->truncatedAt())
2480                     renderView->setBestTruncatedAt(absoluteChildY, child);
2481                 // If we were able to truncate, don't paint.
2482                 if (absoluteChildY >= renderView->truncatedAt())
2483                     break;
2484             }
2485         }
2486
2487         LayoutPoint childPoint = flipForWritingMode(child, paintOffset, ParentToChildFlippingAdjustment);
2488         if (!child->hasSelfPaintingLayer() && !child->isFloating())
2489             child->paint(info, childPoint);
2490
2491         // Check for page-break-after: always, and if it's set, break and bail.
2492         bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
2493         if (checkAfterAlways
2494             && (absoluteChildY + child->height()) > paintInfo.rect.y()
2495             && (absoluteChildY + child->height()) < paintInfo.rect.maxY()) {
2496             view()->setBestTruncatedAt(absoluteChildY + child->height() + max<LayoutUnit>(0, child->collapsedMarginAfter()), this, true);
2497             return;
2498         }
2499     }
2500 }
2501
2502 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
2503 {
2504     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
2505     bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
2506     RenderObject* caretPainter;
2507     bool isContentEditable;
2508     if (type == CursorCaret) {
2509         caretPainter = frame()->selection()->caretRenderer();
2510         isContentEditable = frame()->selection()->isContentEditable();
2511     } else {
2512         caretPainter = frame()->page()->dragCaretController()->caretRenderer();
2513         isContentEditable = frame()->page()->dragCaretController()->isContentEditable();
2514     }
2515
2516     if (caretPainter == this && (isContentEditable || caretBrowsing)) {
2517         // Convert the painting offset into the local coordinate system of this renderer,
2518         // to match the localCaretRect computed by the FrameSelection
2519         LayoutPoint adjustedPaintOffset = paintOffset;
2520         offsetForContents(adjustedPaintOffset);
2521
2522         if (type == CursorCaret)
2523             frame()->selection()->paintCaret(paintInfo.context, adjustedPaintOffset, paintInfo.rect);
2524         else
2525             frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, adjustedPaintOffset, paintInfo.rect);
2526     }
2527 }
2528
2529 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2530 {
2531     PaintPhase paintPhase = paintInfo.phase;
2532
2533     // 1. paint background, borders etc
2534     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
2535         if (hasBoxDecorations())
2536             paintBoxDecorations(paintInfo, paintOffset);
2537         if (hasColumns())
2538             paintColumnRules(paintInfo, paintOffset);
2539     }
2540
2541     if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
2542         paintMask(paintInfo, paintOffset);
2543         return;
2544     }
2545
2546     // We're done.  We don't bother painting any children.
2547     if (paintPhase == PaintPhaseBlockBackground)
2548         return;
2549
2550     // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
2551     LayoutPoint scrolledOffset = paintOffset;
2552     if (hasOverflowClip())
2553         scrolledOffset.move(-layer()->scrolledContentOffset());
2554
2555     // 2. paint contents
2556     if (paintPhase != PaintPhaseSelfOutline) {
2557         if (hasColumns())
2558             paintColumnContents(paintInfo, scrolledOffset);
2559         else
2560             paintContents(paintInfo, scrolledOffset);
2561     }
2562
2563     // 3. paint selection
2564     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
2565     bool isPrinting = document()->printing();
2566     if (!isPrinting && !hasColumns())
2567         paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
2568
2569     // 4. paint floats.
2570     if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
2571         if (hasColumns())
2572             paintColumnContents(paintInfo, scrolledOffset, true);
2573         else
2574             paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
2575     }
2576
2577     // 5. paint outline.
2578     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
2579         paintOutline(paintInfo.context, LayoutRect(paintOffset, size()));
2580
2581     // 6. paint continuation outlines.
2582     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
2583         RenderInline* inlineCont = inlineElementContinuation();
2584         if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE) {
2585             RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->renderer());
2586             RenderBlock* cb = containingBlock();
2587
2588             bool inlineEnclosedInSelfPaintingLayer = false;
2589             for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = box->parent()->enclosingBoxModelObject()) {
2590                 if (box->hasSelfPaintingLayer()) {
2591                     inlineEnclosedInSelfPaintingLayer = true;
2592                     break;
2593                 }
2594             }
2595
2596             if (!inlineEnclosedInSelfPaintingLayer)
2597                 cb->addContinuationWithOutline(inlineRenderer);
2598             else if (!inlineRenderer->firstLineBox())
2599                 inlineRenderer->paintOutline(paintInfo.context, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
2600         }
2601         paintContinuationOutlines(paintInfo, paintOffset);
2602     }
2603
2604     // 7. paint caret.
2605     // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
2606     // then paint the caret.
2607     if (paintPhase == PaintPhaseForeground) {        
2608         paintCaret(paintInfo, scrolledOffset, CursorCaret);
2609         paintCaret(paintInfo, scrolledOffset, DragCaret);
2610     }
2611 }
2612
2613 LayoutPoint RenderBlock::flipFloatForWritingMode(const FloatingObject* child, const LayoutPoint& point) const
2614 {
2615     if (!style()->isFlippedBlocksWritingMode())
2616         return point;
2617     
2618     // This is similar to the ParentToChildFlippingAdjustment in RenderBox::flipForWritingMode.  We have to subtract out our left/top offsets twice, since
2619     // it's going to get added back in.  We hide this complication here so that the calling code looks normal for the unflipped
2620     // case.
2621     if (isHorizontalWritingMode())
2622         return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
2623     return LayoutPoint(point.x() + width() - child->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
2624 }
2625
2626 void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
2627 {
2628     if (!m_floatingObjects)
2629         return;
2630
2631     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2632     FloatingObjectSetIterator end = floatingObjectSet.end();
2633     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2634         FloatingObject* r = *it;
2635         // Only paint the object if our m_shouldPaint flag is set.
2636         if (r->m_shouldPaint && !r->m_renderer->hasSelfPaintingLayer()) {
2637             PaintInfo currentPaintInfo(paintInfo);
2638             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
2639             LayoutPoint childPoint = flipFloatForWritingMode(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->m_renderer->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->m_renderer->y()));
2640             r->m_renderer->paint(currentPaintInfo, childPoint);
2641             if (!preservePhase) {
2642                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
2643                 r->m_renderer->paint(currentPaintInfo, childPoint);
2644                 currentPaintInfo.phase = PaintPhaseFloat;
2645                 r->m_renderer->paint(currentPaintInfo, childPoint);
2646                 currentPaintInfo.phase = PaintPhaseForeground;
2647                 r->m_renderer->paint(currentPaintInfo, childPoint);
2648                 currentPaintInfo.phase = PaintPhaseOutline;
2649                 r->m_renderer->paint(currentPaintInfo, childPoint);
2650             }
2651         }
2652     }
2653 }
2654
2655 void RenderBlock::paintEllipsisBoxes(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2656 {
2657     if (!paintInfo.shouldPaintWithinRoot(this) || !firstLineBox())
2658         return;
2659
2660     if (style()->visibility() == VISIBLE && paintInfo.phase == PaintPhaseForeground) {
2661         // We can check the first box and last box and avoid painting if we don't
2662         // intersect.
2663         LayoutUnit yPos = paintOffset.y() + firstLineBox()->y();
2664         LayoutUnit h = lastLineBox()->y() + lastLineBox()->logicalHeight() - firstLineBox()->y();
2665         if (yPos >= paintInfo.rect.maxY() || yPos + h <= paintInfo.rect.y())
2666             return;
2667
2668         // See if our boxes intersect with the dirty rect.  If so, then we paint
2669         // them.  Note that boxes can easily overlap, so we can't make any assumptions
2670         // based off positions of our first line box or our last line box.
2671         for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2672             yPos = paintOffset.y() + curr->y();
2673             h = curr->logicalHeight();
2674             if (curr->ellipsisBox() && yPos < paintInfo.rect.maxY() && yPos + h > paintInfo.rect.y())
2675                 curr->paintEllipsisBox(paintInfo, paintOffset, curr->lineTop(), curr->lineBottom());
2676         }
2677     }
2678 }
2679
2680 RenderInline* RenderBlock::inlineElementContinuation() const
2681
2682     RenderBoxModelObject* continuation = this->continuation();
2683     return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
2684 }
2685
2686 RenderBlock* RenderBlock::blockElementContinuation() const
2687 {
2688     RenderBoxModelObject* currentContinuation = continuation();
2689     if (!currentContinuation || currentContinuation->isInline())
2690         return 0;
2691     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
2692     if (nextContinuation->isAnonymousBlock())
2693         return nextContinuation->blockElementContinuation();
2694     return nextContinuation;
2695 }
2696     
2697 static ContinuationOutlineTableMap* continuationOutlineTable()
2698 {
2699     DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
2700     return &table;
2701 }
2702
2703 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
2704 {
2705     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
2706     // way of painting.
2707     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
2708     
2709     ContinuationOutlineTableMap* table = continuationOutlineTable();
2710     ListHashSet<RenderInline*>* continuations = table->get(this);
2711     if (!continuations) {
2712         continuations = new ListHashSet<RenderInline*>;
2713         table->set(this, continuations);
2714     }
2715     
2716     continuations->add(flow);
2717 }
2718
2719 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
2720 {
2721     ContinuationOutlineTableMap* table = continuationOutlineTable();
2722     if (table->isEmpty())
2723         return false;
2724         
2725     ListHashSet<RenderInline*>* continuations = table->get(this);
2726     if (!continuations)
2727         return false;
2728
2729     return continuations->contains(flow);
2730 }
2731
2732 void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
2733 {
2734     ContinuationOutlineTableMap* table = continuationOutlineTable();
2735     if (table->isEmpty())
2736         return;
2737         
2738     ListHashSet<RenderInline*>* continuations = table->get(this);
2739     if (!continuations)
2740         return;
2741
2742     LayoutPoint accumulatedPaintOffset = paintOffset;
2743     // Paint each continuation outline.
2744     ListHashSet<RenderInline*>::iterator end = continuations->end();
2745     for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
2746         // Need to add in the coordinates of the intervening blocks.
2747         RenderInline* flow = *it;
2748         RenderBlock* block = flow->containingBlock();
2749         for ( ; block && block != this; block = block->containingBlock())
2750             accumulatedPaintOffset.moveBy(block->location());
2751         ASSERT(block);   
2752         flow->paintOutline(info.context, accumulatedPaintOffset);
2753     }
2754     
2755     // Delete
2756     delete continuations;
2757     table->remove(this);
2758 }
2759
2760 bool RenderBlock::shouldPaintSelectionGaps() const
2761 {
2762     return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
2763 }
2764
2765 bool RenderBlock::isSelectionRoot() const
2766 {
2767     if (!node())
2768         return false;
2769         
2770     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
2771     if (isTable())
2772         return false;
2773         
2774     if (isBody() || isRoot() || hasOverflowClip() || isRelPositioned() ||
2775         isFloatingOrPositioned() || isTableCell() || isInlineBlockOrInlineTable() || hasTransform() ||
2776         hasReflection() || hasMask() || isWritingModeRoot())
2777         return true;
2778     
2779     if (view() && view()->selectionStart()) {
2780         Node* startElement = view()->selectionStart()->node();
2781         if (startElement && startElement->rootEditableElement() == node())
2782             return true;
2783     }
2784     
2785     return false;
2786 }
2787
2788 GapRects RenderBlock::selectionGapRectsForRepaint(RenderBoxModelObject* repaintContainer)
2789 {
2790     ASSERT(!needsLayout());
2791
2792     if (!shouldPaintSelectionGaps())
2793         return GapRects();
2794
2795     // FIXME: this is broken with transforms
2796     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
2797     mapLocalToContainer(repaintContainer, false, false, transformState);
2798     LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint());
2799
2800     if (hasOverflowClip())
2801         offsetFromRepaintContainer -= layer()->scrolledContentOffset();
2802
2803     LayoutUnit lastTop = 0;
2804     LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
2805     LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
2806     
2807     return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight);
2808 }
2809
2810 void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2811 {
2812     if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
2813         LayoutUnit lastTop = 0;
2814         LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
2815         LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
2816         GraphicsContextStateSaver stateSaver(*paintInfo.context);
2817
2818         LayoutRect gapRectsBounds = selectionGaps(this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, &paintInfo);
2819         if (!gapRectsBounds.isEmpty()) {
2820             if (RenderLayer* layer = enclosingLayer()) {
2821                 gapRectsBounds.moveBy(-paintOffset);
2822                 if (!hasLayer()) {
2823                     LayoutRect localBounds(gapRectsBounds);
2824                     flipForWritingMode(localBounds);
2825                     gapRectsBounds = localToContainerQuad(FloatRect(localBounds), layer->renderer()).enclosingBoundingBox();
2826                     gapRectsBounds.move(layer->scrolledContentOffset());
2827                 }
2828                 layer->addBlockSelectionGapsBounds(gapRectsBounds);
2829             }
2830         }
2831     }
2832 }
2833
2834 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, RenderBlock::PositionedObjectsListHashSet* positionedObjects)
2835 {
2836     if (!positionedObjects)
2837         return;
2838     
2839     RenderBlock::PositionedObjectsListHashSet::const_iterator end = positionedObjects->end();
2840     for (RenderBlock::PositionedObjectsListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
2841         RenderBox* r = *it;
2842         paintInfo->context->clipOut(LayoutRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
2843     }
2844 }
2845
2846 static int blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
2847 {
2848     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
2849 }
2850
2851 static int inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
2852 {
2853     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
2854 }
2855
2856 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
2857 {
2858     LayoutRect result;
2859     if (isHorizontalWritingMode())
2860         result = logicalRect;
2861     else
2862         result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
2863     flipForWritingMode(result);
2864     result.moveBy(rootBlockPhysicalPosition);
2865     return result;
2866 }
2867
2868 GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2869                                     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
2870 {
2871     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
2872     // Clip out floating and positioned objects when painting selection gaps.
2873     if (paintInfo) {
2874         // Note that we don't clip out overflow for positioned objects.  We just stick to the border box.
2875         LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
2876         rootBlock->flipForWritingMode(flippedBlockRect);
2877         flippedBlockRect.moveBy(rootBlockPhysicalPosition);
2878         clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), m_positionedObjects.get());
2879         if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
2880             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
2881                 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->m_positionedObjects.get()); // FIXME: Not right for flipped writing modes.
2882         if (m_floatingObjects) {
2883             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2884             FloatingObjectSetIterator end = floatingObjectSet.end();
2885             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2886                 FloatingObject* r = *it;
2887                 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
2888                                     offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
2889                                     r->m_renderer->width(), r->m_renderer->height());
2890                 rootBlock->flipForWritingMode(floatBox);
2891                 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2892                 paintInfo->context->clipOut(floatBox);
2893             }
2894         }
2895     }
2896
2897     // 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
2898     // fixed).
2899     GapRects result;
2900     if (!isBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
2901         return result;
2902
2903     if (hasColumns() || hasTransform() || style()->columnSpan()) {
2904         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
2905         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
2906         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2907         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2908         return result;
2909     }
2910
2911     if (childrenInline())
2912         result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
2913     else
2914         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
2915
2916     // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
2917     if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
2918         result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
2919                                              logicalHeight(), paintInfo));
2920     return result;
2921 }
2922
2923 GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2924                                           LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
2925 {
2926     GapRects result;
2927
2928     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
2929
2930     if (!firstLineBox()) {
2931         if (containsStart) {
2932             // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
2933             // case.
2934             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
2935             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2936             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2937         }
2938         return result;
2939     }
2940
2941     RootInlineBox* lastSelectedLine = 0;
2942     RootInlineBox* curr;
2943     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
2944
2945     // Now paint the gaps for the lines.
2946     for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
2947         LayoutUnit selTop =  curr->selectionTop();
2948         LayoutUnit selHeight = curr->selectionHeight();
2949
2950         if (!containsStart && !lastSelectedLine &&
2951             selectionState() != SelectionStart && selectionState() != SelectionBoth)
2952             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
2953                                                  selTop, paintInfo));
2954         
2955         LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
2956         logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
2957         LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
2958         if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
2959             || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
2960             result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
2961
2962         lastSelectedLine = curr;
2963     }
2964
2965     if (containsStart && !lastSelectedLine)
2966         // VisibleSelection must start just after our last line.
2967         lastSelectedLine = lastRootBox();
2968
2969     if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
2970         // Go ahead and update our lastY to be the bottom of the last selected line.
2971         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
2972         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2973         lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2974     }
2975     return result;
2976 }
2977
2978 GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2979                                          LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
2980 {
2981     GapRects result;
2982
2983     // Go ahead and jump right to the first block child that contains some selected objects.
2984     RenderBox* curr;
2985     for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
2986
2987     for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
2988         SelectionState childState = curr->selectionState();
2989         if (childState == SelectionBoth || childState == SelectionEnd)
2990             sawSelectionEnd = true;
2991
2992         if (curr->isFloatingOrPositioned())
2993             continue; // We must be a normal flow object in order to even be considered.
2994
2995         if (curr->isRelPositioned() && curr->hasLayer()) {
2996             // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
2997             // Just disregard it completely.
2998             LayoutSize relOffset = curr->layer()->relativePositionOffset();
2999             if (relOffset.width() || relOffset.height())
3000                 continue;
3001         }
3002
3003         bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
3004         bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
3005         if (fillBlockGaps) {
3006             // We need to fill the vertical gap above this object.
3007             if (childState == SelectionEnd || childState == SelectionInside)
3008                 // Fill the gap above the object.
3009                 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
3010                                                      curr->logicalTop(), paintInfo));
3011
3012             // 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*
3013             // our object.  We know this if the selection did not end inside our object.
3014             if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
3015                 childState = SelectionNone;
3016
3017             // Fill side gaps on this object based off its state.
3018             bool leftGap, rightGap;
3019             getSelectionGapInfo(childState, leftGap, rightGap);
3020
3021             if (leftGap)
3022                 result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
3023             if (rightGap)
3024                 result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
3025
3026             // Update lastLogicalTop to be just underneath the object.  lastLogicalLeft and lastLogicalRight extend as far as
3027             // they can without bumping into floating or positioned objects.  Ideally they will go right up
3028             // to the border of the root selection block.
3029             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
3030             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
3031             lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
3032         } else if (childState != SelectionNone)
3033             // We must be a block that has some selected object inside it.  Go ahead and recur.
3034             result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()), 
3035                                                             lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo));
3036     }
3037     return result;
3038 }
3039
3040 LayoutRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3041                                           LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo)
3042 {
3043     LayoutUnit logicalTop = lastLogicalTop;
3044     LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
3045     if (logicalHeight <= static_cast<LayoutUnit>(0))
3046         return LayoutRect();
3047
3048     // Get the selection offsets for the bottom of the gap
3049     LayoutUnit logicalLeft = max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
3050     LayoutUnit logicalRight = min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
3051     LayoutUnit logicalWidth = logicalRight - logicalLeft;
3052     if (logicalWidth <= static_cast<LayoutUnit>(0))
3053         return LayoutRect();
3054
3055     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
3056     if (paintInfo)
3057         paintInfo->context->fillRect(gapRect, selectionBackgroundColor(), style()->colorSpace());
3058     return gapRect;
3059 }
3060
3061 LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3062                                                 RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
3063 {
3064     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
3065     LayoutUnit rootBlockLogicalLeft = max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
3066     LayoutUnit rootBlockLogicalRight = min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalLeft, min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
3067     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
3068     if (rootBlockLogicalWidth <= static_cast<LayoutUnit>(0))
3069         return LayoutRect();
3070
3071     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
3072     if (paintInfo)
3073         paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
3074     return gapRect;
3075 }
3076
3077 LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3078                                                  RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
3079 {
3080     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
3081     LayoutUnit rootBlockLogicalLeft = max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalRight, max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
3082     LayoutUnit rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
3083     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
3084     if (rootBlockLogicalWidth <= static_cast<LayoutUnit>(0))
3085         return LayoutRect();
3086
3087     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
3088     if (paintInfo)
3089         paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
3090     return gapRect;
3091 }
3092
3093 void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap)
3094 {
3095     bool ltr = style()->isLeftToRightDirection();
3096     leftGap = (state == RenderObject::SelectionInside) ||
3097               (state == RenderObject::SelectionEnd && ltr) ||
3098               (state == RenderObject::SelectionStart && !ltr);
3099     rightGap = (state == RenderObject::SelectionInside) ||
3100                (state == RenderObject::SelectionStart && ltr) ||
3101                (state == RenderObject::SelectionEnd && !ltr);
3102 }
3103
3104 LayoutUnit RenderBlock::logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
3105 {
3106     LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
3107     if (logicalLeft == logicalLeftOffsetForContent()) {
3108         if (rootBlock != this)
3109             // The border can potentially be further extended by our containingBlock().
3110             return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
3111         return logicalLeft;
3112     } else {
3113         RenderBlock* cb = this;
3114         while (cb != rootBlock) {
3115             logicalLeft += cb->logicalLeft();
3116             cb = cb->containingBlock();
3117         }
3118     }
3119     return logicalLeft;
3120 }
3121
3122 LayoutUnit RenderBlock::logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
3123 {
3124     LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
3125     if (logicalRight == logicalRightOffsetForContent()) {
3126         if (rootBlock != this)
3127             // The border can potentially be further extended by our containingBlock().
3128             return containingBlock()->logicalRightSelectionOffset(rootBlock, position + logicalTop());
3129         return logicalRight;
3130     } else {
3131         RenderBlock* cb = this;
3132         while (cb != rootBlock) {
3133             logicalRight += cb->logicalLeft();
3134             cb = cb->containingBlock();
3135         }
3136     }
3137     return logicalRight;
3138 }
3139
3140 void RenderBlock::insertPositionedObject(RenderBox* o)
3141 {
3142     if (o->isRenderFlowThread())
3143         return;
3144     
3145     // Create the list of special objects if we don't aleady have one
3146     if (!m_positionedObjects)
3147         m_positionedObjects = adoptPtr(new PositionedObjectsListHashSet);
3148
3149     m_positionedObjects->add(o);
3150 }
3151
3152 void RenderBlock::removePositionedObject(RenderBox* o)
3153 {
3154     if (m_positionedObjects)
3155         m_positionedObjects->remove(o);
3156 }
3157
3158 void RenderBlock::removePositionedObjects(RenderBlock* o)
3159 {
3160     if (!m_positionedObjects)
3161         return;
3162     
3163     RenderBox* r;
3164     
3165     Iterator end = m_positionedObjects->end();
3166     
3167     Vector<RenderBox*, 16> deadObjects;
3168
3169     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
3170         r = *it;
3171         if (!o || r->isDescendantOf(o)) {
3172             if (o)
3173                 r->setChildNeedsLayout(true, false);
3174             
3175             // It is parent blocks job to add positioned child to positioned objects list of its containing block
3176             // Parent layout needs to be invalidated to ensure this happens.
3177             RenderObject* p = r->parent();
3178             while (p && !p->isRenderBlock())
3179                 p = p->parent();
3180             if (p)
3181                 p->setChildNeedsLayout(true);
3182             
3183             deadObjects.append(r);
3184         }
3185     }
3186     
3187     for (unsigned i = 0; i < deadObjects.size(); i++)
3188         m_positionedObjects->remove(deadObjects.at(i));
3189 }
3190
3191 RenderBlock::FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o)
3192 {
3193     ASSERT(o->isFloating());
3194
3195     // Create the list of special objects if we don't aleady have one
3196     if (!m_floatingObjects)
3197         m_floatingObjects = adoptPtr(new FloatingObjects(isHorizontalWritingMode()));
3198     else {
3199         // Don't insert the object again if it's already in the list
3200         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3201         FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
3202         if (it != floatingObjectSet.end())
3203             return *it;
3204     }
3205
3206     // Create the special object entry & append it to the list
3207
3208     FloatingObject* newObj = new FloatingObject(o->style()->floating());
3209     
3210     // Our location is irrelevant if we're unsplittable or no pagination is in effect.
3211     // Just go ahead and lay out the float.
3212     if (!o->isPositioned()) {
3213         bool isChildRenderBlock = o->isRenderBlock();
3214         if (isChildRenderBlock && !o->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
3215             o->setChildNeedsLayout(true, false);
3216             
3217         bool affectedByPagination = isChildRenderBlock && view()->layoutState()->m_pageLogicalHeight;
3218         if (!affectedByPagination || isWritingModeRoot()) // We are unsplittable if we're a block flow root.
3219             o->layoutIfNeeded();
3220         else {
3221             o->computeLogicalWidth();
3222             o->computeBlockDirectionMargins(this);
3223         }
3224     }
3225     setLogicalWidthForFloat(newObj, logicalWidthForChild(o) + marginStartForChild(o) + marginEndForChild(o));
3226
3227     newObj->m_shouldPaint = !o->hasSelfPaintingLayer(); // If a layer exists, the float will paint itself.  Otherwise someone else will.
3228     newObj->m_isDescendant = true;
3229     newObj->m_renderer = o;
3230
3231     m_floatingObjects->add(newObj);
3232     
3233     return newObj;
3234 }
3235
3236 void RenderBlock::removeFloatingObject(RenderBox* o)
3237 {
3238     if (m_floatingObjects) {
3239         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3240         FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
3241         if (it != floatingObjectSet.end()) {
3242             FloatingObject* r = *it;
3243             if (childrenInline()) {
3244                 int logicalTop = logicalTopForFloat(r);
3245                 int logicalBottom = logicalBottomForFloat(r);
3246
3247                 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
3248                 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == numeric_limits<int>::max())
3249                     logicalBottom = numeric_limits<int>::max();
3250                 else {
3251                     // Special-case zero- and less-than-zero-height floats: those don't touch
3252                     //