Unreviewed, rolling out r105828.
[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::removeChild(RenderObject* oldChild)
1029 {
1030     // If this child is a block, and if our previous and next siblings are
1031     // both anonymous blocks with inline content, then we can go ahead and
1032     // fold the inline content back together.
1033     RenderObject* prev = oldChild->previousSibling();
1034     RenderObject* next = oldChild->nextSibling();
1035     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1036     if (canMergeAnonymousBlocks && prev && next) {
1037         prev->setNeedsLayoutAndPrefWidthsRecalc();
1038         RenderBlock* nextBlock = toRenderBlock(next);
1039         RenderBlock* prevBlock = toRenderBlock(prev);
1040        
1041         if (prev->childrenInline() != next->childrenInline()) {
1042             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1043             RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1044             
1045             // Place the inline children block inside of the block children block instead of deleting it.
1046             // In order to reuse it, we have to reset it to just be a generic anonymous block.  Make sure
1047             // to clear out inherited column properties by just making a new style, and to also clear the
1048             // column span flag if it is set.
1049             ASSERT(!inlineChildrenBlock->continuation());
1050             RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyle(style());
1051             children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlock->hasLayer());
1052             inlineChildrenBlock->setStyle(newStyle);
1053             
1054             // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1055             blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1056                                                             inlineChildrenBlock->hasLayer() || blockChildrenBlock->hasLayer());
1057             next->setNeedsLayoutAndPrefWidthsRecalc();
1058             
1059             // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1060             // of "this". we null out prev or next so that is not used later in the function.
1061             if (inlineChildrenBlock == prevBlock)
1062                 prev = 0;
1063             else
1064                 next = 0;
1065         } else {
1066             // Take all the children out of the |next| block and put them in
1067             // the |prev| block.
1068             nextBlock->moveAllChildrenTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());        
1069             
1070             // Delete the now-empty block's lines and nuke it.
1071             nextBlock->deleteLineBoxTree();
1072             nextBlock->destroy();
1073             next = 0;
1074         }
1075     }
1076
1077     RenderBox::removeChild(oldChild);
1078
1079     RenderObject* child = prev ? prev : next;
1080     if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && !isFlexibleBoxIncludingDeprecated()) {
1081         // The removal has knocked us down to containing only a single anonymous
1082         // box.  We can go ahead and pull the content right back up into our
1083         // box.
1084         setNeedsLayoutAndPrefWidthsRecalc();
1085         setChildrenInline(child->childrenInline());
1086         RenderBlock* anonBlock = toRenderBlock(children()->removeChildNode(this, child, child->hasLayer()));
1087         anonBlock->moveAllChildrenTo(this, child->hasLayer());
1088         // Delete the now-empty block's lines and nuke it.
1089         anonBlock->deleteLineBoxTree();
1090         anonBlock->destroy();
1091     }
1092
1093     if (!firstChild() && !documentBeingDestroyed()) {
1094         // If this was our last child be sure to clear out our line boxes.
1095         if (childrenInline())
1096             deleteLineBoxTree();
1097     }
1098 }
1099
1100 bool RenderBlock::isSelfCollapsingBlock() const
1101 {
1102     // We are not self-collapsing if we
1103     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1104     // (b) are a table,
1105     // (c) have border/padding,
1106     // (d) have a min-height
1107     // (e) have specified that one of our margins can't collapse using a CSS extension
1108     if (logicalHeight() > 0
1109         || isTable() || borderAndPaddingLogicalHeight()
1110         || style()->logicalMinHeight().isPositive()
1111         || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1112         return false;
1113
1114     Length logicalHeightLength = style()->logicalHeight();
1115     bool hasAutoHeight = logicalHeightLength.isAuto();
1116     if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
1117         hasAutoHeight = true;
1118         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1119             if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1120                 hasAutoHeight = false;
1121         }
1122     }
1123
1124     // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1125     // on whether we have content that is all self-collapsing or not.
1126     if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1127         // If the block has inline children, see if we generated any line boxes.  If we have any
1128         // line boxes, then we can't be self-collapsing, since we have content.
1129         if (childrenInline())
1130             return !firstLineBox();
1131         
1132         // Whether or not we collapse is dependent on whether all our normal flow children
1133         // are also self-collapsing.
1134         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1135             if (child->isFloatingOrPositioned())
1136                 continue;
1137             if (!child->isSelfCollapsingBlock())
1138                 return false;
1139         }
1140         return true;
1141     }
1142     return false;
1143 }
1144
1145 void RenderBlock::startDelayUpdateScrollInfo()
1146 {
1147     if (gDelayUpdateScrollInfo == 0) {
1148         ASSERT(!gDelayedUpdateScrollInfoSet);
1149         gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1150     }
1151     ASSERT(gDelayedUpdateScrollInfoSet);
1152     ++gDelayUpdateScrollInfo;
1153 }
1154
1155 void RenderBlock::finishDelayUpdateScrollInfo()
1156 {
1157     --gDelayUpdateScrollInfo;
1158     ASSERT(gDelayUpdateScrollInfo >= 0);
1159     if (gDelayUpdateScrollInfo == 0) {
1160         ASSERT(gDelayedUpdateScrollInfoSet);
1161
1162         OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1163         gDelayedUpdateScrollInfoSet = 0;
1164
1165         for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1166             RenderBlock* block = *it;
1167             if (block->hasOverflowClip()) {
1168                 block->layer()->updateScrollInfoAfterLayout();
1169             }
1170         }
1171     }
1172 }
1173
1174 void RenderBlock::updateScrollInfoAfterLayout()
1175 {
1176     if (hasOverflowClip()) {
1177         if (gDelayUpdateScrollInfo)
1178             gDelayedUpdateScrollInfoSet->add(this);
1179         else
1180             layer()->updateScrollInfoAfterLayout();
1181     }
1182 }
1183
1184 void RenderBlock::layout()
1185 {
1186     // Update our first letter info now.
1187     updateFirstLetter();
1188
1189     // Table cells call layoutBlock directly, so don't add any logic here.  Put code into
1190     // layoutBlock().
1191     layoutBlock(false);
1192     
1193     // It's safe to check for control clip here, since controls can never be table cells.
1194     // If we have a lightweight clip, there can never be any overflow from children.
1195     if (hasControlClip() && m_overflow)
1196         clearLayoutOverflow();
1197 }
1198
1199 void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight, BlockLayoutPass layoutPass)
1200 {
1201     ASSERT(needsLayout());
1202
1203     if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
1204         return;                                      // cause us to come in here.  Just bail.
1205
1206     if (!relayoutChildren && simplifiedLayout())
1207         return;
1208
1209     LayoutRepainter repainter(*this, everHadLayout() && checkForRepaintDuringLayout());
1210
1211     LayoutUnit oldWidth = logicalWidth();
1212     LayoutUnit oldColumnWidth = desiredColumnWidth();
1213
1214     computeLogicalWidth();
1215     calcColumnWidth();
1216
1217     m_overflow.clear();
1218
1219     if (oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth())
1220         relayoutChildren = true;
1221
1222     // If nothing changed about our floating positioned objects, let's go ahead and try to place them as
1223     // floats to avoid doing two passes.
1224     BlockLayoutPass floatsLayoutPass = layoutPass;
1225     if (floatsLayoutPass == NormalLayoutPass && !relayoutChildren && !positionedFloatsNeedRelayout())
1226         floatsLayoutPass = PositionedFloatLayoutPass;
1227     clearFloats(floatsLayoutPass);
1228
1229     LayoutUnit previousHeight = logicalHeight();
1230     setLogicalHeight(0);
1231     bool hasSpecifiedPageLogicalHeight = false;
1232     bool pageLogicalHeightChanged = false;
1233     ColumnInfo* colInfo = columnInfo();
1234     if (hasColumns()) {
1235         if (!pageLogicalHeight) {
1236             // We need to go ahead and set our explicit page height if one exists, so that we can
1237             // avoid doing two layout passes.
1238             computeLogicalHeight();
1239             LayoutUnit columnHeight = contentLogicalHeight();
1240             if (columnHeight > 0) {
1241                 pageLogicalHeight = columnHeight;
1242                 hasSpecifiedPageLogicalHeight = true;
1243             }
1244             setLogicalHeight(0);
1245         }
1246         if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
1247             colInfo->setColumnHeight(pageLogicalHeight);
1248             pageLogicalHeightChanged = true;
1249         }
1250         
1251         if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
1252             colInfo->clearForcedBreaks();
1253     }
1254
1255     RenderView* renderView = view();
1256     RenderStyle* styleToUse = style();
1257     LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, colInfo);
1258     
1259     if (inRenderFlowThread()) {
1260         // Regions changing widths can force us to relayout our children.
1261         if (logicalWidthChangedInRegions())
1262             relayoutChildren = true;
1263     
1264         // Set our start and end regions. No regions above or below us will be considered by our children. They are
1265         // effectively clamped to our region range.
1266         LayoutUnit oldHeight =  logicalHeight();
1267         LayoutUnit oldLogicalTop = logicalTop();
1268         setLogicalHeight(numeric_limits<LayoutUnit>::max() / 2); 
1269         computeLogicalHeight();
1270         enclosingRenderFlowThread()->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
1271         setLogicalHeight(oldHeight);
1272         setLogicalTop(oldLogicalTop);
1273     }
1274
1275     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
1276     // our current maximal positive and negative margins.  These values are used when we
1277     // are collapsed with adjacent blocks, so for example, if you have block A and B
1278     // collapsing together, then you'd take the maximal positive margin from both A and B
1279     // and subtract it from the maximal negative margin from both A and B to get the
1280     // true collapsed margin.  This algorithm is recursive, so when we finish layout()
1281     // our block knows its current maximal positive/negative values.
1282     //
1283     // Start out by setting our margin values to our current margins.  Table cells have
1284     // no margins, so we don't fill in the values for table cells.
1285     bool isCell = isTableCell();
1286     if (!isCell) {
1287         initMaxMarginValues();
1288         
1289         setMarginBeforeQuirk(styleToUse->marginBefore().quirk());
1290         setMarginAfterQuirk(styleToUse->marginAfter().quirk());
1291
1292         Node* n = node();
1293         if (n && n->hasTagName(formTag) && static_cast<HTMLFormElement*>(n)->isMalformed()) {
1294             // See if this form is malformed (i.e., unclosed). If so, don't give the form
1295             // a bottom margin.
1296             setMaxMarginAfterValues(0, 0);
1297         }
1298         
1299         setPaginationStrut(0);
1300     }
1301
1302     // For overflow:scroll blocks, ensure we have both scrollbars in place always.
1303     if (scrollsOverflow()) {
1304         if (styleToUse->overflowX() == OSCROLL)
1305             layer()->setHasHorizontalScrollbar(true);
1306         if (styleToUse->overflowY() == OSCROLL)
1307             layer()->setHasVerticalScrollbar(true);
1308     }
1309
1310     LayoutUnit repaintLogicalTop = 0;
1311     LayoutUnit repaintLogicalBottom = 0;
1312     LayoutUnit maxFloatLogicalBottom = 0;
1313     if (!firstChild() && !isAnonymousBlock())
1314         setChildrenInline(true);
1315     if (childrenInline())
1316         layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
1317     else
1318         layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
1319
1320     // Expand our intrinsic height to encompass floats.
1321     LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
1322     if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
1323         setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
1324     
1325     if (layoutColumns(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
1326         return;
1327  
1328     // Calculate our new height.
1329     LayoutUnit oldHeight = logicalHeight();
1330     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
1331     computeLogicalHeight();
1332     LayoutUnit newHeight = logicalHeight();
1333     if (oldHeight != newHeight) {
1334         if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
1335             // One of our children's floats may have become an overhanging float for us. We need to look for it.
1336             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1337                 if (child->isBlockFlow() && !child->isFloatingOrPositioned()) {
1338                     RenderBlock* block = toRenderBlock(child);
1339                     if (block->lowestFloatLogicalBottomIncludingPositionedFloats() + block->logicalTop() > newHeight)
1340                         addOverhangingFloats(block, false);
1341                 }
1342             }
1343         }
1344     }
1345
1346     if (previousHeight != newHeight)
1347         relayoutChildren = true;
1348
1349     bool needAnotherLayoutPass = layoutPositionedObjects(relayoutChildren || isRoot());
1350
1351     if (inRenderFlowThread())
1352         enclosingRenderFlowThread()->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
1353
1354     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
1355     computeOverflow(oldClientAfterEdge);
1356     
1357     statePusher.pop();
1358
1359     if (renderView->layoutState()->m_pageLogicalHeight)
1360         setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(logicalTop()));
1361
1362     updateLayerTransform();
1363
1364     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
1365     // we overflow or not.
1366     updateScrollInfoAfterLayout();
1367
1368     // FIXME: This repaint logic should be moved into a separate helper function!
1369     // Repaint with our new bounds if they are different from our old bounds.
1370     bool didFullRepaint = repainter.repaintAfterLayout();
1371     if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
1372         // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1373         // it had to lay out.  We wouldn't need the hasOverflowClip() hack in that case either.
1374         LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1375         LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1376         if (hasOverflowClip()) {
1377             // 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.
1378             // 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.
1379             // layoutInlineChildren should be patched to compute the entire repaint rect.
1380             repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1381             repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1382         }
1383         
1384         LayoutRect repaintRect;
1385         if (isHorizontalWritingMode())
1386             repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
1387         else
1388             repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1389
1390         // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1391         adjustRectForColumns(repaintRect);
1392
1393         repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1394         
1395         if (hasOverflowClip()) {
1396             // Adjust repaint rect for scroll offset
1397             repaintRect.move(-layer()->scrolledContentOffset());
1398
1399             // Don't allow this rect to spill out of our overflow box.
1400             repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1401         }
1402
1403         // Make sure the rect is still non-empty after intersecting for overflow above
1404         if (!repaintRect.isEmpty()) {
1405             // FIXME: Might need rounding once we switch to float, see https://bugs.webkit.org/show_bug.cgi?id=64021
1406             repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1407             if (hasReflection())
1408                 repaintRectangle(reflectedRect(repaintRect));
1409         }
1410     }
1411     
1412     if (needAnotherLayoutPass && layoutPass == NormalLayoutPass) {
1413         setChildNeedsLayout(true, false);
1414         layoutBlock(false, pageLogicalHeight, PositionedFloatLayoutPass);
1415     } else
1416         setNeedsLayout(false);
1417 }
1418
1419 void RenderBlock::addOverflowFromChildren()
1420 {
1421     if (!hasColumns()) {
1422         if (childrenInline())
1423             addOverflowFromInlineChildren();
1424         else
1425             addOverflowFromBlockChildren();
1426     } else {
1427         ColumnInfo* colInfo = columnInfo();
1428         if (columnCount(colInfo)) {
1429             LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1430             addLayoutOverflow(lastRect);
1431             if (!hasOverflowClip())
1432                 addVisualOverflow(lastRect);
1433         }
1434     }
1435 }
1436
1437 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1438 {
1439     // Add overflow from children.
1440     addOverflowFromChildren();
1441
1442     if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
1443         addOverflowFromFloats();
1444
1445     // Add in the overflow from positioned objects.
1446     addOverflowFromPositionedObjects();
1447
1448     if (hasOverflowClip()) {
1449         // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1450         // and bottom padding.  Set the axis we don't care about to be 1, since we want this overflow to always
1451         // be considered reachable.
1452         LayoutRect clientRect(clientBoxRect());
1453         LayoutRect rectToApply;
1454         if (isHorizontalWritingMode())
1455             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1456         else
1457             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1458         addLayoutOverflow(rectToApply);
1459     }
1460         
1461     // Add visual overflow from box-shadow and border-image-outset.
1462     addVisualEffectOverflow();
1463
1464     // Add visual overflow from theme.
1465     addVisualOverflowFromTheme();
1466 }
1467
1468 void RenderBlock::addOverflowFromBlockChildren()
1469 {
1470     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1471         if (!child->isFloatingOrPositioned())
1472             addOverflowFromChild(child);
1473     }
1474 }
1475
1476 void RenderBlock::addOverflowFromFloats()
1477 {
1478     if (!m_floatingObjects)
1479         return;
1480
1481     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1482     FloatingObjectSetIterator end = floatingObjectSet.end();
1483     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1484         FloatingObject* r = *it;
1485         if (r->m_isDescendant && !r->m_renderer->isPositioned())
1486             addOverflowFromChild(r->m_renderer, IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
1487     }
1488     return;
1489 }
1490
1491 void RenderBlock::addOverflowFromPositionedObjects()
1492 {
1493     if (!m_positionedObjects)
1494         return;
1495
1496     RenderBox* positionedObject;
1497     Iterator end = m_positionedObjects->end();
1498     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
1499         positionedObject = *it;
1500         
1501         // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1502         if (positionedObject->style()->position() != FixedPosition)
1503             addOverflowFromChild(positionedObject);
1504     }
1505 }
1506
1507 void RenderBlock::addVisualOverflowFromTheme()
1508 {
1509     if (!style()->hasAppearance())
1510         return;
1511
1512     IntRect inflatedRect = borderBoxRect();
1513     theme()->adjustRepaintRect(this, inflatedRect);
1514     addVisualOverflow(inflatedRect);
1515 }
1516
1517 bool RenderBlock::expandsToEncloseOverhangingFloats() const
1518 {
1519     return isInlineBlockOrInlineTable() || isFloatingOrPositioned() || hasOverflowClip() || (parent() && parent()->isDeprecatedFlexibleBox())
1520            || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
1521 }
1522
1523 void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1524 {
1525     bool isHorizontal = isHorizontalWritingMode();
1526     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1527     
1528     LayoutUnit logicalTop = logicalHeight();
1529     setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
1530
1531     if (!marginInfo.canCollapseWithMarginBefore()) {
1532         child->computeBlockDirectionMargins(this);
1533         LayoutUnit marginBefore = marginBeforeForChild(child);
1534         LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1535         LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1536         if (marginBefore > 0) {
1537             if (marginBefore > collapsedBeforePos)
1538                 collapsedBeforePos = marginBefore;
1539         } else {
1540             if (-marginBefore > collapsedBeforeNeg)
1541                 collapsedBeforeNeg = -marginBefore;
1542         }
1543         logicalTop += (collapsedBeforePos - collapsedBeforeNeg) - marginBefore;
1544     }
1545     
1546     RenderLayer* childLayer = child->layer();
1547     if (childLayer->staticBlockPosition() != logicalTop) {
1548         childLayer->setStaticBlockPosition(logicalTop);
1549         if (hasStaticBlockPosition)
1550             child->setChildNeedsLayout(true, false);
1551     }
1552 }
1553
1554 void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
1555 {
1556     // The float should be positioned taking into account the bottom margin
1557     // of the previous flow.  We add that margin into the height, get the
1558     // float positioned properly, and then subtract the margin out of the
1559     // height again.  In the case of self-collapsing blocks, we always just
1560     // use the top margins, since the self-collapsing block collapsed its
1561     // own bottom margin into its top margin.
1562     //
1563     // Note also that the previous flow may collapse its margin into the top of
1564     // our block.  If this is the case, then we do not add the margin in to our
1565     // height when computing the position of the float.   This condition can be tested
1566     // for by simply calling canCollapseWithMarginBefore.  See
1567     // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1568     // an example of this scenario.
1569     LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? 0 : marginInfo.margin();
1570     setLogicalHeight(logicalHeight() + marginOffset);
1571     positionNewFloats();
1572     setLogicalHeight(logicalHeight() - marginOffset);
1573 }
1574
1575 bool RenderBlock::handleSpecialChild(RenderBox* child, const MarginInfo& marginInfo)
1576 {
1577     // Handle in the given order
1578     return handlePositionedChild(child, marginInfo)
1579         || handleFloatingChild(child, marginInfo)
1580         || handleRunInChild(child);
1581 }
1582
1583
1584 bool RenderBlock::handlePositionedChild(RenderBox* child, const MarginInfo& marginInfo)
1585 {
1586     if (child->isPositioned()) {
1587         child->containingBlock()->insertPositionedObject(child);
1588         adjustPositionedBlock(child, marginInfo);
1589         return true;
1590     }
1591     return false;
1592 }
1593
1594 bool RenderBlock::handleFloatingChild(RenderBox* child, const MarginInfo& marginInfo)
1595 {
1596     if (child->isFloating()) {
1597         insertFloatingObject(child);
1598         adjustFloatingBlock(marginInfo);
1599         return true;
1600     }
1601     return false;
1602 }
1603
1604 bool RenderBlock::handleRunInChild(RenderBox* child)
1605 {
1606     // See if we have a run-in element with inline children.  If the
1607     // children aren't inline, then just treat the run-in as a normal
1608     // block.
1609     if (!child->isRunIn() || !child->childrenInline())
1610         return false;
1611     // FIXME: We don't handle non-block elements with run-in for now.
1612     if (!child->isRenderBlock())
1613         return false;
1614
1615     RenderBlock* blockRunIn = toRenderBlock(child);
1616     RenderObject* curr = blockRunIn->nextSibling();
1617     if (!curr || !curr->isRenderBlock() || !curr->childrenInline() || curr->isRunIn() || curr->isAnonymous() || curr->isFloatingOrPositioned())
1618         return false;
1619
1620     RenderBlock* currBlock = toRenderBlock(curr);
1621
1622     // First we destroy any :before/:after content. It will be regenerated by the new inline.
1623     // Exception is if the run-in itself is generated.
1624     if (child->style()->styleType() != BEFORE && child->style()->styleType() != AFTER) {
1625         RenderObject* generatedContent;
1626         if (child->getCachedPseudoStyle(BEFORE) && (generatedContent = child->beforePseudoElementRenderer()))
1627             generatedContent->destroy();
1628         if (child->getCachedPseudoStyle(AFTER) && (generatedContent = child->afterPseudoElementRenderer()))
1629             generatedContent->destroy();
1630     }
1631
1632     // Remove the old child.
1633     children()->removeChildNode(this, blockRunIn);
1634
1635     // Create an inline.
1636     Node* runInNode = blockRunIn->node();
1637     RenderInline* inlineRunIn = new (renderArena()) RenderInline(runInNode ? runInNode : document());
1638     inlineRunIn->setStyle(blockRunIn->style());
1639
1640     // Move the nodes from the old child to the new child
1641     for (RenderObject* runInChild = blockRunIn->firstChild(); runInChild;) {
1642         RenderObject* nextSibling = runInChild->nextSibling();
1643         blockRunIn->children()->removeChildNode(blockRunIn, runInChild, false);
1644         inlineRunIn->addChild(runInChild); // Use addChild instead of appendChildNode since it handles correct placement of the children relative to :after-generated content.
1645         runInChild = nextSibling;
1646     }
1647
1648     // 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
1649     // anything before the first child. e.g. details tag. See https://bugs.webkit.org/show_bug.cgi?id=58228.
1650     currBlock->addChild(inlineRunIn, currBlock->firstChild());
1651     
1652     // If the run-in had an element, we need to set the new renderer.
1653     if (runInNode)
1654         runInNode->setRenderer(inlineRunIn);
1655
1656     // Destroy the block run-in, which includes deleting its line box tree.
1657     blockRunIn->deleteLineBoxTree();
1658     blockRunIn->destroy();
1659
1660     // The block acts like an inline, so just null out its
1661     // position.
1662     
1663     return true;
1664 }
1665
1666 LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
1667 {
1668     // Get the four margin values for the child and cache them.
1669     const MarginValues childMargins = marginValuesForChild(child);
1670
1671     // Get our max pos and neg top margins.
1672     LayoutUnit posTop = childMargins.positiveMarginBefore();
1673     LayoutUnit negTop = childMargins.negativeMarginBefore();
1674
1675     // For self-collapsing blocks, collapse our bottom margins into our
1676     // top to get new posTop and negTop values.
1677     if (child->isSelfCollapsingBlock()) {
1678         posTop = max(posTop, childMargins.positiveMarginAfter());
1679         negTop = max(negTop, childMargins.negativeMarginAfter());
1680     }
1681     
1682     // See if the top margin is quirky. We only care if this child has
1683     // margins that will collapse with us.
1684     bool topQuirk = child->isMarginBeforeQuirk() || style()->marginBeforeCollapse() == MDISCARD;
1685
1686     if (marginInfo.canCollapseWithMarginBefore()) {
1687         // This child is collapsing with the top of the
1688         // block.  If it has larger margin values, then we need to update
1689         // our own maximal values.
1690         if (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
1691             setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
1692
1693         // The minute any of the margins involved isn't a quirk, don't
1694         // collapse it away, even if the margin is smaller (www.webreference.com
1695         // has an example of this, a <dt> with 0.8em author-specified inside
1696         // a <dl> inside a <td>.
1697         if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
1698             setMarginBeforeQuirk(false);
1699             marginInfo.setDeterminedMarginBeforeQuirk(true);
1700         }
1701
1702         if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
1703             // We have no top margin and our top child has a quirky margin.
1704             // We will pick up this quirky margin and pass it through.
1705             // This deals with the <td><div><p> case.
1706             // Don't do this for a block that split two inlines though.  You do
1707             // still apply margins in this case.
1708             setMarginBeforeQuirk(true);
1709     }
1710
1711     if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1712         marginInfo.setMarginBeforeQuirk(topQuirk);
1713
1714     LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1715     LayoutUnit logicalTop = beforeCollapseLogicalTop;
1716     if (child->isSelfCollapsingBlock()) {
1717         // This child has no height.  We need to compute our
1718         // position before we collapse the child's margins together,
1719         // so that we can get an accurate position for the zero-height block.
1720         LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
1721         LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
1722         marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
1723         
1724         // Now collapse the child's margins together, which means examining our
1725         // bottom margin values as well. 
1726         marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
1727         marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
1728
1729         if (!marginInfo.canCollapseWithMarginBefore())
1730             // We need to make sure that the position of the self-collapsing block
1731             // is correct, since it could have overflowing content
1732             // that needs to be positioned correctly (e.g., a block that
1733             // had a specified height of 0 but that actually had subcontent).
1734             logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
1735     }
1736     else {
1737         if (child->style()->marginBeforeCollapse() == MSEPARATE) {
1738             setLogicalHeight(logicalHeight() + marginInfo.margin() + marginBeforeForChild(child));
1739             logicalTop = logicalHeight();
1740         }
1741         else if (!marginInfo.atBeforeSideOfBlock() ||
1742             (!marginInfo.canCollapseMarginBeforeWithChildren()
1743              && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.marginBeforeQuirk()))) {
1744             // We're collapsing with a previous sibling's margins and not
1745             // with the top of the block.
1746             setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
1747             logicalTop = logicalHeight();
1748         }
1749
1750         marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1751         marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1752
1753         if (marginInfo.margin())
1754             marginInfo.setMarginAfterQuirk(child->isMarginAfterQuirk() || style()->marginAfterCollapse() == MDISCARD);
1755     }
1756     
1757     // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
1758     // collapsed into the page edge.
1759     LayoutState* layoutState = view()->layoutState();
1760     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
1761         && hasNextPage(beforeCollapseLogicalTop)) {
1762         LayoutUnit oldLogicalTop = logicalTop;
1763         logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
1764         setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
1765     }
1766     return logicalTop;
1767 }
1768
1769 LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
1770 {
1771     LayoutUnit heightIncrease = getClearDelta(child, yPos);
1772     if (!heightIncrease)
1773         return yPos;
1774
1775     if (child->isSelfCollapsingBlock()) {
1776         // For self-collapsing blocks that clear, they can still collapse their
1777         // margins with following siblings.  Reset the current margins to represent
1778         // the self-collapsing block's margins only.
1779         // CSS2.1 states:
1780         // "An element that has had clearance applied to it never collapses its top margin with its parent block's bottom margin.
1781         // Therefore if we are at the bottom of the block, let's go ahead and reset margins to only include the
1782         // self-collapsing block's bottom margin.
1783         bool atBottomOfBlock = true;
1784         for (RenderBox* curr = child->nextSiblingBox(); curr && atBottomOfBlock; curr = curr->nextSiblingBox()) {
1785             if (!curr->isFloatingOrPositioned())
1786                 atBottomOfBlock = false;
1787         }
1788         
1789         MarginValues childMargins = marginValuesForChild(child);
1790         if (atBottomOfBlock) {
1791             marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1792             marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1793         } else {
1794             marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
1795             marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
1796         }
1797         
1798         // Adjust our height such that we are ready to be collapsed with subsequent siblings (or the bottom
1799         // of the parent block).
1800         setLogicalHeight(child->y() - max<LayoutUnit>(0, marginInfo.margin()));
1801     } else
1802         // Increase our height by the amount we had to clear.
1803         setLogicalHeight(height() + heightIncrease);
1804     
1805     if (marginInfo.canCollapseWithMarginBefore()) {
1806         // We can no longer collapse with the top of the block since a clear
1807         // occurred.  The empty blocks collapse into the cleared block.
1808         // FIXME: This isn't quite correct.  Need clarification for what to do
1809         // if the height the cleared block is offset by is smaller than the
1810         // margins involved.
1811         setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
1812         marginInfo.setAtBeforeSideOfBlock(false);
1813     }
1814     
1815     return yPos + heightIncrease;
1816 }
1817
1818 LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1819 {
1820     // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
1821     // relayout if there are intruding floats.
1822     LayoutUnit logicalTopEstimate = logicalHeight();
1823     if (!marginInfo.canCollapseWithMarginBefore()) {
1824         LayoutUnit childMarginBefore = child->selfNeedsLayout() ? marginBeforeForChild(child) : collapsedMarginBeforeForChild(child);
1825         logicalTopEstimate += max(marginInfo.margin(), childMarginBefore);
1826     }
1827
1828     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1829     // page.
1830     LayoutState* layoutState = view()->layoutState();
1831     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
1832         && hasNextPage(logicalHeight()))
1833         logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1834
1835     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1836     
1837     estimateWithoutPagination = logicalTopEstimate;
1838
1839     if (layoutState->isPaginated()) {
1840         // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1841         logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
1842     
1843         // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1844         logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
1845         
1846         if (!child->selfNeedsLayout() && child->isRenderBlock())
1847             logicalTopEstimate += toRenderBlock(child)->paginationStrut();
1848     }
1849
1850     return logicalTopEstimate;
1851 }
1852
1853 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart,
1854     LayoutUnit childLogicalWidth, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
1855 {
1856     LayoutUnit startPosition = startOffsetForContent(region, offsetFromLogicalTopOfFirstPage);
1857
1858     // Add in our start margin.
1859     LayoutUnit oldPosition = startPosition + childMarginStart;
1860     LayoutUnit newPosition = oldPosition;
1861
1862     LayoutUnit blockOffset = logicalTopForChild(child);
1863     if (region)
1864         blockOffset = max(blockOffset, blockOffset + (region->offsetFromLogicalTopOfFirstPage() - offsetFromLogicalTopOfFirstPage));
1865
1866     LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, offsetFromLogicalTopOfFirstPage);
1867     if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
1868         if (childMarginStart < 0)
1869             startOff += childMarginStart;
1870         newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
1871         // FIXME: Needs to use epsilon once we switch to float, see https://bugs.webkit.org/show_bug.cgi?id=64021
1872     } else if (startOff != startPosition) {
1873         // The object is shifting to the "end" side of the block. The object might be centered, so we need to
1874         // recalculate our inline direction margins. Note that the containing block content
1875         // width computation will take into account the delta between |startOff| and |startPosition|
1876         // so that we can just pass the content width in directly to the |computeMarginsInContainingBlockInlineDirection|
1877         // function.
1878         LayoutUnit oldMarginStart = marginStartForChild(child);
1879         LayoutUnit oldMarginEnd = marginEndForChild(child);
1880         RenderBox* mutableChild = const_cast<RenderBox*>(child);
1881         mutableChild->computeInlineDirectionMargins(this,
1882             availableLogicalWidthForLine(blockOffset, false, region, offsetFromLogicalTopOfFirstPage), childLogicalWidth);
1883         newPosition = startOff + marginStartForChild(child);
1884         if (inRenderFlowThread()) {
1885             setMarginStartForChild(mutableChild, oldMarginStart);
1886             setMarginEndForChild(mutableChild, oldMarginEnd);
1887         }
1888     }
1889     
1890     return newPosition - oldPosition;
1891 }
1892
1893 void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child)
1894 {
1895     LayoutUnit startPosition = borderStart() + paddingStart();
1896     LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
1897
1898     // Add in our start margin.
1899     LayoutUnit childMarginStart = marginStartForChild(child);
1900     LayoutUnit newPosition = startPosition + childMarginStart;
1901         
1902     // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats.  They need
1903     // to shift over as necessary to dodge any floats that might get in the way.
1904     if (child->avoidsFloats() && containsFloats() && !inRenderFlowThread())
1905         newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child), logicalWidthForChild(child));
1906
1907     setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), ApplyLayoutDelta);
1908 }
1909
1910 void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1911 {
1912     if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
1913         // Update our max pos/neg bottom margins, since we collapsed our bottom margins
1914         // with our children.
1915         setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
1916
1917         if (!marginInfo.marginAfterQuirk())
1918             setMarginAfterQuirk(false);
1919
1920         if (marginInfo.marginAfterQuirk() && marginAfter() == 0)
1921             // We have no bottom margin and our last child has a quirky margin.
1922             // We will pick up this quirky margin and pass it through.
1923             // This deals with the <td><div><p> case.
1924             setMarginAfterQuirk(true);
1925     }
1926 }
1927
1928 void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1929 {
1930     marginInfo.setAtAfterSideOfBlock(true);
1931
1932     // If we can't collapse with children then go ahead and add in the bottom margin.
1933     if (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
1934         && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.marginAfterQuirk()))
1935         setLogicalHeight(logicalHeight() + marginInfo.margin());
1936         
1937     // Now add in our bottom border/padding.
1938     setLogicalHeight(logicalHeight() + afterSide);
1939
1940     // Negative margins can cause our height to shrink below our minimal height (border/padding).
1941     // If this happens, ensure that the computed height is increased to the minimal height.
1942     setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
1943
1944     // Update our bottom collapsed margin info.
1945     setCollapsedBottomMargin(marginInfo);
1946 }
1947
1948 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
1949 {
1950     if (isHorizontalWritingMode()) {
1951         if (applyDelta == ApplyLayoutDelta)
1952             view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
1953         child->setX(logicalLeft);
1954     } else {
1955         if (applyDelta == ApplyLayoutDelta)
1956             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
1957         child->setY(logicalLeft);
1958     }
1959 }
1960
1961 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
1962 {
1963     if (isHorizontalWritingMode()) {
1964         if (applyDelta == ApplyLayoutDelta)
1965             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
1966         child->setY(logicalTop);
1967     } else {
1968         if (applyDelta == ApplyLayoutDelta)
1969             view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
1970         child->setX(logicalTop);
1971     }
1972 }
1973
1974 void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
1975 {
1976     if (gPercentHeightDescendantsMap) {
1977         if (HashSet<RenderBox*>* descendants = gPercentHeightDescendantsMap->get(this)) {
1978             HashSet<RenderBox*>::iterator end = descendants->end();
1979             for (HashSet<RenderBox*>::iterator it = descendants->begin(); it != end; ++it) {
1980                 RenderBox* box = *it;
1981                 while (box != this) {
1982                     if (box->normalChildNeedsLayout())
1983                         break;
1984                     box->setChildNeedsLayout(true, false);
1985                     box = box->containingBlock();
1986                     ASSERT(box);
1987                     if (!box)
1988                         break;
1989                 }
1990             }
1991         }
1992     }
1993
1994     LayoutUnit beforeEdge = borderBefore() + paddingBefore();
1995     LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
1996
1997     setLogicalHeight(beforeEdge);
1998     
1999     // Lay out our hypothetical grid line as though it occurs at the top of the block.
2000     if (view()->layoutState()->currentLineGrid() == this)
2001         layoutLineGridBox();
2002
2003     // The margin struct caches all our current margin collapsing state.  The compact struct caches state when we encounter compacts,
2004     MarginInfo marginInfo(this, beforeEdge, afterEdge);
2005
2006     // Fieldsets need to find their legend and position it inside the border of the object.
2007     // The legend then gets skipped during normal layout.  The same is true for ruby text.
2008     // It doesn't get included in the normal layout process but is instead skipped.
2009     RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
2010
2011     LayoutUnit previousFloatLogicalBottom = 0;
2012     maxFloatLogicalBottom = 0;
2013
2014     RenderBox* next = firstChildBox();
2015
2016     while (next) {
2017         RenderBox* child = next;
2018         next = child->nextSiblingBox();
2019
2020         if (childToExclude == child)
2021             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
2022
2023         // Make sure we layout children if they need it.
2024         // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
2025         // an auto value.  Add a method to determine this, so that we can avoid the relayout.
2026         RenderStyle* childStyle = child->style();
2027         if (relayoutChildren || ((childStyle->logicalHeight().isPercent() || childStyle->logicalMinHeight().isPercent() || childStyle->logicalMaxHeight().isPercent()) && !isRenderView()))
2028             child->setChildNeedsLayout(true, false);
2029
2030         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2031         if (relayoutChildren && child->needsPreferredWidthsRecalculation())
2032             child->setPreferredLogicalWidthsDirty(true, false);
2033
2034         // Handle the four types of special elements first.  These include positioned content, floating content, compacts and
2035         // run-ins.  When we encounter these four types of objects, we don't actually lay them out as normal flow blocks.
2036         if (handleSpecialChild(child, marginInfo))
2037             continue;
2038
2039         // Lay out the child.
2040         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
2041     }
2042     
2043     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
2044     // determining the correct collapsed bottom margin information.
2045     handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
2046 }
2047
2048 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
2049 {
2050     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
2051     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
2052
2053     // The child is a normal flow object.  Compute the margins we will use for collapsing now.
2054     child->computeBlockDirectionMargins(this);
2055
2056     // Do not allow a collapse if the margin-before-collapse style is set to SEPARATE.
2057     RenderStyle* childStyle = child->style();
2058     if (childStyle->marginBeforeCollapse() == MSEPARATE) {
2059         marginInfo.setAtBeforeSideOfBlock(false);
2060         marginInfo.clearMargin();
2061     }
2062
2063     // Try to guess our correct logical top position.  In most cases this guess will
2064     // be correct.  Only if we're wrong (when we compute the real logical top position)
2065     // will we have to potentially relayout.
2066     LayoutUnit estimateWithoutPagination;
2067     LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
2068
2069     // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
2070     LayoutRect oldRect(child->x(), child->y() , child->width(), child->height());
2071     LayoutUnit oldLogicalTop = logicalTopForChild(child);
2072
2073 #if !ASSERT_DISABLED
2074     LayoutSize oldLayoutDelta = view()->layoutDelta();
2075 #endif
2076     // Go ahead and position the child as though it didn't collapse with the top.
2077     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
2078
2079     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
2080     bool markDescendantsWithFloats = false;
2081     if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
2082         markDescendantsWithFloats = true;
2083     else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
2084         // If an element might be affected by the presence of floats, then always mark it for
2085         // layout.
2086         LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottomIncludingPositionedFloats());
2087         if (fb > logicalTopEstimate)
2088             markDescendantsWithFloats = true;
2089     }
2090
2091     if (childRenderBlock) {
2092         if (markDescendantsWithFloats)
2093             childRenderBlock->markAllDescendantsWithFloatsForLayout();
2094         if (!child->isWritingModeRoot())
2095             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottomIncludingPositionedFloats());
2096     }
2097
2098     if (!child->needsLayout())
2099         child->markForPaginationRelayoutIfNeeded();
2100
2101     bool childHadLayout = child->everHadLayout();
2102     bool childNeededLayout = child->needsLayout();
2103     if (childNeededLayout)
2104         child->layout();
2105
2106     // Cache if we are at the top of the block right now.
2107     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
2108
2109     // Now determine the correct ypos based off examination of collapsing margin
2110     // values.
2111     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
2112
2113     // Now check for clear.
2114     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
2115     
2116     bool paginated = view()->layoutState()->isPaginated();
2117     if (paginated)
2118         logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
2119             atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
2120
2121     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
2122
2123     // Now we have a final top position.  See if it really does end up being different from our estimate.
2124     if (logicalTopAfterClear != logicalTopEstimate) {
2125         if (child->shrinkToAvoidFloats()) {
2126             // The child's width depends on the line width.
2127             // When the child shifts to clear an item, its width can
2128             // change (because it has more available line width).
2129             // So go ahead and mark the item as dirty.
2130             child->setChildNeedsLayout(true, false);
2131         }
2132         
2133         if (childRenderBlock) {
2134             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
2135                 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2136             if (!child->needsLayout())
2137                 child->markForPaginationRelayoutIfNeeded();
2138         }
2139
2140         // Our guess was wrong. Make the child lay itself out again.
2141         child->layoutIfNeeded();
2142     }
2143
2144     // We are no longer at the top of the block if we encounter a non-empty child.  
2145     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
2146     if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
2147         marginInfo.setAtBeforeSideOfBlock(false);
2148
2149     // Now place the child in the correct left position
2150     determineLogicalLeftPositionForChild(child);
2151
2152     // Update our height now that the child has been placed in the correct position.
2153     setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
2154     if (childStyle->marginAfterCollapse() == MSEPARATE) {
2155         setLogicalHeight(logicalHeight() + marginAfterForChild(child));
2156         marginInfo.clearMargin();
2157     }
2158     // If the child has overhanging floats that intrude into following siblings (or possibly out
2159     // of this block), then the parent gets notified of the floats now.
2160     if (childRenderBlock && childRenderBlock->containsFloats())
2161         maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
2162
2163     LayoutSize childOffset(child->x() - oldRect.x(), child->y() - oldRect.y());
2164     if (childOffset.width() || childOffset.height()) {
2165         view()->addLayoutDelta(childOffset);
2166
2167         // If the child moved, we have to repaint it as well as any floating/positioned
2168         // descendants.  An exception is if we need a layout.  In this case, we know we're going to
2169         // repaint ourselves (and the child) anyway.
2170         if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
2171             child->repaintDuringLayoutIfMoved(oldRect);
2172     }
2173
2174     if (!childHadLayout && child->checkForRepaintDuringLayout()) {
2175         child->repaint();
2176         child->repaintOverhangingFloats(true);
2177     }
2178
2179     if (paginated) {
2180         // Check for an after page/column break.
2181         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
2182         if (newHeight != height())
2183             setLogicalHeight(newHeight);
2184     }
2185
2186     ASSERT(oldLayoutDelta == view()->layoutDelta());
2187 }
2188
2189 void RenderBlock::simplifiedNormalFlowLayout()
2190 {
2191     if (childrenInline()) {
2192         ListHashSet<RootInlineBox*> lineBoxes;
2193         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
2194             RenderObject* o = walker.current();
2195             if (!o->isPositioned() && (o->isReplaced() || o->isFloating())) {
2196                 o->layoutIfNeeded();
2197                 if (toRenderBox(o)->inlineBoxWrapper()) {
2198                     RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
2199                     lineBoxes.add(box);
2200                 }
2201             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
2202                 o->setNeedsLayout(false);
2203         }
2204
2205         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
2206         GlyphOverflowAndFallbackFontsMap textBoxDataMap;                  
2207         for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
2208             RootInlineBox* box = *it;
2209             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
2210         }
2211     } else {
2212         for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
2213             if (!box->isPositioned())
2214                 box->layoutIfNeeded();
2215         }
2216     }
2217 }
2218
2219 bool RenderBlock::simplifiedLayout()
2220 {
2221     if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
2222         return false;
2223
2224     LayoutStateMaintainer statePusher(view(), this, IntSize(x(), y()), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
2225     
2226     if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
2227         return false;
2228
2229     // Lay out positioned descendants or objects that just need to recompute overflow.
2230     if (needsSimplifiedNormalFlowLayout())
2231         simplifiedNormalFlowLayout();
2232
2233     // Lay out our positioned objects if our positioned child bit is set.
2234     if (posChildNeedsLayout() && layoutPositionedObjects(false))
2235         return false; // If a positioned float is causing our normal flow to change, then we have to bail and do a full layout.
2236
2237     // Recompute our overflow information.
2238     // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
2239     // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
2240     // For now just always recompute overflow.  This is no worse performance-wise than the old code that called rightmostPosition and
2241     // lowestPosition on every relayout so it's not a regression.
2242     m_overflow.clear();
2243     computeOverflow(clientLogicalBottom(), true);
2244
2245     statePusher.pop();
2246     
2247     updateLayerTransform();
2248
2249     updateScrollInfoAfterLayout();
2250
2251     setNeedsLayout(false);
2252     return true;
2253 }
2254
2255 bool RenderBlock::positionedFloatsNeedRelayout()
2256 {
2257     if (!hasPositionedFloats())
2258         return false;
2259     
2260     RenderBox* positionedObject;
2261     Iterator end = m_positionedObjects->end();
2262     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2263         positionedObject = *it;
2264         if (!positionedObject->isFloating())
2265             continue;
2266
2267         if (positionedObject->needsLayout())
2268             return true;
2269
2270         if (positionedObject->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && positionedObject->parent() != this && positionedObject->parent()->isBlockFlow())
2271             return true;
2272         
2273         if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(logicalTop()) != pageLogicalOffset()))
2274             return true;
2275     }
2276     
2277     return false;
2278 }
2279
2280 bool RenderBlock::layoutPositionedObjects(bool relayoutChildren)
2281 {
2282     if (!m_positionedObjects)
2283         return false;
2284         
2285     if (hasColumns())
2286         view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
2287
2288     bool didFloatingBoxRelayout = false;
2289
2290     RenderBox* r;
2291     Iterator end = m_positionedObjects->end();
2292     for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2293         r = *it;
2294         // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
2295         // non-positioned block.  Rather than trying to detect all of these movement cases, we just always lay out positioned
2296         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
2297         // positioned explicitly) this should not incur a performance penalty.
2298         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
2299             r->setChildNeedsLayout(true, false);
2300             
2301         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2302         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
2303             r->setPreferredLogicalWidthsDirty(true, false);
2304         
2305         if (!r->needsLayout())
2306             r->markForPaginationRelayoutIfNeeded();
2307         
2308         // FIXME: Technically we could check the old placement and the new placement of the box and only invalidate if
2309         // the margin box of the object actually changed.
2310         if (r->needsLayout() && r->isFloating())
2311             didFloatingBoxRelayout = true;
2312
2313         // 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
2314         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
2315         if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
2316             r->setNeedsLayout(false);
2317             
2318         // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
2319         // If it's wrong we'll lay out again.
2320         LayoutUnit oldLogicalTop = 0;
2321         bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout(); 
2322         if (needsBlockDirectionLocationSetBeforeLayout) {
2323             if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
2324                 r->computeLogicalHeight();
2325             else
2326                 r->computeLogicalWidth();
2327             oldLogicalTop = logicalTopForChild(r);
2328         }
2329             
2330         r->layoutIfNeeded();
2331         
2332         // Lay out again if our estimate was wrong.
2333         if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
2334             r->setChildNeedsLayout(true, false);
2335             r->layoutIfNeeded();
2336         }
2337     }
2338     
2339     if (hasColumns())
2340         view()->layoutState()->m_columnInfo = columnInfo(); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
2341         
2342     return didFloatingBoxRelayout;
2343 }
2344
2345 void RenderBlock::markPositionedObjectsForLayout()
2346 {
2347     if (m_positionedObjects) {
2348         RenderBox* r;
2349         Iterator end = m_positionedObjects->end();
2350         for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
2351             r = *it;
2352             r->setChildNeedsLayout(true);
2353         }
2354     }
2355 }
2356
2357 void RenderBlock::markForPaginationRelayoutIfNeeded()
2358 {
2359     ASSERT(!needsLayout());
2360     if (needsLayout())
2361         return;
2362
2363     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(logicalTop()) != pageLogicalOffset()))
2364         setChildNeedsLayout(true, false);
2365 }
2366
2367 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
2368 {
2369     // Repaint any overhanging floats (if we know we're the one to paint them).
2370     // Otherwise, bail out.
2371     if (!hasOverhangingFloats())
2372         return;
2373
2374     // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2375     // in this block. Better yet would be to push extra state for the containers of other floats.
2376     LayoutStateDisabler layoutStateDisabler(view());
2377     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2378     FloatingObjectSetIterator end = floatingObjectSet.end();
2379     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2380         FloatingObject* r = *it;
2381         // Only repaint the object if it is overhanging, is not in its own layer, and
2382         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2383         // condition is replaced with being a descendant of us.
2384         if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->m_shouldPaint) && !r->m_renderer->hasSelfPaintingLayer()) {
2385             r->m_renderer->repaint();
2386             r->m_renderer->repaintOverhangingFloats();
2387         }
2388     }
2389 }
2390  
2391 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2392 {
2393     LayoutPoint adjustedPaintOffset = paintOffset + location();
2394     
2395     PaintPhase phase = paintInfo.phase;
2396
2397     // Check if we need to do anything at all.
2398     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
2399     // paints the root's background.
2400     if (!isRoot()) {
2401         LayoutRect overflowBox = visualOverflowRect();
2402         flipForWritingMode(overflowBox);
2403         overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
2404         overflowBox.moveBy(adjustedPaintOffset);
2405         if (!overflowBox.intersects(paintInfo.rect))
2406             return;
2407     }
2408
2409     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
2410     paintObject(paintInfo, adjustedPaintOffset);
2411     if (pushedClip)
2412         popContentsClip(paintInfo, phase, adjustedPaintOffset);
2413
2414     // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
2415     // z-index.  We paint after we painted the background/border, so that the scrollbars will
2416     // sit above the background/border.
2417     if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this))
2418         layer()->paintOverflowControls(paintInfo.context, adjustedPaintOffset, paintInfo.rect);
2419 }
2420
2421 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2422 {
2423     if (paintInfo.context->paintingDisabled())
2424         return;
2425
2426     const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
2427     bool ruleTransparent = style()->columnRuleIsTransparent();
2428     EBorderStyle ruleStyle = style()->columnRuleStyle();
2429     LayoutUnit ruleThickness = style()->columnRuleWidth();
2430     LayoutUnit colGap = columnGap();
2431     bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent && ruleThickness <= colGap;
2432     if (!renderRule)
2433         return;
2434
2435     ColumnInfo* colInfo = columnInfo();
2436     unsigned colCount = columnCount(colInfo);
2437
2438     bool antialias = shouldAntialiasLines(paintInfo.context);
2439
2440     if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
2441         LayoutUnit currLogicalLeftOffset = style()->isLeftToRightDirection() ? 0 : contentLogicalWidth();
2442         LayoutUnit ruleAdd = logicalLeftOffsetForContent();
2443         LayoutUnit ruleLogicalLeft = style()->isLeftToRightDirection() ? 0 : contentLogicalWidth();
2444         LayoutUnit inlineDirectionSize = colInfo->desiredColumnWidth();
2445         BoxSide boxSide = isHorizontalWritingMode()
2446             ? style()->isLeftToRightDirection() ? BSLeft : BSRight
2447             : style()->isLeftToRightDirection() ? BSTop : BSBottom;
2448
2449         for (unsigned i = 0; i < colCount; i++) {
2450             // Move to the next position.
2451             if (style()->isLeftToRightDirection()) {
2452                 ruleLogicalLeft += inlineDirectionSize + colGap / 2;
2453                 currLogicalLeftOffset += inlineDirectionSize + colGap;
2454             } else {
2455                 ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
2456                 currLogicalLeftOffset -= (inlineDirectionSize + colGap);
2457             }
2458            
2459             // Now paint the column rule.
2460             if (i < colCount - 1) {
2461                 LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd : paintOffset.x() + borderLeft() + paddingLeft();
2462                 LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleThickness : ruleLeft + contentWidth();
2463                 LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd;
2464                 LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleThickness;
2465                 drawLineForBoxSide(paintInfo.context, ruleLeft, ruleTop, ruleRight, ruleBottom, boxSide, ruleColor, ruleStyle, 0, 0, antialias);
2466             }
2467             
2468             ruleLogicalLeft = currLogicalLeftOffset;
2469         }
2470     } else {
2471         LayoutUnit ruleLeft = isHorizontalWritingMode() ? borderLeft() + paddingLeft() : colGap / 2 - colGap - ruleThickness / 2 + borderBefore() + paddingBefore();
2472         LayoutUnit ruleWidth = isHorizontalWritingMode() ? contentWidth() : ruleThickness;
2473         LayoutUnit ruleTop = isHorizontalWritingMode() ? colGap / 2 - colGap - ruleThickness / 2 + borderBefore() + paddingBefore() : borderStart() + paddingStart();
2474         LayoutUnit ruleHeight = isHorizontalWritingMode() ? ruleThickness : contentHeight();
2475         LayoutRect ruleRect(ruleLeft, ruleTop, ruleWidth, ruleHeight);
2476
2477         flipForWritingMode(ruleRect);
2478         ruleRect.moveBy(paintOffset);
2479
2480         BoxSide boxSide = isHorizontalWritingMode()
2481             ? !style()->isFlippedBlocksWritingMode() ? BSTop : BSBottom
2482             : !style()->isFlippedBlocksWritingMode() ? BSLeft : BSRight;
2483
2484         LayoutSize step(0, !style()->isFlippedBlocksWritingMode() ? colInfo->columnHeight() + colGap : -(colInfo->columnHeight() + colGap));
2485         if (!isHorizontalWritingMode())
2486             step = step.transposedSize();
2487
2488         for (unsigned i = 1; i < colCount; i++) {
2489             ruleRect.move(step);
2490             drawLineForBoxSide(paintInfo.context, ruleRect.x(), ruleRect.y(), ruleRect.maxX(), ruleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
2491         }
2492     }
2493 }
2494
2495 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
2496 {
2497     // We need to do multiple passes, breaking up our child painting into strips.
2498     GraphicsContext* context = paintInfo.context;
2499     ColumnInfo* colInfo = columnInfo();
2500     unsigned colCount = columnCount(colInfo);
2501     if (!colCount)
2502         return;
2503     LayoutUnit currLogicalTopOffset = 0;
2504     for (unsigned i = 0; i < colCount; i++) {
2505         // For each rect, we clip to the rect, and then we adjust our coords.
2506         LayoutRect colRect = columnRectAt(colInfo, i);
2507         flipForWritingMode(colRect);
2508         LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
2509         LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
2510         if (colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
2511             if (isHorizontalWritingMode())
2512                 offset.expand(0, colRect.y() - borderTop() - paddingTop());
2513             else
2514                 offset.expand(colRect.x() - borderLeft() - paddingLeft(), 0);
2515         }
2516         colRect.moveBy(paintOffset);
2517         PaintInfo info(paintInfo);
2518         info.rect.intersect(colRect);
2519         
2520         if (!info.rect.isEmpty()) {
2521             GraphicsContextStateSaver stateSaver(*context);
2522             
2523             // Each strip pushes a clip, since column boxes are specified as being
2524             // like overflow:hidden.
2525             context->clip(colRect);
2526
2527             // Adjust our x and y when painting.
2528             LayoutPoint adjustedPaintOffset = paintOffset + offset;
2529             if (paintingFloats)
2530                 paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
2531             else
2532                 paintContents(info, adjustedPaintOffset);
2533         }
2534
2535         LayoutUnit blockDelta = (isHorizontalWritingMode() ? colRect.height() : colRect.width());
2536         if (style()->isFlippedBlocksWritingMode())
2537             currLogicalTopOffset += blockDelta;
2538         else
2539             currLogicalTopOffset -= blockDelta;
2540     }
2541 }
2542
2543 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2544 {
2545     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
2546     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2547     // will do a full repaint().
2548     if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
2549         return;
2550
2551     // 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
2552     // us to mess up painting aligned things (such as underlines in text) with both the render tree and line box tree's error.
2553     LayoutPoint roundedPaintOffset = roundedIntPoint(paintOffset);
2554     if (childrenInline())
2555         m_lineBoxes.paint(this, paintInfo, roundedPaintOffset);
2556     else
2557         paintChildren(paintInfo, roundedPaintOffset);
2558 }
2559
2560 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2561 {
2562     PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
2563     newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
2564     
2565     // We don't paint our own background, but we do let the kids paint their backgrounds.
2566     PaintInfo info(paintInfo);
2567     info.phase = newPhase;
2568     info.updatePaintingRootForChildren(this);
2569     
2570     // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
2571     // NSViews.  Do not add any more code for this.
2572     RenderView* renderView = view();
2573     bool usePrintRect = !renderView->printRect().isEmpty();
2574     
2575     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {        
2576         // Check for page-break-before: always, and if it's set, break and bail.
2577         bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
2578         LayoutUnit absoluteChildY = paintOffset.y() + child->y();
2579         if (checkBeforeAlways
2580             && absoluteChildY > paintInfo.rect.y()
2581             && absoluteChildY < paintInfo.rect.maxY()) {
2582             view()->setBestTruncatedAt(absoluteChildY, this, true);
2583             return;
2584         }
2585
2586         if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
2587             // Paginate block-level replaced elements.
2588             if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
2589                 if (absoluteChildY < renderView->truncatedAt())
2590                     renderView->setBestTruncatedAt(absoluteChildY, child);
2591                 // If we were able to truncate, don't paint.
2592                 if (absoluteChildY >= renderView->truncatedAt())
2593                     break;
2594             }
2595         }
2596
2597         LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
2598         if (!child->hasSelfPaintingLayer() && !child->isFloating())
2599             child->paint(info, childPoint);
2600
2601         // Check for page-break-after: always, and if it's set, break and bail.
2602         bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
2603         if (checkAfterAlways
2604             && (absoluteChildY + child->height()) > paintInfo.rect.y()
2605             && (absoluteChildY + child->height()) < paintInfo.rect.maxY()) {
2606             view()->setBestTruncatedAt(absoluteChildY + child->height() + max<LayoutUnit>(0, child->collapsedMarginAfter()), this, true);
2607             return;
2608         }
2609     }
2610 }
2611
2612 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
2613 {
2614     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
2615     bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
2616     RenderObject* caretPainter;
2617     bool isContentEditable;
2618     if (type == CursorCaret) {
2619         caretPainter = frame()->selection()->caretRenderer();
2620         isContentEditable = frame()->selection()->isContentEditable();
2621     } else {
2622         caretPainter = frame()->page()->dragCaretController()->caretRenderer();
2623         isContentEditable = frame()->page()->dragCaretController()->isContentEditable();
2624     }
2625
2626     if (caretPainter == this && (isContentEditable || caretBrowsing)) {
2627         if (type == CursorCaret)
2628             frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
2629         else
2630             frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
2631     }
2632 }
2633
2634 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2635 {
2636     PaintPhase paintPhase = paintInfo.phase;
2637
2638     // 1. paint background, borders etc
2639     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
2640         if (hasBoxDecorations())
2641             paintBoxDecorations(paintInfo, paintOffset);
2642         if (hasColumns())
2643             paintColumnRules(paintInfo, paintOffset);
2644     }
2645
2646     if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
2647         paintMask(paintInfo, paintOffset);
2648         return;
2649     }
2650
2651     // We're done.  We don't bother painting any children.
2652     if (paintPhase == PaintPhaseBlockBackground)
2653         return;
2654
2655     // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
2656     LayoutPoint scrolledOffset = paintOffset;
2657     if (hasOverflowClip())
2658         scrolledOffset.move(-layer()->scrolledContentOffset());
2659
2660     // 2. paint contents
2661     if (paintPhase != PaintPhaseSelfOutline) {
2662         if (hasColumns())
2663             paintColumnContents(paintInfo, scrolledOffset);
2664         else
2665             paintContents(paintInfo, scrolledOffset);
2666     }
2667
2668     // 3. paint selection
2669     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
2670     bool isPrinting = document()->printing();
2671     if (!isPrinting && !hasColumns())
2672         paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
2673
2674     // 4. paint floats.
2675     if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
2676         if (hasColumns())
2677             paintColumnContents(paintInfo, scrolledOffset, true);
2678         else
2679             paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
2680     }
2681
2682     // 5. paint outline.
2683     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
2684         paintOutline(paintInfo.context, LayoutRect(paintOffset, size()));
2685
2686     // 6. paint continuation outlines.
2687     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
2688         RenderInline* inlineCont = inlineElementContinuation();
2689         if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE) {
2690             RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->renderer());
2691             RenderBlock* cb = containingBlock();
2692
2693             bool inlineEnclosedInSelfPaintingLayer = false;
2694             for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = box->parent()->enclosingBoxModelObject()) {
2695                 if (box->hasSelfPaintingLayer()) {
2696                     inlineEnclosedInSelfPaintingLayer = true;
2697                     break;
2698                 }
2699             }
2700
2701             if (!inlineEnclosedInSelfPaintingLayer)
2702                 cb->addContinuationWithOutline(inlineRenderer);
2703             else if (!inlineRenderer->firstLineBox())
2704                 inlineRenderer->paintOutline(paintInfo.context, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
2705         }
2706         paintContinuationOutlines(paintInfo, paintOffset);
2707     }
2708
2709     // 7. paint caret.
2710     // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
2711     // then paint the caret.
2712     if (paintPhase == PaintPhaseForeground) {        
2713         paintCaret(paintInfo, paintOffset, CursorCaret);
2714         paintCaret(paintInfo, paintOffset, DragCaret);
2715     }
2716 }
2717
2718 LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
2719 {
2720     if (!style()->isFlippedBlocksWritingMode())
2721         return point;
2722     
2723     // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
2724     // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
2725     // case.
2726     if (isHorizontalWritingMode())
2727         return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
2728     return LayoutPoint(point.x() + width() - child->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
2729 }
2730
2731 void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
2732 {
2733     if (!m_floatingObjects)
2734         return;
2735
2736     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2737     FloatingObjectSetIterator end = floatingObjectSet.end();
2738     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2739         FloatingObject* r = *it;
2740         // Only paint the object if our m_shouldPaint flag is set.
2741         if (r->m_shouldPaint && !r->m_renderer->hasSelfPaintingLayer()) {
2742             PaintInfo currentPaintInfo(paintInfo);
2743             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
2744             LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->m_renderer->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->m_renderer->y()));
2745             r->m_renderer->paint(currentPaintInfo, childPoint);
2746             if (!preservePhase) {
2747                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
2748                 r->m_renderer->paint(currentPaintInfo, childPoint);
2749                 currentPaintInfo.phase = PaintPhaseFloat;
2750                 r->m_renderer->paint(currentPaintInfo, childPoint);
2751                 currentPaintInfo.phase = PaintPhaseForeground;
2752                 r->m_renderer->paint(currentPaintInfo, childPoint);
2753                 currentPaintInfo.phase = PaintPhaseOutline;
2754                 r->m_renderer->paint(currentPaintInfo, childPoint);
2755             }
2756         }
2757     }
2758 }
2759
2760 void RenderBlock::paintEllipsisBoxes(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2761 {
2762     if (!paintInfo.shouldPaintWithinRoot(this) || !firstLineBox())
2763         return;
2764
2765     if (style()->visibility() == VISIBLE && paintInfo.phase == PaintPhaseForeground) {
2766         // We can check the first box and last box and avoid painting if we don't
2767         // intersect.
2768         LayoutUnit yPos = paintOffset.y() + firstLineBox()->y();
2769         LayoutUnit h = lastLineBox()->y() + lastLineBox()->logicalHeight() - firstLineBox()->y();
2770         if (yPos >= paintInfo.rect.maxY() || yPos + h <= paintInfo.rect.y())
2771             return;
2772
2773         // See if our boxes intersect with the dirty rect.  If so, then we paint
2774         // them.  Note that boxes can easily overlap, so we can't make any assumptions
2775         // based off positions of our first line box or our last line box.
2776         for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2777             yPos = paintOffset.y() + curr->y();
2778             h = curr->logicalHeight();
2779             if (curr->ellipsisBox() && yPos < paintInfo.rect.maxY() && yPos + h > paintInfo.rect.y())
2780                 curr->paintEllipsisBox(paintInfo, paintOffset, curr->lineTop(), curr->lineBottom());
2781         }
2782     }
2783 }
2784
2785 RenderInline* RenderBlock::inlineElementContinuation() const
2786
2787     RenderBoxModelObject* continuation = this->continuation();
2788     return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
2789 }
2790
2791 RenderBlock* RenderBlock::blockElementContinuation() const
2792 {
2793     RenderBoxModelObject* currentContinuation = continuation();
2794     if (!currentContinuation || currentContinuation->isInline())
2795         return 0;
2796     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
2797     if (nextContinuation->isAnonymousBlock())
2798         return nextContinuation->blockElementContinuation();
2799     return nextContinuation;
2800 }
2801     
2802 static ContinuationOutlineTableMap* continuationOutlineTable()
2803 {
2804     DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
2805     return &table;
2806 }
2807
2808 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
2809 {
2810     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
2811     // way of painting.
2812     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
2813     
2814     ContinuationOutlineTableMap* table = continuationOutlineTable();
2815     ListHashSet<RenderInline*>* continuations = table->get(this);
2816     if (!continuations) {
2817         continuations = new ListHashSet<RenderInline*>;
2818         table->set(this, continuations);
2819     }
2820     
2821     continuations->add(flow);
2822 }
2823
2824 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
2825 {
2826     ContinuationOutlineTableMap* table = continuationOutlineTable();
2827     if (table->isEmpty())
2828         return false;
2829         
2830     ListHashSet<RenderInline*>* continuations = table->get(this);
2831     if (!continuations)
2832         return false;
2833
2834     return continuations->contains(flow);
2835 }
2836
2837 void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
2838 {
2839     ContinuationOutlineTableMap* table = continuationOutlineTable();
2840     if (table->isEmpty())
2841         return;
2842         
2843     ListHashSet<RenderInline*>* continuations = table->get(this);
2844     if (!continuations)
2845         return;
2846
2847     LayoutPoint accumulatedPaintOffset = paintOffset;
2848     // Paint each continuation outline.
2849     ListHashSet<RenderInline*>::iterator end = continuations->end();
2850     for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
2851         // Need to add in the coordinates of the intervening blocks.
2852         RenderInline* flow = *it;
2853         RenderBlock* block = flow->containingBlock();
2854         for ( ; block && block != this; block = block->containingBlock())
2855             accumulatedPaintOffset.moveBy(block->location());
2856         ASSERT(block);   
2857         flow->paintOutline(info.context, accumulatedPaintOffset);
2858     }
2859     
2860     // Delete
2861     delete continuations;
2862     table->remove(this);
2863 }
2864
2865 bool RenderBlock::shouldPaintSelectionGaps() const
2866 {
2867     return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
2868 }
2869
2870 bool RenderBlock::isSelectionRoot() const
2871 {
2872     if (!node())
2873         return false;
2874         
2875     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
2876     if (isTable())
2877         return false;
2878         
2879     if (isBody() || isRoot() || hasOverflowClip() || isRelPositioned() ||
2880         isFloatingOrPositioned() || isTableCell() || isInlineBlockOrInlineTable() || hasTransform() ||
2881         hasReflection() || hasMask() || isWritingModeRoot())
2882         return true;
2883     
2884     if (view() && view()->selectionStart()) {
2885         Node* startElement = view()->selectionStart()->node();
2886         if (startElement && startElement->rootEditableElement() == node())
2887             return true;
2888     }
2889     
2890     return false;
2891 }
2892
2893 GapRects RenderBlock::selectionGapRectsForRepaint(RenderBoxModelObject* repaintContainer)
2894 {
2895     ASSERT(!needsLayout());
2896
2897     if (!shouldPaintSelectionGaps())
2898         return GapRects();
2899
2900     // FIXME: this is broken with transforms
2901     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
2902     mapLocalToContainer(repaintContainer, false, false, transformState);
2903     LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint());
2904
2905     if (hasOverflowClip())
2906         offsetFromRepaintContainer -= layer()->scrolledContentOffset();
2907
2908     LayoutUnit lastTop = 0;
2909     LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
2910     LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
2911     
2912     return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight);
2913 }
2914
2915 void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2916 {
2917     if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
2918         LayoutUnit lastTop = 0;
2919         LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
2920         LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
2921         GraphicsContextStateSaver stateSaver(*paintInfo.context);
2922
2923         LayoutRect gapRectsBounds = selectionGaps(this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, &paintInfo);
2924         if (!gapRectsBounds.isEmpty()) {
2925             if (RenderLayer* layer = enclosingLayer()) {
2926                 gapRectsBounds.moveBy(-paintOffset);
2927                 if (!hasLayer()) {
2928                     LayoutRect localBounds(gapRectsBounds);
2929                     flipForWritingMode(localBounds);
2930                     gapRectsBounds = localToContainerQuad(FloatRect(localBounds), layer->renderer()).enclosingBoundingBox();
2931                     gapRectsBounds.move(layer->scrolledContentOffset());
2932                 }
2933                 layer->addBlockSelectionGapsBounds(gapRectsBounds);
2934             }
2935         }
2936     }
2937 }
2938
2939 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, RenderBlock::PositionedObjectsListHashSet* positionedObjects)
2940 {
2941     if (!positionedObjects)
2942         return;
2943     
2944     RenderBlock::PositionedObjectsListHashSet::const_iterator end = positionedObjects->end();
2945     for (RenderBlock::PositionedObjectsListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
2946         RenderBox* r = *it;
2947         paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
2948     }
2949 }
2950
2951 static int blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
2952 {
2953     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
2954 }
2955
2956 static int inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
2957 {
2958     return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
2959 }
2960
2961 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
2962 {
2963     LayoutRect result;
2964     if (isHorizontalWritingMode())
2965         result = logicalRect;
2966     else
2967         result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
2968     flipForWritingMode(result);
2969     result.moveBy(rootBlockPhysicalPosition);
2970     return result;
2971 }
2972
2973 GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2974                                     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
2975 {
2976     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
2977     // Clip out floating and positioned objects when painting selection gaps.
2978     if (paintInfo) {
2979         // Note that we don't clip out overflow for positioned objects.  We just stick to the border box.
2980         LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
2981         rootBlock->flipForWritingMode(flippedBlockRect);
2982         flippedBlockRect.moveBy(rootBlockPhysicalPosition);
2983         clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), m_positionedObjects.get());
2984         if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
2985             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
2986                 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->m_positionedObjects.get()); // FIXME: Not right for flipped writing modes.
2987         if (m_floatingObjects) {
2988             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2989             FloatingObjectSetIterator end = floatingObjectSet.end();
2990             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2991                 FloatingObject* r = *it;
2992                 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
2993                                     offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
2994                                     r->m_renderer->width(), r->m_renderer->height());
2995                 rootBlock->flipForWritingMode(floatBox);
2996                 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2997                 paintInfo->context->clipOut(floatBox);
2998             }
2999         }
3000     }
3001
3002     // 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
3003     // fixed).
3004     GapRects result;
3005     if (!isBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
3006         return result;
3007
3008     if (hasColumns() || hasTransform() || style()->columnSpan()) {
3009         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
3010         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3011         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
3012         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
3013         return result;
3014     }
3015
3016     if (childrenInline())
3017         result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
3018     else
3019         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
3020
3021     // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
3022     if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
3023         result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
3024                                              logicalHeight(), paintInfo));
3025     return result;
3026 }
3027
3028 GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3029                                           LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
3030 {
3031     GapRects result;
3032
3033     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
3034
3035     if (!firstLineBox()) {
3036         if (containsStart) {
3037             // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
3038             // case.
3039             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3040             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
3041             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
3042         }
3043         return result;
3044     }
3045
3046     RootInlineBox* lastSelectedLine = 0;
3047     RootInlineBox* curr;
3048     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
3049
3050     // Now paint the gaps for the lines.
3051     for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
3052         LayoutUnit selTop =  curr->selectionTop();
3053         LayoutUnit selHeight = curr->selectionHeight();
3054
3055         if (!containsStart && !lastSelectedLine &&
3056             selectionState() != SelectionStart && selectionState() != SelectionBoth)
3057             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
3058                                                  selTop, paintInfo));
3059         
3060         LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
3061         logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
3062         LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
3063         if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
3064             || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
3065             result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
3066
3067         lastSelectedLine = curr;
3068     }
3069
3070     if (containsStart && !lastSelectedLine)
3071         // VisibleSelection must start just after our last line.
3072         lastSelectedLine = lastRootBox();
3073
3074     if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
3075         // Go ahead and update our lastY to be the bottom of the last selected line.
3076         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
3077         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
3078         lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
3079     }
3080     return result;
3081 }
3082
3083 GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3084                                          LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
3085 {
3086     GapRects result;
3087
3088     // Go ahead and jump right to the first block child that contains some selected objects.
3089     RenderBox* curr;
3090     for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
3091
3092     for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
3093         SelectionState childState = curr->selectionState();
3094         if (childState == SelectionBoth || childState == SelectionEnd)
3095             sawSelectionEnd = true;
3096
3097         if (curr->isFloatingOrPositioned())
3098             continue; // We must be a normal flow object in order to even be considered.
3099
3100         if (curr->isRelPositioned() && curr->hasLayer()) {
3101             // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
3102             // Just disregard it completely.
3103             LayoutSize relOffset = curr->layer()->relativePositionOffset();
3104             if (relOffset.width() || relOffset.height())
3105                 continue;
3106         }
3107
3108         bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
3109         bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
3110         if (fillBlockGaps) {
3111             // We need to fill the vertical gap above this object.
3112             if (childState == SelectionEnd || childState == SelectionInside)
3113                 // Fill the gap above the object.
3114                 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, 
3115                                                      curr->logicalTop(), paintInfo));
3116
3117             // 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*
3118             // our object.  We know this if the selection did not end inside our object.
3119             if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
3120                 childState = SelectionNone;
3121
3122             // Fill side gaps on this object based off its state.
3123             bool leftGap, rightGap;
3124             getSelectionGapInfo(childState, leftGap, rightGap);
3125
3126             if (leftGap)
3127                 result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
3128             if (rightGap)
3129                 result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
3130
3131             // Update lastLogicalTop to be just underneath the object.  lastLogicalLeft and lastLogicalRight extend as far as
3132             // they can without bumping into floating or positioned objects.  Ideally they will go right up
3133             // to the border of the root selection block.
3134             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
3135             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
3136             lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
3137         } else if (childState != SelectionNone)
3138             // We must be a block that has some selected object inside it.  Go ahead and recur.
3139             result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()), 
3140                                                             lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo));
3141     }
3142     return result;
3143 }
3144
3145 LayoutRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3146                                           LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo)
3147 {
3148     LayoutUnit logicalTop = lastLogicalTop;
3149     LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
3150     if (logicalHeight <= static_cast<LayoutUnit>(0))
3151         return LayoutRect();
3152
3153     // Get the selection offsets for the bottom of the gap
3154     LayoutUnit logicalLeft = max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
3155     LayoutUnit logicalRight = min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
3156     LayoutUnit logicalWidth = logicalRight - logicalLeft;
3157     if (logicalWidth <= static_cast<LayoutUnit>(0))
3158         return LayoutRect();
3159
3160     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
3161     if (paintInfo)
3162         paintInfo->context->fillRect(gapRect, selectionBackgroundColor(), style()->colorSpace());
3163     return gapRect;
3164 }
3165
3166 LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3167                                                 RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
3168 {
3169     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
3170     LayoutUnit rootBlockLogicalLeft = max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
3171     LayoutUnit rootBlockLogicalRight = min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalLeft, min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
3172     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
3173     if (rootBlockLogicalWidth <= static_cast<LayoutUnit>(0))
3174         return LayoutRect();
3175
3176     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
3177     if (paintInfo)
3178         paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
3179     return gapRect;
3180 }
3181
3182 LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3183                                                  RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
3184 {
3185     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
3186     LayoutUnit rootBlockLogicalLeft = max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalRight, max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
3187     LayoutUnit rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
3188     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
3189     if (rootBlockLogicalWidth <= static_cast<LayoutUnit>(0))
3190         return LayoutRect();
3191
3192     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
3193     if (paintInfo)
3194         paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
3195     return gapRect;
3196 }
3197
3198 void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap)
3199 {