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