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