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