2011-01-05 Abhishek Arya <inferno@chromium.org>
[WebKit-https.git] / 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 "RenderFlexibleBox.h"
39 #include "RenderImage.h"
40 #include "RenderInline.h"
41 #include "RenderLayer.h"
42 #include "RenderMarquee.h"
43 #include "RenderReplica.h"
44 #include "RenderTableCell.h"
45 #include "RenderTextFragment.h"
46 #include "RenderTheme.h"
47 #include "RenderView.h"
48 #include "SelectionController.h"
49 #include "Settings.h"
50 #include "TransformState.h"
51 #include <wtf/StdLibExtras.h>
52
53 using namespace std;
54 using namespace WTF;
55 using namespace Unicode;
56
57 namespace WebCore {
58
59 using namespace HTMLNames;
60
61 typedef WTF::HashMap<const RenderBox*, ColumnInfo*> ColumnInfoMap;
62 static ColumnInfoMap* gColumnInfoMap = 0;
63
64 typedef WTF::HashMap<const RenderBlock*, HashSet<RenderBox*>*> PercentHeightDescendantsMap;
65 static PercentHeightDescendantsMap* gPercentHeightDescendantsMap = 0;
66
67 typedef WTF::HashMap<const RenderBox*, HashSet<RenderBlock*>*> PercentHeightContainerMap;
68 static PercentHeightContainerMap* gPercentHeightContainerMap = 0;
69     
70 typedef WTF::HashMap<RenderBlock*, ListHashSet<RenderInline*>*> ContinuationOutlineTableMap;
71
72 typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
73 static int gDelayUpdateScrollInfo = 0;
74 static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
75
76 // Our MarginInfo state used when laying out block children.
77 RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, int beforeBorderPadding, int afterBorderPadding)
78     : m_atBeforeSideOfBlock(true)
79     , m_atAfterSideOfBlock(false)
80     , m_marginBeforeQuirk(false)
81     , m_marginAfterQuirk(false)
82     , m_determinedMarginBeforeQuirk(false)
83 {
84     // Whether or not we can collapse our own margins with our children.  We don't do this
85     // if we had any border/padding (obviously), if we're the root or HTML elements, or if
86     // we're positioned, floating, a table cell.
87     m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isPositioned()
88         && !block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable()
89         && !block->isWritingModeRoot();
90
91     m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && (beforeBorderPadding == 0) && block->style()->marginBeforeCollapse() != MSEPARATE;
92
93     // If any height other than auto is specified in CSS, then we don't collapse our bottom
94     // margins with our children's margins.  To do otherwise would be to risk odd visual
95     // effects when the children overflow out of the parent block and yet still collapse
96     // with it.  We also don't collapse if we have any bottom border/padding.
97     m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && (afterBorderPadding == 0) &&
98         (block->style()->logicalHeight().isAuto() && block->style()->logicalHeight().value() == 0) && block->style()->marginAfterCollapse() != MSEPARATE;
99     
100     m_quirkContainer = block->isTableCell() || block->isBody() || block->style()->marginBeforeCollapse() == MDISCARD || 
101         block->style()->marginAfterCollapse() == MDISCARD;
102
103     m_positiveMargin = m_canCollapseMarginBeforeWithChildren ? block->maxPositiveMarginBefore() : 0;
104     m_negativeMargin = m_canCollapseMarginBeforeWithChildren ? block->maxNegativeMarginBefore() : 0;
105 }
106
107 // -------------------------------------------------------------------------------------------------------
108
109 RenderBlock::RenderBlock(Node* node)
110       : RenderBox(node)
111       , m_floatingObjects(0)
112       , m_positionedObjects(0)
113       , m_rareData(0)
114       , m_lineHeight(-1)
115 {
116     setChildrenInline(true);
117 }
118
119 RenderBlock::~RenderBlock()
120 {
121     delete m_floatingObjects;
122     delete m_positionedObjects;
123     
124     if (hasColumns())
125         delete gColumnInfoMap->take(this);
126
127     if (gPercentHeightDescendantsMap) {
128         if (HashSet<RenderBox*>* descendantSet = gPercentHeightDescendantsMap->take(this)) {
129             HashSet<RenderBox*>::iterator end = descendantSet->end();
130             for (HashSet<RenderBox*>::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
131                 HashSet<RenderBlock*>* containerSet = gPercentHeightContainerMap->get(*descendant);
132                 ASSERT(containerSet);
133                 if (!containerSet)
134                     continue;
135                 ASSERT(containerSet->contains(this));
136                 containerSet->remove(this);
137                 if (containerSet->isEmpty()) {
138                     gPercentHeightContainerMap->remove(*descendant);
139                     delete containerSet;
140                 }
141             }
142             delete descendantSet;
143         }
144     }
145 }
146
147 void RenderBlock::destroy()
148 {
149     // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
150     // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
151     children()->destroyLeftoverChildren();
152
153     // Destroy our continuation before anything other than anonymous children.
154     // The reason we don't destroy it before anonymous children is that they may
155     // have continuations of their own that are anonymous children of our continuation.
156     RenderBoxModelObject* continuation = this->continuation();
157     if (continuation) {
158         continuation->destroy();
159         setContinuation(0);
160     }
161     
162     if (!documentBeingDestroyed()) {
163         if (firstLineBox()) {
164             // We can't wait for RenderBox::destroy to clear the selection,
165             // because by then we will have nuked the line boxes.
166             // FIXME: The SelectionController should be responsible for this when it
167             // is notified of DOM mutations.
168             if (isSelectionBorder())
169                 view()->clearSelection();
170
171             // If we are an anonymous block, then our line boxes might have children
172             // that will outlast this block. In the non-anonymous block case those
173             // children will be destroyed by the time we return from this function.
174             if (isAnonymousBlock()) {
175                 for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
176                     while (InlineBox* childBox = box->firstChild())
177                         childBox->remove();
178                 }
179             }
180         } else if (isInline() && parent())
181             parent()->dirtyLinesFromChangedChild(this);
182     }
183
184     m_lineBoxes.deleteLineBoxes(renderArena());
185
186     RenderBox::destroy();
187 }
188
189 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
190 {
191     setReplaced(newStyle->isDisplayReplacedType());
192     
193     if (style() && parent() && diff == StyleDifferenceLayout && style()->position() != newStyle->position()) {
194         if (newStyle->position() == StaticPosition)
195             // Clear our positioned objects list. Our absolutely positioned descendants will be
196             // inserted into our containing block's positioned objects list during layout.
197             removePositionedObjects(0);
198         else if (style()->position() == StaticPosition) {
199             // Remove our absolutely positioned descendants from their current containing block.
200             // They will be inserted into our positioned objects list during layout.
201             RenderObject* cb = parent();
202             while (cb && (cb->style()->position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
203                 if (cb->style()->position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
204                     cb = cb->containingBlock();
205                     break;
206                 }
207                 cb = cb->parent();
208             }
209             
210             if (cb->isRenderBlock())
211                 toRenderBlock(cb)->removePositionedObjects(this);
212         }
213     }
214
215     RenderBox::styleWillChange(diff, newStyle);
216 }
217
218 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
219 {
220     RenderBox::styleDidChange(diff, oldStyle);
221
222     if (!isAnonymousBlock()) {
223         // Ensure that all of our continuation blocks pick up the new style.
224         for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
225             RenderBoxModelObject* nextCont = currCont->continuation();
226             currCont->setContinuation(0);
227             currCont->setStyle(style());
228             currCont->setContinuation(nextCont);
229         }
230     }
231
232     // FIXME: We could save this call when the change only affected non-inherited properties
233     for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
234         if (child->isAnonymousBlock()) {
235             RefPtr<RenderStyle> newStyle = RenderStyle::create();
236             newStyle->inheritFrom(style());
237             if (style()->specifiesColumns()) {
238                 if (child->style()->specifiesColumns())
239                     newStyle->inheritColumnPropertiesFrom(style());
240                 if (child->style()->columnSpan())
241                     newStyle->setColumnSpan(true);
242             }
243             newStyle->setDisplay(BLOCK);
244             child->setStyle(newStyle.release());
245         }
246     }
247
248     m_lineHeight = -1;
249
250     // Update pseudos for :before and :after now.
251     if (!isAnonymous() && document()->usesBeforeAfterRules() && canHaveChildren()) {
252         updateBeforeAfterContent(BEFORE);
253         updateBeforeAfterContent(AFTER);
254     }
255 }
256
257 void RenderBlock::updateBeforeAfterContent(PseudoId pseudoId)
258 {
259     // If this is an anonymous wrapper, then the parent applies its own pseudo-element style to it.
260     if (parent() && parent()->createsAnonymousWrapper())
261         return;
262     return children()->updateBeforeAfterContent(this, pseudoId);
263 }
264
265 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
266 {
267     if (beforeChild && beforeChild->parent() == this)
268         return this;
269
270     RenderBlock* curr = toRenderBlock(continuation());
271     RenderBlock* nextToLast = this;
272     RenderBlock* last = this;
273     while (curr) {
274         if (beforeChild && beforeChild->parent() == curr) {
275             if (curr->firstChild() == beforeChild)
276                 return last;
277             return curr;
278         }
279
280         nextToLast = last;
281         last = curr;
282         curr = toRenderBlock(curr->continuation());
283     }
284
285     if (!beforeChild && !last->firstChild())
286         return nextToLast;
287     return last;
288 }
289
290 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
291 {
292     RenderBlock* flow = continuationBefore(beforeChild);
293     ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
294     RenderBoxModelObject* beforeChildParent = 0;
295     if (beforeChild)
296         beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
297     else {
298         RenderBoxModelObject* cont = flow->continuation();
299         if (cont)
300             beforeChildParent = cont;
301         else
302             beforeChildParent = flow;
303     }
304
305     if (newChild->isFloatingOrPositioned())
306         return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
307
308     // A continuation always consists of two potential candidates: a block or an anonymous
309     // column span box holding column span children.
310     bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
311     bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
312     bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
313
314     if (flow == beforeChildParent)
315         return flow->addChildIgnoringContinuation(newChild, beforeChild);
316     
317     // The goal here is to match up if we can, so that we can coalesce and create the
318     // minimal # of continuations needed for the inline.
319     if (childIsNormal == bcpIsNormal)
320         return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
321     if (flowIsNormal == childIsNormal)
322         return flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
323     return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
324 }
325
326
327 void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
328 {
329     ASSERT(!continuation()); // We don't yet support column spans that aren't immediate children of the multi-column block.
330         
331     // The goal is to locate a suitable box in which to place our child.
332     RenderBlock* beforeChildParent = toRenderBlock(beforeChild && beforeChild->parent()->isRenderBlock() ? beforeChild->parent() : lastChild());
333     
334     // If the new child is floating or positioned it can just go in that block.
335     if (newChild->isFloatingOrPositioned())
336         return beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
337
338     // See if the child can be placed in the box.
339     bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
340     bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
341
342     if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans)
343         return beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
344
345     if (!beforeChild) {
346         // Create a new block of the correct type.
347         RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
348         children()->appendChildNode(this, newBox);
349         newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
350         return;
351     }
352
353     RenderObject* immediateChild = beforeChild;
354     bool isPreviousBlockViable = true;
355     while (immediateChild->parent() != this) {
356         if (isPreviousBlockViable)
357             isPreviousBlockViable = !immediateChild->previousSibling();
358         immediateChild = immediateChild->parent();
359     }
360     if (isPreviousBlockViable && immediateChild->previousSibling())
361         return toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); // Treat like an append.
362         
363     // Split our anonymous blocks.
364     RenderObject* newBeforeChild = splitAnonymousBlocksAroundChild(beforeChild);
365     
366     // Create a new anonymous box of the appropriate type.
367     RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
368     children()->insertChildNode(this, newBox, newBeforeChild);
369     newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
370     return;
371 }
372
373 RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
374 {
375     for (RenderObject* curr = this; curr; curr = curr->parent()) {
376         if (!curr->isRenderBlock() || curr->isFloatingOrPositioned() || curr->isTableCell() || curr->isRoot() || curr->isRenderView() || curr->hasOverflowClip()
377             || curr->isInlineBlockOrInlineTable())
378             return 0;
379         
380         RenderBlock* currBlock = toRenderBlock(curr);
381         if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
382             return currBlock;
383             
384         if (currBlock->isAnonymousColumnSpanBlock())
385             return 0;
386     }
387     return 0;
388 }
389
390 RenderBlock* RenderBlock::clone() const
391 {
392     RenderBlock* cloneBlock;
393     if (isAnonymousBlock())
394         cloneBlock = createAnonymousBlock();
395     else {
396         cloneBlock = new (renderArena()) RenderBlock(node());
397         cloneBlock->setStyle(style());
398     }
399     cloneBlock->setChildrenInline(childrenInline());
400     return cloneBlock;
401 }
402
403 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
404                               RenderBlock* middleBlock,
405                               RenderObject* beforeChild, RenderBoxModelObject* oldCont)
406 {
407     // Create a clone of this inline.
408     RenderBlock* cloneBlock = clone();
409     if (!isAnonymousBlock())
410         cloneBlock->setContinuation(oldCont);
411
412     // Now take all of the children from beforeChild to the end and remove
413     // them from |this| and place them in the clone.
414     if (!beforeChild && isAfterContent(lastChild()))
415         beforeChild = lastChild();
416     moveChildrenTo(cloneBlock, beforeChild, 0);
417     
418     // Hook |clone| up as the continuation of the middle block.
419     if (!cloneBlock->isAnonymousBlock())
420         middleBlock->setContinuation(cloneBlock);
421
422     // We have been reparented and are now under the fromBlock.  We need
423     // to walk up our block parent chain until we hit the containing anonymous columns block.
424     // Once we hit the anonymous columns block we're done.
425     RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
426     RenderBoxModelObject* currChild = this;
427     
428     while (curr && curr != fromBlock) {
429         ASSERT(curr->isRenderBlock());
430         
431         RenderBlock* blockCurr = toRenderBlock(curr);
432         
433         // Create a new clone.
434         RenderBlock* cloneChild = cloneBlock;
435         cloneBlock = blockCurr->clone();
436
437         // Insert our child clone as the first child.
438         cloneBlock->children()->appendChildNode(cloneBlock, cloneChild);
439
440         // Hook the clone up as a continuation of |curr|.  Note we do encounter
441         // anonymous blocks possibly as we walk up the block chain.  When we split an
442         // anonymous block, there's no need to do any continuation hookup, since we haven't
443         // actually split a real element.
444         if (!blockCurr->isAnonymousBlock()) {
445             oldCont = blockCurr->continuation();
446             blockCurr->setContinuation(cloneBlock);
447             cloneBlock->setContinuation(oldCont);
448         }
449
450         // Someone may have indirectly caused a <q> to split.  When this happens, the :after content
451         // has to move into the inline continuation.  Call updateBeforeAfterContent to ensure that the inline's :after
452         // content gets properly destroyed.
453         if (document()->usesBeforeAfterRules())
454             blockCurr->children()->updateBeforeAfterContent(blockCurr, AFTER);
455
456         // Now we need to take all of the children starting from the first child
457         // *after* currChild and append them all to the clone.
458         RenderObject* afterContent = isAfterContent(cloneBlock->lastChild()) ? cloneBlock->lastChild() : 0;
459         blockCurr->moveChildrenTo(cloneBlock, currChild->nextSibling(), 0, afterContent);
460
461         // Keep walking up the chain.
462         currChild = curr;
463         curr = toRenderBoxModelObject(curr->parent());
464     }
465
466     // Now we are at the columns block level. We need to put the clone into the toBlock.
467     toBlock->children()->appendChildNode(toBlock, cloneBlock);
468
469     // Now take all the children after currChild and remove them from the fromBlock
470     // and put them in the toBlock.
471     fromBlock->moveChildrenTo(toBlock, currChild->nextSibling(), 0);
472 }
473
474 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
475                             RenderObject* newChild, RenderBoxModelObject* oldCont)
476 {
477     RenderBlock* pre = 0;
478     RenderBlock* block = containingColumnsBlock();
479     
480     // Delete our line boxes before we do the inline split into continuations.
481     block->deleteLineBoxTree();
482     
483     bool madeNewBeforeBlock = false;
484     if (block->isAnonymousColumnsBlock()) {
485         // We can reuse this block and make it the preBlock of the next continuation.
486         pre = block;
487         pre->removePositionedObjects(0);
488         block = toRenderBlock(block->parent());
489     } else {
490         // No anonymous block available for use.  Make one.
491         pre = block->createAnonymousColumnsBlock();
492         pre->setChildrenInline(false);
493         madeNewBeforeBlock = true;
494     }
495
496     RenderBlock* post = block->createAnonymousColumnsBlock();
497     post->setChildrenInline(false);
498
499     RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
500     if (madeNewBeforeBlock)
501         block->children()->insertChildNode(block, pre, boxFirst);
502     block->children()->insertChildNode(block, newBlockBox, boxFirst);
503     block->children()->insertChildNode(block, post, boxFirst);
504     block->setChildrenInline(false);
505     
506     if (madeNewBeforeBlock)
507         block->moveChildrenTo(pre, boxFirst, 0);
508
509     splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
510
511     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
512     // time in makeChildrenNonInline by just setting this explicitly up front.
513     newBlockBox->setChildrenInline(false);
514
515     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
516     // connected, thus allowing newChild access to a renderArena should it need
517     // to wrap itself in additional boxes (e.g., table construction).
518     newBlockBox->addChild(newChild);
519
520     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
521     // get deleted properly.  Because objects moves from the pre block into the post block, we want to
522     // make new line boxes instead of leaving the old line boxes around.
523     pre->setNeedsLayoutAndPrefWidthsRecalc();
524     block->setNeedsLayoutAndPrefWidthsRecalc();
525     post->setNeedsLayoutAndPrefWidthsRecalc();
526 }
527
528 RenderObject* RenderBlock::splitAnonymousBlocksAroundChild(RenderObject* beforeChild)
529 {
530     while (beforeChild->parent() != this) {
531         RenderBlock* blockToSplit = toRenderBlock(beforeChild->parent());
532         if (blockToSplit->firstChild() != beforeChild) {
533             // We have to split the parentBlock into two blocks.
534             RenderBlock* post = createAnonymousBlockWithSameTypeAs(blockToSplit);
535             post->setChildrenInline(blockToSplit->childrenInline());
536             RenderBlock* parentBlock = toRenderBlock(blockToSplit->parent());
537             parentBlock->children()->insertChildNode(parentBlock, post, blockToSplit->nextSibling());
538             blockToSplit->moveChildrenTo(post, beforeChild, 0, blockToSplit->hasLayer());
539             post->setNeedsLayoutAndPrefWidthsRecalc();
540             blockToSplit->setNeedsLayoutAndPrefWidthsRecalc();
541             beforeChild = post;
542         } else
543             beforeChild = blockToSplit;
544     }
545     return beforeChild;
546 }
547
548 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
549 {
550     RenderBlock* pre = 0;
551     RenderBlock* post = 0;
552     RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|.  Assign to a variable
553                                // so that we don't have to patch all of the rest of the code later on.
554     
555     // Delete the block's line boxes before we do the split.
556     block->deleteLineBoxTree();
557
558     if (beforeChild && beforeChild->parent() != this)
559         beforeChild = splitAnonymousBlocksAroundChild(beforeChild);
560
561     if (beforeChild != firstChild()) {
562         pre = block->createAnonymousColumnsBlock();
563         pre->setChildrenInline(block->childrenInline());
564     }
565
566     if (beforeChild) {
567         post = block->createAnonymousColumnsBlock();
568         post->setChildrenInline(block->childrenInline());
569     }
570
571     RenderObject* boxFirst = block->firstChild();
572     if (pre)
573         block->children()->insertChildNode(block, pre, boxFirst);
574     block->children()->insertChildNode(block, newBlockBox, boxFirst);
575     if (post)
576         block->children()->insertChildNode(block, post, boxFirst);
577     block->setChildrenInline(false);
578     
579     // 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).
580     block->moveChildrenTo(pre, boxFirst, beforeChild, true);
581     block->moveChildrenTo(post, beforeChild, 0, true);
582
583     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
584     // time in makeChildrenNonInline by just setting this explicitly up front.
585     newBlockBox->setChildrenInline(false);
586
587     // We delayed adding the newChild until now so that the |newBlockBox| would be fully
588     // connected, thus allowing newChild access to a renderArena should it need
589     // to wrap itself in additional boxes (e.g., table construction).
590     newBlockBox->addChild(newChild);
591
592     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
593     // get deleted properly.  Because objects moved from the pre block into the post block, we want to
594     // make new line boxes instead of leaving the old line boxes around.
595     if (pre)
596         pre->setNeedsLayoutAndPrefWidthsRecalc();
597     block->setNeedsLayoutAndPrefWidthsRecalc();
598     if (post)
599         post->setNeedsLayoutAndPrefWidthsRecalc();
600 }
601
602 RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
603 {
604     // FIXME: This function is the gateway for the addition of column-span support.  It will
605     // be added to in three stages:
606     // (1) Immediate children of a multi-column block can span.
607     // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
608     // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
609     // cross the streams and have to cope with both types of continuations mixed together).
610     // This function currently supports (1) and (2).
611     RenderBlock* columnsBlockAncestor = 0;
612     if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isFloatingOrPositioned()
613         && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
614         if (style()->specifiesColumns())
615             columnsBlockAncestor = this;
616         else if (parent() && parent()->isRenderBlock())
617             columnsBlockAncestor = toRenderBlock(parent())->containingColumnsBlock(false);
618     }
619     return columnsBlockAncestor;
620 }
621
622 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
623 {
624     // Make sure we don't append things after :after-generated content if we have it.
625     if (!beforeChild) {
626         RenderObject* lastRenderer = lastChild();
627         if (isAfterContent(lastRenderer))
628             beforeChild = lastRenderer;
629         else if (lastRenderer && lastRenderer->isAnonymousBlock() && isAfterContent(lastRenderer->lastChild()))
630             beforeChild = lastRenderer->lastChild();
631     }
632
633     // If the requested beforeChild is not one of our children, then this is because
634     // there is an anonymous container within this object that contains the beforeChild.
635     if (beforeChild && beforeChild->parent() != this) {
636         RenderObject* anonymousChild = beforeChild->parent();
637         ASSERT(anonymousChild);
638
639         while (anonymousChild->parent() != this)
640             anonymousChild = anonymousChild->parent();
641
642         ASSERT(anonymousChild->isAnonymous());
643
644         if (anonymousChild->isAnonymousBlock()) {
645             // Insert the child into the anonymous block box instead of here.
646             if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
647                 beforeChild->parent()->addChild(newChild, beforeChild);
648             else
649                 addChild(newChild, beforeChild->parent());
650             return;
651         }
652
653         ASSERT(anonymousChild->isTable());
654         if ((newChild->isTableCol() && newChild->style()->display() == TABLE_COLUMN_GROUP)
655                 || (newChild->isRenderBlock() && newChild->style()->display() == TABLE_CAPTION)
656                 || newChild->isTableSection()
657                 || newChild->isTableRow()
658                 || newChild->isTableCell()) {
659             // Insert into the anonymous table.
660             anonymousChild->addChild(newChild, beforeChild);
661             return;
662         }
663
664         // Go on to insert before the anonymous table.
665         beforeChild = anonymousChild;
666     }
667
668     // Check for a spanning element in columns.
669     RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
670     if (columnsBlockAncestor) {
671         // We are placing a column-span element inside a block. 
672         RenderBlock* newBox = createAnonymousColumnSpanBlock();
673         
674         if (columnsBlockAncestor != this) {
675             // We are nested inside a multi-column element and are being split by the span.  We have to break up
676             // our block into continuations.
677             RenderBoxModelObject* oldContinuation = continuation();
678             setContinuation(newBox);
679
680             // Someone may have put a <p> inside a <q>, causing a split.  When this happens, the :after content
681             // has to move into the inline continuation.  Call updateBeforeAfterContent to ensure that our :after
682             // content gets properly destroyed.
683             bool isLastChild = (beforeChild == lastChild());
684             if (document()->usesBeforeAfterRules())
685                 children()->updateBeforeAfterContent(this, AFTER);
686             if (isLastChild && beforeChild != lastChild())
687                 beforeChild = 0; // We destroyed the last child, so now we need to update our insertion
688                                  // point to be 0.  It's just a straight append now.
689
690             splitFlow(beforeChild, newBox, newChild, oldContinuation);
691             return;
692         }
693
694         // We have to perform a split of this block's children.  This involves creating an anonymous block box to hold
695         // the column-spanning |newChild|.  We take all of the children from before |newChild| and put them into
696         // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
697         makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
698         return;
699     }
700
701     bool madeBoxesNonInline = false;
702
703     // A block has to either have all of its children inline, or all of its children as blocks.
704     // So, if our children are currently inline and a block child has to be inserted, we move all our
705     // inline children into anonymous block boxes.
706     if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrPositioned()) {
707         // This is a block with inline content. Wrap the inline content in anonymous blocks.
708         makeChildrenNonInline(beforeChild);
709         madeBoxesNonInline = true;
710
711         if (beforeChild && beforeChild->parent() != this) {
712             beforeChild = beforeChild->parent();
713             ASSERT(beforeChild->isAnonymousBlock());
714             ASSERT(beforeChild->parent() == this);
715         }
716     } else if (!childrenInline() && (newChild->isFloatingOrPositioned() || newChild->isInline())) {
717         // If we're inserting an inline child but all of our children are blocks, then we have to make sure
718         // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
719         // a new one is created and inserted into our list of children in the appropriate position.
720         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
721
722         if (afterChild && afterChild->isAnonymousBlock()) {
723             afterChild->addChild(newChild);
724             return;
725         }
726
727         if (newChild->isInline()) {
728             // No suitable existing anonymous box - create a new one.
729             RenderBlock* newBox = createAnonymousBlock();
730             RenderBox::addChild(newBox, beforeChild);
731             newBox->addChild(newChild);
732             return;
733         }
734     }
735
736     RenderBox::addChild(newChild, beforeChild);
737
738     if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
739         toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
740     // this object may be dead here
741 }
742
743 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
744 {
745     if (continuation() && !isAnonymousBlock())
746         return addChildToContinuation(newChild, beforeChild);
747     return addChildIgnoringContinuation(newChild, beforeChild);
748 }
749
750 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
751 {
752     if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
753         return addChildToAnonymousColumnBlocks(newChild, beforeChild);
754     return addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
755 }
756
757 static void getInlineRun(RenderObject* start, RenderObject* boundary,
758                          RenderObject*& inlineRunStart,
759                          RenderObject*& inlineRunEnd)
760 {
761     // Beginning at |start| we find the largest contiguous run of inlines that
762     // we can.  We denote the run with start and end points, |inlineRunStart|
763     // and |inlineRunEnd|.  Note that these two values may be the same if
764     // we encounter only one inline.
765     //
766     // We skip any non-inlines we encounter as long as we haven't found any
767     // inlines yet.
768     //
769     // |boundary| indicates a non-inclusive boundary point.  Regardless of whether |boundary|
770     // is inline or not, we will not include it in a run with inlines before it.  It's as though we encountered
771     // a non-inline.
772     
773     // Start by skipping as many non-inlines as we can.
774     RenderObject * curr = start;
775     bool sawInline;
776     do {
777         while (curr && !(curr->isInline() || curr->isFloatingOrPositioned()))
778             curr = curr->nextSibling();
779         
780         inlineRunStart = inlineRunEnd = curr;
781         
782         if (!curr)
783             return; // No more inline children to be found.
784         
785         sawInline = curr->isInline();
786         
787         curr = curr->nextSibling();
788         while (curr && (curr->isInline() || curr->isFloatingOrPositioned()) && (curr != boundary)) {
789             inlineRunEnd = curr;
790             if (curr->isInline())
791                 sawInline = true;
792             curr = curr->nextSibling();
793         }
794     } while (!sawInline);
795 }
796
797 void RenderBlock::deleteLineBoxTree()
798 {
799     m_lineBoxes.deleteLineBoxTree(renderArena());
800 }
801
802 RootInlineBox* RenderBlock::createRootInlineBox() 
803 {
804     return new (renderArena()) RootInlineBox(this);
805 }
806
807 RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
808 {
809     RootInlineBox* rootBox = createRootInlineBox();
810     m_lineBoxes.appendLineBox(rootBox);
811     return rootBox;
812 }
813
814 void RenderBlock::moveChildTo(RenderBlock* to, RenderObject* child, RenderObject* beforeChild, bool fullRemoveInsert)
815 {
816     ASSERT(this == child->parent());
817     ASSERT(!beforeChild || to == beforeChild->parent());
818     to->children()->insertChildNode(to, children()->removeChildNode(this, child, fullRemoveInsert), beforeChild, fullRemoveInsert);
819 }
820
821 void RenderBlock::moveChildrenTo(RenderBlock* to, RenderObject* startChild, RenderObject* endChild, RenderObject* beforeChild, bool fullRemoveInsert)
822 {
823     ASSERT(!beforeChild || to == beforeChild->parent());
824     RenderObject* nextChild = startChild;
825     while (nextChild && nextChild != endChild) {
826         RenderObject* child = nextChild;
827         nextChild = child->nextSibling();
828         to->children()->insertChildNode(to, children()->removeChildNode(this, child, fullRemoveInsert), beforeChild, fullRemoveInsert);
829         if (child == endChild)
830             return;
831     }
832 }
833
834 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
835 {    
836     // makeChildrenNonInline takes a block whose children are *all* inline and it
837     // makes sure that inline children are coalesced under anonymous
838     // blocks.  If |insertionPoint| is defined, then it represents the insertion point for
839     // the new block child that is causing us to have to wrap all the inlines.  This
840     // means that we cannot coalesce inlines before |insertionPoint| with inlines following
841     // |insertionPoint|, because the new child is going to be inserted in between the inlines,
842     // splitting them.
843     ASSERT(isInlineBlockOrInlineTable() || !isInline());
844     ASSERT(!insertionPoint || insertionPoint->parent() == this);
845
846     setChildrenInline(false);
847
848     RenderObject *child = firstChild();
849     if (!child)
850         return;
851
852     deleteLineBoxTree();
853
854     while (child) {
855         RenderObject *inlineRunStart, *inlineRunEnd;
856         getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
857
858         if (!inlineRunStart)
859             break;
860
861         child = inlineRunEnd->nextSibling();
862
863         RenderBlock* block = createAnonymousBlock();
864         children()->insertChildNode(this, block, inlineRunStart);
865         moveChildrenTo(block, inlineRunStart, child);
866     }
867
868 #ifndef NDEBUG
869     for (RenderObject *c = firstChild(); c; c = c->nextSibling())
870         ASSERT(!c->isInline());
871 #endif
872
873     repaint();
874 }
875
876 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
877 {
878     ASSERT(child->isAnonymousBlock());
879     ASSERT(!child->childrenInline());
880     
881     if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
882         return;
883     
884     RenderObject* firstAnChild = child->m_children.firstChild();
885     RenderObject* lastAnChild = child->m_children.lastChild();
886     if (firstAnChild) {
887         RenderObject* o = firstAnChild;
888         while (o) {
889             o->setParent(this);
890             o = o->nextSibling();
891         }
892         firstAnChild->setPreviousSibling(child->previousSibling());
893         lastAnChild->setNextSibling(child->nextSibling());
894         if (child->previousSibling())
895             child->previousSibling()->setNextSibling(firstAnChild);
896         if (child->nextSibling())
897             child->nextSibling()->setPreviousSibling(lastAnChild);
898             
899         if (child == m_children.firstChild())
900             m_children.setFirstChild(firstAnChild);
901         if (child == m_children.lastChild())
902             m_children.setLastChild(lastAnChild);
903     } else {
904         if (child == m_children.firstChild())
905             m_children.setFirstChild(child->nextSibling());
906         if (child == m_children.lastChild())
907             m_children.setLastChild(child->previousSibling());
908
909         if (child->previousSibling())
910             child->previousSibling()->setNextSibling(child->nextSibling());
911         if (child->nextSibling())
912             child->nextSibling()->setPreviousSibling(child->previousSibling());
913     }
914     child->setParent(0);
915     child->setPreviousSibling(0);
916     child->setNextSibling(0);
917     
918     child->children()->setFirstChild(0);
919     child->m_next = 0;
920
921     child->destroy();
922 }
923
924 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
925 {
926     if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
927         return false;
928
929     if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation()))
930         || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation())))
931         return false;
932
933     // FIXME: This check isn't required when inline run-ins can't be split into continuations.
934     if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
935         return false;
936
937     if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
938         || (next && (next->isRubyRun() || next->isRubyBase())))
939         return false;
940
941     if (!prev || !next)
942         return true;
943
944     // Make sure the types of the anonymous blocks match up.
945     return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
946            && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
947 }
948
949 void RenderBlock::removeChild(RenderObject* oldChild)
950 {
951     // If this child is a block, and if our previous and next siblings are
952     // both anonymous blocks with inline content, then we can go ahead and
953     // fold the inline content back together.
954     RenderObject* prev = oldChild->previousSibling();
955     RenderObject* next = oldChild->nextSibling();
956     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
957     if (canMergeAnonymousBlocks && prev && next) {
958         prev->setNeedsLayoutAndPrefWidthsRecalc();
959         RenderBlock* nextBlock = toRenderBlock(next);
960         RenderBlock* prevBlock = toRenderBlock(prev);
961        
962         if (prev->childrenInline() != next->childrenInline()) {
963             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
964             RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
965             
966             // Place the inline children block inside of the block children block instead of deleting it.
967             // In order to reuse it, we have to reset it to just be a generic anonymous block.  Make sure
968             // to clear out inherited column properties by just making a new style, and to also clear the
969             // column span flag if it is set.
970             ASSERT(!inlineChildrenBlock->continuation());
971             RefPtr<RenderStyle> newStyle = RenderStyle::create();
972             newStyle->inheritFrom(style());
973             children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlock->hasLayer());
974             inlineChildrenBlock->setStyle(newStyle);
975             
976             // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
977             blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
978                                                             inlineChildrenBlock->hasLayer() || blockChildrenBlock->hasLayer());
979             next->setNeedsLayoutAndPrefWidthsRecalc();
980             
981             // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
982             // of "this". we null out prev or next so that is not used later in the function.
983             if (inlineChildrenBlock == prevBlock)
984                 prev = 0;
985             else
986                 next = 0;
987         } else {
988             // Take all the children out of the |next| block and put them in
989             // the |prev| block.
990             nextBlock->moveAllChildrenTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
991
992             // FIXME: When we destroy nextBlock, it might happen that nextBlock's next sibling block and
993             // oldChild can get merged. Since oldChild is getting removed, we do not want to move
994             // nextBlock's next sibling block's children into it. By setting a fake continuation,
995             // we prevent this from happening. This is not the best approach, we should replace this
996             // something better later to automatically detect that oldChild is getting removed.
997             RenderBlock* oldChildBlock = 0;
998             if (oldChild->isAnonymous() && oldChild->isRenderBlock() && !toRenderBlock(oldChild)->continuation()) {
999                 oldChildBlock = toRenderBlock(oldChild);
1000                 oldChildBlock->setContinuation(oldChildBlock);                
1001             }          
1002             
1003             // Delete the now-empty block's lines and nuke it.
1004             nextBlock->deleteLineBoxTree();
1005             nextBlock->destroy();
1006             next = 0;
1007
1008             // FIXME: Revert the continuation change done above.
1009             if (oldChildBlock)
1010                 oldChildBlock->setContinuation(0);
1011         }
1012     }
1013
1014     RenderBox::removeChild(oldChild);
1015
1016     RenderObject* child = prev ? prev : next;
1017     if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && !isFlexibleBox()) {
1018         // The removal has knocked us down to containing only a single anonymous
1019         // box.  We can go ahead and pull the content right back up into our
1020         // box.
1021         setNeedsLayoutAndPrefWidthsRecalc();
1022         setChildrenInline(child->childrenInline());
1023         RenderBlock* anonBlock = toRenderBlock(children()->removeChildNode(this, child, child->hasLayer()));
1024         anonBlock->moveAllChildrenTo(this, child->hasLayer());
1025         // Delete the now-empty block's lines and nuke it.
1026         anonBlock->deleteLineBoxTree();
1027         anonBlock->destroy();
1028     }
1029
1030     if (!firstChild() && !documentBeingDestroyed()) {
1031         // If this was our last child be sure to clear out our line boxes.
1032         if (childrenInline())
1033             lineBoxes()->deleteLineBoxes(renderArena());
1034     }
1035 }
1036
1037 bool RenderBlock::isSelfCollapsingBlock() const
1038 {
1039     // We are not self-collapsing if we
1040     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1041     // (b) are a table,
1042     // (c) have border/padding,
1043     // (d) have a min-height
1044     // (e) have specified that one of our margins can't collapse using a CSS extension
1045     if (logicalHeight() > 0
1046         || isTable() || borderAndPaddingLogicalHeight()
1047         || style()->logicalMinHeight().isPositive()
1048         || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1049         return false;
1050
1051     Length logicalHeightLength = style()->logicalHeight();
1052     bool hasAutoHeight = logicalHeightLength.isAuto();
1053     if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
1054         hasAutoHeight = true;
1055         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1056             if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1057                 hasAutoHeight = false;
1058         }
1059     }
1060
1061     // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1062     // on whether we have content that is all self-collapsing or not.
1063     if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1064         // If the block has inline children, see if we generated any line boxes.  If we have any
1065         // line boxes, then we can't be self-collapsing, since we have content.
1066         if (childrenInline())
1067             return !firstLineBox();
1068         
1069         // Whether or not we collapse is dependent on whether all our normal flow children
1070         // are also self-collapsing.
1071         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1072             if (child->isFloatingOrPositioned())
1073                 continue;
1074             if (!child->isSelfCollapsingBlock())
1075                 return false;
1076         }
1077         return true;
1078     }
1079     return false;
1080 }
1081
1082 void RenderBlock::startDelayUpdateScrollInfo()
1083 {
1084     if (gDelayUpdateScrollInfo == 0) {
1085         ASSERT(!gDelayedUpdateScrollInfoSet);
1086         gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1087     }
1088     ASSERT(gDelayedUpdateScrollInfoSet);
1089     ++gDelayUpdateScrollInfo;
1090 }
1091
1092 void RenderBlock::finishDelayUpdateScrollInfo()
1093 {
1094     --gDelayUpdateScrollInfo;
1095     ASSERT(gDelayUpdateScrollInfo >= 0);
1096     if (gDelayUpdateScrollInfo == 0) {
1097         ASSERT(gDelayedUpdateScrollInfoSet);
1098
1099         OwnPtr<DelayedUpdateScrollInfoSet> infoSet(gDelayedUpdateScrollInfoSet);
1100         gDelayedUpdateScrollInfoSet = 0;
1101
1102         for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1103             RenderBlock* block = *it;
1104             if (block->hasOverflowClip()) {
1105                 block->layer()->updateScrollInfoAfterLayout();
1106             }
1107         }
1108     }
1109 }
1110
1111 void RenderBlock::updateScrollInfoAfterLayout()
1112 {
1113     if (hasOverflowClip()) {
1114         if (gDelayUpdateScrollInfo)
1115             gDelayedUpdateScrollInfoSet->add(this);
1116         else
1117             layer()->updateScrollInfoAfterLayout();
1118     }
1119 }
1120
1121 void RenderBlock::layout()
1122 {
1123     // Update our first letter info now.
1124     updateFirstLetter();
1125
1126     // Table cells call layoutBlock directly, so don't add any logic here.  Put code into
1127     // layoutBlock().
1128     layoutBlock(false);
1129     
1130     // It's safe to check for control clip here, since controls can never be table cells.
1131     // If we have a lightweight clip, there can never be any overflow from children.
1132     if (hasControlClip() && m_overflow)
1133         clearLayoutOverflow();
1134 }
1135
1136 void RenderBlock::layoutBlock(bool relayoutChildren, int pageLogicalHeight)
1137 {
1138     ASSERT(needsLayout());
1139
1140     if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
1141         return;                                      // cause us to come in here.  Just bail.
1142
1143     if (!relayoutChildren && layoutOnlyPositionedObjects())
1144         return;
1145
1146     LayoutRepainter repainter(*this, m_everHadLayout && checkForRepaintDuringLayout());
1147
1148     int oldWidth = logicalWidth();
1149     int oldColumnWidth = desiredColumnWidth();
1150
1151     computeLogicalWidth();
1152     calcColumnWidth();
1153
1154     m_overflow.clear();
1155
1156     if (oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth())
1157         relayoutChildren = true;
1158
1159     clearFloats();
1160
1161     int previousHeight = logicalHeight();
1162     setLogicalHeight(0);
1163     bool hasSpecifiedPageLogicalHeight = false;
1164     bool pageLogicalHeightChanged = false;
1165     ColumnInfo* colInfo = columnInfo();
1166     if (hasColumns()) {
1167         if (!pageLogicalHeight) {
1168             // We need to go ahead and set our explicit page height if one exists, so that we can
1169             // avoid doing two layout passes.
1170             computeLogicalHeight();
1171             int columnHeight = contentLogicalHeight();
1172             if (columnHeight > 0) {
1173                 pageLogicalHeight = columnHeight;
1174                 hasSpecifiedPageLogicalHeight = true;
1175             }
1176             setLogicalHeight(0);
1177         }
1178         if (colInfo->columnHeight() != pageLogicalHeight && m_everHadLayout) {
1179             colInfo->setColumnHeight(pageLogicalHeight);
1180             pageLogicalHeightChanged = true;
1181         }
1182         
1183         if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
1184             colInfo->clearForcedBreaks();
1185     }
1186
1187     LayoutStateMaintainer statePusher(view(), this, IntSize(x(), y()), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, colInfo);
1188
1189     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
1190     // our current maximal positive and negative margins.  These values are used when we
1191     // are collapsed with adjacent blocks, so for example, if you have block A and B
1192     // collapsing together, then you'd take the maximal positive margin from both A and B
1193     // and subtract it from the maximal negative margin from both A and B to get the
1194     // true collapsed margin.  This algorithm is recursive, so when we finish layout()
1195     // our block knows its current maximal positive/negative values.
1196     //
1197     // Start out by setting our margin values to our current margins.  Table cells have
1198     // no margins, so we don't fill in the values for table cells.
1199     bool isCell = isTableCell();
1200     if (!isCell) {
1201         initMaxMarginValues();
1202         
1203         setMarginBeforeQuirk(style()->marginBefore().quirk());
1204         setMarginAfterQuirk(style()->marginAfter().quirk());
1205
1206         Node* n = node();
1207         if (n && n->hasTagName(formTag) && static_cast<HTMLFormElement*>(n)->isMalformed()) {
1208             // See if this form is malformed (i.e., unclosed). If so, don't give the form
1209             // a bottom margin.
1210             setMaxMarginAfterValues(0, 0);
1211         }
1212         
1213         setPaginationStrut(0);
1214     }
1215
1216     // For overflow:scroll blocks, ensure we have both scrollbars in place always.
1217     if (scrollsOverflow()) {
1218         if (style()->overflowX() == OSCROLL)
1219             layer()->setHasHorizontalScrollbar(true);
1220         if (style()->overflowY() == OSCROLL)
1221             layer()->setHasVerticalScrollbar(true);
1222     }
1223
1224     int repaintLogicalTop = 0;
1225     int repaintLogicalBottom = 0;
1226     int maxFloatLogicalBottom = 0;
1227     if (!firstChild() && !isAnonymousBlock())
1228         setChildrenInline(true);
1229     if (childrenInline())
1230         layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
1231     else
1232         layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
1233
1234     // Expand our intrinsic height to encompass floats.
1235     int toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
1236     if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
1237         setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
1238     
1239     if (layoutColumns(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
1240         return;
1241  
1242     // Calculate our new height.
1243     int oldHeight = logicalHeight();
1244     int oldClientAfterEdge = clientLogicalBottom();
1245     computeLogicalHeight();
1246     int newHeight = logicalHeight();
1247     if (oldHeight != newHeight) {
1248         if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
1249             // One of our children's floats may have become an overhanging float for us. We need to look for it.
1250             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1251                 if (child->isBlockFlow() && !child->isFloatingOrPositioned()) {
1252                     RenderBlock* block = toRenderBlock(child);
1253                     if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
1254                         addOverhangingFloats(block, -block->logicalLeft(), -block->logicalTop(), false);
1255                 }
1256             }
1257         }
1258     }
1259
1260     if (previousHeight != newHeight)
1261         relayoutChildren = true;
1262
1263     layoutPositionedObjects(relayoutChildren || isRoot());
1264
1265     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
1266     computeOverflow(oldClientAfterEdge);
1267     
1268     statePusher.pop();
1269
1270     if (view()->layoutState()->m_pageLogicalHeight)
1271         setPageLogicalOffset(view()->layoutState()->pageLogicalOffset(y()));
1272
1273     updateLayerTransform();
1274
1275     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
1276     // we overflow or not.
1277     updateScrollInfoAfterLayout();
1278
1279     // Repaint with our new bounds if they are different from our old bounds.
1280     bool didFullRepaint = repainter.repaintAfterLayout();
1281     if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (style()->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
1282         // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1283         // it had to lay out.  We wouldn't need the hasOverflowClip() hack in that case either.
1284         int repaintLogicalLeft = logicalLeftVisualOverflow();
1285         int repaintLogicalRight = logicalRightVisualOverflow();
1286         if (hasOverflowClip()) {
1287             // 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.
1288             // 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.
1289             // layoutInlineChildren should be patched to compute the entire repaint rect.
1290             repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1291             repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1292         }
1293         
1294         IntRect repaintRect;
1295         if (style()->isHorizontalWritingMode())
1296             repaintRect = IntRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
1297         else
1298             repaintRect = IntRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1299
1300         // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1301         adjustRectForColumns(repaintRect);
1302
1303         repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1304         
1305         if (hasOverflowClip()) {
1306             // Adjust repaint rect for scroll offset
1307             repaintRect.move(-layer()->scrolledContentOffset());
1308
1309             // Don't allow this rect to spill out of our overflow box.
1310             repaintRect.intersect(IntRect(0, 0, width(), height()));
1311         }
1312
1313         // Make sure the rect is still non-empty after intersecting for overflow above
1314         if (!repaintRect.isEmpty()) {
1315             repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1316             if (hasReflection())
1317                 repaintRectangle(reflectedRect(repaintRect));
1318         }
1319     }
1320     setNeedsLayout(false);
1321 }
1322
1323 void RenderBlock::addOverflowFromChildren()
1324 {
1325     if (!hasColumns()) {
1326         if (childrenInline())
1327             addOverflowFromInlineChildren();
1328         else
1329             addOverflowFromBlockChildren();
1330     } else {
1331         ColumnInfo* colInfo = columnInfo();
1332         if (columnCount(colInfo)) {
1333             IntRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1334             int overflowLeft = !style()->isLeftToRightDirection() ? min(0, lastRect.x()) : 0;
1335             int overflowRight = style()->isLeftToRightDirection() ? max(width(), lastRect.x() + lastRect.width()) : 0;
1336             int overflowHeight = borderTop() + paddingTop() + colInfo->columnHeight();
1337             addLayoutOverflow(IntRect(overflowLeft, 0, overflowRight - overflowLeft, overflowHeight));
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(r->left() + r->m_renderer->marginLeft(), r->top() + r->m_renderer->marginTop()));
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, nextPageTop(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, nextPageTop(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, height(), 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(y()) != 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 currXOffset = style()->isLeftToRightDirection() ? 0 : contentWidth();
2241     int ruleAdd = borderLeft() + paddingLeft();
2242     int ruleX = style()->isLeftToRightDirection() ? 0 : contentWidth();
2243     for (unsigned i = 0; i < colCount; i++) {
2244         IntRect colRect = columnRectAt(colInfo, i);
2245
2246         // Move to the next position.
2247         if (style()->isLeftToRightDirection()) {
2248             ruleX += colRect.width() + colGap / 2;
2249             currXOffset += colRect.width() + colGap;
2250         } else {
2251             ruleX -= (colRect.width() + colGap / 2);
2252             currXOffset -= (colRect.width() + colGap);
2253         }
2254        
2255         // Now paint the column rule.
2256         if (i < colCount - 1) {
2257             int ruleStart = tx + ruleX - ruleWidth / 2 + ruleAdd;
2258             int ruleEnd = ruleStart + ruleWidth;
2259             int ruleTop = ty + borderTop() + paddingTop();
2260             int ruleBottom = ruleTop + contentHeight();
2261             drawLineForBoxSide(paintInfo.context, ruleStart, ruleTop, ruleEnd, ruleBottom,
2262                                style()->isLeftToRightDirection() ? BSLeft : BSRight, ruleColor, ruleStyle, 0, 0);
2263         }
2264         
2265         ruleX = currXOffset;
2266     }
2267 }
2268
2269 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, int tx, int ty, bool paintingFloats)
2270 {
2271     // We need to do multiple passes, breaking up our child painting into strips.
2272     GraphicsContext* context = paintInfo.context;
2273     int colGap = columnGap();
2274     ColumnInfo* colInfo = columnInfo();
2275     unsigned colCount = columnCount(colInfo);
2276     if (!colCount)
2277         return;
2278     int currXOffset = style()->isLeftToRightDirection() ? 0 : contentWidth() - columnRectAt(colInfo, 0).width();
2279     int currYOffset = 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         colRect.move(tx, ty);
2284         PaintInfo info(paintInfo);
2285         info.rect.intersect(colRect);
2286         
2287         if (!info.rect.isEmpty()) {
2288             context->save();
2289             
2290             // Each strip pushes a clip, since column boxes are specified as being
2291             // like overflow:hidden.
2292             context->clip(colRect);
2293             
2294             // Adjust our x and y when painting.
2295             int finalX = tx + currXOffset;
2296             int finalY = ty + currYOffset;
2297             if (paintingFloats)
2298                 paintFloats(info, finalX, finalY, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
2299             else
2300                 paintContents(info, finalX, finalY);
2301
2302             context->restore();
2303         }
2304         
2305         // Move to the next position.
2306         if (style()->isLeftToRightDirection())
2307             currXOffset += colRect.width() + colGap;
2308         else
2309             currXOffset -= (colRect.width() + colGap);
2310         
2311         currYOffset -= colRect.height();
2312     }
2313 }
2314
2315 void RenderBlock::paintContents(PaintInfo& paintInfo, int tx, int ty)
2316 {
2317     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
2318     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2319     // will do a full repaint().
2320     if (document()->mayCauseFlashOfUnstyledContent() && !isRenderView())
2321         return;
2322
2323     if (childrenInline())
2324         m_lineBoxes.paint(this, paintInfo, tx, ty);
2325     else
2326         paintChildren(paintInfo, tx, ty);
2327 }
2328
2329 void RenderBlock::paintChildren(PaintInfo& paintInfo, int tx, int ty)
2330 {
2331     PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
2332     newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
2333     
2334     // We don't paint our own background, but we do let the kids paint their backgrounds.
2335     PaintInfo info(paintInfo);
2336     info.phase = newPhase;
2337     info.updatePaintingRootForChildren(this);
2338     
2339     // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
2340     // NSViews.  Do not add any more code for this.
2341     RenderView* renderView = view();
2342     bool usePrintRect = !renderView->printRect().isEmpty();
2343     
2344     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {        
2345         // Check for page-break-before: always, and if it's set, break and bail.
2346         bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
2347         if (checkBeforeAlways
2348             && (ty + child->y()) > paintInfo.rect.y()
2349             && (ty + child->y()) < paintInfo.rect.bottom()) {
2350             view()->setBestTruncatedAt(ty + child->y(), this, true);
2351             return;
2352         }
2353
2354         if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
2355             // Paginate block-level replaced elements.
2356             if (ty + child->y() + child->height() > renderView->printRect().bottom()) {
2357                 if (ty + child->y() < renderView->truncatedAt())
2358                     renderView->setBestTruncatedAt(ty + child->y(), child);
2359                 // If we were able to truncate, don't paint.
2360                 if (ty + child->y() >= renderView->truncatedAt())
2361                     break;
2362             }
2363         }
2364
2365         IntPoint childPoint = flipForWritingMode(child, IntPoint(tx, ty), ParentToChildFlippingAdjustment);
2366         if (!child->hasSelfPaintingLayer() && !child->isFloating())
2367             child->paint(info, childPoint.x(), childPoint.y());
2368
2369         // Check for page-break-after: always, and if it's set, break and bail.
2370         bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
2371         if (checkAfterAlways
2372             && (ty + child->y() + child->height()) > paintInfo.rect.y()
2373             && (ty + child->y() + child->height()) < paintInfo.rect.bottom()) {
2374             view()->setBestTruncatedAt(ty + child->y() + child->height() + max(0, child->collapsedMarginAfter()), this, true);
2375             return;
2376         }
2377     }
2378 }
2379
2380 void RenderBlock::paintCaret(PaintInfo& paintInfo, int tx, int ty, CaretType type)
2381 {
2382     SelectionController* selection = type == CursorCaret ? frame()->selection() : frame()->page()->dragCaretController();
2383
2384     // Paint the caret if the SelectionController says so or if caret browsing is enabled
2385     bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
2386     RenderObject* caretPainter = selection->caretRenderer();
2387     if (caretPainter == this && (selection->isContentEditable() || caretBrowsing)) {
2388         // Convert the painting offset into the local coordinate system of this renderer,
2389         // to match the localCaretRect computed by the SelectionController
2390         offsetForContents(tx, ty);
2391
2392         if (type == CursorCaret)
2393             frame()->selection()->paintCaret(paintInfo.context, tx, ty, paintInfo.rect);
2394         else
2395             frame()->selection()->paintDragCaret(paintInfo.context, tx, ty, paintInfo.rect);
2396     }
2397 }
2398
2399 void RenderBlock::paintObject(PaintInfo& paintInfo, int tx, int ty)
2400 {
2401     PaintPhase paintPhase = paintInfo.phase;
2402
2403     // 1. paint background, borders etc
2404     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
2405         if (hasBoxDecorations())
2406             paintBoxDecorations(paintInfo, tx, ty);
2407         if (hasColumns())
2408             paintColumnRules(paintInfo, tx, ty);
2409     }
2410
2411     if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
2412         paintMask(paintInfo, tx, ty);
2413         return;
2414     }
2415
2416     // We're done.  We don't bother painting any children.
2417     if (paintPhase == PaintPhaseBlockBackground)
2418         return;
2419
2420     // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
2421     int scrolledX = tx;
2422     int scrolledY = ty;
2423     if (hasOverflowClip()) {
2424         IntSize offset = layer()->scrolledContentOffset();
2425         scrolledX -= offset.width();
2426         scrolledY -= offset.height();
2427     }
2428
2429     // 2. paint contents
2430     if (paintPhase != PaintPhaseSelfOutline) {
2431         if (hasColumns())
2432             paintColumnContents(paintInfo, scrolledX, scrolledY);
2433         else
2434             paintContents(paintInfo, scrolledX, scrolledY);
2435     }
2436
2437     // 3. paint selection
2438     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
2439     bool isPrinting = document()->printing();
2440     if (!isPrinting && !hasColumns())
2441         paintSelection(paintInfo, scrolledX, scrolledY); // Fill in gaps in selection on lines and between blocks.
2442
2443     // 4. paint floats.
2444     if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
2445         if (hasColumns())
2446             paintColumnContents(paintInfo, scrolledX, scrolledY, true);
2447         else
2448             paintFloats(paintInfo, scrolledX, scrolledY, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
2449     }
2450
2451     // 5. paint outline.
2452     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
2453         paintOutline(paintInfo.context, tx, ty, width(), height());
2454
2455     // 6. paint continuation outlines.
2456     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
2457         RenderInline* inlineCont = inlineElementContinuation();
2458         if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE) {
2459             RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->renderer());
2460             RenderBlock* cb = containingBlock();
2461
2462             bool inlineEnclosedInSelfPaintingLayer = false;
2463             for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = box->parent()->enclosingBoxModelObject()) {
2464                 if (box->hasSelfPaintingLayer()) {
2465                     inlineEnclosedInSelfPaintingLayer = true;
2466                     break;
2467                 }
2468             }
2469
2470             if (!inlineEnclosedInSelfPaintingLayer)
2471                 cb->addContinuationWithOutline(inlineRenderer);
2472             else if (!inlineRenderer->firstLineBox())
2473                 inlineRenderer->paintOutline(paintInfo.context, tx - x() + inlineRenderer->containingBlock()->x(),
2474                                              ty - y() + inlineRenderer->containingBlock()->y());
2475         }
2476         paintContinuationOutlines(paintInfo, tx, ty);
2477     }
2478
2479     // 7. paint caret.
2480     // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
2481     // then paint the caret.
2482     if (paintPhase == PaintPhaseForeground) {        
2483         paintCaret(paintInfo, scrolledX, scrolledY, CursorCaret);
2484         paintCaret(paintInfo, scrolledX, scrolledY, DragCaret);
2485     }
2486 }
2487
2488 void RenderBlock::paintFloats(PaintInfo& paintInfo, int tx, int ty, bool preservePhase)
2489 {
2490     if (!m_floatingObjects)
2491         return;
2492
2493     FloatingObject* r;
2494     DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
2495     for (; (r = it.current()); ++it) {
2496         // Only paint the object if our m_shouldPaint flag is set.
2497         if (r->m_shouldPaint && !r->m_renderer->hasSelfPaintingLayer()) {
2498             PaintInfo currentPaintInfo(paintInfo);
2499             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
2500             IntPoint childPoint = flipForWritingMode(r->m_renderer, IntPoint(tx + r->left() + r->m_renderer->marginLeft() - r->m_renderer->x(), ty + r->top() + r->m_renderer->marginTop() - r->m_renderer->y()), ParentToChildFlippingAdjustment);
2501             r->m_renderer->paint(currentPaintInfo, childPoint.x(), childPoint.y());
2502             if (!preservePhase) {
2503                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
2504                 r->m_renderer->paint(currentPaintInfo, childPoint.x(), childPoint.y());
2505                 currentPaintInfo.phase = PaintPhaseFloat;
2506                 r->m_renderer->paint(currentPaintInfo, childPoint.x(), childPoint.y());
2507                 currentPaintInfo.phase = PaintPhaseForeground;
2508                 r->m_renderer->paint(currentPaintInfo, childPoint.x(), childPoint.y());
2509                 currentPaintInfo.phase = PaintPhaseOutline;
2510                 r->m_renderer->paint(currentPaintInfo, childPoint.x(), childPoint.y());
2511             }
2512         }
2513     }
2514 }
2515
2516 void RenderBlock::paintEllipsisBoxes(PaintInfo& paintInfo, int tx, int ty)
2517 {
2518     if (!paintInfo.shouldPaintWithinRoot(this) || !firstLineBox())
2519         return;
2520
2521     if (style()->visibility() == VISIBLE && paintInfo.phase == PaintPhaseForeground) {
2522         // We can check the first box and last box and avoid painting if we don't
2523         // intersect.
2524         int yPos = ty + firstLineBox()->y();
2525         int h = lastLineBox()->y() + lastLineBox()->logicalHeight() - firstLineBox()->y();
2526         if (yPos >= paintInfo.rect.bottom() || yPos + h <= paintInfo.rect.y())
2527             return;
2528
2529         // See if our boxes intersect with the dirty rect.  If so, then we paint
2530         // them.  Note that boxes can easily overlap, so we can't make any assumptions
2531         // based off positions of our first line box or our last line box.
2532         for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2533             yPos = ty + curr->y();
2534             h = curr->logicalHeight();
2535             if (curr->ellipsisBox() && yPos < paintInfo.rect.bottom() && yPos + h > paintInfo.rect.y())
2536                 curr->paintEllipsisBox(paintInfo, tx, ty);
2537         }
2538     }
2539 }
2540
2541 RenderInline* RenderBlock::inlineElementContinuation() const
2542
2543     RenderBoxModelObject* continuation = this->continuation();
2544     return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
2545 }
2546
2547 RenderBlock* RenderBlock::blockElementContinuation() const
2548 {
2549     RenderBoxModelObject* currentContinuation = continuation();
2550     if (!currentContinuation || currentContinuation->isInline())
2551         return 0;
2552     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
2553     if (nextContinuation->isAnonymousBlock())
2554         return nextContinuation->blockElementContinuation();
2555     return nextContinuation;
2556 }
2557     
2558 static ContinuationOutlineTableMap* continuationOutlineTable()
2559 {
2560     DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
2561     return &table;
2562 }
2563
2564 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
2565 {
2566     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
2567     // way of painting.
2568     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
2569     
2570     ContinuationOutlineTableMap* table = continuationOutlineTable();
2571     ListHashSet<RenderInline*>* continuations = table->get(this);
2572     if (!continuations) {
2573         continuations = new ListHashSet<RenderInline*>;
2574         table->set(this, continuations);
2575     }
2576     
2577     continuations->add(flow);
2578 }
2579
2580 void RenderBlock::paintContinuationOutlines(PaintInfo& info, int tx, int ty)
2581 {
2582     ContinuationOutlineTableMap* table = continuationOutlineTable();
2583     if (table->isEmpty())
2584         return;
2585         
2586     ListHashSet<RenderInline*>* continuations = table->get(this);
2587     if (!continuations)
2588         return;
2589         
2590     // Paint each continuation outline.
2591     ListHashSet<RenderInline*>::iterator end = continuations->end();
2592     for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
2593         // Need to add in the coordinates of the intervening blocks.
2594         RenderInline* flow = *it;
2595         RenderBlock* block = flow->containingBlock();
2596         for ( ; block && block != this; block = block->containingBlock()) {
2597             tx += block->x();
2598             ty += block->y();
2599         }
2600         ASSERT(block);   
2601         flow->paintOutline(info.context, tx, ty);
2602     }
2603     
2604     // Delete
2605     delete continuations;
2606     table->remove(this);
2607 }
2608
2609 bool RenderBlock::shouldPaintSelectionGaps() const
2610 {
2611     return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
2612 }
2613
2614 bool RenderBlock::isSelectionRoot() const
2615 {
2616     if (!node())
2617         return false;
2618         
2619     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
2620     if (isTable())
2621         return false;
2622         
2623     if (isBody() || isRoot() || hasOverflowClip() || isRelPositioned() ||
2624         isFloatingOrPositioned() || isTableCell() || isInlineBlockOrInlineTable() || hasTransform() ||
2625         hasReflection() || hasMask() || isWritingModeRoot())
2626         return true;
2627     
2628     if (view() && view()->selectionStart()) {
2629         Node* startElement = view()->selectionStart()->node();
2630         if (startElement && startElement->rootEditableElement() == node())
2631             return true;
2632     }
2633     
2634     return false;
2635 }
2636
2637 GapRects RenderBlock::selectionGapRectsForRepaint(RenderBoxModelObject* repaintContainer)
2638 {
2639     ASSERT(!needsLayout());
2640
2641     if (!shouldPaintSelectionGaps())
2642         return GapRects();
2643
2644     // FIXME: this is broken with transforms
2645     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
2646     mapLocalToContainer(repaintContainer, false, false, transformState);
2647     IntPoint offsetFromRepaintContainer = roundedIntPoint(transformState.mappedPoint());
2648
2649     if (hasOverflowClip())
2650         offsetFromRepaintContainer -= layer()->scrolledContentOffset();
2651
2652     int lastTop = 0;
2653     int lastLeft = logicalLeftSelectionOffset(this, lastTop);
2654     int lastRight = logicalRightSelectionOffset(this, lastTop);
2655     
2656     return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight);
2657 }
2658
2659 void RenderBlock::paintSelection(PaintInfo& paintInfo, int tx, int ty)
2660 {
2661     if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
2662         int lastTop = 0;
2663         int lastLeft = logicalLeftSelectionOffset(this, lastTop);
2664         int lastRight = logicalRightSelectionOffset(this, lastTop);
2665         paintInfo.context->save();
2666         IntRect gapRectsBounds = selectionGaps(this, IntPoint(tx, ty), IntSize(), lastTop, lastLeft, lastRight, &paintInfo);
2667         if (!gapRectsBounds.isEmpty()) {
2668             if (RenderLayer* layer = enclosingLayer()) {
2669                 gapRectsBounds.move(IntSize(-tx, -ty));
2670                 if (!hasLayer()) {
2671                     IntRect localBounds(gapRectsBounds);
2672                     flipForWritingMode(localBounds);
2673                     gapRectsBounds = localToContainerQuad(FloatRect(localBounds), layer->renderer()).enclosingBoundingBox();
2674                     gapRectsBounds.move(layer->scrolledContentOffset());
2675                 }
2676                 layer->addBlockSelectionGapsBounds(gapRectsBounds);
2677             }
2678         }
2679         paintInfo.context->restore();
2680     }
2681 }
2682
2683 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const IntPoint& offset, RenderBlock::PositionedObjectsListHashSet* positionedObjects)
2684 {
2685     if (!positionedObjects)
2686         return;
2687     
2688     RenderBlock::PositionedObjectsListHashSet::const_iterator end = positionedObjects->end();
2689     for (RenderBlock::PositionedObjectsListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
2690         RenderBox* r = *it;
2691         paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
2692     }
2693 }
2694
2695 static int blockDirectionOffset(RenderBlock* rootBlock, const IntSize& offsetFromRootBlock)
2696 {
2697     return rootBlock->style()->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
2698 }
2699
2700 static int inlineDirectionOffset(RenderBlock* rootBlock, const IntSize& offsetFromRootBlock)
2701 {
2702     return rootBlock->style()->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
2703 }
2704
2705 IntRect RenderBlock::logicalRectToPhysicalRect(const IntPoint& rootBlockPhysicalPosition, const IntRect& logicalRect)
2706 {
2707     IntRect result;
2708     if (style()->isHorizontalWritingMode())
2709         result = logicalRect;
2710     else
2711         result = IntRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
2712     flipForWritingMode(result);
2713     result.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2714     return result;
2715 }
2716
2717 GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const IntPoint& rootBlockPhysicalPosition, const IntSize& offsetFromRootBlock,
2718                                     int& lastLogicalTop, int& lastLogicalLeft, int& lastLogicalRight, const PaintInfo* paintInfo)
2719 {
2720     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
2721     // Clip out floating and positioned objects when painting selection gaps.
2722     if (paintInfo) {
2723         // Note that we don't clip out overflow for positioned objects.  We just stick to the border box.
2724         IntRect flippedBlockRect = IntRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
2725         rootBlock->flipForWritingMode(flippedBlockRect);
2726         flippedBlockRect.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2727         clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), m_positionedObjects);
2728         if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
2729             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
2730                 clipOutPositionedObjects(paintInfo, IntPoint(cb->x(), cb->y()), cb->m_positionedObjects); // FIXME: Not right for flipped writing modes.
2731         if (m_floatingObjects) {
2732             for (DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects); it.current(); ++it) {
2733                 FloatingObject* r = it.current();
2734                 IntRect floatBox = IntRect(offsetFromRootBlock.width() + r->left() + r->m_renderer->marginLeft(),
2735                                            offsetFromRootBlock.height() + r->top() + r->m_renderer->marginTop(),
2736                                            r->m_renderer->width(), r->m_renderer->height());
2737                 rootBlock->flipForWritingMode(floatBox);
2738                 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2739                 paintInfo->context->clipOut(floatBox);
2740             }
2741         }
2742     }
2743
2744     // 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
2745     // fixed).
2746     GapRects result;
2747     if (!isBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
2748         return result;
2749
2750     if (hasColumns() || hasTransform() || style()->columnSpan()) {
2751         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
2752         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
2753         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2754         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2755         return result;
2756     }
2757
2758     if (childrenInline())
2759         result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
2760     else
2761         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
2762
2763     // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
2764     if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
2765         result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
2766                                              logicalHeight(), paintInfo));
2767     return result;
2768 }
2769
2770 GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const IntPoint& rootBlockPhysicalPosition, const IntSize& offsetFromRootBlock,
2771                                           int& lastLogicalTop, int& lastLogicalLeft, int& lastLogicalRight, const PaintInfo* paintInfo)
2772 {
2773     GapRects result;
2774
2775     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
2776
2777     if (!firstLineBox()) {
2778         if (containsStart) {
2779             // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
2780             // case.
2781             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
2782             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2783             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2784         }
2785         return result;
2786     }
2787
2788     RootInlineBox* lastSelectedLine = 0;
2789     RootInlineBox* curr;
2790     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
2791
2792     // Now paint the gaps for the lines.
2793     for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
2794         int selTop =  curr->selectionTop();
2795         int selHeight = curr->selectionHeight();
2796
2797         if (!containsStart && !lastSelectedLine &&
2798             selectionState() != SelectionStart && selectionState() != SelectionBoth)
2799             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
2800                                                  selTop, paintInfo));
2801         
2802         IntRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
2803         logicalRect.move(style()->isHorizontalWritingMode() ? offsetFromRootBlock : IntSize(offsetFromRootBlock.height(), offsetFromRootBlock.width()));
2804         IntRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
2805         if (!paintInfo || (style()->isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.bottom() && physicalRect.bottom() > paintInfo->rect.y())
2806             || (!style()->isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.right() && physicalRect.right() > paintInfo->rect.x()))
2807             result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
2808
2809         lastSelectedLine = curr;
2810     }
2811
2812     if (containsStart && !lastSelectedLine)
2813         // VisibleSelection must start just after our last line.
2814         lastSelectedLine = lastRootBox();
2815
2816     if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
2817         // Go ahead and update our lastY to be the bottom of the last selected line.
2818         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
2819         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2820         lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2821     }
2822     return result;
2823 }
2824
2825 GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const IntPoint& rootBlockPhysicalPosition, const IntSize& offsetFromRootBlock,
2826                                          int& lastLogicalTop, int& lastLogicalLeft, int& lastLogicalRight, const PaintInfo* paintInfo)
2827 {
2828     GapRects result;
2829
2830     // Go ahead and jump right to the first block child that contains some selected objects.
2831     RenderBox* curr;
2832     for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
2833
2834     for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
2835         SelectionState childState = curr->selectionState();
2836         if (childState == SelectionBoth || childState == SelectionEnd)
2837             sawSelectionEnd = true;
2838
2839         if (curr->isFloatingOrPositioned())
2840             continue; // We must be a normal flow object in order to even be considered.
2841
2842         if (curr->isRelPositioned() && curr->hasLayer()) {
2843             // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
2844             // Just disregard it completely.
2845             IntSize relOffset = curr->layer()->relativePositionOffset();
2846             if (relOffset.width() || relOffset.height())
2847                 continue;
2848         }
2849
2850         bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
2851         bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
2852         if (fillBlockGaps) {
2853             // We need to fill the vertical gap above this object.
2854             if (childState == SelectionEnd || childState == SelectionInside)
2855                 // Fill the gap above the object.
2856                 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
2857                                                      curr->logicalTop(), paintInfo));
2858
2859             // 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*
2860             // our object.  We know this if the selection did not end inside our object.
2861             if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
2862                 childState = SelectionNone;
2863
2864             // Fill side gaps on this object based off its state.
2865             bool leftGap, rightGap;
2866             getSelectionGapInfo(childState, leftGap, rightGap);
2867
2868             if (leftGap)
2869                 result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
2870             if (rightGap)
2871                 result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
2872
2873             // Update lastLogicalTop to be just underneath the object.  lastLogicalLeft and lastLogicalRight extend as far as
2874             // they can without bumping into floating or positioned objects.  Ideally they will go right up
2875             // to the border of the root selection block.
2876             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
2877             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
2878             lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
2879         } else if (childState != SelectionNone)
2880             // We must be a block that has some selected object inside it.  Go ahead and recur.
2881             result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, IntSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()), 
2882                                                             lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo));
2883     }
2884     return result;
2885 }
2886
2887 IntRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const IntPoint& rootBlockPhysicalPosition, const IntSize& offsetFromRootBlock,
2888                                        int lastLogicalTop, int lastLogicalLeft, int lastLogicalRight, int logicalBottom, const PaintInfo* paintInfo)
2889 {
2890     int logicalTop = lastLogicalTop;
2891     int logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
2892     if (logicalHeight <= 0)
2893         return IntRect();
2894
2895     // Get the selection offsets for the bottom of the gap
2896     int logicalLeft = max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
2897     int logicalRight = min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
2898     int logicalWidth = logicalRight - logicalLeft;
2899     if (logicalWidth <= 0)
2900         return IntRect();
2901
2902     IntRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, IntRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
2903     if (paintInfo)
2904         paintInfo->context->fillRect(gapRect, selectionBackgroundColor(), style()->colorSpace());
2905     return gapRect;
2906 }
2907
2908 IntRect RenderBlock::logicalLeftSelectionGap(RenderBlock* rootBlock, const IntPoint& rootBlockPhysicalPosition, const IntSize& offsetFromRootBlock,
2909                                              RenderObject* selObj, int logicalLeft, int logicalTop, int logicalHeight, const PaintInfo* paintInfo)
2910 {
2911     int rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
2912     int rootBlockLogicalLeft = max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
2913     int rootBlockLogicalRight = min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalLeft, min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
2914     int rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2915     if (rootBlockLogicalWidth <= 0)
2916         return IntRect();
2917
2918     IntRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, IntRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2919     if (paintInfo)
2920         paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
2921     return gapRect;
2922 }
2923
2924 IntRect RenderBlock::logicalRightSelectionGap(RenderBlock* rootBlock, const IntPoint& rootBlockPhysicalPosition, const IntSize& offsetFromRootBlock,
2925                                               RenderObject* selObj, int logicalRight, int logicalTop, int logicalHeight, const PaintInfo* paintInfo)
2926 {
2927     int rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
2928     int rootBlockLogicalLeft = max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalRight, max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
2929     int rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
2930     int rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2931     if (rootBlockLogicalWidth <= 0)
2932         return IntRect();
2933
2934     IntRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, IntRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2935     if (paintInfo)
2936         paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
2937     return gapRect;
2938 }
2939
2940 void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap)
2941 {
2942     bool ltr = style()->isLeftToRightDirection();
2943     leftGap = (state == RenderObject::SelectionInside) ||
2944               (state == RenderObject::SelectionEnd && ltr) ||
2945               (state == RenderObject::SelectionStart && !ltr);
2946     rightGap = (state == RenderObject::SelectionInside) ||
2947                (state == RenderObject::SelectionStart && ltr) ||
2948                (state == RenderObject::SelectionEnd && !ltr);
2949 }
2950
2951 int RenderBlock::logicalLeftSelectionOffset(RenderBlock* rootBlock, int position)
2952 {
2953     int logicalLeft = logicalLeftOffsetForLine(position, false);
2954     if (logicalLeft == logicalLeftOffsetForContent()) {
2955         if (rootBlock != this)
2956             // The border can potentially be further extended by our containingBlock().
2957             return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
2958         return logicalLeft;
2959     } else {
2960         RenderBlock* cb = this;
2961         while (cb != rootBlock) {
2962             logicalLeft += cb->logicalLeft();
2963             cb = cb->containingBlock();
2964         }
2965     }
2966     return logicalLeft;
2967 }
2968
2969 int RenderBlock::logicalRightSelectionOffset(RenderBlock* rootBlock, int position)
2970 {
2971     int logicalRight = logicalRightOffsetForLine(position, false);
2972     if (logicalRight == logicalRightOffsetForContent()) {
2973         if (rootBlock != this)
2974             // The border can potentially be further extended by our containingBlock().
2975             return containingBlock()->logicalRightSelectionOffset(rootBlock, position + logicalTop());
2976         return logicalRight;
2977     } else {
2978         RenderBlock* cb = this;
2979         while (cb != rootBlock) {
2980             logicalRight += cb->logicalLeft();
2981             cb = cb->containingBlock();
2982         }
2983     }
2984     return logicalRight;
2985 }
2986
2987 void RenderBlock::insertPositionedObject(RenderBox* o)
2988 {
2989     // Create the list of special objects if we don't aleady have one
2990     if (!m_positionedObjects)
2991         m_positionedObjects = new PositionedObjectsListHashSet;
2992
2993     m_positionedObjects->add(o);
2994 }
2995
2996 void RenderBlock::removePositionedObject(RenderBox* o)
2997 {
2998     if (m_positionedObjects)
2999         m_positionedObjects->remove(o);
3000 }
3001
3002 void RenderBlock::removePositionedObjects(RenderBlock* o)
3003 {
3004     if (!m_positionedObjects)
3005         return;
3006     
3007     RenderBox* r;
3008     
3009     Iterator end = m_positionedObjects->end();
3010     
3011     Vector<RenderBox*, 16> deadObjects;
3012
3013     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
3014         r = *it;
3015         if (!o || r->isDescendantOf(o)) {
3016             if (o)
3017                 r->setChildNeedsLayout(true, false);
3018             
3019             // It is parent blocks job to add positioned child to positioned objects list of its containing block
3020             // Parent layout needs to be invalidated to ensure this happens.
3021             RenderObject* p = r->parent();
3022             while (p && !p->isRenderBlock())
3023                 p = p->parent();
3024             if (p)
3025                 p->setChildNeedsLayout(true);
3026             
3027             deadObjects.append(r);
3028         }
3029     }
3030     
3031     for (unsigned i = 0; i < deadObjects.size(); i++)
3032         m_positionedObjects->remove(deadObjects.at(i));
3033 }
3034
3035 RenderBlock::FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o)
3036 {
3037     ASSERT(o->isFloating());
3038
3039     // Create the list of special objects if we don't aleady have one
3040     if (!m_floatingObjects) {
3041         m_floatingObjects = new DeprecatedPtrList<FloatingObject>;
3042         m_floatingObjects->setAutoDelete(true);
3043     } else {
3044         // Don't insert the object again if it's already in the list
3045         DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
3046         FloatingObject* f;
3047         while ( (f = it.current()) ) {
3048             if (f->m_renderer == o)
3049                 return f;
3050             ++it;
3051         }
3052     }
3053
3054     // Create the special object entry & append it to the list
3055
3056     FloatingObject* newObj = new FloatingObject(o->style()->floating() == FLEFT ? FloatingObject::FloatLeft : FloatingObject::FloatRight);
3057     
3058     // Our location is irrelevant if we're unsplittable or no pagination is in effect.
3059     // Just go ahead and lay out the float.
3060     bool isChildRenderBlock = o->isRenderBlock();
3061     if (isChildRenderBlock && !o->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
3062         o->setChildNeedsLayout(true, false);
3063         
3064     bool affectedByPagination = isChildRenderBlock && view()->layoutState()->m_pageLogicalHeight;
3065     if (!affectedByPagination || isWritingModeRoot()) // We are unsplittable if we're a block flow root.
3066         o->layoutIfNeeded();
3067     else {
3068         o->computeLogicalWidth();
3069         o->computeBlockDirectionMargins(this);
3070     }
3071     setLogicalWidthForFloat(newObj, logicalWidthForChild(o) + marginStartForChild(o) + marginEndForChild(o));
3072
3073     newObj->m_shouldPaint = !o->hasSelfPaintingLayer(); // If a layer exists, the float will paint itself.  Otherwise someone else will.
3074     newObj->m_isDescendant = true;
3075     newObj->m_renderer = o;
3076
3077     m_floatingObjects->append(newObj);
3078     
3079     return newObj;
3080 }
3081
3082 void RenderBlock::removeFloatingObject(RenderBox* o)
3083 {
3084     if (m_floatingObjects) {
3085         DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
3086         while (it.current()) {
3087             if (it.current()->m_renderer == o) {
3088                 if (childrenInline()) {
3089                     int logicalTop = logicalTopForFloat(it.current());
3090                     int logicalBottom = logicalBottomForFloat(it.current());
3091                     
3092                     // Special-case zero- and less-than-zero-height floats: those don't touch
3093                     // the line that they're on, but it still needs to be dirtied. This is
3094                     // accomplished by pretending they have a height of 1.
3095                     logicalBottom = max(logicalBottom, logicalTop + 1);
3096                     markLinesDirtyInBlockRange(0, logicalBottom);
3097                 }
3098                 m_floatingObjects->removeRef(it.current());
3099             }
3100             ++it;
3101         }
3102     }
3103 }
3104
3105 void RenderBlock::removeFloatingObjectsBelow(FloatingObject* lastFloat, int y)
3106 {
3107     if (!m_floatingObjects)
3108         return;
3109     
3110     FloatingObject* curr = m_floatingObjects->last();
3111     while (curr != lastFloat && (!curr->isPlaced() || curr->top() >= y)) {
3112         m_floatingObjects->removeLast();
3113         curr = m_floatingObjects->last();
3114     }
3115 }
3116
3117 bool RenderBlock::positionNewFloats()
3118 {
3119     if (!m_floatingObjects)
3120         return false;
3121     
3122     FloatingObject* floatingObject = m_floatingObjects->last();
3123
3124     // If all floats have already been positioned, then we have no work to do.
3125     if (!floatingObject || floatingObject->isPlaced())
3126         return false;
3127
3128     // Move backwards through our floating object list until we find a float that has
3129     // already been positioned.  Then we'll be able to move forward, positioning all of
3130     // the new floats that need it.
3131     FloatingObject* lastFloat = m_floatingObjects->getPrev();
3132     while (lastFloat && !lastFloat->isPlaced()) {
3133         floatingObject = m_floatingObjects->prev();
3134         lastFloat = m_floatingObjects->getPrev();
3135     }
3136
3137     int logicalTop = logicalHeight();
3138     
3139     // The float cannot start above the top position of the last positioned float.
3140     if (lastFloat)
3141         logicalTop = max(logicalTopForFloat(lastFloat), logicalTop);
3142
3143     // Now walk through the set of unpositioned floats and place them.
3144     while (floatingObject) {
3145         // The containing block is responsible for positioning floats, so if we have floats in our
3146         // list that come from somewhere else, do not attempt to position them.
3147         if (floatingObject->renderer()->containingBlock() != this) {
3148             floatingObject = m_floatingObjects->next();
3149             continue;
3150         }
3151
3152         RenderBox* childBox = floatingObject->renderer();
3153         int childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
3154
3155         int rightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
3156         int leftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
3157         int floatLogicalWidth = logicalWidthForFloat(floatingObject); // The width we look for.
3158         if (rightOffset - leftOffset < floatLogicalWidth)
3159             floatLogicalWidth = rightOffset - leftOffset; // Never look for more than what will be available.
3160         
3161         IntRect oldRect(childBox->x(), childBox->y() , childBox->width(), childBox->height());
3162
3163         if (childBox->style()->clear() & CLEFT)
3164             logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
3165         if (childBox->style()->clear() & CRIGHT)
3166             logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
3167
3168         int floatLogicalLeft;
3169         if (childBox->style()->floating() == FLEFT) {
3170             int heightRemainingLeft = 1;
3171             int heightRemainingRight = 1;
3172             floatLogicalLeft = logicalLeftOffsetForLine(logicalTop, leftOffset, false, &heightRemainingLeft);
3173             while (logicalRightOffsetForLine(logicalTop, rightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
3174                 logicalTop += min(heightRemainingLeft, heightRemainingRight);
3175                 floatLogicalLeft = logicalLeftOffsetForLine(logicalTop, leftOffset, false, &heightRemainingLeft);
3176             }
3177             floatLogicalLeft = max(0, floatLogicalLeft);
3178         } else {
3179             int heightRemainingLeft = 1;
3180             int heightRemainingRight = 1;
3181             floatLogicalLeft = logicalRightOffsetForLine(logicalTop, rightOffset, false, &heightRemainingRight);
3182             while (floatLogicalLeft - logicalLeftOffsetForLine(logicalTop, leftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
3183                 logicalTop += min(heightRemainingLeft, heightRemainingRight);
3184                 floatLogicalLeft = logicalRightOffsetForLine(logicalTop, rightOffset, false, &heightRemainingRight);
3185             }
3186             floatLogicalLeft -= logicalWidthForFloat(floatingObject); // Use the original width of the float here, since the local variable
3187                                                                       // |floatLogicalWidth| was capped to the available line width.
3188                                                                       // See fast/block/float/clamped-right-float.html.
3189         }
3190         
3191         setLogicalLeftForFloat(floatingObject, floatLogicalLeft);
3192         setLogicalLeftForChild(childBox, floatLogicalLeft + childLogicalLeftMargin);
3193         setLogicalTopForChild(childBox, logicalTop + marginBeforeForChild(childBox));
3194
3195         if (view()->layoutState()->isPaginated()) {
3196             RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
3197
3198             if (!childBox->needsLayout())
3199                 childBox->markForPaginationRelayoutIfNeeded();;
3200             childBox->layoutIfNeeded();
3201
3202             // If we are unsplittable and don't fit, then we need to move down.
3203             // We include our margins as part of the unsplittable area.
3204             int newLogicalTop = adjustForUnsplittableChild(childBox, logicalTop, true);
3205             
3206             // See if we have a pagination strut that is making us move down further.
3207             // Note that an unsplittable child can't also have a pagination strut, so this is
3208             // exclusive with the case above.
3209             if (childBlock && childBlock->paginationStrut()) {
3210                 newLogicalTop += childBlock->paginationStrut();
3211                 childBlock->setPaginationStrut(0);
3212             }
3213             
3214             if (newLogicalTop != logicalTop) {
3215                 floatingObject->m_paginationStrut = newLogicalTop - logicalTop;
3216                 logicalTop = newLogicalTop;
3217                 setLogicalTopForChild(childBox, logicalTop + marginBeforeForChild(childBox));
3218                 if (childBlock)
3219                     childBlock->setChildNeedsLayout(true, false);
3220                 childBox->layoutIfNeeded();
3221             }
3222         }
3223
3224         setLogicalTopForFloat(floatingObject, logicalTop);
3225         setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
3226
3227         floatingObject->setIsPlaced();
3228
3229         // If the child moved, we have to repaint it.
3230         if (childBox->checkForRepaintDuringLayout())
3231             childBox->repaintDuringLayoutIfMoved(oldRect);
3232
3233         floatingObject = m_floatingObjects->next();
3234     }
3235     return true;
3236 }
3237
3238 bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine)
3239 {
3240     bool didPosition = positionNewFloats();
3241     if (!didPosition || !newFloat->m_paginationStrut)
3242         return didPosition;
3243     
3244     int floatLogicalTop = logicalTopForFloat(newFloat);
3245     int paginationStrut = newFloat->m_paginationStrut;
3246     FloatingObject* f = m_floatingObjects->last();
3247     
3248     ASSERT(f == newFloat);
3249
3250     if (floatLogicalTop - paginationStrut != logicalHeight())
3251         return didPosition;
3252
3253     for (f = m_floatingObjects->prev(); f && f != lastFloatFromPreviousLine; f = m_floatingObjects->prev()) {
3254         if (logicalTopForFloat(f) == logicalHeight()) {
3255             ASSERT(!f->m_paginationStrut);
3256             f->m_paginationStrut = paginationStrut;
3257             RenderBox* o = f->m_renderer;
3258             setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
3259             if (o->isRenderBlock())
3260                 toRenderBlock(o)->setChildNeedsLayout(true, false);
3261             o->layoutIfNeeded();
3262             setLogicalTopForFloat(f, logicalTopForFloat(f) + f->m_paginationStrut);
3263         }
3264     }
3265         
3266     setLogicalHeight(logicalHeight() + paginationStrut);
3267     
3268     return didPosition;