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