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