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