Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderBlock.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2007 David Smith (catfish.man@gmail.com)
5  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6  * Copyright (C) Research In Motion Limited 2010. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #include "config.h"
25 #include "core/rendering/RenderBlock.h"
26
27 #include "core/HTMLNames.h"
28 #include "core/accessibility/AXObjectCache.h"
29 #include "core/dom/Document.h"
30 #include "core/dom/Element.h"
31 #include "core/dom/StyleEngine.h"
32 #include "core/dom/shadow/ShadowRoot.h"
33 #include "core/editing/Editor.h"
34 #include "core/editing/FrameSelection.h"
35 #include "core/events/OverflowEvent.h"
36 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
37 #include "core/frame/FrameView.h"
38 #include "core/frame/LocalFrame.h"
39 #include "core/frame/Settings.h"
40 #include "core/page/Page.h"
41 #include "core/paint/BlockPainter.h"
42 #include "core/paint/BoxPainter.h"
43 #include "core/paint/DrawingRecorder.h"
44 #include "core/rendering/GraphicsContextAnnotator.h"
45 #include "core/rendering/HitTestLocation.h"
46 #include "core/rendering/HitTestResult.h"
47 #include "core/rendering/InlineIterator.h"
48 #include "core/rendering/InlineTextBox.h"
49 #include "core/rendering/PaintInfo.h"
50 #include "core/rendering/RenderCombineText.h"
51 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
52 #include "core/rendering/RenderFlexibleBox.h"
53 #include "core/rendering/RenderFlowThread.h"
54 #include "core/rendering/RenderGrid.h"
55 #include "core/rendering/RenderInline.h"
56 #include "core/rendering/RenderLayer.h"
57 #include "core/rendering/RenderObjectInlines.h"
58 #include "core/rendering/RenderRegion.h"
59 #include "core/rendering/RenderTableCell.h"
60 #include "core/rendering/RenderTextControl.h"
61 #include "core/rendering/RenderTextFragment.h"
62 #include "core/rendering/RenderTheme.h"
63 #include "core/rendering/RenderView.h"
64 #include "core/rendering/TextAutosizer.h"
65 #include "core/rendering/shapes/ShapeOutsideInfo.h"
66 #include "core/rendering/style/ContentData.h"
67 #include "core/rendering/style/RenderStyle.h"
68 #include "platform/geometry/FloatQuad.h"
69 #include "platform/geometry/TransformState.h"
70 #include "platform/graphics/GraphicsContextCullSaver.h"
71 #include "platform/graphics/GraphicsContextStateSaver.h"
72 #include "wtf/StdLibExtras.h"
73 #include "wtf/TemporaryChange.h"
74
75 using namespace WTF;
76 using namespace Unicode;
77
78 namespace blink {
79
80 using namespace HTMLNames;
81
82 struct SameSizeAsRenderBlock : public RenderBox {
83     RenderObjectChildList children;
84     RenderLineBoxList lineBoxes;
85     int pageLogicalOffset;
86     uint32_t bitfields;
87 };
88
89 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
90
91 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
92 static ColumnInfoMap* gColumnInfoMap = 0;
93
94 static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
95 static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
96
97 static TrackedContainerMap* gPositionedContainerMap = 0;
98 static TrackedContainerMap* gPercentHeightContainerMap = 0;
99
100 typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
101 static int gDelayUpdateScrollInfo = 0;
102 static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
103
104 static bool gColumnFlowSplitEnabled = true;
105
106 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
107 // only works on RenderBlocks. If this changes, this class should be shared with other RenderBoxes.
108 class OverflowEventDispatcher {
109     WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
110 public:
111     OverflowEventDispatcher(const RenderBlock* block)
112         : m_block(block)
113         , m_hadHorizontalLayoutOverflow(false)
114         , m_hadVerticalLayoutOverflow(false)
115     {
116         m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document().hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
117         if (m_shouldDispatchEvent) {
118             m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
119             m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
120         }
121     }
122
123     ~OverflowEventDispatcher()
124     {
125         if (!m_shouldDispatchEvent)
126             return;
127
128         bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
129         bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
130
131         bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
132         bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
133
134         if (!horizontalLayoutOverflowChanged && !verticalLayoutOverflowChanged)
135             return;
136
137         RefPtrWillBeRawPtr<OverflowEvent> event = OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow);
138         event->setTarget(m_block->node());
139         m_block->document().enqueueAnimationFrameEvent(event.release());
140     }
141
142 private:
143     const RenderBlock* m_block;
144     bool m_shouldDispatchEvent;
145     bool m_hadHorizontalLayoutOverflow;
146     bool m_hadVerticalLayoutOverflow;
147 };
148
149 RenderBlock::RenderBlock(ContainerNode* node)
150     : RenderBox(node)
151     , m_hasMarginBeforeQuirk(false)
152     , m_hasMarginAfterQuirk(false)
153     , m_beingDestroyed(false)
154     , m_hasMarkupTruncation(false)
155     , m_hasBorderOrPaddingLogicalWidthChanged(false)
156     , m_hasOnlySelfCollapsingChildren(false)
157     , m_descendantsWithFloatsMarkedForLayout(false)
158 {
159     // RenderBlockFlow calls setChildrenInline(true).
160     // By default, subclasses do not have inline children.
161 }
162
163 void RenderBlock::trace(Visitor* visitor)
164 {
165     visitor->trace(m_children);
166     RenderBox::trace(visitor);
167 }
168
169 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
170 {
171     if (OwnPtr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
172         TrackedRendererListHashSet::iterator end = descendantSet->end();
173         for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
174             TrackedContainerMap::iterator it = containerMap->find(*descendant);
175             ASSERT(it != containerMap->end());
176             if (it == containerMap->end())
177                 continue;
178             HashSet<RenderBlock*>* containerSet = it->value.get();
179             ASSERT(containerSet->contains(block));
180             containerSet->remove(block);
181             if (containerSet->isEmpty())
182                 containerMap->remove(it);
183         }
184     }
185 }
186
187 static void appendImageIfNotNull(Vector<ImageResource*>& imageResources, const StyleImage* styleImage)
188 {
189     if (styleImage && styleImage->cachedImage()) {
190         ImageResource* imageResource = styleImage->cachedImage();
191         if (imageResource && !imageResource->isLoaded())
192             imageResources.append(styleImage->cachedImage());
193     }
194 }
195
196 static void appendLayers(Vector<ImageResource*>& images, const FillLayer& styleLayer)
197 {
198     for (const FillLayer* layer = &styleLayer; layer; layer = layer->next())
199         appendImageIfNotNull(images, layer->image());
200 }
201
202 static void appendImagesFromStyle(Vector<ImageResource*>& images, RenderStyle& blockStyle)
203 {
204     appendLayers(images, blockStyle.backgroundLayers());
205     appendLayers(images, blockStyle.maskLayers());
206
207     const ContentData* contentData = blockStyle.contentData();
208     if (contentData && contentData->isImage())
209         appendImageIfNotNull(images, toImageContentData(contentData)->image());
210     if (blockStyle.boxReflect())
211         appendImageIfNotNull(images, blockStyle.boxReflect()->mask().image());
212     appendImageIfNotNull(images, blockStyle.listStyleImage());
213     appendImageIfNotNull(images, blockStyle.borderImageSource());
214     appendImageIfNotNull(images, blockStyle.maskBoxImageSource());
215     if (blockStyle.shapeOutside())
216         appendImageIfNotNull(images, blockStyle.shapeOutside()->image());
217 }
218
219 void RenderBlock::removeFromGlobalMaps()
220 {
221     if (hasColumns())
222         gColumnInfoMap->take(this);
223     if (gPercentHeightDescendantsMap)
224         removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
225     if (gPositionedDescendantsMap)
226         removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
227 }
228
229 RenderBlock::~RenderBlock()
230 {
231 #if !ENABLE(OILPAN)
232     removeFromGlobalMaps();
233 #endif
234 }
235
236 void RenderBlock::destroy()
237 {
238     RenderBox::destroy();
239 #if ENABLE(OILPAN)
240     // RenderObject::removeChild called in destory() depends on gColumnInfoMap.
241     removeFromGlobalMaps();
242 #endif
243 }
244
245 void RenderBlock::willBeDestroyed()
246 {
247     // Mark as being destroyed to avoid trouble with merges in removeChild().
248     m_beingDestroyed = true;
249
250     // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
251     // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
252     children()->destroyLeftoverChildren();
253
254     // Destroy our continuation before anything other than anonymous children.
255     // The reason we don't destroy it before anonymous children is that they may
256     // have continuations of their own that are anonymous children of our continuation.
257     RenderBoxModelObject* continuation = this->continuation();
258     if (continuation) {
259         continuation->destroy();
260         setContinuation(0);
261     }
262
263     if (!documentBeingDestroyed()) {
264         if (firstLineBox()) {
265             // We can't wait for RenderBox::destroy to clear the selection,
266             // because by then we will have nuked the line boxes.
267             // FIXME: The FrameSelection should be responsible for this when it
268             // is notified of DOM mutations.
269             if (isSelectionBorder())
270                 view()->clearSelection();
271
272             // If we are an anonymous block, then our line boxes might have children
273             // that will outlast this block. In the non-anonymous block case those
274             // children will be destroyed by the time we return from this function.
275             if (isAnonymousBlock()) {
276                 for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
277                     while (InlineBox* childBox = box->firstChild())
278                         childBox->remove();
279                 }
280             }
281         } else if (parent())
282             parent()->dirtyLinesFromChangedChild(this);
283     }
284
285     m_lineBoxes.deleteLineBoxes();
286
287     if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
288         gDelayedUpdateScrollInfoSet->remove(this);
289
290     if (TextAutosizer* textAutosizer = document().textAutosizer())
291         textAutosizer->destroy(this);
292
293     RenderBox::willBeDestroyed();
294 }
295
296 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
297 {
298     RenderStyle* oldStyle = style();
299
300     setReplaced(newStyle.isDisplayInlineType());
301
302     if (oldStyle && parent()) {
303         bool oldStyleIsContainer = oldStyle->position() != StaticPosition || oldStyle->hasTransformRelatedProperty();
304         bool newStyleIsContainer = newStyle.position() != StaticPosition || newStyle.hasTransformRelatedProperty();
305
306         if (oldStyleIsContainer && !newStyleIsContainer) {
307             // Clear our positioned objects list. Our absolutely positioned descendants will be
308             // inserted into our containing block's positioned objects list during layout.
309             removePositionedObjects(0, NewContainingBlock);
310         } else if (!oldStyleIsContainer && newStyleIsContainer) {
311             // Remove our absolutely positioned descendants from their current containing block.
312             // They will be inserted into our positioned objects list during layout.
313             RenderObject* cb = parent();
314             while (cb && (cb->style()->position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
315                 if (cb->style()->position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
316                     cb = cb->containingBlock();
317                     break;
318                 }
319                 cb = cb->parent();
320             }
321
322             if (cb->isRenderBlock())
323                 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
324         }
325     }
326
327     RenderBox::styleWillChange(diff, newStyle);
328 }
329
330 static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
331 {
332     if (newStyle->isHorizontalWritingMode())
333         return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
334             || oldStyle->borderRightWidth() != newStyle->borderRightWidth()
335             || oldStyle->paddingLeft() != newStyle->paddingLeft()
336             || oldStyle->paddingRight() != newStyle->paddingRight();
337
338     return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
339         || oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
340         || oldStyle->paddingTop() != newStyle->paddingTop()
341         || oldStyle->paddingBottom() != newStyle->paddingBottom();
342 }
343
344 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
345 {
346     RenderBox::styleDidChange(diff, oldStyle);
347
348     RenderStyle* newStyle = style();
349
350     if (!isAnonymousBlock()) {
351         // Ensure that all of our continuation blocks pick up the new style.
352         for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
353             RenderBoxModelObject* nextCont = currCont->continuation();
354             currCont->setContinuation(0);
355             currCont->setStyle(newStyle);
356             currCont->setContinuation(nextCont);
357         }
358     }
359
360     if (TextAutosizer* textAutosizer = document().textAutosizer())
361         textAutosizer->record(this);
362
363     propagateStyleToAnonymousChildren(true);
364
365     // It's possible for our border/padding to change, but for the overall logical width of the block to
366     // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
367     m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff.needsFullLayout() && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
368
369     // If the style has unloaded images, want to notify the ResourceLoadPriorityOptimizer so that
370     // network priorities can be set.
371     Vector<ImageResource*> images;
372     appendImagesFromStyle(images, *newStyle);
373     if (images.isEmpty())
374         ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
375     else
376         ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
377 }
378
379 void RenderBlock::invalidatePaintOfSubtreesIfNeeded(const PaintInvalidationState& childPaintInvalidationState)
380 {
381     RenderBox::invalidatePaintOfSubtreesIfNeeded(childPaintInvalidationState);
382
383     // Take care of positioned objects. This is required as PaintInvalidationState keeps a single clip rect.
384     if (TrackedRendererListHashSet* positionedObjects = this->positionedObjects()) {
385         TrackedRendererListHashSet::iterator end = positionedObjects->end();
386         for (TrackedRendererListHashSet::iterator it = positionedObjects->begin(); it != end; ++it) {
387             RenderBox* box = *it;
388
389             // One of the renderers we're skipping over here may be the child's paint invalidation container,
390             // so we can't pass our own paint invalidation container along.
391             const RenderLayerModelObject& paintInvalidationContainerForChild = *box->containerForPaintInvalidation();
392
393             // If it's a new paint invalidation container, we won't have properly accumulated the offset into the
394             // PaintInvalidationState.
395             // FIXME: Teach PaintInvalidationState to handle this case. crbug.com/371485
396             if (paintInvalidationContainerForChild != childPaintInvalidationState.paintInvalidationContainer()) {
397                 ForceHorriblySlowRectMapping slowRectMapping(&childPaintInvalidationState);
398                 PaintInvalidationState disabledPaintInvalidationState(childPaintInvalidationState, *this, paintInvalidationContainerForChild);
399                 box->invalidateTreeIfNeeded(disabledPaintInvalidationState);
400                 continue;
401             }
402
403             // If the positioned renderer is absolutely positioned and it is inside
404             // a relatively positioned inline element, we need to account for
405             // the inline elements position in PaintInvalidationState.
406             if (box->style()->position() == AbsolutePosition) {
407                 RenderObject* container = box->container(&paintInvalidationContainerForChild, 0);
408                 if (container->isRelPositioned() && container->isRenderInline()) {
409                     // FIXME: We should be able to use PaintInvalidationState for this.
410                     // Currently, we will place absolutely positioned elements inside
411                     // relatively positioned inline blocks in the wrong location. crbug.com/371485
412                     ForceHorriblySlowRectMapping slowRectMapping(&childPaintInvalidationState);
413                     PaintInvalidationState disabledPaintInvalidationState(childPaintInvalidationState, *this, paintInvalidationContainerForChild);
414                     box->invalidateTreeIfNeeded(disabledPaintInvalidationState);
415                     continue;
416                 }
417             }
418
419             box->invalidateTreeIfNeeded(childPaintInvalidationState);
420         }
421     }
422 }
423
424 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
425 {
426     if (beforeChild && beforeChild->parent() == this)
427         return this;
428
429     RenderBlock* curr = toRenderBlock(continuation());
430     RenderBlock* nextToLast = this;
431     RenderBlock* last = this;
432     while (curr) {
433         if (beforeChild && beforeChild->parent() == curr) {
434             if (curr->firstChild() == beforeChild)
435                 return last;
436             return curr;
437         }
438
439         nextToLast = last;
440         last = curr;
441         curr = toRenderBlock(curr->continuation());
442     }
443
444     if (!beforeChild && !last->firstChild())
445         return nextToLast;
446     return last;
447 }
448
449 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
450 {
451     RenderBlock* flow = continuationBefore(beforeChild);
452     ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
453     RenderBoxModelObject* beforeChildParent = 0;
454     if (beforeChild)
455         beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
456     else {
457         RenderBoxModelObject* cont = flow->continuation();
458         if (cont)
459             beforeChildParent = cont;
460         else
461             beforeChildParent = flow;
462     }
463
464     if (newChild->isFloatingOrOutOfFlowPositioned()) {
465         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
466         return;
467     }
468
469     // A continuation always consists of two potential candidates: a block or an anonymous
470     // column span box holding column span children.
471     bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
472     bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
473     bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
474
475     if (flow == beforeChildParent) {
476         flow->addChildIgnoringContinuation(newChild, beforeChild);
477         return;
478     }
479
480     // The goal here is to match up if we can, so that we can coalesce and create the
481     // minimal # of continuations needed for the inline.
482     if (childIsNormal == bcpIsNormal) {
483         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
484         return;
485     }
486     if (flowIsNormal == childIsNormal) {
487         flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
488         return;
489     }
490     beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
491 }
492
493
494 void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
495 {
496     ASSERT(!continuation()); // We don't yet support column spans that aren't immediate children of the multi-column block.
497
498     // The goal is to locate a suitable box in which to place our child.
499     RenderBlock* beforeChildParent = 0;
500     if (beforeChild) {
501         RenderObject* curr = beforeChild;
502         while (curr && curr->parent() != this)
503             curr = curr->parent();
504         beforeChildParent = toRenderBlock(curr);
505         ASSERT(beforeChildParent);
506         ASSERT(beforeChildParent->isAnonymousColumnsBlock() || beforeChildParent->isAnonymousColumnSpanBlock());
507     } else
508         beforeChildParent = toRenderBlock(lastChild());
509
510     // If the new child is floating or positioned it can just go in that block.
511     if (newChild->isFloatingOrOutOfFlowPositioned()) {
512         beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
513         return;
514     }
515
516     // See if the child can be placed in the box.
517     bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
518     bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
519
520     if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans) {
521         beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
522         return;
523     }
524
525     if (!beforeChild) {
526         // Create a new block of the correct type.
527         RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
528         children()->appendChildNode(this, newBox);
529         newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
530         return;
531     }
532
533     RenderObject* immediateChild = beforeChild;
534     bool isPreviousBlockViable = true;
535     while (immediateChild->parent() != this) {
536         if (isPreviousBlockViable)
537             isPreviousBlockViable = !immediateChild->previousSibling();
538         immediateChild = immediateChild->parent();
539     }
540     if (isPreviousBlockViable && immediateChild->previousSibling()) {
541         toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); // Treat like an append.
542         return;
543     }
544
545     // Split our anonymous blocks.
546     RenderObject* newBeforeChild = splitAnonymousBoxesAroundChild(beforeChild);
547
548
549     // Create a new anonymous box of the appropriate type.
550     RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
551     children()->insertChildNode(this, newBox, newBeforeChild);
552     newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
553     return;
554 }
555
556 RenderBlockFlow* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
557 {
558     RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
559     for (RenderObject* curr = this; curr; curr = curr->parent()) {
560         if (!curr->isRenderBlock() || curr->isFloatingOrOutOfFlowPositioned() || curr->isTableCell() || curr->isDocumentElement() || curr->isRenderView() || curr->hasOverflowClip()
561             || curr->isInlineBlockOrInlineTable())
562             return 0;
563
564         // FIXME: Renderers that do special management of their children (tables, buttons,
565         // lists, flexboxes, etc.) breaks when the flow is split through them. Disabling
566         // multi-column for them to avoid this problem.)
567         if (!curr->isRenderBlockFlow() || curr->isListItem())
568             return 0;
569
570         RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
571         if (!currBlock->createsAnonymousWrapper())
572             firstChildIgnoringAnonymousWrappers = currBlock;
573
574         if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
575             return toRenderBlockFlow(firstChildIgnoringAnonymousWrappers);
576
577         if (currBlock->isAnonymousColumnSpanBlock())
578             return 0;
579     }
580     return 0;
581 }
582
583 RenderBlock* RenderBlock::clone() const
584 {
585     RenderBlock* cloneBlock;
586     if (isAnonymousBlock()) {
587         cloneBlock = createAnonymousBlock();
588         cloneBlock->setChildrenInline(childrenInline());
589     }
590     else {
591         RenderObject* cloneRenderer = toElement(node())->createRenderer(style());
592         cloneBlock = toRenderBlock(cloneRenderer);
593         cloneBlock->setStyle(style());
594
595         // This takes care of setting the right value of childrenInline in case
596         // generated content is added to cloneBlock and 'this' does not have
597         // generated content added yet.
598         cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
599     }
600     cloneBlock->setFlowThreadState(flowThreadState());
601     return cloneBlock;
602 }
603
604 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
605                               RenderBlock* middleBlock,
606                               RenderObject* beforeChild, RenderBoxModelObject* oldCont)
607 {
608     // Create a clone of this inline.
609     RenderBlock* cloneBlock = clone();
610     if (!isAnonymousBlock())
611         cloneBlock->setContinuation(oldCont);
612
613     if (!beforeChild && isAfterContent(lastChild()))
614         beforeChild = lastChild();
615
616     // If we are moving inline children from |this| to cloneBlock, then we need
617     // to clear our line box tree.
618     if (beforeChild && childrenInline())
619         deleteLineBoxTree();
620
621     // Now take all of the children from beforeChild to the end and remove
622     // them from |this| and place them in the clone.
623     moveChildrenTo(cloneBlock, beforeChild, 0, true);
624
625     // Hook |clone| up as the continuation of the middle block.
626     if (!cloneBlock->isAnonymousBlock())
627         middleBlock->setContinuation(cloneBlock);
628
629     // We have been reparented and are now under the fromBlock.  We need
630     // to walk up our block parent chain until we hit the containing anonymous columns block.
631     // Once we hit the anonymous columns block we're done.
632     RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
633     RenderBoxModelObject* currChild = this;
634     RenderObject* currChildNextSibling = currChild->nextSibling();
635
636     while (curr && curr->isDescendantOf(fromBlock) && curr != fromBlock) {
637         ASSERT_WITH_SECURITY_IMPLICATION(curr->isRenderBlock());
638
639         RenderBlock* blockCurr = toRenderBlock(curr);
640
641         // Create a new clone.
642         RenderBlock* cloneChild = cloneBlock;
643         cloneBlock = blockCurr->clone();
644
645         // Insert our child clone as the first child.
646         cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
647
648         // Hook the clone up as a continuation of |curr|.  Note we do encounter
649         // anonymous blocks possibly as we walk up the block chain.  When we split an
650         // anonymous block, there's no need to do any continuation hookup, since we haven't
651         // actually split a real element.
652         if (!blockCurr->isAnonymousBlock()) {
653             oldCont = blockCurr->continuation();
654             blockCurr->setContinuation(cloneBlock);
655             cloneBlock->setContinuation(oldCont);
656         }
657
658         // Now we need to take all of the children starting from the first child
659         // *after* currChild and append them all to the clone.
660         blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
661
662         // Keep walking up the chain.
663         currChild = curr;
664         currChildNextSibling = currChild->nextSibling();
665         curr = toRenderBoxModelObject(curr->parent());
666     }
667
668     // Now we are at the columns block level. We need to put the clone into the toBlock.
669     toBlock->children()->appendChildNode(toBlock, cloneBlock);
670
671     // Now take all the children after currChild and remove them from the fromBlock
672     // and put them in the toBlock.
673     fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
674 }
675
676 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
677                             RenderObject* newChild, RenderBoxModelObject* oldCont)
678 {
679     RenderBlock* pre = 0;
680     RenderBlock* block = containingColumnsBlock();
681
682     // Delete our line boxes before we do the inline split into continuations.
683     block->deleteLineBoxTree();
684
685     bool madeNewBeforeBlock = false;
686     if (block->isAnonymousColumnsBlock()) {
687         // We can reuse this block and make it the preBlock of the next continuation.
688         pre = block;
689         pre->removePositionedObjects(0);
690         if (block->isRenderBlockFlow())
691             toRenderBlockFlow(pre)->removeFloatingObjects();
692         block = toRenderBlock(block->parent());
693     } else {
694         // No anonymous block available for use.  Make one.
695         pre = block->createAnonymousColumnsBlock();
696         pre->setChildrenInline(false);
697         madeNewBeforeBlock = true;
698     }
699
700     RenderBlock* post = block->createAnonymousColumnsBlock();
701     post->setChildrenInline(false);
702
703     RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
704     if (madeNewBeforeBlock)
705         block->children()->insertChildNode(block, pre, boxFirst);
706     block->children()->insertChildNode(block, newBlockBox, boxFirst);
707     block->children()->insertChildNode(block, post, boxFirst);
708     block->setChildrenInline(false);
709
710     if (madeNewBeforeBlock)
711         block->moveChildrenTo(pre, boxFirst, 0, true);
712
713     splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
714
715     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
716     // time in makeChildrenNonInline by just setting this explicitly up front.
717     newBlockBox->setChildrenInline(false);
718
719     newBlockBox->addChild(newChild);
720
721     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
722     // get deleted properly.  Because objects moves from the pre block into the post block, we want to
723     // make new line boxes instead of leaving the old line boxes around.
724     pre->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
725     block->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
726     post->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
727 }
728
729 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlockFlow* newBlockBox, RenderObject* newChild)
730 {
731     RenderBlockFlow* pre = 0;
732     RenderBlockFlow* post = 0;
733     RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|.  Assign to a variable
734                                // so that we don't have to patch all of the rest of the code later on.
735
736     // Delete the block's line boxes before we do the split.
737     block->deleteLineBoxTree();
738
739     if (beforeChild && beforeChild->parent() != this)
740         beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
741
742     if (beforeChild != firstChild()) {
743         pre = block->createAnonymousColumnsBlock();
744         pre->setChildrenInline(block->childrenInline());
745     }
746
747     if (beforeChild) {
748         post = block->createAnonymousColumnsBlock();
749         post->setChildrenInline(block->childrenInline());
750     }
751
752     RenderObject* boxFirst = block->firstChild();
753     if (pre)
754         block->children()->insertChildNode(block, pre, boxFirst);
755     block->children()->insertChildNode(block, newBlockBox, boxFirst);
756     if (post)
757         block->children()->insertChildNode(block, post, boxFirst);
758     block->setChildrenInline(false);
759
760     // 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).
761     block->moveChildrenTo(pre, boxFirst, beforeChild, true);
762     block->moveChildrenTo(post, beforeChild, 0, true);
763
764     // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
765     // time in makeChildrenNonInline by just setting this explicitly up front.
766     newBlockBox->setChildrenInline(false);
767
768     newBlockBox->addChild(newChild);
769
770     // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
771     // get deleted properly.  Because objects moved from the pre block into the post block, we want to
772     // make new line boxes instead of leaving the old line boxes around.
773     if (pre)
774         pre->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
775     block->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
776     if (post)
777         post->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
778 }
779
780 RenderBlockFlow* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
781 {
782     // FIXME: This function is the gateway for the addition of column-span support.  It will
783     // be added to in three stages:
784     // (1) Immediate children of a multi-column block can span.
785     // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
786     // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
787     // cross the streams and have to cope with both types of continuations mixed together).
788     // This function currently supports (1) and (2).
789     RenderBlockFlow* columnsBlockAncestor = 0;
790     if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
791         && !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
792         columnsBlockAncestor = containingColumnsBlock(false);
793         if (columnsBlockAncestor) {
794             // Make sure that none of the parent ancestors have a continuation.
795             // If yes, we do not want split the block into continuations.
796             RenderObject* curr = this;
797             while (curr && curr != columnsBlockAncestor) {
798                 if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
799                     columnsBlockAncestor = 0;
800                     break;
801                 }
802                 curr = curr->parent();
803             }
804         }
805     }
806     return columnsBlockAncestor;
807 }
808
809 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
810 {
811     if (beforeChild && beforeChild->parent() != this) {
812         RenderObject* beforeChildContainer = beforeChild->parent();
813         while (beforeChildContainer->parent() != this)
814             beforeChildContainer = beforeChildContainer->parent();
815         ASSERT(beforeChildContainer);
816
817         if (beforeChildContainer->isAnonymous()) {
818             // If the requested beforeChild is not one of our children, then this is because
819             // there is an anonymous container within this object that contains the beforeChild.
820             RenderObject* beforeChildAnonymousContainer = beforeChildContainer;
821             if (beforeChildAnonymousContainer->isAnonymousBlock()
822                 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
823                 || beforeChildAnonymousContainer->isRenderFullScreen()
824                 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
825                 ) {
826                 // Insert the child into the anonymous block box instead of here.
827                 if (newChild->isInline() || newChild->isFloatingOrOutOfFlowPositioned() || beforeChild->parent()->slowFirstChild() != beforeChild)
828                     beforeChild->parent()->addChild(newChild, beforeChild);
829                 else
830                     addChild(newChild, beforeChild->parent());
831                 return;
832             }
833
834             ASSERT(beforeChildAnonymousContainer->isTable());
835             if (newChild->isTablePart()) {
836                 // Insert into the anonymous table.
837                 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
838                 return;
839             }
840
841             beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
842
843             ASSERT(beforeChild->parent() == this);
844             if (beforeChild->parent() != this) {
845                 // We should never reach here. If we do, we need to use the
846                 // safe fallback to use the topmost beforeChild container.
847                 beforeChild = beforeChildContainer;
848             }
849         }
850     }
851
852     // Check for a spanning element in columns.
853     if (gColumnFlowSplitEnabled && !document().regionBasedColumnsEnabled()) {
854         RenderBlockFlow* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
855         if (columnsBlockAncestor) {
856             TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
857             // We are placing a column-span element inside a block.
858             RenderBlockFlow* newBox = createAnonymousColumnSpanBlock();
859
860             if (columnsBlockAncestor != this && !isRenderFlowThread()) {
861                 // We are nested inside a multi-column element and are being split by the span. We have to break up
862                 // our block into continuations.
863                 RenderBoxModelObject* oldContinuation = continuation();
864
865                 // When we split an anonymous block, there's no need to do any continuation hookup,
866                 // since we haven't actually split a real element.
867                 if (!isAnonymousBlock())
868                     setContinuation(newBox);
869
870                 splitFlow(beforeChild, newBox, newChild, oldContinuation);
871                 return;
872             }
873
874             // We have to perform a split of this block's children. This involves creating an anonymous block box to hold
875             // the column-spanning |newChild|. We take all of the children from before |newChild| and put them into
876             // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
877             makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
878             return;
879         }
880     }
881
882     bool madeBoxesNonInline = false;
883
884     // A block has to either have all of its children inline, or all of its children as blocks.
885     // So, if our children are currently inline and a block child has to be inserted, we move all our
886     // inline children into anonymous block boxes.
887     if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
888         // This is a block with inline content. Wrap the inline content in anonymous blocks.
889         makeChildrenNonInline(beforeChild);
890         madeBoxesNonInline = true;
891
892         if (beforeChild && beforeChild->parent() != this) {
893             beforeChild = beforeChild->parent();
894             ASSERT(beforeChild->isAnonymousBlock());
895             ASSERT(beforeChild->parent() == this);
896         }
897     } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
898         // If we're inserting an inline child but all of our children are blocks, then we have to make sure
899         // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
900         // a new one is created and inserted into our list of children in the appropriate position.
901         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
902
903         if (afterChild && afterChild->isAnonymousBlock()) {
904             afterChild->addChild(newChild);
905             return;
906         }
907
908         if (newChild->isInline()) {
909             // No suitable existing anonymous box - create a new one.
910             RenderBlock* newBox = createAnonymousBlock();
911             RenderBox::addChild(newBox, beforeChild);
912             newBox->addChild(newChild);
913             return;
914         }
915     }
916
917     RenderBox::addChild(newChild, beforeChild);
918
919     if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
920         toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
921     // this object may be dead here
922 }
923
924 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
925 {
926     if (continuation() && !isAnonymousBlock())
927         addChildToContinuation(newChild, beforeChild);
928     else
929         addChildIgnoringContinuation(newChild, beforeChild);
930 }
931
932 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
933 {
934     if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
935         addChildToAnonymousColumnBlocks(newChild, beforeChild);
936     else
937         addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
938 }
939
940 static void getInlineRun(RenderObject* start, RenderObject* boundary,
941                          RenderObject*& inlineRunStart,
942                          RenderObject*& inlineRunEnd)
943 {
944     // Beginning at |start| we find the largest contiguous run of inlines that
945     // we can.  We denote the run with start and end points, |inlineRunStart|
946     // and |inlineRunEnd|.  Note that these two values may be the same if
947     // we encounter only one inline.
948     //
949     // We skip any non-inlines we encounter as long as we haven't found any
950     // inlines yet.
951     //
952     // |boundary| indicates a non-inclusive boundary point.  Regardless of whether |boundary|
953     // is inline or not, we will not include it in a run with inlines before it.  It's as though we encountered
954     // a non-inline.
955
956     // Start by skipping as many non-inlines as we can.
957     RenderObject * curr = start;
958     bool sawInline;
959     do {
960         while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
961             curr = curr->nextSibling();
962
963         inlineRunStart = inlineRunEnd = curr;
964
965         if (!curr)
966             return; // No more inline children to be found.
967
968         sawInline = curr->isInline();
969
970         curr = curr->nextSibling();
971         while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
972             inlineRunEnd = curr;
973             if (curr->isInline())
974                 sawInline = true;
975             curr = curr->nextSibling();
976         }
977     } while (!sawInline);
978 }
979
980 void RenderBlock::deleteLineBoxTree()
981 {
982     ASSERT(!m_lineBoxes.firstLineBox());
983 }
984
985 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
986 {
987     // makeChildrenNonInline takes a block whose children are *all* inline and it
988     // makes sure that inline children are coalesced under anonymous
989     // blocks.  If |insertionPoint| is defined, then it represents the insertion point for
990     // the new block child that is causing us to have to wrap all the inlines.  This
991     // means that we cannot coalesce inlines before |insertionPoint| with inlines following
992     // |insertionPoint|, because the new child is going to be inserted in between the inlines,
993     // splitting them.
994     ASSERT(isInlineBlockOrInlineTable() || !isInline());
995     ASSERT(!insertionPoint || insertionPoint->parent() == this);
996
997     setChildrenInline(false);
998
999     RenderObject *child = firstChild();
1000     if (!child)
1001         return;
1002
1003     deleteLineBoxTree();
1004
1005     while (child) {
1006         RenderObject *inlineRunStart, *inlineRunEnd;
1007         getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
1008
1009         if (!inlineRunStart)
1010             break;
1011
1012         child = inlineRunEnd->nextSibling();
1013
1014         RenderBlock* block = createAnonymousBlock();
1015         children()->insertChildNode(this, block, inlineRunStart);
1016         moveChildrenTo(block, inlineRunStart, child);
1017     }
1018
1019 #if ENABLE(ASSERT)
1020     for (RenderObject *c = firstChild(); c; c = c->nextSibling())
1021         ASSERT(!c->isInline());
1022 #endif
1023
1024     setShouldDoFullPaintInvalidation();
1025 }
1026
1027 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
1028 {
1029     ASSERT(child->isAnonymousBlock());
1030     ASSERT(!child->childrenInline());
1031
1032     if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
1033         return;
1034
1035     RenderObject* firstAnChild = child->m_children.firstChild();
1036     RenderObject* lastAnChild = child->m_children.lastChild();
1037     if (firstAnChild) {
1038         RenderObject* o = firstAnChild;
1039         while (o) {
1040             o->setParent(this);
1041             o = o->nextSibling();
1042         }
1043         firstAnChild->setPreviousSibling(child->previousSibling());
1044         lastAnChild->setNextSibling(child->nextSibling());
1045         if (child->previousSibling())
1046             child->previousSibling()->setNextSibling(firstAnChild);
1047         if (child->nextSibling())
1048             child->nextSibling()->setPreviousSibling(lastAnChild);
1049
1050         if (child == m_children.firstChild())
1051             m_children.setFirstChild(firstAnChild);
1052         if (child == m_children.lastChild())
1053             m_children.setLastChild(lastAnChild);
1054     } else {
1055         if (child == m_children.firstChild())
1056             m_children.setFirstChild(child->nextSibling());
1057         if (child == m_children.lastChild())
1058             m_children.setLastChild(child->previousSibling());
1059
1060         if (child->previousSibling())
1061             child->previousSibling()->setNextSibling(child->nextSibling());
1062         if (child->nextSibling())
1063             child->nextSibling()->setPreviousSibling(child->previousSibling());
1064     }
1065
1066     child->children()->setFirstChild(0);
1067     child->m_next = nullptr;
1068
1069     // Remove all the information in the flow thread associated with the leftover anonymous block.
1070     child->removeFromRenderFlowThread();
1071
1072     // RenderGrid keeps track of its children, we must notify it about changes in the tree.
1073     if (child->parent()->isRenderGrid())
1074         toRenderGrid(child->parent())->dirtyGrid();
1075
1076     child->setParent(0);
1077     child->setPreviousSibling(0);
1078     child->setNextSibling(0);
1079
1080     child->destroy();
1081 }
1082
1083 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
1084 {
1085     if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
1086         return false;
1087
1088     if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
1089         || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
1090         return false;
1091
1092     if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
1093         || (next && (next->isRubyRun() || next->isRubyBase())))
1094         return false;
1095
1096     if (!prev || !next)
1097         return true;
1098
1099     // Make sure the types of the anonymous blocks match up.
1100     return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
1101            && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
1102 }
1103
1104 void RenderBlock::collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock* child)
1105 {
1106     // It's possible that this block's destruction may have been triggered by the
1107     // child's removal. Just bail if the anonymous child block is already being
1108     // destroyed. See crbug.com/282088
1109     if (child->beingDestroyed())
1110         return;
1111     parent->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
1112     parent->setChildrenInline(child->childrenInline());
1113     RenderObject* nextSibling = child->nextSibling();
1114
1115     RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
1116     CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
1117
1118     parent->children()->removeChildNode(parent, child, child->hasLayer());
1119     // FIXME: Get rid of the temporary disabling of continuations. This is needed by the old
1120     // multicol implementation, because of buggy block continuation handling (which is hard and
1121     // rather pointless to fix at this point). Support for block continuations can be removed
1122     // together with the old multicol implementation. crbug.com/408123
1123     RenderBoxModelObject* temporarilyInactiveContinuation = parent->continuation();
1124     if (temporarilyInactiveContinuation)
1125         parent->setContinuation(0);
1126     child->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
1127     if (temporarilyInactiveContinuation)
1128         parent->setContinuation(temporarilyInactiveContinuation);
1129     // Explicitly delete the child's line box tree, or the special anonymous
1130     // block handling in willBeDestroyed will cause problems.
1131     child->deleteLineBoxTree();
1132     child->destroy();
1133 }
1134
1135 void RenderBlock::removeChild(RenderObject* oldChild)
1136 {
1137     // No need to waste time in merging or removing empty anonymous blocks.
1138     // We can just bail out if our document is getting destroyed.
1139     if (documentBeingDestroyed()) {
1140         RenderBox::removeChild(oldChild);
1141         return;
1142     }
1143
1144     // This protects against column split flows when anonymous blocks are getting merged.
1145     TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
1146
1147     // If this child is a block, and if our previous and next siblings are
1148     // both anonymous blocks with inline content, then we can go ahead and
1149     // fold the inline content back together.
1150     RenderObject* prev = oldChild->previousSibling();
1151     RenderObject* next = oldChild->nextSibling();
1152     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1153     if (canMergeAnonymousBlocks && prev && next) {
1154         prev->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
1155         RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
1156         RenderBlockFlow* prevBlock = toRenderBlockFlow(prev);
1157
1158         if (prev->childrenInline() != next->childrenInline()) {
1159             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1160             RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1161
1162             // Place the inline children block inside of the block children block instead of deleting it.
1163             // In order to reuse it, we have to reset it to just be a generic anonymous block.  Make sure
1164             // to clear out inherited column properties by just making a new style, and to also clear the
1165             // column span flag if it is set.
1166             ASSERT(!inlineChildrenBlock->continuation());
1167             RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
1168             // Cache this value as it might get changed in setStyle() call.
1169             bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
1170             inlineChildrenBlock->setStyle(newStyle);
1171             children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlockHasLayer);
1172
1173             // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1174             blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1175                                                             inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer());
1176             next->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
1177
1178             // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1179             // of "this". we null out prev or next so that is not used later in the function.
1180             if (inlineChildrenBlock == prevBlock)
1181                 prev = 0;
1182             else
1183                 next = 0;
1184         } else {
1185             // Take all the children out of the |next| block and put them in
1186             // the |prev| block.
1187             nextBlock->moveAllChildrenIncludingFloatsTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
1188
1189             // Delete the now-empty block's lines and nuke it.
1190             nextBlock->deleteLineBoxTree();
1191             nextBlock->destroy();
1192             next = 0;
1193         }
1194     }
1195
1196     RenderBox::removeChild(oldChild);
1197
1198     RenderObject* child = prev ? prev : next;
1199     if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
1200         // The removal has knocked us down to containing only a single anonymous
1201         // box.  We can go ahead and pull the content right back up into our
1202         // box.
1203         collapseAnonymousBlockChild(this, toRenderBlock(child));
1204     } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
1205         // It's possible that the removal has knocked us down to a single anonymous
1206         // block with pseudo-style element siblings (e.g. first-letter). If these
1207         // are floating, then we need to pull the content up also.
1208         RenderBlock* anonymousBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
1209         if ((anonymousBlock->previousSibling() || anonymousBlock->nextSibling())
1210             && (!anonymousBlock->previousSibling() || (anonymousBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonymousBlock->previousSibling()->isFloating() && !anonymousBlock->previousSibling()->previousSibling()))
1211             && (!anonymousBlock->nextSibling() || (anonymousBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonymousBlock->nextSibling()->isFloating() && !anonymousBlock->nextSibling()->nextSibling()))) {
1212             collapseAnonymousBlockChild(this, anonymousBlock);
1213         }
1214     }
1215
1216     if (!firstChild()) {
1217         // If this was our last child be sure to clear out our line boxes.
1218         if (childrenInline())
1219             deleteLineBoxTree();
1220
1221         // If we are an empty anonymous block in the continuation chain,
1222         // we need to remove ourself and fix the continuation chain.
1223         if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild->isListMarker()) {
1224             RenderObject* containingBlockIgnoringAnonymous = containingBlock();
1225             while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymous())
1226                 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
1227             for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
1228                 if (curr->virtualContinuation() != this)
1229                     continue;
1230
1231                 // Found our previous continuation. We just need to point it to
1232                 // |this|'s next continuation.
1233                 RenderBoxModelObject* nextContinuation = continuation();
1234                 if (curr->isRenderInline())
1235                     toRenderInline(curr)->setContinuation(nextContinuation);
1236                 else if (curr->isRenderBlock())
1237                     toRenderBlock(curr)->setContinuation(nextContinuation);
1238                 else
1239                     ASSERT_NOT_REACHED();
1240
1241                 break;
1242             }
1243             setContinuation(0);
1244             destroy();
1245         }
1246     }
1247 }
1248
1249 bool RenderBlock::isSelfCollapsingBlock() const
1250 {
1251     // We are not self-collapsing if we
1252     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1253     // (b) are a table,
1254     // (c) have border/padding,
1255     // (d) have a min-height
1256     // (e) have specified that one of our margins can't collapse using a CSS extension
1257     // (f) establish a new block formatting context.
1258
1259     // The early exit must be done before we check for clean layout.
1260     // We should be able to give a quick answer if the box is a relayout boundary.
1261     // Being a relayout boundary implies a block formatting context, and also
1262     // our internal layout shouldn't affect our container in any way.
1263     if (createsBlockFormattingContext())
1264         return false;
1265
1266     // Placeholder elements are not laid out until the dimensions of their parent text control are known, so they
1267     // don't get layout until their parent has had layout - this is unique in the layout tree and means
1268     // when we call isSelfCollapsingBlock on them we find that they still need layout.
1269     ASSERT(!needsLayout() || (node() && node()->isElementNode() && toElement(node())->shadowPseudoId() == "-webkit-input-placeholder"));
1270
1271     if (logicalHeight() > 0
1272         || isTable() || borderAndPaddingLogicalHeight()
1273         || style()->logicalMinHeight().isPositive()
1274         || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1275         return false;
1276
1277     Length logicalHeightLength = style()->logicalHeight();
1278     bool hasAutoHeight = logicalHeightLength.isAuto();
1279     if (logicalHeightLength.isPercent() && !document().inQuirksMode()) {
1280         hasAutoHeight = true;
1281         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1282             if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1283                 hasAutoHeight = false;
1284         }
1285     }
1286
1287     // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1288     // on whether we have content that is all self-collapsing or not.
1289     if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1290         // If the block has inline children, see if we generated any line boxes.  If we have any
1291         // line boxes, then we can't be self-collapsing, since we have content.
1292         if (childrenInline())
1293             return !firstLineBox();
1294
1295         // Whether or not we collapse is dependent on whether all our normal flow children
1296         // are also self-collapsing.
1297         if (m_hasOnlySelfCollapsingChildren)
1298             return true;
1299         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1300             if (child->isFloatingOrOutOfFlowPositioned())
1301                 continue;
1302             if (!child->isSelfCollapsingBlock())
1303                 return false;
1304         }
1305         return true;
1306     }
1307     return false;
1308 }
1309
1310 void RenderBlock::startDelayUpdateScrollInfo()
1311 {
1312     if (gDelayUpdateScrollInfo == 0) {
1313         ASSERT(!gDelayedUpdateScrollInfoSet);
1314         gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1315     }
1316     ASSERT(gDelayedUpdateScrollInfoSet);
1317     ++gDelayUpdateScrollInfo;
1318 }
1319
1320 void RenderBlock::finishDelayUpdateScrollInfo()
1321 {
1322     --gDelayUpdateScrollInfo;
1323     ASSERT(gDelayUpdateScrollInfo >= 0);
1324     if (gDelayUpdateScrollInfo == 0) {
1325         ASSERT(gDelayedUpdateScrollInfoSet);
1326
1327         OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1328         gDelayedUpdateScrollInfoSet = 0;
1329
1330         for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1331             RenderBlock* block = *it;
1332             if (block->hasOverflowClip()) {
1333                 block->layer()->scrollableArea()->updateAfterLayout();
1334             }
1335         }
1336     }
1337 }
1338
1339 void RenderBlock::updateScrollInfoAfterLayout()
1340 {
1341     if (hasOverflowClip()) {
1342         if (style()->slowIsFlippedBlocksWritingMode()) {
1343             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=97937
1344             // Workaround for now. We cannot delay the scroll info for overflow
1345             // for items with opposite writing directions, as the contents needs
1346             // to overflow in that direction
1347             layer()->scrollableArea()->updateAfterLayout();
1348             return;
1349         }
1350
1351         if (gDelayUpdateScrollInfo)
1352             gDelayedUpdateScrollInfoSet->add(this);
1353         else
1354             layer()->scrollableArea()->updateAfterLayout();
1355     }
1356 }
1357
1358 void RenderBlock::layout()
1359 {
1360     OverflowEventDispatcher dispatcher(this);
1361
1362     // Update our first letter info now.
1363     updateFirstLetter();
1364
1365     // Table cells call layoutBlock directly, so don't add any logic here.  Put code into
1366     // layoutBlock().
1367     layoutBlock(false);
1368
1369     // It's safe to check for control clip here, since controls can never be table cells.
1370     // If we have a lightweight clip, there can never be any overflow from children.
1371     if (hasControlClip() && m_overflow)
1372         clearLayoutOverflow();
1373
1374     invalidateBackgroundObscurationStatus();
1375 }
1376
1377 bool RenderBlock::updateImageLoadingPriorities()
1378 {
1379     Vector<ImageResource*> images;
1380     appendImagesFromStyle(images, *style());
1381
1382     if (images.isEmpty())
1383         return false;
1384
1385     LayoutRect viewBounds = viewRect();
1386     LayoutRect objectBounds = absoluteContentBox();
1387     // The object bounds might be empty right now, so intersects will fail since it doesn't deal
1388     // with empty rects. Use LayoutRect::contains in that case.
1389     bool isVisible;
1390     if (!objectBounds.isEmpty())
1391         isVisible =  viewBounds.intersects(objectBounds);
1392     else
1393         isVisible = viewBounds.contains(objectBounds);
1394
1395     ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
1396         ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
1397
1398     LayoutRect screenArea;
1399     if (!objectBounds.isEmpty()) {
1400         screenArea = viewBounds;
1401         screenArea.intersect(objectBounds);
1402     }
1403
1404     for (Vector<ImageResource*>::iterator it = images.begin(), end = images.end(); it != end; ++it)
1405         ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->notifyImageResourceVisibility(*it, status, screenArea);
1406
1407     return true;
1408 }
1409
1410 bool RenderBlock::widthAvailableToChildrenHasChanged()
1411 {
1412     bool widthAvailableToChildrenHasChanged = m_hasBorderOrPaddingLogicalWidthChanged;
1413     m_hasBorderOrPaddingLogicalWidthChanged = false;
1414
1415     // If we use border-box sizing, have percentage padding, and our parent has changed width then the width available to our children has changed even
1416     // though our own width has remained the same.
1417     widthAvailableToChildrenHasChanged |= style()->boxSizing() == BORDER_BOX && needsPreferredWidthsRecalculation() && view()->layoutState()->containingBlockLogicalWidthChanged();
1418
1419     return widthAvailableToChildrenHasChanged;
1420 }
1421
1422 bool RenderBlock::updateLogicalWidthAndColumnWidth()
1423 {
1424     LayoutUnit oldWidth = logicalWidth();
1425     LayoutUnit oldColumnWidth = desiredColumnWidth();
1426
1427     updateLogicalWidth();
1428     calcColumnWidth();
1429
1430     return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth() || widthAvailableToChildrenHasChanged();
1431 }
1432
1433 void RenderBlock::layoutBlock(bool)
1434 {
1435     ASSERT_NOT_REACHED();
1436     clearNeedsLayout();
1437 }
1438
1439 void RenderBlock::addOverflowFromChildren()
1440 {
1441     if (!hasColumns()) {
1442         if (childrenInline())
1443             toRenderBlockFlow(this)->addOverflowFromInlineChildren();
1444         else
1445             addOverflowFromBlockChildren();
1446     } else {
1447         ColumnInfo* colInfo = columnInfo();
1448         if (columnCount(colInfo)) {
1449             LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1450             addLayoutOverflow(lastRect);
1451             addContentsVisualOverflow(lastRect);
1452         }
1453     }
1454 }
1455
1456 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool)
1457 {
1458     m_overflow.clear();
1459
1460     // Add overflow from children.
1461     addOverflowFromChildren();
1462
1463     // Add in the overflow from positioned objects.
1464     addOverflowFromPositionedObjects();
1465
1466     if (hasOverflowClip()) {
1467         // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1468         // and bottom padding.  Set the axis we don't care about to be 1, since we want this overflow to always
1469         // be considered reachable.
1470         LayoutRect clientRect(noOverflowRect());
1471         LayoutRect rectToApply;
1472         if (isHorizontalWritingMode())
1473             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1474         else
1475             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1476         addLayoutOverflow(rectToApply);
1477         if (hasRenderOverflow())
1478             m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
1479     }
1480
1481     addVisualEffectOverflow();
1482
1483     addVisualOverflowFromTheme();
1484 }
1485
1486 void RenderBlock::addOverflowFromBlockChildren()
1487 {
1488     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1489         if (!child->isFloatingOrOutOfFlowPositioned())
1490             addOverflowFromChild(child);
1491     }
1492 }
1493
1494 void RenderBlock::addOverflowFromPositionedObjects()
1495 {
1496     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1497     if (!positionedDescendants)
1498         return;
1499
1500     RenderBox* positionedObject;
1501     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1502     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1503         positionedObject = *it;
1504
1505         // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1506         if (positionedObject->style()->position() != FixedPosition)
1507             addOverflowFromChild(positionedObject, LayoutSize(positionedObject->x(), positionedObject->y()));
1508     }
1509 }
1510
1511 void RenderBlock::addVisualOverflowFromTheme()
1512 {
1513     if (!style()->hasAppearance())
1514         return;
1515
1516     IntRect inflatedRect = pixelSnappedBorderBoxRect();
1517     RenderTheme::theme().adjustPaintInvalidationRect(this, inflatedRect);
1518     addVisualOverflow(inflatedRect);
1519 }
1520
1521 bool RenderBlock::createsBlockFormattingContext() const
1522 {
1523     return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || isFlexItemIncludingDeprecated()
1524         || style()->specifiesColumns() || isRenderFlowThread() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isDocumentElement() || style()->columnSpan();
1525 }
1526
1527 void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox* child)
1528 {
1529     // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
1530     // an auto value. Add a method to determine this, so that we can avoid the relayout.
1531     if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()))
1532         child->setChildNeedsLayout(MarkOnlyThis);
1533
1534     // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1535     if (relayoutChildren && child->needsPreferredWidthsRecalculation())
1536         child->setPreferredLogicalWidthsDirty(MarkOnlyThis);
1537 }
1538
1539 void RenderBlock::simplifiedNormalFlowLayout()
1540 {
1541     if (childrenInline()) {
1542         ListHashSet<RootInlineBox*> lineBoxes;
1543         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
1544             RenderObject* o = walker.current();
1545             if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
1546                 o->layoutIfNeeded();
1547                 if (toRenderBox(o)->inlineBoxWrapper()) {
1548                     RootInlineBox& box = toRenderBox(o)->inlineBoxWrapper()->root();
1549                     lineBoxes.add(&box);
1550                 }
1551             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline())) {
1552                 o->clearNeedsLayout();
1553             }
1554         }
1555
1556         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
1557         GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1558         for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
1559             RootInlineBox* box = *it;
1560             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
1561         }
1562     } else {
1563         for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
1564             if (!box->isOutOfFlowPositioned())
1565                 box->layoutIfNeeded();
1566         }
1567     }
1568 }
1569
1570 bool RenderBlock::simplifiedLayout()
1571 {
1572     // Check if we need to do a full layout.
1573     if (normalChildNeedsLayout() || selfNeedsLayout())
1574         return false;
1575
1576     // Check that we actually need to do a simplified layout.
1577     if (!posChildNeedsLayout() && !(needsSimplifiedNormalFlowLayout() || needsPositionedMovementLayout()))
1578         return false;
1579
1580
1581     {
1582         // LayoutState needs this deliberate scope to pop before paint invalidation.
1583         LayoutState state(*this, locationOffset());
1584
1585         if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
1586             return false;
1587
1588         TextAutosizer::LayoutScope textAutosizerLayoutScope(this);
1589
1590         // Lay out positioned descendants or objects that just need to recompute overflow.
1591         if (needsSimplifiedNormalFlowLayout())
1592             simplifiedNormalFlowLayout();
1593
1594         // Lay out our positioned objects if our positioned child bit is set.
1595         // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
1596         // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the
1597         // relative positioned container. So if we can have fixed pos objects in our positioned objects list check if any of them
1598         // are statically positioned and thus need to move with their absolute ancestors.
1599         bool canContainFixedPosObjects = canContainFixedPositionObjects();
1600         if (posChildNeedsLayout() || needsPositionedMovementLayout() || canContainFixedPosObjects)
1601             layoutPositionedObjects(false, needsPositionedMovementLayout() ? ForcedLayoutAfterContainingBlockMoved : (!posChildNeedsLayout() && canContainFixedPosObjects ? LayoutOnlyFixedPositionedObjects : DefaultLayout));
1602
1603         // Recompute our overflow information.
1604         // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
1605         // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
1606         // For now just always recompute overflow. This is no worse performance-wise than the old code that called rightmostPosition and
1607         // lowestPosition on every relayout so it's not a regression.
1608         // computeOverflow expects the bottom edge before we clamp our height. Since this information isn't available during
1609         // simplifiedLayout, we cache the value in m_overflow.
1610         LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
1611         computeOverflow(oldClientAfterEdge, true);
1612     }
1613
1614     updateLayerTransformAfterLayout();
1615
1616     updateScrollInfoAfterLayout();
1617
1618     clearNeedsLayout();
1619     return true;
1620 }
1621
1622 void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope& layoutScope)
1623 {
1624     if (child->style()->position() != FixedPosition)
1625         return;
1626
1627     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode());
1628     bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode());
1629     if (!hasStaticBlockPosition && !hasStaticInlinePosition)
1630         return;
1631
1632     RenderObject* o = child->parent();
1633     while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition)
1634         o = o->parent();
1635     if (o->style()->position() != AbsolutePosition)
1636         return;
1637
1638     RenderBox* box = toRenderBox(child);
1639     if (hasStaticInlinePosition) {
1640         LogicalExtentComputedValues computedValues;
1641         box->computeLogicalWidth(computedValues);
1642         LayoutUnit newLeft = computedValues.m_position;
1643         if (newLeft != box->logicalLeft())
1644             layoutScope.setChildNeedsLayout(child);
1645     } else if (hasStaticBlockPosition) {
1646         LayoutUnit oldTop = box->logicalTop();
1647         box->updateLogicalHeight();
1648         if (box->logicalTop() != oldTop)
1649             layoutScope.setChildNeedsLayout(child);
1650     }
1651 }
1652
1653 LayoutUnit RenderBlock::marginIntrinsicLogicalWidthForChild(RenderBox* child) const
1654 {
1655     // A margin has three types: fixed, percentage, and auto (variable).
1656     // Auto and percentage margins become 0 when computing min/max width.
1657     // Fixed margins can be added in as is.
1658     Length marginLeft = child->style()->marginStartUsing(style());
1659     Length marginRight = child->style()->marginEndUsing(style());
1660     LayoutUnit margin = 0;
1661     if (marginLeft.isFixed())
1662         margin += marginLeft.value();
1663     if (marginRight.isFixed())
1664         margin += marginRight.value();
1665     return margin;
1666 }
1667
1668 void RenderBlock::layoutPositionedObjects(bool relayoutChildren, PositionedLayoutBehavior info)
1669 {
1670     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1671     if (!positionedDescendants)
1672         return;
1673
1674     if (hasColumns())
1675         view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
1676
1677     RenderBox* r;
1678     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1679     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1680         r = *it;
1681
1682         r->setMayNeedPaintInvalidation(true);
1683
1684         SubtreeLayoutScope layoutScope(*r);
1685         // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
1686         // if this is a fixed position element, mark it for layout if it has an abspos ancestor and needs to move with that ancestor, i.e.
1687         // it has static position.
1688         markFixedPositionObjectForLayoutIfNeeded(r, layoutScope);
1689         if (info == LayoutOnlyFixedPositionedObjects) {
1690             r->layoutIfNeeded();
1691             continue;
1692         }
1693
1694         // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
1695         // non-positioned block.  Rather than trying to detect all of these movement cases, we just always lay out positioned
1696         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
1697         // positioned explicitly) this should not incur a performance penalty.
1698         if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
1699             layoutScope.setChildNeedsLayout(r);
1700
1701         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1702         if (relayoutChildren && r->needsPreferredWidthsRecalculation())
1703             r->setPreferredLogicalWidthsDirty(MarkOnlyThis);
1704
1705         if (!r->needsLayout())
1706             r->markForPaginationRelayoutIfNeeded(layoutScope);
1707
1708         // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
1709         // If it's wrong we'll lay out again.
1710         LayoutUnit oldLogicalTop = 0;
1711         bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
1712         if (needsBlockDirectionLocationSetBeforeLayout) {
1713             if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
1714                 r->updateLogicalHeight();
1715             else
1716                 r->updateLogicalWidth();
1717             oldLogicalTop = logicalTopForChild(r);
1718         }
1719
1720         // FIXME: We should be able to do a r->setNeedsPositionedMovementLayout() here instead of a full layout. Need
1721         // to investigate why it does not trigger the correct invalidations in that case. crbug.com/350756
1722         if (info == ForcedLayoutAfterContainingBlockMoved)
1723             r->setNeedsLayout();
1724
1725         r->layoutIfNeeded();
1726
1727         // Lay out again if our estimate was wrong.
1728         if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop)
1729             r->forceChildLayout();
1730     }
1731
1732     if (hasColumns())
1733         view()->layoutState()->setColumnInfo(columnInfo()); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
1734 }
1735
1736 void RenderBlock::markPositionedObjectsForLayout()
1737 {
1738     if (TrackedRendererListHashSet* positionedDescendants = positionedObjects()) {
1739         TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1740         for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it)
1741             (*it)->setChildNeedsLayout();
1742     }
1743 }
1744
1745 void RenderBlock::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutScope)
1746 {
1747     ASSERT(!needsLayout());
1748     if (needsLayout())
1749         return;
1750
1751     if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(*this, logicalTop()) != pageLogicalOffset()))
1752         layoutScope.setChildNeedsLayout(this);
1753 }
1754
1755 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1756 {
1757     BlockPainter(*this).paint(paintInfo, paintOffset);
1758 }
1759
1760 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1761 {
1762     BlockPainter(*this).paintChildren(paintInfo, paintOffset);
1763 }
1764
1765 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1766 {
1767     BlockPainter(*this).paintObject(paintInfo, paintOffset);
1768 }
1769
1770 RenderInline* RenderBlock::inlineElementContinuation() const
1771 {
1772     RenderBoxModelObject* continuation = this->continuation();
1773     return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
1774 }
1775
1776 RenderBlock* RenderBlock::blockElementContinuation() const
1777 {
1778     RenderBoxModelObject* currentContinuation = continuation();
1779     if (!currentContinuation || currentContinuation->isInline())
1780         return 0;
1781     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
1782     if (nextContinuation->isAnonymousBlock())
1783         return nextContinuation->blockElementContinuation();
1784     return nextContinuation;
1785 }
1786
1787 ContinuationOutlineTableMap* continuationOutlineTable()
1788 {
1789     DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
1790     return &table;
1791 }
1792
1793 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
1794 {
1795     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
1796     // way of painting.
1797     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
1798
1799     ContinuationOutlineTableMap* table = continuationOutlineTable();
1800     ListHashSet<RenderInline*>* continuations = table->get(this);
1801     if (!continuations) {
1802         continuations = new ListHashSet<RenderInline*>;
1803         table->set(this, adoptPtr(continuations));
1804     }
1805
1806     continuations->add(flow);
1807 }
1808
1809 bool RenderBlock::shouldPaintSelectionGaps() const
1810 {
1811     return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
1812 }
1813
1814 bool RenderBlock::isSelectionRoot() const
1815 {
1816     if (isPseudoElement())
1817         return false;
1818     ASSERT(node() || isAnonymous());
1819
1820     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
1821     if (isTable())
1822         return false;
1823
1824     if (isBody() || isDocumentElement() || hasOverflowClip()
1825         || isPositioned() || isFloating()
1826         || isTableCell() || isInlineBlockOrInlineTable()
1827         || hasTransformRelatedProperty() || hasReflection() || hasMask() || isWritingModeRoot()
1828         || isRenderFlowThread() || isFlexItemIncludingDeprecated())
1829         return true;
1830
1831     if (view() && view()->selectionStart()) {
1832         Node* startElement = view()->selectionStart()->node();
1833         if (startElement && startElement->rootEditableElement() == node())
1834             return true;
1835     }
1836
1837     return false;
1838 }
1839
1840 GapRects RenderBlock::selectionGapRectsForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer) const
1841 {
1842     ASSERT(!needsLayout());
1843
1844     if (!shouldPaintSelectionGaps())
1845         return GapRects();
1846
1847     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
1848     mapLocalToContainer(paintInvalidationContainer, transformState, ApplyContainerFlip | UseTransforms);
1849     LayoutPoint offsetFromPaintInvalidationContainer = roundedLayoutPoint(transformState.mappedPoint());
1850
1851     if (hasOverflowClip())
1852         offsetFromPaintInvalidationContainer -= scrolledContentOffset();
1853
1854     LayoutUnit lastTop = 0;
1855     LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
1856     LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
1857
1858     return selectionGaps(this, offsetFromPaintInvalidationContainer, IntSize(), lastTop, lastLeft, lastRight);
1859 }
1860
1861 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, TrackedRendererListHashSet* positionedObjects)
1862 {
1863     if (!positionedObjects)
1864         return;
1865
1866     TrackedRendererListHashSet::const_iterator end = positionedObjects->end();
1867     for (TrackedRendererListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
1868         RenderBox* r = *it;
1869         paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
1870     }
1871 }
1872
1873 LayoutUnit RenderBlock::blockDirectionOffset(const LayoutSize& offsetFromBlock) const
1874 {
1875     return isHorizontalWritingMode() ? offsetFromBlock.height() : offsetFromBlock.width();
1876 }
1877
1878 LayoutUnit RenderBlock::inlineDirectionOffset(const LayoutSize& offsetFromBlock) const
1879 {
1880     return isHorizontalWritingMode() ? offsetFromBlock.width() : offsetFromBlock.height();
1881 }
1882
1883 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect) const
1884 {
1885     LayoutRect result;
1886     if (isHorizontalWritingMode())
1887         result = logicalRect;
1888     else
1889         result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
1890     flipForWritingMode(result);
1891     result.moveBy(rootBlockPhysicalPosition);
1892     return result;
1893 }
1894
1895 GapRects RenderBlock::selectionGaps(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
1896                                     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo) const
1897 {
1898     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
1899     // Clip out floating and positioned objects when painting selection gaps.
1900     if (paintInfo) {
1901         // Note that we don't clip out overflow for positioned objects.  We just stick to the border box.
1902         LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
1903         rootBlock->flipForWritingMode(flippedBlockRect);
1904         flippedBlockRect.moveBy(rootBlockPhysicalPosition);
1905         clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), positionedObjects());
1906         if (isBody() || isDocumentElement()) // The <body> must make sure to examine its containingBlock's positioned objects.
1907             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
1908                 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
1909         clipOutFloatingObjects(rootBlock, paintInfo, rootBlockPhysicalPosition, offsetFromRootBlock);
1910     }
1911
1912     // 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
1913     // fixed).
1914     GapRects result;
1915     if (!isRenderBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
1916         return result;
1917
1918     if (hasColumns() || hasTransformRelatedProperty() || style()->columnSpan()) {
1919         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
1920         lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
1921         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
1922         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
1923         return result;
1924     }
1925
1926     if (childrenInline())
1927         result = toRenderBlockFlow(this)->inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
1928     else
1929         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
1930
1931     // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
1932     if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
1933         result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
1934                                              logicalHeight(), paintInfo));
1935     return result;
1936 }
1937
1938 GapRects RenderBlock::blockSelectionGaps(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
1939                                          LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo) const
1940 {
1941     GapRects result;
1942
1943     // Go ahead and jump right to the first block child that contains some selected objects.
1944     RenderBox* curr;
1945     for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
1946
1947     for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
1948         SelectionState childState = curr->selectionState();
1949         if (childState == SelectionBoth || childState == SelectionEnd)
1950             sawSelectionEnd = true;
1951
1952         if (curr->isFloatingOrOutOfFlowPositioned())
1953             continue; // We must be a normal flow object in order to even be considered.
1954
1955         if (curr->isRelPositioned() && curr->hasLayer()) {
1956             // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
1957             // Just disregard it completely.
1958             LayoutSize relOffset = curr->layer()->offsetForInFlowPosition();
1959             if (relOffset.width() || relOffset.height())
1960                 continue;
1961         }
1962
1963         bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
1964         bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
1965         if (fillBlockGaps) {
1966             // We need to fill the vertical gap above this object.
1967             if (childState == SelectionEnd || childState == SelectionInside)
1968                 // Fill the gap above the object.
1969                 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
1970                                                      curr->logicalTop(), paintInfo));
1971
1972             // 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*
1973             // our object.  We know this if the selection did not end inside our object.
1974             if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
1975                 childState = SelectionNone;
1976
1977             // Fill side gaps on this object based off its state.
1978             bool leftGap, rightGap;
1979             getSelectionGapInfo(childState, leftGap, rightGap);
1980
1981             if (leftGap)
1982                 result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
1983             if (rightGap)
1984                 result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
1985
1986             // Update lastLogicalTop to be just underneath the object.  lastLogicalLeft and lastLogicalRight extend as far as
1987             // they can without bumping into floating or positioned objects.  Ideally they will go right up
1988             // to the border of the root selection block.
1989             lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + curr->logicalBottom();
1990             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
1991             lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
1992         } else if (childState != SelectionNone)
1993             // We must be a block that has some selected object inside it.  Go ahead and recur.
1994             result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()),
1995                                                             lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo));
1996     }
1997     return result;
1998 }
1999
2000 IntRect alignSelectionRectToDevicePixels(LayoutRect& rect)
2001 {
2002     LayoutUnit roundedX = rect.x().round();
2003     return IntRect(roundedX, rect.y().round(),
2004         (rect.maxX() - roundedX).round(),
2005         snapSizeToPixel(rect.height(), rect.y()));
2006 }
2007
2008 LayoutRect RenderBlock::blockSelectionGap(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2009                                           LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo) const
2010 {
2011     LayoutUnit logicalTop = lastLogicalTop;
2012     LayoutUnit logicalHeight = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalBottom - logicalTop;
2013     if (logicalHeight <= 0)
2014         return LayoutRect();
2015
2016     // Get the selection offsets for the bottom of the gap
2017     LayoutUnit logicalLeft = std::max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
2018     LayoutUnit logicalRight = std::min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
2019     LayoutUnit logicalWidth = logicalRight - logicalLeft;
2020     if (logicalWidth <= 0)
2021         return LayoutRect();
2022
2023     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
2024     if (paintInfo) {
2025         IntRect selectionGapRect = alignSelectionRectToDevicePixels(gapRect);
2026         DrawingRecorder recorder(paintInfo->context, this, paintInfo->phase, selectionGapRect);
2027         paintInfo->context->fillRect(selectionGapRect, selectionBackgroundColor());
2028     }
2029     return gapRect;
2030 }
2031
2032 LayoutRect RenderBlock::logicalLeftSelectionGap(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2033                                                 const RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo) const
2034 {
2035     LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
2036     LayoutUnit rootBlockLogicalLeft = std::max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
2037     LayoutUnit rootBlockLogicalRight = std::min(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + logicalLeft, std::min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
2038     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2039     if (rootBlockLogicalWidth <= 0)
2040         return LayoutRect();
2041
2042     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2043     if (paintInfo) {
2044         IntRect selectionGapRect = alignSelectionRectToDevicePixels(gapRect);
2045         DrawingRecorder recorder(paintInfo->context, this, paintInfo->phase, selectionGapRect);
2046         paintInfo->context->fillRect(selectionGapRect, selObj->selectionBackgroundColor());
2047     }
2048     return gapRect;
2049 }
2050
2051 LayoutRect RenderBlock::logicalRightSelectionGap(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2052                                                  const RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo) const
2053 {
2054     LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
2055     LayoutUnit rootBlockLogicalLeft = std::max(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + logicalRight, max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
2056     LayoutUnit rootBlockLogicalRight = std::min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
2057     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2058     if (rootBlockLogicalWidth <= 0)
2059         return LayoutRect();
2060
2061     LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2062     if (paintInfo) {
2063         IntRect selectionGapRect = alignSelectionRectToDevicePixels(gapRect);
2064         DrawingRecorder recorder(paintInfo->context, this, paintInfo->phase, selectionGapRect);
2065         paintInfo->context->fillRect(selectionGapRect, selObj->selectionBackgroundColor());
2066     }
2067     return gapRect;
2068 }
2069
2070 void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap) const
2071 {
2072     bool ltr = style()->isLeftToRightDirection();
2073     leftGap = (state == RenderObject::SelectionInside) ||
2074               (state == RenderObject::SelectionEnd && ltr) ||
2075               (state == RenderObject::SelectionStart && !ltr);
2076     rightGap = (state == RenderObject::SelectionInside) ||
2077                (state == RenderObject::SelectionStart && ltr) ||
2078                (state == RenderObject::SelectionEnd && !ltr);
2079 }
2080
2081 LayoutUnit RenderBlock::logicalLeftSelectionOffset(const RenderBlock* rootBlock, LayoutUnit position) const
2082 {
2083     // The border can potentially be further extended by our containingBlock().
2084     if (rootBlock != this)
2085         return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
2086     return logicalLeftOffsetForContent();
2087 }
2088
2089 LayoutUnit RenderBlock::logicalRightSelectionOffset(const RenderBlock* rootBlock, LayoutUnit position) const
2090 {
2091     // The border can potentially be further extended by our containingBlock().
2092     if (rootBlock != this)
2093         return containingBlock()->logicalRightSelectionOffset(rootBlock, position + logicalTop());
2094     return logicalRightOffsetForContent();
2095 }
2096
2097 RenderBlock* RenderBlock::blockBeforeWithinSelectionRoot(LayoutSize& offset) const
2098 {
2099     if (isSelectionRoot())
2100         return 0;
2101
2102     const RenderObject* object = this;
2103     RenderObject* sibling;
2104     do {
2105         sibling = object->previousSibling();
2106         while (sibling && (!sibling->isRenderBlock() || toRenderBlock(sibling)->isSelectionRoot()))
2107             sibling = sibling->previousSibling();
2108
2109         offset -= LayoutSize(toRenderBlock(object)->logicalLeft(), toRenderBlock(object)->logicalTop());
2110         object = object->parent();
2111     } while (!sibling && object && object->isRenderBlock() && !toRenderBlock(object)->isSelectionRoot());
2112
2113     if (!sibling)
2114         return 0;
2115
2116     RenderBlock* beforeBlock = toRenderBlock(sibling);
2117
2118     offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
2119
2120     RenderObject* child = beforeBlock->lastChild();
2121     while (child && child->isRenderBlock()) {
2122         beforeBlock = toRenderBlock(child);
2123         offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
2124         child = beforeBlock->lastChild();
2125     }
2126     return beforeBlock;
2127 }
2128
2129 void RenderBlock::setSelectionState(SelectionState state)
2130 {
2131     RenderBox::setSelectionState(state);
2132
2133     if (inlineBoxWrapper() && canUpdateSelectionOnRootLineBoxes())
2134         inlineBoxWrapper()->root().setHasSelectedChildren(state != SelectionNone);
2135 }
2136
2137 void RenderBlock::insertIntoTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
2138 {
2139     if (!descendantsMap) {
2140         descendantsMap = new TrackedDescendantsMap;
2141         containerMap = new TrackedContainerMap;
2142     }
2143
2144     TrackedRendererListHashSet* descendantSet = descendantsMap->get(this);
2145     if (!descendantSet) {
2146         descendantSet = new TrackedRendererListHashSet;
2147         descendantsMap->set(this, adoptPtr(descendantSet));
2148     }
2149     bool added = descendantSet->add(descendant).isNewEntry;
2150     if (!added) {
2151         ASSERT(containerMap->get(descendant));
2152         ASSERT(containerMap->get(descendant)->contains(this));
2153         return;
2154     }
2155
2156     HashSet<RenderBlock*>* containerSet = containerMap->get(descendant);
2157     if (!containerSet) {
2158         containerSet = new HashSet<RenderBlock*>;
2159         containerMap->set(descendant, adoptPtr(containerSet));
2160     }
2161     ASSERT(!containerSet->contains(this));
2162     containerSet->add(this);
2163 }
2164
2165 void RenderBlock::removeFromTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
2166 {
2167     if (!descendantsMap)
2168         return;
2169
2170     OwnPtr<HashSet<RenderBlock*> > containerSet = containerMap->take(descendant);
2171     if (!containerSet)
2172         return;
2173
2174     HashSet<RenderBlock*>::iterator end = containerSet->end();
2175     for (HashSet<RenderBlock*>::iterator it = containerSet->begin(); it != end; ++it) {
2176         RenderBlock* container = *it;
2177
2178         // FIXME: Disabling this assert temporarily until we fix the layout
2179         // bugs associated with positioned objects not properly cleared from
2180         // their ancestor chain before being moved. See webkit bug 93766.
2181         // ASSERT(descendant->isDescendantOf(container));
2182
2183         TrackedDescendantsMap::iterator descendantsMapIterator = descendantsMap->find(container);
2184         ASSERT(descendantsMapIterator != descendantsMap->end());
2185         if (descendantsMapIterator == descendantsMap->end())
2186             continue;
2187         TrackedRendererListHashSet* descendantSet = descendantsMapIterator->value.get();
2188         ASSERT(descendantSet->contains(descendant));
2189         descendantSet->remove(descendant);
2190         if (descendantSet->isEmpty())
2191             descendantsMap->remove(descendantsMapIterator);
2192     }
2193 }
2194
2195 TrackedRendererListHashSet* RenderBlock::positionedObjects() const
2196 {
2197     if (gPositionedDescendantsMap)
2198         return gPositionedDescendantsMap->get(this);
2199     return 0;
2200 }
2201
2202 void RenderBlock::insertPositionedObject(RenderBox* o)
2203 {
2204     ASSERT(!isAnonymousBlock());
2205
2206     if (o->isRenderFlowThread())
2207         return;
2208
2209     insertIntoTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
2210 }
2211
2212 void RenderBlock::removePositionedObject(RenderBox* o)
2213 {
2214     removeFromTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
2215 }
2216
2217 void RenderBlock::removePositionedObjects(RenderBlock* o, ContainingBlockState containingBlockState)
2218 {
2219     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2220     if (!positionedDescendants)
2221         return;
2222
2223     RenderBox* r;
2224
2225     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2226
2227     Vector<RenderBox*, 16> deadObjects;
2228
2229     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2230         r = *it;
2231         if (!o || r->isDescendantOf(o)) {
2232             if (containingBlockState == NewContainingBlock) {
2233                 r->setChildNeedsLayout(MarkOnlyThis);
2234                 if (r->needsPreferredWidthsRecalculation())
2235                     r->setPreferredLogicalWidthsDirty(MarkOnlyThis);
2236             }
2237
2238             // It is parent blocks job to add positioned child to positioned objects list of its containing block
2239             // Parent layout needs to be invalidated to ensure this happens.
2240             RenderObject* p = r->parent();
2241             while (p && !p->isRenderBlock())
2242                 p = p->parent();
2243             if (p)
2244                 p->setChildNeedsLayout();
2245
2246             deadObjects.append(r);
2247         }
2248     }
2249
2250     for (unsigned i = 0; i < deadObjects.size(); i++)
2251         removePositionedObject(deadObjects.at(i));
2252 }
2253
2254 void RenderBlock::addPercentHeightDescendant(RenderBox* descendant)
2255 {
2256     insertIntoTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
2257 }
2258
2259 void RenderBlock::removePercentHeightDescendant(RenderBox* descendant)
2260 {
2261     removeFromTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
2262 }
2263
2264 TrackedRendererListHashSet* RenderBlock::percentHeightDescendants() const
2265 {
2266     return gPercentHeightDescendantsMap ? gPercentHeightDescendantsMap->get(this) : 0;
2267 }
2268
2269 bool RenderBlock::hasPercentHeightContainerMap()
2270 {
2271     return gPercentHeightContainerMap;
2272 }
2273
2274 bool RenderBlock::hasPercentHeightDescendant(RenderBox* descendant)
2275 {
2276     // We don't null check gPercentHeightContainerMap since the caller
2277     // already ensures this and we need to call this function on every
2278     // descendant in clearPercentHeightDescendantsFrom().
2279     ASSERT(gPercentHeightContainerMap);
2280     return gPercentHeightContainerMap->contains(descendant);
2281 }
2282
2283 void RenderBlock::dirtyForLayoutFromPercentageHeightDescendants(SubtreeLayoutScope& layoutScope)
2284 {
2285     if (!gPercentHeightDescendantsMap)
2286         return;
2287
2288     TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this);
2289     if (!descendants)
2290         return;
2291
2292     TrackedRendererListHashSet::iterator end = descendants->end();
2293     for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
2294         RenderBox* box = *it;
2295         while (box != this) {
2296             if (box->normalChildNeedsLayout())
2297                 break;
2298             layoutScope.setChildNeedsLayout(box);
2299             box = box->containingBlock();
2300             ASSERT(box);
2301             if (!box)
2302                 break;
2303         }
2304     }
2305 }
2306
2307 void RenderBlock::removePercentHeightDescendantIfNeeded(RenderBox* descendant)
2308 {
2309     // We query the map directly, rather than looking at style's
2310     // logicalHeight()/logicalMinHeight()/logicalMaxHeight() since those
2311     // can change with writing mode/directional changes.
2312     if (!hasPercentHeightContainerMap())
2313         return;
2314
2315     if (!hasPercentHeightDescendant(descendant))
2316         return;
2317
2318     removePercentHeightDescendant(descendant);
2319 }
2320
2321 void RenderBlock::clearPercentHeightDescendantsFrom(RenderBox* parent)
2322 {
2323     ASSERT(gPercentHeightContainerMap);
2324     for (RenderObject* curr = parent->slowFirstChild(); curr; curr = curr->nextInPreOrder(parent)) {
2325         if (!curr->isBox())
2326             continue;
2327
2328         RenderBox* box = toRenderBox(curr);
2329         if (!hasPercentHeightDescendant(box))
2330             continue;
2331
2332         removePercentHeightDescendant(box);
2333     }
2334 }
2335
2336 LayoutUnit RenderBlock::textIndentOffset() const
2337 {
2338     LayoutUnit cw = 0;
2339     if (style()->textIndent().isPercent())
2340         cw = containingBlock()->availableLogicalWidth();
2341     return minimumValueForLength(style()->textIndent(), cw);
2342 }
2343
2344 void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
2345 {
2346     if (logicalTop >= logicalBottom)
2347         return;
2348
2349     RootInlineBox* lowestDirtyLine = lastRootBox();
2350     RootInlineBox* afterLowest = lowestDirtyLine;
2351     while (lowestDirtyLine && lowestDirtyLine->lineBottomWithLeading() >= logicalBottom && logicalBottom < LayoutUnit::max()) {
2352         afterLowest = lowestDirtyLine;
2353         lowestDirtyLine = lowestDirtyLine->prevRootBox();
2354     }
2355
2356     while (afterLowest && afterLowest != highest && (afterLowest->lineBottomWithLeading() >= logicalTop || afterLowest->lineBottomWithLeading() < 0)) {
2357         afterLowest->markDirty();
2358         afterLowest = afterLowest->prevRootBox();
2359     }
2360 }
2361
2362 bool RenderBlock::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset)
2363 {
2364     if (!scrollsOverflow())
2365         return false;
2366
2367     return layer()->scrollableArea()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
2368 }
2369
2370 Node* RenderBlock::nodeForHitTest() const
2371 {
2372     // If we are in the margins of block elements that are part of a
2373     // continuation we're actually still inside the enclosing element
2374     // that was split. Use the appropriate inner node.
2375     return isAnonymousBlockContinuation() ? continuation()->node() : node();
2376 }
2377
2378 bool RenderBlock::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2379 {
2380     LayoutPoint adjustedLocation(accumulatedOffset + location());
2381     LayoutSize localOffset = toLayoutSize(adjustedLocation);
2382
2383     if (!isRenderView()) {
2384         // Check if we need to do anything at all.
2385         // If we have clipping, then we can't have any spillout.
2386         LayoutRect overflowBox = hasOverflowClip() ? borderBoxRect() : visualOverflowRect();
2387         flipForWritingMode(overflowBox);
2388         overflowBox.moveBy(adjustedLocation);
2389         if (!locationInContainer.intersects(overflowBox))
2390             return false;
2391     }
2392
2393     if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground)
2394         && visibleToHitTestRequest(request)
2395         && isPointInOverflowControl(result, locationInContainer.point(), adjustedLocation)) {
2396         updateHitTestResult(result, locationInContainer.point() - localOffset);
2397         // FIXME: isPointInOverflowControl() doesn't handle rect-based tests yet.
2398         if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer))
2399            return true;
2400     }
2401
2402     if (style()->clipPath()) {
2403         switch (style()->clipPath()->type()) {
2404         case ClipPathOperation::SHAPE: {
2405             ShapeClipPathOperation* clipPath = toShapeClipPathOperation(style()->clipPath());
2406             // FIXME: handle marginBox etc.
2407             if (!clipPath->path(borderBoxRect()).contains(locationInContainer.point() - localOffset, clipPath->windRule()))
2408                 return false;
2409             break;
2410         }
2411         case ClipPathOperation::REFERENCE:
2412             // FIXME: handle REFERENCE
2413             break;
2414         }
2415     }
2416
2417     // If we have clipping, then we can't have any spillout.
2418     bool useOverflowClip = hasOverflowClip() && !hasSelfPaintingLayer();
2419     bool useClip = (hasControlClip() || useOverflowClip);
2420     bool checkChildren = !useClip;
2421     if (!checkChildren) {
2422         if (hasControlClip()) {
2423             checkChildren = locationInContainer.intersects(controlClipRect(adjustedLocation));
2424         } else {
2425             LayoutRect clipRect = overflowClipRect(adjustedLocation, IncludeOverlayScrollbarSize);
2426             if (style()->hasBorderRadius())
2427                 checkChildren = locationInContainer.intersects(style()->getRoundedBorderFor(clipRect));
2428             else
2429                 checkChildren = locationInContainer.intersects(clipRect);
2430         }
2431     }
2432     if (checkChildren) {
2433         // Hit test descendants first.
2434         LayoutSize scrolledOffset(localOffset);
2435         if (hasOverflowClip())
2436             scrolledOffset -= scrolledContentOffset();
2437
2438         // Hit test contents if we don't have columns.
2439         if (!hasColumns()) {
2440             if (hitTestContents(request, result, locationInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
2441                 updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2442                 return true;
2443             }
2444             if (hitTestAction == HitTestFloat && hitTestFloats(request, result, locationInContainer, toLayoutPoint(scrolledOffset)))
2445                 return true;
2446         } else if (hitTestColumns(request, result, locationInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
2447             updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2448             return true;
2449         }
2450     }
2451
2452     // Check if the point is outside radii.
2453     if (style()->hasBorderRadius()) {
2454         LayoutRect borderRect = borderBoxRect();
2455         borderRect.moveBy(adjustedLocation);
2456         RoundedRect border = style()->getRoundedBorderFor(borderRect);
2457         if (!locationInContainer.intersects(border))
2458             return false;
2459     }
2460
2461     // Now hit test our background
2462     if (hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) {
2463         LayoutRect boundsRect(adjustedLocation, size());
2464         if (visibleToHitTestRequest(request) && locationInContainer.intersects(boundsRect)) {
2465             updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2466             if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer, boundsRect))
2467                 return true;
2468         }
2469     }
2470
2471     return false;
2472 }
2473
2474 class ColumnRectIterator {
2475     WTF_MAKE_NONCOPYABLE(ColumnRectIterator);
2476 public:
2477     ColumnRectIterator(const RenderBlock& block)
2478         : m_block(block)
2479         , m_colInfo(block.columnInfo())
2480         , m_direction(m_block.style()->slowIsFlippedBlocksWritingMode() ? 1 : -1)
2481         , m_isHorizontal(block.isHorizontalWritingMode())
2482         , m_logicalLeft(block.logicalLeftOffsetForContent())
2483     {
2484         int colCount = m_colInfo->columnCount();
2485         m_colIndex = colCount - 1;
2486         m_currLogicalTopOffset = colCount * m_colInfo->columnHeight() * m_direction;
2487         update();
2488     }
2489
2490     void advance()
2491     {
2492         ASSERT(hasMore());
2493         m_colIndex--;
2494         update();
2495     }
2496
2497     LayoutRect columnRect() const { return m_colRect; }
2498     bool hasMore() const { return m_colIndex >= 0; }
2499
2500     void adjust(LayoutSize& offset) const
2501     {
2502         LayoutUnit currLogicalLeftOffset = (m_isHorizontal ? m_colRect.x() : m_colRect.y()) - m_logicalLeft;
2503         offset += m_isHorizontal ? LayoutSize(currLogicalLeftOffset, m_currLogicalTopOffset) : LayoutSize(m_currLogicalTopOffset, currLogicalLeftOffset);
2504         if (m_colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
2505             if (m_isHorizontal)
2506                 offset.expand(0, m_colRect.y() - m_block.borderTop() - m_block.paddingTop());
2507             else
2508                 offset.expand(m_colRect.x() - m_block.borderLeft() - m_block.paddingLeft(), 0);
2509         }
2510     }
2511
2512 private:
2513     void update()
2514     {
2515         if (m_colIndex < 0)
2516             return;
2517
2518         m_colRect = m_block.columnRectAt(const_cast<ColumnInfo*>(m_colInfo), m_colIndex);
2519         m_block.flipForWritingMode(m_colRect);
2520         m_currLogicalTopOffset -= (m_isHorizontal ? m_colRect.height() : m_colRect.width()) * m_direction;
2521     }
2522
2523     const RenderBlock& m_block;
2524     const ColumnInfo* const m_colInfo;
2525     const int m_direction;
2526     const bool m_isHorizontal;
2527     const LayoutUnit m_logicalLeft;
2528     int m_colIndex;
2529     LayoutUnit m_currLogicalTopOffset;
2530     LayoutRect m_colRect;
2531 };
2532
2533 bool RenderBlock::hitTestColumns(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2534 {
2535     // We need to do multiple passes, breaking up our hit testing into strips.
2536     if (!hasColumns())
2537         return false;
2538
2539     for (ColumnRectIterator it(*this); it.hasMore(); it.advance()) {
2540         LayoutRect hitRect = locationInContainer.boundingBox();
2541         LayoutRect colRect = it.columnRect();
2542         colRect.moveBy(accumulatedOffset);
2543         if (locationInContainer.intersects(colRect)) {
2544             // The point is inside this column.
2545             // Adjust accumulatedOffset to change where we hit test.
2546             LayoutSize offset;
2547             it.adjust(offset);
2548             LayoutPoint finalLocation = accumulatedOffset + offset;
2549             if (!result.isRectBasedTest() || colRect.contains(hitRect))
2550                 return hitTestContents(request, result, locationInContainer, finalLocation, hitTestAction) || (hitTestAction == HitTestFloat && hitTestFloats(request, result, locationInContainer, finalLocation));
2551
2552             hitTestContents(request, result, locationInContainer, finalLocation, hitTestAction);
2553         }
2554     }
2555
2556     return false;
2557 }
2558
2559 void RenderBlock::adjustForColumnRect(LayoutSize& offset, const LayoutPoint& locationInContainer) const
2560 {
2561     for (ColumnRectIterator it(*this); it.hasMore(); it.advance()) {
2562         LayoutRect colRect = it.columnRect();
2563         if (colRect.contains(locationInContainer)) {
2564             it.adjust(offset);
2565             return;
2566         }
2567     }
2568 }
2569
2570 bool RenderBlock::hitTestContents(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2571 {
2572     if (childrenInline() && !isTable()) {
2573         // We have to hit-test our line boxes.
2574         if (m_lineBoxes.hitTest(this, request, result, locationInContainer, accumulatedOffset, hitTestAction))
2575             return true;
2576     } else {
2577         // Hit test our children.
2578         HitTestAction childHitTest = hitTestAction;
2579         if (hitTestAction == HitTestChildBlockBackgrounds)
2580             childHitTest = HitTestChildBlockBackground;
2581         for (RenderBox* child = lastChildBox(); child; child = child->previousSiblingBox()) {
2582             LayoutPoint childPoint = flipForWritingModeForChild(child, accumulatedOffset);
2583             if (!child->hasSelfPaintingLayer() && !child->isFloating() && child->nodeAtPoint(request, result, locationInContainer, childPoint, childHitTest))
2584                 return true;
2585         }
2586     }
2587
2588     return false;
2589 }
2590
2591 Position RenderBlock::positionForBox(InlineBox *box, bool start) const
2592 {
2593     if (!box)
2594         return Position();
2595
2596     if (!box->renderer().nonPseudoNode())
2597         return createLegacyEditingPosition(nonPseudoNode(), start ? caretMinOffset() : caretMaxOffset());
2598
2599     if (!box->isInlineTextBox())
2600         return createLegacyEditingPosition(box->renderer().nonPseudoNode(), start ? box->renderer().caretMinOffset() : box->renderer().caretMaxOffset());
2601
2602     InlineTextBox* textBox = toInlineTextBox(box);
2603     return createLegacyEditingPosition(box->renderer().nonPseudoNode(), start ? textBox->start() : textBox->start() + textBox->len());
2604 }
2605
2606 static inline bool isEditingBoundary(RenderObject* ancestor, RenderObject* child)
2607 {
2608     ASSERT(!ancestor || ancestor->nonPseudoNode());
2609     ASSERT(child && child->nonPseudoNode());
2610     return !ancestor || !ancestor->parent() || (ancestor->hasLayer() && ancestor->parent()->isRenderView())
2611         || ancestor->nonPseudoNode()->hasEditableStyle() == child->nonPseudoNode()->hasEditableStyle();
2612 }
2613
2614 // FIXME: This function should go on RenderObject as an instance method. Then
2615 // all cases in which positionForPoint recurs could call this instead to
2616 // prevent crossing editable boundaries. This would require many tests.
2617 static PositionWithAffinity positionForPointRespectingEditingBoundaries(RenderBlock* parent, RenderBox* child, const LayoutPoint& pointInParentCoordinates)
2618 {
2619     LayoutPoint childLocation = child->location();
2620     if (child->isRelPositioned())
2621         childLocation += child->offsetForInFlowPosition();
2622
2623     // FIXME: This is wrong if the child's writing-mode is different from the parent's.
2624     LayoutPoint pointInChildCoordinates(toLayoutPoint(pointInParentCoordinates - childLocation));
2625
2626     // If this is an anonymous renderer, we just recur normally
2627     Node* childNode = child->nonPseudoNode();
2628     if (!childNode)
2629         return child->positionForPoint(pointInChildCoordinates);
2630
2631     // Otherwise, first make sure that the editability of the parent and child agree.
2632     // If they don't agree, then we return a visible position just before or after the child
2633     RenderObject* ancestor = parent;
2634     while (ancestor && !ancestor->nonPseudoNode())
2635         ancestor = ancestor->parent();
2636
2637     // If we can't find an ancestor to check editability on, or editability is unchanged, we recur like normal
2638     if (isEditingBoundary(ancestor, child))
2639         return child->positionForPoint(pointInChildCoordinates);
2640
2641     // Otherwise return before or after the child, depending on if the click was to the logical left or logical right of the child
2642     LayoutUnit childMiddle = parent->logicalWidthForChild(child) / 2;
2643     LayoutUnit logicalLeft = parent->isHorizontalWritingMode() ? pointInChildCoordinates.x() : pointInChildCoordinates.y();
2644     if (logicalLeft < childMiddle)
2645         return ancestor->createPositionWithAffinity(childNode->nodeIndex(), DOWNSTREAM);
2646     return ancestor->createPositionWithAffinity(childNode->nodeIndex() + 1, UPSTREAM);
2647 }
2648
2649 PositionWithAffinity RenderBlock::positionForPointWithInlineChildren(const LayoutPoint& pointInLogicalContents)
2650 {
2651     ASSERT(childrenInline());
2652
2653     if (!firstRootBox())
2654         return createPositionWithAffinity(0, DOWNSTREAM);
2655
2656     bool linesAreFlipped = style()->isFlippedLinesWritingMode();
2657     bool blocksAreFlipped = style()->slowIsFlippedBlocksWritingMode();
2658
2659     // look for the closest line box in the root box which is at the passed-in y coordinate
2660     InlineBox* closestBox = 0;
2661     RootInlineBox* firstRootBoxWithChildren = 0;
2662     RootInlineBox* lastRootBoxWithChildren = 0;
2663     for (RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox()) {
2664         if (!root->firstLeafChild())
2665             continue;
2666         if (!firstRootBoxWithChildren)
2667             firstRootBoxWithChildren = root;
2668
2669         if (!linesAreFlipped && root->isFirstAfterPageBreak() && (pointInLogicalContents.y() < root->lineTopWithLeading()
2670             || (blocksAreFlipped && pointInLogicalContents.y() == root->lineTopWithLeading())))
2671             break;
2672
2673         lastRootBoxWithChildren = root;
2674
2675         // check if this root line box is located at this y coordinate
2676         if (pointInLogicalContents.y() < root->selectionBottom() || (blocksAreFlipped && pointInLogicalContents.y() == root->selectionBottom())) {
2677             if (linesAreFlipped) {
2678                 RootInlineBox* nextRootBoxWithChildren = root->nextRootBox();
2679                 while (nextRootBoxWithChildren && !nextRootBoxWithChildren->firstLeafChild())
2680                     nextRootBoxWithChildren = nextRootBoxWithChildren->nextRootBox();
2681
2682                 if (nextRootBoxWithChildren && nextRootBoxWithChildren->isFirstAfterPageBreak() && (pointInLogicalContents.y() > nextRootBoxWithChildren->lineTopWithLeading()
2683                     || (!blocksAreFlipped && pointInLogicalContents.y() == nextRootBoxWithChildren->lineTopWithLeading())))
2684                     continue;
2685             }
2686             closestBox = root->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
2687             if (closestBox)
2688                 break;
2689         }
2690     }
2691
2692     bool moveCaretToBoundary = document().frame()->editor().behavior().shouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom();
2693
2694     if (!moveCaretToBoundary && !closestBox && lastRootBoxWithChildren) {
2695         // y coordinate is below last root line box, pretend we hit it
2696         closestBox = lastRootBoxWithChildren->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
2697     }
2698
2699     if (closestBox) {
2700         if (moveCaretToBoundary) {
2701             LayoutUnit firstRootBoxWithChildrenTop = std::min<LayoutUnit>(firstRootBoxWithChildren->selectionTop(), firstRootBoxWithChildren->logicalTop());
2702             if (pointInLogicalContents.y() < firstRootBoxWithChildrenTop
2703                 || (blocksAreFlipped && pointInLogicalContents.y() == firstRootBoxWithChildrenTop)) {
2704                 InlineBox* box = firstRootBoxWithChildren->firstLeafChild();
2705                 if (box->isLineBreak()) {
2706                     if (InlineBox* newBox = box->nextLeafChildIgnoringLineBreak())
2707                         box = newBox;
2708                 }
2709                 // y coordinate is above first root line box, so return the start of the first
2710                 return PositionWithAffinity(positionForBox(box, true), DOWNSTREAM);
2711             }
2712         }
2713
2714         // pass the box a top position that is inside it
2715         LayoutPoint point(pointInLogicalContents.x(), closestBox->root().blockDirectionPointInLine());
2716         if (!isHorizontalWritingMode())
2717             point = point.transposedPoint();
2718         if (closestBox->renderer().isReplaced())
2719             return positionForPointRespectingEditingBoundaries(this, &toRenderBox(closestBox->renderer()), point);
2720         return closestBox->renderer().positionForPoint(point);
2721     }
2722
2723     if (lastRootBoxWithChildren) {
2724         // We hit this case for Mac behavior when the Y coordinate is below the last box.
2725         ASSERT(moveCaretToBoundary);
2726         InlineBox* logicallyLastBox;
2727         if (lastRootBoxWithChildren->getLogicalEndBoxWithNode(logicallyLastBox))
2728             return PositionWithAffinity(positionForBox(logicallyLastBox, false), DOWNSTREAM);
2729     }
2730
2731     // Can't reach this. We have a root line box, but it has no kids.
2732     // FIXME: This should ASSERT_NOT_REACHED(), but clicking on placeholder text
2733     // seems to hit this code path.
2734     return createPositionWithAffinity(0, DOWNSTREAM);
2735 }
2736
2737 static inline bool isChildHitTestCandidate(RenderBox* box)
2738 {
2739     return box->height() && box->style()->visibility() == VISIBLE && !box->isFloatingOrOutOfFlowPositioned();
2740 }
2741
2742 PositionWithAffinity RenderBlock::positionForPoint(const LayoutPoint& point)
2743 {
2744     if (isTable())
2745         return RenderBox::positionForPoint(point);
2746
2747     if (isReplaced()) {
2748         // FIXME: This seems wrong when the object's writing-mode doesn't match the line's writing-mode.
2749         LayoutUnit pointLogicalLeft = isHorizontalWritingMode() ? point.x() : point.y();
2750         LayoutUnit pointLogicalTop = isHorizontalWritingMode() ? point.y() : point.x();
2751
2752         if (pointLogicalLeft < 0)
2753             return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
2754         if (pointLogicalLeft >= logicalWidth())
2755             return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
2756         if (pointLogicalTop < 0)
2757             return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
2758         if (pointLogicalTop >= logicalHeight())
2759             return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
2760     }
2761
2762     LayoutPoint pointInContents = point;
2763     offsetForContents(pointInContents);
2764     LayoutPoint pointInLogicalContents(pointInContents);
2765     if (!isHorizontalWritingMode())
2766         pointInLogicalContents = pointInLogicalContents.transposedPoint();
2767
2768     if (childrenInline())
2769         return positionForPointWithInlineChildren(pointInLogicalContents);
2770
2771     RenderBox* lastCandidateBox = lastChildBox();
2772     while (lastCandidateBox && !isChildHitTestCandidate(lastCandidateBox))
2773         lastCandidateBox = lastCandidateBox->previousSiblingBox();
2774
2775     bool blocksAreFlipped = style()->slowIsFlippedBlocksWritingMode();
2776     if (lastCandidateBox) {
2777         if (pointInLogicalContents.y() > logicalTopForChild(lastCandidateBox)
2778             || (!blocksAreFlipped && pointInLogicalContents.y() == logicalTopForChild(lastCandidateBox)))
2779             return positionForPointRespectingEditingBoundaries(this, lastCandidateBox, pointInContents);
2780
2781         for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
2782             if (!isChildHitTestCandidate(childBox))
2783                 continue;
2784             LayoutUnit childLogicalBottom = logicalTopForChild(childBox) + logicalHeightForChild(childBox);
2785             // We hit child if our click is above the bottom of its padding box (like IE6/7 and FF3).
2786             if (isChildHitTestCandidate(childBox) && (pointInLogicalContents.y() < childLogicalBottom
2787                 || (blocksAreFlipped && pointInLogicalContents.y() == childLogicalBottom)))
2788                 return positionForPointRespectingEditingBoundaries(this, childBox, pointInContents);
2789         }
2790     }
2791
2792     // We only get here if there are no hit test candidate children below the click.
2793     return RenderBox::positionForPoint(point);
2794 }
2795
2796 void RenderBlock::offsetForContents(LayoutPoint& offset) const
2797 {
2798     offset = flipForWritingMode(offset);
2799
2800     if (hasOverflowClip())
2801         offset += scrolledContentOffset();
2802
2803     if (hasColumns())
2804         adjustPointToColumnContents(offset);
2805
2806     offset = flipForWritingMode(offset);
2807 }
2808
2809 LayoutUnit RenderBlock::availableLogicalWidth() const
2810 {
2811     // If we have multiple columns, then the available logical width is reduced to our column width.
2812     if (hasColumns())
2813         return desiredColumnWidth();
2814     return RenderBox::availableLogicalWidth();
2815 }
2816
2817 int RenderBlock::columnGap() const
2818 {
2819     if (style()->hasNormalColumnGap())
2820         return style()->fontDescription().computedPixelSize(); // "1em" is recommended as the normal gap setting. Matches <p> margins.
2821     return static_cast<int>(style()->columnGap());
2822 }
2823
2824 void RenderBlock::calcColumnWidth()
2825 {
2826     if (document().regionBasedColumnsEnabled())
2827         return;
2828
2829     // Calculate our column width and column count.
2830     // FIXME: Can overflow on fast/block/float/float-not-removed-from-next-sibling4.html, see https://bugs.webkit.org/show_bug.cgi?id=68744
2831     unsigned desiredColumnCount = 1;
2832     LayoutUnit desiredColumnWidth = contentLogicalWidth();
2833
2834     // For now, we don't support multi-column layouts when printing, since we have to do a lot of work for proper pagination.
2835     if (document().paginated() || !style()->specifiesColumns()) {
2836         setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
2837         return;
2838     }
2839
2840     LayoutUnit availWidth = desiredColumnWidth;
2841     LayoutUnit colGap = columnGap();
2842     LayoutUnit colWidth = std::max<LayoutUnit>(1, LayoutUnit(style()->columnWidth()));
2843     int colCount = std::max<int>(1, style()->columnCount());
2844
2845     if (style()->hasAutoColumnWidth() && !style()->hasAutoColumnCount()) {
2846         desiredColumnCount = colCount;
2847         desiredColumnWidth = std::max<LayoutUnit>(0, (availWidth - ((desiredColumnCount - 1) * colGap)) / desiredColumnCount);
2848     } else if (!style()->hasAutoColumnWidth() && style()->hasAutoColumnCount()) {
2849         desiredColumnCount = std::max<LayoutUnit>(1, (availWidth + colGap) / (colWidth + colGap));
2850         desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
2851     } else {
2852         desiredColumnCount = std::max<LayoutUnit>(std::min<LayoutUnit>(colCount, (availWidth + colGap) / (colWidth + colGap)), 1);
2853         desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
2854     }
2855     setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
2856 }
2857
2858 bool RenderBlock::requiresColumns(int desiredColumnCount) const
2859 {
2860     // Paged overflow is treated as multicol here, unless this element was the one that got its
2861     // overflow propagated to the viewport.
2862     bool isPaginated = style()->isOverflowPaged() && node() != document().viewportDefiningElement();
2863
2864     return firstChild()
2865         && (desiredColumnCount != 1 || !style()->hasAutoColumnWidth() || isPaginated)
2866         && !firstChild()->isAnonymousColumnsBlock()
2867         && !firstChild()->isAnonymousColumnSpanBlock() && !isFlexibleBoxIncludingDeprecated();
2868 }
2869
2870 void RenderBlock::setDesiredColumnCountAndWidth(int count, LayoutUnit width)
2871 {
2872     bool destroyColumns = !requiresColumns(count);
2873     if (destroyColumns) {
2874         if (hasColumns()) {
2875             gColumnInfoMap->take(this);
2876             setHasColumns(false);
2877         }
2878     } else {
2879         ColumnInfo* info;
2880         if (hasColumns())
2881             info = gColumnInfoMap->get(this);
2882         else {
2883             if (!gColumnInfoMap)
2884                 gColumnInfoMap = new ColumnInfoMap;
2885             info = new ColumnInfo;
2886             gColumnInfoMap->add(this, adoptPtr(info));
2887             setHasColumns(true);
2888         }
2889         info->setDesiredColumnWidth(width);
2890         if (style()->isOverflowPaged()) {
2891             info->setDesiredColumnCount(1);
2892             info->setProgressionAxis(style()->hasInlinePaginationAxis() ? ColumnInfo::InlineAxis : ColumnInfo::BlockAxis);
2893         } else {
2894             info->setDesiredColumnCount(count);
2895             info->setProgressionAxis(ColumnInfo::InlineAxis);
2896         }
2897     }
2898 }
2899
2900 LayoutUnit RenderBlock::desiredColumnWidth() const
2901 {
2902     if (!hasColumns())
2903         return contentLogicalWidth();
2904     return gColumnInfoMap->get(this)->desiredColumnWidth();
2905 }
2906
2907 ColumnInfo* RenderBlock::columnInfo() const
2908 {
2909     if (!hasColumns())
2910         return 0;
2911     return gColumnInfoMap->get(this);
2912 }
2913
2914 unsigned RenderBlock::columnCount(ColumnInfo* colInfo) const
2915 {
2916     ASSERT(hasColumns());
2917     ASSERT(gColumnInfoMap->get(this) == colInfo);
2918     return colInfo->columnCount();
2919 }
2920
2921 LayoutRect RenderBlock::columnRectAt(ColumnInfo* colInfo, unsigned index) const
2922 {
2923     ASSERT(hasColumns() && gColumnInfoMap->get(this) == colInfo);
2924
2925     // Compute the appropriate rect based off our information.
2926     LayoutUnit colLogicalWidth = colInfo->desiredColumnWidth();
2927     LayoutUnit colLogicalHeight = colInfo->columnHeight();
2928     LayoutUnit colLogicalTop = borderBefore() + paddingBefore();
2929     LayoutUnit colLogicalLeft = logicalLeftOffsetForContent();
2930     LayoutUnit colGap = columnGap();
2931     if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
2932         if (style()->isLeftToRightDirection())
2933             colLogicalLeft += index * (colLogicalWidth + colGap);
2934         else
2935             colLogicalLeft += contentLogicalWidth() - colLogicalWidth - index * (colLogicalWidth + colGap);
2936     } else {
2937         colLogicalTop += index * (colLogicalHeight + colGap);
2938     }
2939
2940     if (isHorizontalWritingMode())
2941         return LayoutRect(colLogicalLeft, colLogicalTop, colLogicalWidth, colLogicalHeight);
2942     return LayoutRect(colLogicalTop, colLogicalLeft, colLogicalHeight, colLogicalWidth);
2943 }
2944
2945 void RenderBlock::adjustPointToColumnContents(LayoutPoint& point) const
2946 {
2947     // Just bail if we have no columns.
2948     if (!hasColumns())
2949         return;
2950
2951     ColumnInfo* colInfo = columnInfo();
2952     if (!columnCount(colInfo))
2953         return;
2954
2955     // Determine which columns we intersect.
2956     LayoutUnit colGap = columnGap();
2957     LayoutUnit halfColGap = colGap / 2;
2958     LayoutPoint columnPoint(columnRectAt(colInfo, 0).location());
2959     LayoutUnit logicalOffset = 0;
2960     for (unsigned i = 0; i < colInfo->columnCount(); i++) {
2961         // Add in half the column gap to the left and right of the rect.
2962         LayoutRect colRect = columnRectAt(colInfo, i);
2963         flipForWritingMode(colRect);
2964         if (isHorizontalWritingMode() == (colInfo->progressionAxis() == ColumnInfo::InlineAxis)) {
2965             LayoutRect gapAndColumnRect(colRect.x() - halfColGap, colRect.y(), colRect.width() + colGap, colRect.height());
2966             if (point.x() >= gapAndColumnRect.x() && point.x() < gapAndColumnRect.maxX()) {
2967                 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
2968                     // FIXME: The clamping that follows is not completely right for right-to-left
2969                     // content.
2970                     // Clamp everything above the column to its top left.
2971                     if (point.y() < gapAndColumnRect.y())
2972                         point = gapAndColumnRect.location();
2973                     // Clamp everything below the column to the next column's top left. If there is
2974                     // no next column, this still maps to just after this column.
2975                     else if (point.y() >= gapAndColumnRect.maxY()) {
2976                         point = gapAndColumnRect.location();
2977                         point.move(0, gapAndColumnRect.height());
2978                     }
2979                 } else {
2980                     if (point.x() < colRect.x())
2981                         point.setX(colRect.x());
2982                     else if (point.x() >= colRect.maxX())
2983                         point.setX(colRect.maxX() - 1);
2984                 }
2985
2986                 // We're inside the column.  Translate the x and y into our column coordinate space.
2987                 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
2988                     point.move(columnPoint.x() - colRect.x(), (!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset));
2989                 else
2990                     point.move((!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset) - colRect.x() + borderLeft() + paddingLeft(), 0);
2991                 return;
2992             }
2993
2994             // Move to the next position.
2995             logicalOffset += colInfo->progressionAxis() == ColumnInfo::InlineAxis ? colRect.height() : colRect.width();
2996         } else {
2997             LayoutRect gapAndColumnRect(colRect.x(), colRect.y() - halfColGap, colRect.width(), colRect.height() + colGap);
2998             if (point.y() >= gapAndColumnRect.y() && point.y() < gapAndColumnRect.maxY()) {
2999                 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
3000                     // FIXME: The clamping that follows is not completely right for right-to-left
3001                     // content.
3002                     // Clamp everything above the column to its top left.
3003                     if (point.x() < gapAndColumnRect.x())
3004                         point = gapAndColumnRect.location();
3005                     // Clamp everything below the column to the next column's top left. If there is
3006                     // no next column, this still maps to just after this column.
3007                     else if (point.x() >= gapAndColumnRect.maxX()) {
3008                         point = gapAndColumnRect.location();
3009                         point.move(gapAndColumnRect.width(), 0);
3010                     }
3011                 } else {
3012                     if (point.y() < colRect.y())
3013                         point.setY(colRect.y());
3014                     else if (point.y() >= colRect.maxY())
3015                         point.setY(colRect.maxY() - 1);
3016                 }
3017
3018                 // We're inside the column.  Translate the x and y into our column coordinate space.
3019                 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3020                     point.move((!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset), columnPoint.y() - colRect.y());
3021                 else
3022                     point.move(0, (!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset) - colRect.y() + borderTop() + paddingTop());
3023                 return;
3024             }
3025
3026             // Move to the next position.
3027             logicalOffset += colInfo->progressionAxis() == ColumnInfo::InlineAxis ? colRect.width() : colRect.height();
3028         }
3029     }
3030 }
3031
3032 void RenderBlock::adjustRectForColumns(LayoutRect& r) const
3033 {
3034     // Just bail if we have no columns.
3035     if (!hasColumns())
3036         return;
3037
3038     ColumnInfo* colInfo = columnInfo();
3039
3040     // Determine which columns we intersect.
3041     unsigned colCount = columnCount(colInfo);
3042     if (!colCount)
3043         return;
3044
3045     // Begin with a result rect that is empty.
3046     LayoutRect result;
3047
3048     bool isHorizontal = isHorizontalWritingMode();
3049     LayoutUnit beforeBorderPadding = borderBefore() + paddingBefore();
3050     LayoutUnit colHeight = colInfo->columnHeight();
3051     if (!colHeight)
3052         return;
3053
3054     LayoutUnit startOffset = std::max(isHorizontal ? r.y() : r.x(), beforeBorderPadding);
3055     LayoutUnit endOffset = std::max(std::min<LayoutUnit>(isHorizontal ? r.maxY() : r.maxX(), beforeBorderPadding + colCount * colHeight), beforeBorderPadding);
3056
3057     // FIXME: Can overflow on fast/block/float/float-not-removed-from-next-sibling4.html, see https://bugs.webkit.org/show_bug.cgi?id=68744
3058     unsigned startColumn = (startOffset - beforeBorderPadding) / colHeight;
3059     unsigned endColumn = (endOffset - beforeBorderPadding) / colHeight;
3060
3061     if (startColumn == endColumn) {
3062         // The rect is fully contained within one column. Adjust for our offsets
3063         // and issue paint invalidations only that portion.
3064         LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent();
3065         LayoutRect colRect = columnRectAt(colInfo, startColumn);
3066         LayoutRect paintInvalidationRect = r;
3067
3068         if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
3069             if (isHorizontal)
3070                 paintInvalidationRect.move(colRect.x() - logicalLeftOffset, - static_cast<int>(startColumn) * colHeight);
3071             else
3072                 paintInvalidationRect.move(- static_cast<int>(startColumn) * colHeight, colRect.y() - logicalLeftOffset);
3073         } else {
3074             if (isHorizontal)
3075                 paintInvalidationRect.move(0, colRect.y() - startColumn * colHeight - beforeBorderPadding);
3076             else
3077                 paintInvalidationRect.move(colRect.x() - startColumn * colHeight - beforeBorderPadding, 0);
3078         }
3079         paintInvalidationRect.intersect(colRect);
3080         result.unite(paintInvalidationRect);
3081     } else {
3082         // We span multiple columns. We can just unite the start and end column to get the final
3083         // paint invalidation rect.
3084         result.unite(columnRectAt(colInfo, startColumn));
3085         result.unite(columnRectAt(colInfo, endColumn));
3086     }
3087
3088     r = result;
3089 }
3090
3091 LayoutPoint RenderBlock::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
3092 {
3093     ASSERT(hasColumns());
3094     if (!hasColumns() || !style()->slowIsFlippedBlocksWritingMode())
3095         return point;
3096     ColumnInfo* colInfo = columnInfo();
3097     LayoutUnit columnLogicalHeight = colInfo->columnHeight();
3098     LayoutUnit expandedLogicalHeight = borderBefore() + paddingBefore() + columnCount(colInfo) * columnLogicalHeight + borderAfter() + paddingAfter() + scrollbarLogicalHeight();
3099     if (isHorizontalWritingMode())
3100         return LayoutPoint(point.x(), expandedLogicalHeight - point.y());
3101     return LayoutPoint(expandedLogicalHeight - point.x(), point.y());
3102 }
3103
3104 void RenderBlock::adjustStartEdgeForWritingModeIncludingColumns(LayoutRect& rect) const
3105 {
3106     ASSERT(hasColumns());
3107     if (!hasColumns() || !style()->slowIsFlippedBlocksWritingMode())
3108         return;
3109
3110     ColumnInfo* colInfo = columnInfo();
3111     LayoutUnit columnLogicalHeight = colInfo->columnHeight();
3112     LayoutUnit expandedLogicalHeight = borderBefore() + paddingBefore() + columnCount(colInfo) * columnLogicalHeight + borderAfter() + paddingAfter() + scrollbarLogicalHeight();
3113
3114     if (isHorizontalWritingMode())
3115         rect.setY(expandedLogicalHeight - rect.maxY());
3116     else
3117         rect.setX(expandedLogicalHeight - rect.maxX());
3118 }
3119
3120 LayoutSize RenderBlock::columnOffset(const LayoutPoint& point) const
3121 {
3122     if (!hasColumns())
3123         return LayoutSize();
3124
3125     ColumnInfo* colInfo = columnInfo();
3126
3127     LayoutUnit logicalLeft = logicalLeftOffsetForContent();
3128     unsigned colCount = columnCount(colInfo);
3129     LayoutUnit colLogicalWidth = colInfo->desiredColumnWidth();
3130     LayoutUnit colLogicalHeight = colInfo->columnHeight();
3131
3132     for (unsigned i = 0; i < colCount; ++i) {
3133         // Compute the edges for a given column in the block progression direction.
3134         LayoutRect sliceRect = LayoutRect(logicalLeft, borderBefore() + paddingBefore() + i * colLogicalHeight, colLogicalWidth, colLogicalHeight);
3135         if (!isHorizontalWritingMode())
3136             sliceRect = sliceRect.transposedRect();
3137
3138         LayoutUnit logicalOffset = i * colLogicalHeight;
3139
3140         // Now we're in the same coordinate space as the point.  See if it is inside the rectangle.
3141         if (isHorizontalWritingMode()) {
3142             if (point.y() >= sliceRect.y() && point.y() < sliceRect.maxY()) {
3143                 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3144                     return LayoutSize(columnRectAt(colInfo, i).x() - logicalLeft, -logicalOffset);
3145                 return LayoutSize(0, columnRectAt(colInfo, i).y() - logicalOffset - borderBefore() - paddingBefore());
3146             }
3147         } else {
3148             if (point.x() >= sliceRect.x() && point.x() < sliceRect.maxX()) {
3149                 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3150                     return LayoutSize(-logicalOffset, columnRectAt(colInfo, i).y() - logicalLeft);
3151                 return LayoutSize(columnRectAt(colInfo, i).x() - logicalOffset - borderBefore() - paddingBefore(), 0);
3152             }
3153         }
3154     }
3155
3156     return LayoutSize();
3157 }
3158
3159 void RenderBlock::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
3160 {
3161     if (childrenInline()) {
3162         // FIXME: Remove this const_cast.
3163         toRenderBlockFlow(const_cast<RenderBlock*>(this))->computeInlinePreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
3164     } else {
3165         computeBlockPreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
3166     }
3167
3168     maxLogicalWidth = std::max(minLogicalWidth, maxLogicalWidth);
3169
3170     adjustIntrinsicLogicalWidthsForColumns(minLogicalWidth, maxLogicalWidth);
3171
3172     if (isTableCell()) {
3173         Length tableCellWidth = toRenderTableCell(this)->styleOrColLogicalWidth();
3174         if (tableCellWidth.isFixed() && tableCellWidth.value() > 0)
3175             maxLogicalWidth = std::max(minLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(tableCellWidth.value()));
3176     }
3177
3178     int scrollbarWidth = instrinsicScrollbarLogicalWidth();
3179     maxLogicalWidth += scrollbarWidth;
3180     minLogicalWidth += scrollbarWidth;
3181 }
3182
3183 void RenderBlock::computePreferredLogicalWidths()
3184 {
3185     ASSERT(preferredLogicalWidthsDirty());
3186
3187     updateFirstLetter();
3188
3189     m_minPreferredLogicalWidth = 0;
3190     m_maxPreferredLogicalWidth = 0;
3191
3192     // FIXME: The isFixed() calls here should probably be checking for isSpecified since you
3193     // should be able to use percentage, calc or viewport relative values for width.
3194     RenderStyle* styleToUse = style();
3195     if (!isTableCell() && styleToUse->logicalWidth().isFixed() && styleToUse->logicalWidth().value() >= 0
3196         && !(isDeprecatedFlexItem() && !styleToUse->logicalWidth().intValue()))
3197         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalWidth().value());
3198     else
3199         computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
3200
3201     if (styleToUse->logicalMinWidth().isFixed() && styleToUse->logicalMinWidth().value() > 0) {
3202         m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
3203         m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
3204     }
3205
3206     if (styleToUse->logicalMaxWidth().isFixed()) {
3207         m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
3208         m_minPreferredLogicalWidth = std::min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
3209     }
3210
3211     // Table layout uses integers, ceil the preferred widths to ensure that they can contain the contents.
3212     if (isTableCell()) {
3213         m_minPreferredLogicalWidth = m_minPreferredLogicalWidth.ceil();
3214         m_maxPreferredLogicalWidth = m_maxPreferredLogicalWidth.ceil();
3215     }
3216
3217     LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
3218     m_minPreferredLogicalWidth += borderAndPadding;
3219     m_maxPreferredLogicalWidth += borderAndPadding;
3220
3221     clearPreferredLogicalWidthsDirty();
3222 }
3223
3224 void RenderBlock::adjustIntrinsicLogicalWidthsForColumns(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
3225 {
3226     if (!style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth()) {
3227         // The min/max intrinsic widths calculated really tell how much space elements need when
3228         // laid out inside the columns. In order to eventually end up with the desired column width,
3229         // we need to convert them to values pertaining to the multicol container.
3230         int columnCount = style()->hasAutoColumnCount() ? 1 : style()->columnCount();
3231         LayoutUnit columnWidth;
3232         LayoutUnit gapExtra = (columnCount - 1) * columnGap();
3233         if (style()->hasAutoColumnWidth()) {
3234             minLogicalWidth = minLogicalWidth * columnCount + gapExtra;
3235         } else {
3236             columnWidth = style()->columnWidth();
3237             minLogicalWidth = std::min(minLogicalWidth, columnWidth);
3238         }
3239         // FIXME: If column-count is auto here, we should resolve it to calculate the maximum
3240         // intrinsic width, instead of pretending that it's 1. The only way to do that is by
3241         // performing a layout pass, but this is not an appropriate time or place for layout. The
3242         // good news is that if height is unconstrained and there are no explicit breaks, the
3243         // resolved column-count really should be 1.
3244         maxLogicalWidth = std::max(maxLogicalWidth, columnWidth) * columnCount + gapExtra;
3245     }
3246 }
3247
3248 void RenderBlock::computeBlockPreferredLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
3249 {
3250     RenderStyle* styleToUse = style();
3251     bool nowrap = styleToUse->whiteSpace() == NOWRAP;
3252
3253     RenderObject* child = firstChild();
3254     RenderBlock* containingBlock = this->containingBlock();
3255     LayoutUnit floatLeftWidth = 0, floatRightWidth = 0;
3256     while (child) {
3257         // Positioned children don't affect the min/max width
3258         if (child->isOutOfFlowPositioned()) {
3259             child = child->nextSibling();
3260             continue;
3261         }
3262
3263         RefPtr<RenderStyle> childStyle = child->style();
3264         if (child->isFloating() || (child->isBox() && toRenderBox(child)->avoidsFloats())) {
3265             LayoutUnit floatTotalWidth = floatLeftWidth + floatRightWidth;
3266             if (childStyle->clear() & CLEFT) {
3267                 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
3268                 floatLeftWidth = 0;
3269             }
3270             if (childStyle->clear() & CRIGHT) {
3271                 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
3272                 floatRightWidth = 0;
3273             }
3274         }
3275
3276         // A margin basically has three types: fixed, percentage, and auto (variable).
3277         // Auto and percentage margins simply become 0 when computing min/max width.
3278         // Fixed margins can be added in as is.
3279         Length startMarginLength = childStyle->marginStartUsing(styleToUse);
3280         Length endMarginLength = childStyle->marginEndUsing(styleToUse);
3281         LayoutUnit margin = 0;
3282         LayoutUnit marginStart = 0;
3283         LayoutUnit marginEnd = 0;
3284         if (startMarginLength.isFixed())
3285             marginStart += startMarginLength.value();
3286         if (endMarginLength.isFixed())
3287             marginEnd += endMarginLength.value();
3288         margin = marginStart + marginEnd;
3289
3290         LayoutUnit childMinPreferredLogicalWidth, childMaxPreferredLogicalWidth;
3291         if (child->isBox() && child->isHorizontalWritingMode() != isHorizontalWritingMode()) {
3292             RenderBox* childBox = toRenderBox(child);
3293             LogicalExtentComputedValues computedValues;
3294             childBox->computeLogicalHeight(childBox->borderAndPaddingLogicalHeight(), 0, computedValues);
3295             childMinPreferredLogicalWidth = childMaxPreferredLogicalWidth = computedValues.m_extent;
3296         } else {
3297             childMinPreferredLogicalWidth = child->minPreferredLogicalWidth();
3298             childMaxPreferredLogicalWidth = child->maxPreferredLogicalWidth();
3299         }
3300
3301         LayoutUnit w = childMinPreferredLogicalWidth + margin;
3302         minLogicalWidth = std::max(w, minLogicalWidth);
3303
3304         // IE ignores tables for calculation of nowrap. Makes some sense.
3305         if (nowrap && !child->isTable())
3306             maxLogicalWidth = std::max(w, maxLogicalWidth);
3307
3308         w = childMaxPreferredLogicalWidth + margin;
3309
3310         if (!child->isFloating()) {
3311             if (child->isBox() && toRenderBox(child)->avoidsFloats()) {
3312                 // Determine a left and right max value based off whether or not the floats can fit in the
3313                 // margins of the object.  For negative margins, we will attempt to overlap the float if the negative margin
3314                 // is smaller than the float width.
3315                 bool ltr = containingBlock ? containingBlock->style()->isLeftToRightDirection() : styleToUse->isLeftToRightDirection();
3316                 LayoutUnit marginLogicalLeft = ltr ? marginStart : marginEnd;
3317                 LayoutUnit marginLogicalRight = ltr ? marginEnd : marginStart;
3318                 LayoutUnit maxLeft = marginLogicalLeft > 0 ? std::max(floatLeftWidth, marginLogicalLeft) : floatLeftWidth + marginLogicalLeft;
3319                 LayoutUnit maxRight = marginLogicalRight > 0 ? std::max(floatRightWidth, marginLogicalRight) : floatRightWidth + marginLogicalRight;
3320                 w = childMaxPreferredLogicalWidth + maxLeft + maxRight;
3321                 w = std::max(w, floatLeftWidth + floatRightWidth);
3322             } else {
3323                 maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
3324             }
3325             floatLeftWidth = floatRightWidth = 0;
3326         }
3327
3328         if (child->isFloating()) {
3329             if (childStyle->floating() == LeftFloat)
3330                 floatLeftWidth += w;
3331             else
3332                 floatRightWidth += w;
3333         } else {
3334             maxLogicalWidth = std::max(w, maxLogicalWidth);
3335         }
3336
3337         child = child->nextSibling();
3338     }
3339
3340     // Always make sure these values are non-negative.
3341     minLogicalWidth = std::max<LayoutUnit>(0, minLogicalWidth);
3342     maxLogicalWidth = std::max<LayoutUnit>(0, maxLogicalWidth);
3343
3344     maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
3345 }
3346
3347 bool RenderBlock::hasLineIfEmpty() const
3348 {
3349     if (!node())
3350         return false;
3351
3352     if (node()->isRootEditableElement())
3353         return true;
3354
3355     if (node()->isShadowRoot() && isHTMLInputElement(*toShadowRoot(node())->host()))
3356         return true;
3357
3358     return false;
3359 }
3360
3361 LayoutUnit RenderBlock::lineHeight(bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
3362 {
3363     // Inline blocks are replaced elements. Otherwise, just pass off to
3364     // the base class.  If we're being queried as though we're the root line
3365     // box, then the fact that we're an inline-block is irrelevant, and we behave
3366     // just like a block.
3367     if (isReplaced() && linePositionMode == PositionOnContainingLine)
3368         return RenderBox::lineHeight(firstLine, direction, linePositionMode);
3369
3370     RenderStyle* s = style(firstLine && document().styleEngine()->usesFirstLineRules());
3371     return s->computedLineHeight();
3372 }
3373
3374 int RenderBlock::beforeMarginInLineDirection(LineDirectionMode direction) const
3375 {
3376     return direction == HorizontalLine ? marginTop() : marginRight();
3377 }
3378
3379 int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
3380 {
3381     // Inline blocks are replaced elements. Otherwise, just pass off to
3382     // the base class.  If we're being queried as though we're the root line
3383     // box, then the fact that we're an inline-block is irrelevant, and we behave
3384     // just like a block.
3385     if (isInline() && linePositionMode == PositionOnContainingLine) {
3386         // For "leaf" theme objects, let the theme decide what the baseline position is.
3387         // FIXME: Might be better to have a custom CSS property instead, so that if the theme
3388         // is turned off, checkboxes/radios will still have decent baselines.
3389         // FIXME: Need to patch form controls to deal with vertical lines.
3390         if (style()->hasAppearance() && !RenderTheme::theme().isControlContainer(style()->appearance()))
3391             return RenderTheme::theme().baselinePosition(this);
3392
3393         // CSS2.1 states that the baseline of an inline block is the baseline of the last line box in
3394         // the normal flow.
3395         // We give up on finding a baseline if we have a vertical scrollbar, or if we are scrolled
3396         // vertically (e.g., an overflow:hidden block that has had scrollTop moved).
3397         bool ignoreBaseline = (layer() && layer()->scrollableArea()
3398             && (direction == HorizontalLine
3399                 ? (layer()->scrollableArea()->verticalScrollbar() || layer()->scrollableArea()->scrollYOffset())
3400                 : (layer()->scrollableArea()->horizontalScrollbar() || layer()->scrollableArea()->scrollXOffset())))
3401             || (isWritingModeRoot() && !isRubyRun());
3402
3403         int baselinePos = ignoreBaseline ? -1 : inlineBlockBaseline(direction);
3404
3405         if (isDeprecatedFlexibleBox()) {
3406             // Historically, we did this check for all baselines. But we can't
3407             // remove this code from deprecated flexbox, because it effectively
3408             // breaks -webkit-line-clamp, which is used in the wild -- we would
3409             // calculate the baseline as if -webkit-line-clamp wasn't used.
3410             // For simplicity, we use this for all uses of deprecated flexbox.
3411             LayoutUnit bottomOfContent = direction == HorizontalLine ? borderTop() + paddingTop() + contentHeight() : borderRight() + paddingRight() + contentWidth();
3412             if (baselinePos > bottomOfContent)
3413                 baselinePos = -1;
3414         }
3415         if (baselinePos != -1)
3416             return beforeMarginInLineDirection(direction) + baselinePos;
3417
3418         return RenderBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
3419     }
3420
3421     // If we're not replaced, we'll only get called with PositionOfInteriorLineBoxes.
3422     // Note that inline-block counts as replaced here.
3423     ASSERT(linePositionMode == PositionOfInteriorLineBoxes);
3424
3425     const FontMetrics& fontMetrics = style(firstLine)->fontMetrics();
3426     return fontMetrics.ascent(baselineType) + (lineHeight(firstLine, direction, linePositionMode) - fontMetrics.height()) / 2;
3427 }
3428
3429 LayoutUnit RenderBlock::minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const
3430 {
3431     if (!document().inNoQuirksMode() && replacedHeight)
3432         return replacedHeight;
3433
3434     if (!(style(isFirstLine)->lineBoxContain() & LineBoxContainBlock))
3435         return 0;
3436
3437     return std::max<LayoutUnit>(replacedHeight, lineHeight(isFirstLine, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
3438 }
3439
3440 int RenderBlock::firstLineBoxBaseline() const
3441 {
3442     if (isWritingModeRoot() && !isRubyRun())
3443         return -1;
3444
3445     if (childrenInline()) {
3446         if (firstLineBox())
3447             return firstLineBox()->logicalTop() + style(true)->fontMetrics().ascent(firstRootBox()->baselineType());
3448         else
3449             return -1;
3450     }
3451     else {
3452         for (RenderBox* curr = firstChildBox(); curr; curr = curr->nextSiblingBox()) {
3453             if (!curr->isFloatingOrOutOfFlowPositioned()) {
3454                 int result = curr->firstLineBoxBaseline();
3455                 if (result != -1)
3456                     return curr->logicalTop() + result; // Translate to our coordinate space.
3457             }
3458         }
3459     }
3460
3461     return -1;
3462 }
3463
3464 int RenderBlock::inlineBlockBaseline(LineDirectionMode direction) const
3465 {
3466     if (!style()->isOverflowVisible()) {
3467         // We are not calling RenderBox::baselinePosition here because the caller should add the margin-top/margin-right, not us.
3468         return direction == HorizontalLine ? height() + m_marginBox.bottom() : width() + m_marginBox.left();
3469     }
3470
3471     return lastLineBoxBaseline(direction);
3472 }
3473
3474 int RenderBlock::lastLineBoxBaseline(LineDirectionMode lineDirection) const
3475 {
3476     if (isWritingModeRoot() && !isRubyRun())
3477         return -1;
3478
3479     if (childrenInline()) {
3480         if (!firstLineBox() && hasLineIfEmpty()) {
3481             const FontMetrics& fontMetrics = firstLineStyle()->fontMetrics();
3482             return fontMetrics.ascent()
3483                  + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3484                  + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
3485         }
3486         if (lastLineBox())
3487             return lastLineBox()->logicalTop() + style(lastLineBox() == firstLineBox())->fontMetrics().ascent(lastRootBox()->baselineType());
3488         return -1;
3489     } else {
3490         bool haveNormalFlowChild = false;
3491         for (RenderBox* curr = lastChildBox(); curr; curr = curr->previousSiblingBox()) {
3492             if (!curr->isFloatingOrOutOfFlowPositioned()) {
3493                 haveNormalFlowChild = true;
3494                 int result = curr->inlineBlockBaseline(lineDirection);
3495                 if (result != -1)
3496                     return curr->logicalTop() + result; // Translate to our coordinate space.
3497             }
3498         }
3499         if (!haveNormalFlowChild && hasLineIfEmpty()) {
3500             const FontMetrics& fontMetrics = firstLineStyle()->fontMetrics();
3501             return fontMetrics.ascent()
3502                  + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3503                  + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
3504         }
3505     }
3506
3507     return -1;
3508 }
3509
3510 static inline bool isRenderBlockFlowOrRenderButton(RenderObject* renderObject)
3511 {
3512     // We include isRenderButton in this check because buttons are implemented
3513     // using flex box but should still support first-line|first-letter.
3514     // The flex box and grid specs require that flex box and grid do not
3515     // support first-line|first-letter, though.
3516     // FIXME: Remove when buttons are implemented with align-items instead
3517     // of flex box.
3518     return renderObject->isRenderBlockFlow() || renderObject->isRenderButton();
3519 }
3520
3521 RenderBlock* RenderBlock::firstLineBlock() const
3522 {
3523     RenderBlock* firstLineBlock = const_cast<RenderBlock*>(this);
3524     bool hasPseudo = false;
3525     while (true) {
3526         hasPseudo = firstLineBlock->style()->hasPseudoStyle(FIRST_LINE);
3527         if (hasPseudo)
3528             break;
3529         RenderObject* parentBlock = firstLineBlock->parent();
3530         if (firstLineBlock->isReplaced() || firstLineBlock->isFloating()
3531             || !parentBlock
3532             || !isRenderBlockFlowOrRenderButton(parentBlock))
3533             break;
3534         ASSERT_WITH_SECURITY_IMPLICATION(parentBlock->isRenderBlock());
3535         if (toRenderBlock(parentBlock)->firstChild() != firstLineBlock)
3536             break;
3537         firstLineBlock = toRenderBlock(parentBlock);
3538     }
3539
3540     if (!hasPseudo)
3541         return 0;
3542
3543     return firstLineBlock;
3544 }
3545
3546 static RenderStyle* styleForFirstLetter(RenderObject* firstLetterBlock, RenderObject* firstLetterContainer)
3547 {
3548     RenderStyle* pseudoStyle = firstLetterBlock->getCachedPseudoStyle(FIRST_LETTER, firstLetterContainer->firstLineStyle());
3549     // Force inline display (except for floating first-letters).
3550     pseudoStyle->setDisplay(pseudoStyle->isFloating() ? BLOCK : INLINE);
3551     // CSS2 says first-letter can't be positioned.
3552     pseudoStyle->setPosition(StaticPosition);
3553     return pseudoStyle;
3554 }
3555
3556 // CSS 2.1 http://www.w3.org/TR/CSS21/selector.html#first-letter
3557 // "Punctuation (i.e, characters defined in Unicode [UNICODE] in the "open" (Ps), "close" (Pe),
3558 // "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes), that precedes or follows the first letter should be included"
3559 static inline bool isPunctuationForFirstLetter(UChar c)
3560 {
3561     CharCategory charCategory = category(c);
3562     return charCategory == Punctuation_Open
3563         || charCategory == Punctuation_Close
3564         || charCategory == Punctuation_InitialQuote
3565         || charCategory == Punctuation_FinalQuote
3566         || charCategory == Punctuation_Other;
3567 }
3568
3569 static inline bool isSpaceForFirstLetter(UChar c)
3570 {
3571     return isSpaceOrNewline(c) || c == noBreakSpace;
3572 }
3573
3574 static inline RenderObject* findFirstLetterBlock(RenderBlock* start)
3575 {
3576     RenderObject* firstLetterBlock = start;
3577     while (true) {
3578         bool canHaveFirstLetterRenderer = firstLetterBlock->style()->hasPseudoStyle(FIRST_LETTER)
3579             && firstLetterBlock->canHaveGeneratedChildren()
3580             && isRenderBlockFlowOrRenderButton(firstLetterBlock);
3581         if (canHaveFirstLetterRenderer)
3582             return firstLetterBlock;
3583
3584         RenderObject* parentBlock = firstLetterBlock->parent();
3585         if (firstLetterBlock->isReplaced() || !parentBlock
3586             || !isRenderBlockFlowOrRenderButton(parentBlock)) {
3587             return 0;
3588         }
3589         ASSERT(parentBlock->isRenderBlock());
3590         if (toRenderBlock(parentBlock)->firstChild() != firstLetterBlock)
3591             return 0;
3592         firstLetterBlock = parentBlock;
3593     }
3594
3595     return 0;
3596 }
3597
3598 void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderObject* currentChild)
3599 {
3600     RenderObject* firstLetter = currentChild->parent();
3601     RenderObject* firstLetterContainer = firstLetter->parent();
3602     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3603     ASSERT(firstLetter->isFloating() || firstLetter->isInline());
3604
3605     if (RenderStyle::stylePropagationDiff(firstLetter->style(), pseudoStyle) == Reattach) {
3606         // The first-letter renderer needs to be replaced. Create a new renderer of the right type.
3607         RenderBoxModelObject* newFirstLetter;
3608         if (pseudoStyle->display() == INLINE)
3609             newFirstLetter = RenderInline::createAnonymous(&document());
3610         else
3611             newFirstLetter = RenderBlockFlow::createAnonymous(&document());
3612         newFirstLetter->setStyle(pseudoStyle);
3613
3614         // Move the first letter into the new renderer.
3615         while (RenderObject* child = firstLetter->slowFirstChild()) {
3616             if (child->isText())
3617                 toRenderText(child)->removeAndDestroyTextBoxes();
3618             firstLetter->removeChild(child);
3619             newFirstLetter->addChild(child, 0);
3620         }
3621
3622         RenderObject* nextSibling = firstLetter->nextSibling();
3623         if (RenderTextFragment* remainingText = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText()) {
3624             ASSERT(remainingText->isAnonymous() || remainingText->node()->renderer() == remainingText);
3625             // Replace the old renderer with the new one.
3626             remainingText->setFirstLetter(newFirstLetter);
3627             newFirstLetter->setFirstLetterRemainingText(remainingText);
3628         }
3629         // To prevent removal of single anonymous block in RenderBlock::removeChild and causing
3630         // |nextSibling| to go stale, we remove the old first letter using removeChildNode first.
3631         firstLetterContainer->virtualChildren()->removeChildNode(firstLetterContainer, firstLetter);
3632         firstLetter->destroy();
3633         firstLetter = newFirstLetter;
3634         firstLetterContainer->addChild(firstLetter, nextSibling);
3635     } else {
3636         firstLetter->setStyle(pseudoStyle);
3637     }
3638
3639     for (RenderObject* genChild = firstLetter->slowFirstChild(); genChild; genChild = genChild->nextSibling()) {
3640         if (genChild->isText())
3641             genChild->setStyle(pseudoStyle);
3642     }
3643 }
3644
3645 static inline unsigned firstLetterLength(const String& text)
3646 {
3647     unsigned length = 0;
3648     unsigned textLength = text.length();
3649
3650     if (textLength == 0)
3651         return length;
3652
3653     // Account for leading spaces first.
3654     while (length < textLength && isSpaceForFirstLetter(text[length]))
3655         length++;
3656
3657     // Now account for leading punctuation.
3658     while (length < textLength && isPunctuationForFirstLetter(text[length]))
3659         length++;
3660
3661     // Bail if we didn't find a letter before the end of the text or before a space.
3662     if (isSpaceForFirstLetter(text[length]) || length == textLength)
3663         return 0;
3664
3665     // Account the next character for first letter.
3666     length++;
3667
3668     // Keep looking allowed punctuation for the :first-letter.
3669     for (unsigned scanLength = length; scanLength < textLength; ++scanLength) {
3670         UChar c = text[scanLength];
3671
3672         if (!isPunctuationForFirstLetter(c))
3673             break;
3674
3675         length = scanLength + 1;
3676     }
3677     return length;
3678 }
3679
3680 void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderText& currentChild, unsigned length)
3681 {
3682     ASSERT(length);
3683
3684     RenderObject* firstLetterContainer = currentChild.parent();
3685     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3686     RenderBoxModelObject* firstLetter = 0;
3687     if (pseudoStyle->display() == INLINE)
3688         firstLetter = RenderInline::createAnonymous(&document());
3689     else
3690         firstLetter = RenderBlockFlow::createAnonymous(&document());
3691     firstLetter->setStyle(pseudoStyle);
3692
3693     // FIXME: The first letter code should not modify the render tree during
3694     // layout. crbug.com/370458
3695     DeprecatedDisableModifyRenderTreeStructureAsserts disabler;
3696
3697     firstLetterContainer->addChild(firstLetter, &currentChild);
3698
3699     // The original string is going to be either a generated content string or a DOM node's
3700     // string.  We want the original string before it got transformed in case first-letter has
3701     // no text-transform or a different text-transform applied to it.
3702     String oldText = currentChild.originalText();
3703     ASSERT(oldText.impl());
3704
3705     // Construct a text fragment for the text after the first letter.
3706     // This text fragment might be empty.
3707     RenderTextFragment* remainingText =
3708         new RenderTextFragment(currentChild.node() ? currentChild.node() : &currentChild.document(), oldText.impl(), length, oldText.length() - length);
3709     remainingText->setStyle(currentChild.style());
3710     if (remainingText->node())
3711         remainingText->node()->setRenderer(remainingText);
3712
3713     firstLetterContainer->addChild(remainingText, &currentChild);
3714     firstLetterContainer->removeChild(&currentChild);
3715     remainingText->setFirstLetter(firstLetter);
3716     firstLetter->setFirstLetterRemainingText(remainingText);
3717
3718     // construct text fragment for the first letter
3719     RenderTextFragment* letter =
3720         new RenderTextFragment(remainingText->node() ? remainingText->node() : &remainingText->document(), oldText.impl(), 0, length);
3721     letter->setStyle(pseudoStyle);
3722     firstLetter->addChild(letter);
3723
3724     currentChild.destroy();
3725 }
3726
3727 // Once we see any of these renderers we can stop looking for first-letter as
3728 // they signal the end of the first line of text.
3729 bool RenderBlock::isInvalidFirstLetterRenderer(RenderObject* obj) const
3730 {
3731     return (obj->isBR() || (obj->isText() && toRenderText(obj)->isWordBreak()));
3732 }
3733
3734 void RenderBlock::updateFirstLetter()
3735 {
3736     if (!document().styleEngine()->usesFirstLetterRules())
3737         return;
3738     // Don't recur
3739     if (style()->styleType() == FIRST_LETTER)
3740         return;
3741
3742     // FIXME: We need to destroy the first-letter object if it is no longer the first child. Need to find
3743     // an efficient way to check for that situation though before implementing anything.
3744     RenderObject* firstLetterBlock = findFirstLetterBlock(this);
3745     if (!firstLetterBlock)
3746         return;
3747
3748     // Drill into inlines looking for our first text child.
3749     RenderObject* currChild = firstLetterBlock->slowFirstChild();
3750     unsigned length = 0;
3751     while (currChild) {
3752         if (currChild->isText()) {
3753             // FIXME: If there is leading punctuation in a different RenderText than
3754             // the first letter, we'll not apply the correct style to it.
3755             length = firstLetterLength(toRenderText(currChild)->originalText());
3756             if (length || isInvalidFirstLetterRenderer(currChild))
3757                 break;
3758             currChild = currChild->nextSibling();
3759         } else if (currChild->isListMarker()) {
3760             currChild = currChild->nextSibling();
3761         } else if (currChild->isFloatingOrOutOfFlowPositioned()) {
3762             if (currChild->style()->styleType() == FIRST_LETTER) {
3763                 currChild = currChild->slowFirstChild();
3764                 break;
3765             }
3766             currChild = currChild->nextSibling();
3767         } else if (currChild->isReplaced() || currChild->isRenderButton() || currChild->isMenuList()) {
3768             break;
3769         } else if (currChild->isFlexibleBoxIncludingDeprecated() || currChild->isRenderGrid()) {
3770             return;
3771         } else if (currChild->style()->hasPseudoStyle(FIRST_LETTER) && currChild->canHaveGeneratedChildren())  {
3772             // We found a lower-level node with first-letter, which supersedes the higher-level style
3773             firstLetterBlock = currChild;
3774             currChild = currChild->slowFirstChild();
3775         } else {
3776             currChild = currChild->slowFirstChild();
3777         }
3778     }
3779
3780     if (!currChild)
3781         return;
3782
3783     // If the child already has style, then it has already been created, so we just want
3784     // to update it.
3785     if (currChild->parent()->style()->styleType() == FIRST_LETTER) {
3786         updateFirstLetterStyle(firstLetterBlock, currChild);
3787         return;
3788     }
3789
3790     // FIXME: This black-list of disallowed RenderText subclasses is fragile.
3791     // Should counter be on this list? What about RenderTextFragment?
3792     if (!currChild->isText() || isInvalidFirstLetterRenderer(currChild))
3793         return;
3794
3795     createFirstLetterRenderer(firstLetterBlock, toRenderText(*currChild), length);
3796 }
3797
3798 // Helper methods for obtaining the last line, computing line counts and heights for line counts
3799 // (crawling into blocks).
3800 static bool shouldCheckLines(RenderObject* obj)
3801 {
3802     return !obj->isFloatingOrOutOfFlowPositioned()
3803         && obj->isRenderBlock() && obj->style()->height().isAuto()
3804         && (!obj->isDeprecatedFlexibleBox() || obj->style()->boxOrient() == VERTICAL);
3805 }
3806
3807 static int getHeightForLineCount(RenderBlock* block, int l, bool includeBottom, int& count)
3808 {
3809     if (block->style()->visibility() == VISIBLE) {
3810         if (block->isRenderBlockFlow() && block->childrenInline()) {
3811             for (RootInlineBox* box = toRenderBlockFlow(block)->firstRootBox(); box; box = box->nextRootBox()) {
3812                 if (++count == l)
3813                     return box->lineBottom() + (includeBottom ? (block->borderBottom() + block->paddingBottom()) : LayoutUnit());
3814             }
3815         } else {
3816             RenderBox* normalFlowChildWithoutLines = 0;
3817             for (RenderBox* obj = block->firstChildBox(); obj; obj = obj->nextSiblingBox()) {
3818                 if (shouldCheckLines(obj)) {
3819                     int result = getHeightForLineCount(toRenderBlock(obj), l, false, count);
3820                     if (result != -1)
3821                         return result + obj->y() + (includeBottom ? (block->borderBottom() + block->paddingBottom()) : LayoutUnit());
3822                 } else if (!obj->isFloatingOrOutOfFlowPositioned()) {
3823                     normalFlowChildWithoutLines = obj;
3824                 }
3825             }
3826             if (normalFlowChildWithoutLines && l == 0)
3827                 return normalFlowChildWithoutLines->y() + normalFlowChildWithoutLines->height();
3828         }
3829     }
3830
3831     return -1;
3832 }
3833
3834 RootInlineBox* RenderBlock::lineAtIndex(int i) const
3835 {
3836     ASSERT(i >= 0);
3837
3838     if (style()->visibility() != VISIBLE)
3839         return 0;
3840
3841     if (childrenInline()) {
3842         for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox())
3843             if (!i--)
3844                 return box;
3845     } else {
3846         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
3847             if (!shouldCheckLines(child))
3848                 continue;
3849             if (RootInlineBox* box = toRenderBlock(child)->lineAtIndex(i))
3850                 return box;
3851         }
3852     }
3853
3854     return 0;
3855 }
3856
3857 int RenderBlock::lineCount(const RootInlineBox* stopRootInlineBox, bool* found) const
3858 {
3859     int count = 0;
3860
3861     if (style()->visibility() == VISIBLE) {
3862         if (childrenInline())
3863             for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox()) {
3864                 count++;
3865                 if (box == stopRootInlineBox) {
3866                     if (found)
3867                         *found = true;
3868                     break;
3869                 }
3870             }
3871         else
3872             for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling())
3873                 if (shouldCheckLines(obj)) {
3874                     bool recursiveFound = false;
3875                     count += toRenderBlock(obj)->lineCount(stopRootInlineBox, &recursiveFound);
3876                     if (recursiveFound) {
3877                         if (found)
3878                             *found = true;
3879                         break;
3880                     }
3881                 }
3882     }
3883     return count;
3884 }
3885
3886 int RenderBlock::heightForLineCount(int l)
3887 {
3888     int count = 0;
3889     return getHeightForLineCount(this, l, true, count);
3890 }
3891
3892 void RenderBlock::clearTruncation()
3893 {
3894     if (style()->visibility() == VISIBLE) {
3895         if (childrenInline() && hasMarkupTruncation()) {
3896             setHasMarkupTruncation(false);
3897             for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox())
3898                 box->clearTruncation();
3899         } else {
3900             for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling()) {
3901                 if (shouldCheckLines(obj))
3902                     toRenderBlock(obj)->clearTruncation();
3903             }
3904         }
3905     }
3906 }
3907
3908 void RenderBlock::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
3909 {
3910     // For blocks inside inlines, we go ahead and include margins so that we run right up to the
3911     // inline boxes above and below us (thus getting merged with them to form a single irregular
3912     // shape).
3913     if (isAnonymousBlockContinuation()) {
3914         // FIXME: This is wrong for block-flows that are horizontal.
3915         // https://bugs.webkit.org/show_bug.cgi?id=46781
3916         rects.append(pixelSnappedIntRect(accumulatedOffset.x(), accumulatedOffset.y() - collapsedMarginBefore(),
3917                                 width(), height() + collapsedMarginBefore() + collapsedMarginAfter()));
3918         continuation()->absoluteRects(rects, accumulatedOffset - toLayoutSize(location() +
3919                 inlineElementContinuation()->containingBlock()->location()));
3920     } else
3921         rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
3922 }
3923
3924 void RenderBlock::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
3925 {
3926     // For blocks inside inlines, we go ahead and include margins so that we run right up to the
3927     // inline boxes above and below us (thus getting merged with them to form a single irregular
3928     // shape).
3929     if (isAnonymousBlockContinuation()) {
3930         // FIXME: This is wrong for block-flows that are horizontal.
3931         // https://bugs.webkit.org/show_bug.cgi?id=46781
3932         FloatRect localRect(0, -collapsedMarginBefore().toFloat(),
3933             width().toFloat(), (height() + collapsedMarginBefore() + collapsedMarginAfter()).toFloat());
3934         quads.append(localToAbsoluteQuad(localRect, 0 /* mode */, wasFixed));
3935         continuation()->absoluteQuads(quads, wasFixed);
3936     } else {
3937         quads.append(RenderBox::localToAbsoluteQuad(FloatRect(0, 0, width().toFloat(), height().toFloat()), 0 /* mode */, wasFixed));
3938     }
3939 }
3940
3941 LayoutRect RenderBlock::rectWithOutlineForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, LayoutUnit outlineWidth, const PaintInvalidationState* paintInvalidationState) const
3942 {
3943     LayoutRect r(RenderBox::rectWithOutlineForPaintInvalidation(paintInvalidationContainer, outlineWidth, paintInvalidationState));
3944     if (isAnonymousBlockContinuation())
3945         r.inflateY(collapsedMarginBefore()); // FIXME: This is wrong for block-flows that are horizontal.
3946     return r;
3947 }
3948
3949 RenderObject* RenderBlock::hoverAncestor() const
3950 {
3951     return isAnonymousBlockContinuation() ? continuation() : RenderBox::hoverAncestor();
3952 }
3953
3954 void RenderBlock::updateDragState(bool dragOn)
3955 {
3956     RenderBox::updateDragState(dragOn);
3957     if (continuation())
3958         continuation()->updateDragState(dragOn);
3959 }
3960
3961 void RenderBlock::childBecameNonInline(RenderObject*)
3962 {
3963     makeChildrenNonInline();
3964     if (isAnonymousBlock() && parent() && parent()->isRenderBlock())
3965         toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
3966     // |this| may be dead here
3967 }
3968
3969 void RenderBlock::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
3970 {
3971     if (result.innerNode())
3972         return;
3973
3974     if (Node* n = nodeForHitTest()) {
3975         result.setInnerNode(n);
3976         if (!result.innerNonSharedNode())
3977             result.setInnerNonSharedNode(n);
3978         result.setLocalPoint(point);
3979     }
3980 }
3981
3982 LayoutRect RenderBlock::localCaretRect(InlineBox* inlineBox, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
3983 {
3984     // Do the normal calculation in most cases.
3985     if (firstChild())
3986         return RenderBox::localCaretRect(inlineBox, caretOffset, extraWidthToEndOfLine);
3987
3988     LayoutRect caretRect = localCaretRectForEmptyElement(width(), textIndentOffset());
3989
3990     if (extraWidthToEndOfLine)
3991         *extraWidthToEndOfLine = width() - caretRect.maxX();
3992
3993     return caretRect;
3994 }
3995
3996 void RenderBlock::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer) const
3997 {
3998     // For blocks inside inlines, we go ahead and include margins so that we run right up to the
3999     // inline boxes above and below us (thus getting merged with them to form a single irregular
4000     // shape).
4001     if (inlineElementContinuation()) {
4002         // FIXME: This check really isn't accurate.
4003         bool nextInlineHasLineBox = inlineElementContinuation()->firstLineBox();
4004         // FIXME: This is wrong. The principal renderer may not be the continuation preceding this block.
4005         // FIXME: This is wrong for block-flows that are horizontal.
4006         // https://bugs.webkit.org/show_bug.cgi?id=46781
4007         bool prevInlineHasLineBox = toRenderInline(inlineElementContinuation()->node()->renderer())->firstLineBox();
4008         LayoutUnit topMargin = prevInlineHasLineBox ? collapsedMarginBefore() : LayoutUnit();
4009         LayoutUnit bottomMargin = nextInlineHasLineBox ? collapsedMarginAfter() : LayoutUnit();
4010         LayoutRect rect(additionalOffset.x(), additionalOffset.y() - topMargin, width(), height() + topMargin + bottomMargin);
4011         if (!rect.isEmpty())
4012             rects.append(rect);
4013     } else if (width() && height()) {
4014         rects.append(LayoutRect(additionalOffset, size()));
4015     }
4016
4017     if (!hasOverflowClip() && !hasControlClip()) {
4018         for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
4019             LayoutUnit top = std::max<LayoutUnit>(curr->lineTop(), curr->top());
4020             LayoutUnit bottom = std::min<LayoutUnit>(curr->lineBottom(), curr->top() + curr->height());
4021             LayoutRect rect(additionalOffset.x() + curr->x(), additionalOffset.y() + top, curr->width(), bottom - top);
4022             if (!rect.isEmpty())
4023                 rects.append(rect);
4024         }
4025
4026         addChildFocusRingRects(rects, additionalOffset, paintContainer);
4027     }
4028
4029     if (inlineElementContinuation())
4030         inlineElementContinuation()->addFocusRingRects(rects, additionalOffset + (inlineElementContinuation()->containingBlock()->location() - location()), paintContainer);
4031 }
4032
4033 void RenderBlock::computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint& layerOffset) const
4034 {
4035     RenderBox::computeSelfHitTestRects(rects, layerOffset);
4036
4037     if (hasHorizontalLayoutOverflow() || hasVerticalLayoutOverflow()) {
4038         for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
4039             LayoutUnit top = std::max<LayoutUnit>(curr->lineTop(), curr->top());
4040             LayoutUnit bottom = std::min<LayoutUnit>(curr->lineBottom(), curr->top() + curr->height());
4041             LayoutRect rect(layerOffset.x() + curr->x(), layerOffset.y() + top, curr->width(), bottom - top);
4042             // It's common for this rect to be entirely contained in our box, so exclude that simple case.
4043             if (!rect.isEmpty() && (rects.isEmpty() || !rects[0].contains(rect)))
4044                 rects.append(rect);
4045         }
4046     }
4047 }
4048
4049 RenderBox* RenderBlock::createAnonymousBoxWithSameTypeAs(const RenderObject* parent) const
4050 {
4051     if (isAnonymousColumnsBlock())
4052         return createAnonymousColumnsWithParentRenderer(parent);
4053     if (isAnonymousColumnSpanBlock())
4054         return createAnonymousColumnSpanWithParentRenderer(parent);
4055     return createAnonymousWithParentRendererAndDisplay(parent, style()->display());
4056 }
4057
4058 LayoutUnit RenderBlock::nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
4059 {
4060     LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
4061     if (!pageLogicalHeight)
4062         return logicalOffset;
4063
4064     // The logicalOffset is in our coordinate space.  We can add in our pushed offset.
4065     LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset);
4066     if (pageBoundaryRule == ExcludePageBoundary)
4067         return logicalOffset + (remainingLogicalHeight ? remainingLogicalHeight : pageLogicalHeight);
4068     return logicalOffset + remainingLogicalHeight;
4069 }
4070
4071 LayoutUnit RenderBlock::pageLogicalHeightForOffset(LayoutUnit offset) const
4072 {
4073     RenderView* renderView = view();
4074     RenderFlowThread* flowThread = flowThreadContainingBlock();
4075     if (!flowThread)
4076         return renderView->layoutState()->pageLogicalHeight();
4077     return flowThread->pageLogicalHeightForOffset(offset + offsetFromLogicalTopOfFirstPage());
4078 }
4079
4080 LayoutUnit RenderBlock::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const
4081 {
4082     RenderView* renderView = view();
4083     offset += offsetFromLogicalTopOfFirstPage();
4084
4085     RenderFlowThread* flowThread = flowThreadContainingBlock();
4086     if (!flowThread) {
4087         LayoutUnit pageLogicalHeight = renderView->layoutState()->pageLogicalHeight();
4088         LayoutUnit remainingHeight = pageLogicalHeight - intMod(offset, pageLogicalHeight);
4089         if (pageBoundaryRule == IncludePageBoundary) {
4090             // If includeBoundaryPoint is true the line exactly on the top edge of a
4091             // column will act as being part of the previous column.
4092             remainingHeight = intMod(remainingHeight, pageLogicalHeight);
4093         }
4094         return remainingHeight;
4095     }
4096
4097     return flowThread->pageRemainingLogicalHeightForOffset(offset, pageBoundaryRule);
4098 }
4099
4100 void RenderBlock::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
4101 {
4102     if (RenderFlowThread* flowThread = flowThreadContainingBlock())
4103         flowThread->setPageBreak(offsetFromLogicalTopOfFirstPage() + offset, spaceShortage);
4104 }
4105
4106 void RenderBlock::updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight)
4107 {
4108     if (RenderFlowThread* flowThread = flowThreadContainingBlock())
4109         flowThread->updateMinimumPageHeight(offsetFromLogicalTopOfFirstPage() + offset, minHeight);
4110     else if (ColumnInfo* colInfo = view()->layoutState()->columnInfo())
4111         colInfo->updateMinimumColumnHeight(minHeight);
4112 }
4113
4114 LayoutUnit RenderBlock::offsetFromLogicalTopOfFirstPage() const
4115 {
4116     LayoutState* layoutState = view()->layoutState();
4117     if (layoutState && !layoutState->isPaginated())
4118         return 0;
4119
4120     RenderFlowThread* flowThread = flowThreadContainingBlock();
4121     if (flowThread)
4122         return flowThread->offsetFromLogicalTopOfFirstRegion(this);
4123
4124     if (layoutState) {
4125         ASSERT(layoutState->renderer() == this);
4126
4127         LayoutSize offsetDelta = layoutState->layoutOffset() - layoutState->pageOffset();
4128         return isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width();
4129     }
4130
4131     ASSERT_NOT_REACHED();
4132     return 0;
4133 }
4134
4135 LayoutUnit RenderBlock::collapsedMarginBeforeForChild(const RenderBox* child) const
4136 {
4137     // If the child has the same directionality as we do, then we can just return its
4138     // collapsed margin.
4139     if (!child->isWritingModeRoot())
4140         return child->collapsedMarginBefore();
4141
4142     // The child has a different directionality.  If the child is parallel, then it's just
4143     // flipped relative to us.  We can use the collapsed margin for the opposite edge.
4144     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4145         return child->collapsedMarginAfter();
4146
4147     // The child is perpendicular to us, which means its margins don't collapse but are on the
4148     // "logical left/right" sides of the child box.  We can just return the raw margin in this case.
4149     return marginBeforeForChild(child);
4150 }
4151
4152 LayoutUnit RenderBlock::collapsedMarginAfterForChild(const  RenderBox* child) const
4153 {
4154     // If the child has the same directionality as we do, then we can just return its
4155     // collapsed margin.
4156     if (!child->isWritingModeRoot())
4157         return child->collapsedMarginAfter();
4158
4159     // The child has a different directionality.  If the child is parallel, then it's just
4160     // flipped relative to us.  We can use the collapsed margin for the opposite edge.
4161     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4162         return child->collapsedMarginBefore();
4163
4164     // The child is perpendicular to us, which means its margins don't collapse but are on the
4165     // "logical left/right" side of the child box.  We can just return the raw margin in this case.
4166     return marginAfterForChild(child);
4167 }
4168
4169 bool RenderBlock::hasMarginBeforeQuirk(const RenderBox* child) const
4170 {
4171     // If the child has the same directionality as we do, then we can just return its
4172     // margin quirk.
4173     if (!child->isWritingModeRoot())
4174         return child->isRenderBlock() ? toRenderBlock(child)->hasMarginBeforeQuirk() : child->style()->hasMarginBeforeQuirk();
4175
4176     // The child has a different directionality. If the child is parallel, then it's just
4177     // flipped relative to us. We can use the opposite edge.
4178     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4179         return child->isRenderBlock() ? toRenderBlock(child)->hasMarginAfterQuirk() : child->style()->hasMarginAfterQuirk();
4180
4181     // The child is perpendicular to us and box sides are never quirky in html.css, and we don't really care about
4182     // whether or not authors specified quirky ems, since they're an implementation detail.
4183     return false;
4184 }
4185
4186 bool RenderBlock::hasMarginAfterQuirk(const RenderBox* child) const
4187 {
4188     // If the child has the same directionality as we do, then we can just return its
4189     // margin quirk.
4190     if (!child->isWritingModeRoot())
4191         return child->isRenderBlock() ? toRenderBlock(child)->hasMarginAfterQuirk() : child->style()->hasMarginAfterQuirk();
4192
4193     // The child has a different directionality. If the child is parallel, then it's just
4194     // flipped relative to us. We can use the opposite edge.
4195     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4196         return child->isRenderBlock() ? toRenderBlock(child)->hasMarginBeforeQuirk() : child->style()->hasMarginBeforeQuirk();
4197
4198     // The child is perpendicular to us and box sides are never quirky in html.css, and we don't really care about
4199     // whether or not authors specified quirky ems, since they're an implementation detail.
4200     return false;
4201 }
4202
4203 const char* RenderBlock::renderName() const
4204 {
4205     if (isBody())
4206         return "RenderBody"; // FIXME: Temporary hack until we know that the regression tests pass.
4207     if (isFloating())
4208         return "RenderBlock (floating)";
4209     if (isOutOfFlowPositioned())
4210         return "RenderBlock (positioned)";
4211     if (style()) {
4212         if (isAnonymousColumnsBlock())
4213             return "RenderBlock (anonymous multi-column)";
4214         if (isAnonymousColumnSpanBlock())
4215             return "RenderBlock (anonymous multi-column span)";
4216         if (isAnonymousBlock())
4217             return "RenderBlock (anonymous)";
4218     }
4219     if (isAnonymous())
4220         return "RenderBlock (generated)";
4221     if (isRelPositioned())
4222         return "RenderBlock (relative positioned)";
4223     return "RenderBlock";
4224 }
4225
4226 RenderBlock* RenderBlock::createAnonymousWithParentRendererAndDisplay(const RenderObject* parent, EDisplay display)
4227 {
4228     // FIXME: Do we need to convert all our inline displays to block-type in the anonymous logic ?
4229     EDisplay newDisplay;
4230     RenderBlock* newBox = 0;
4231     if (display == FLEX || display == INLINE_FLEX) {
4232         newBox = RenderFlexibleBox::createAnonymous(&parent->document());
4233         newDisplay = FLEX;
4234     } else {
4235         newBox = RenderBlockFlow::createAnonymous(&parent->document());
4236         newDisplay = BLOCK;
4237     }
4238
4239     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), newDisplay);
4240     parent->updateAnonymousChildStyle(newBox, newStyle.get());
4241     newBox->setStyle(newStyle.release());
4242     return newBox;
4243 }
4244
4245 RenderBlockFlow* RenderBlock::createAnonymousColumnsWithParentRenderer(const RenderObject* parent)
4246 {
4247     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
4248     newStyle->inheritColumnPropertiesFrom(parent->style());
4249
4250     RenderBlockFlow* newBox = RenderBlockFlow::createAnonymous(&parent->document());
4251     parent->updateAnonymousChildStyle(newBox, newStyle.get());
4252     newBox->setStyle(newStyle.release());
4253     return newBox;
4254 }
4255
4256 RenderBlockFlow* RenderBlock::createAnonymousColumnSpanWithParentRenderer(const RenderObject* parent)
4257 {
4258     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
4259     newStyle->setColumnSpan(ColumnSpanAll);
4260
4261     RenderBlockFlow* newBox = RenderBlockFlow::createAnonymous(&parent->document());
4262     parent->updateAnonymousChildStyle(newBox, newStyle.get());
4263     newBox->setStyle(newStyle.release());
4264     return newBox;
4265 }
4266
4267 static bool recalcNormalFlowChildOverflowIfNeeded(RenderObject* renderer)
4268 {
4269     if (renderer->isOutOfFlowPositioned() || !renderer->needsOverflowRecalcAfterStyleChange())
4270         return false;
4271
4272     ASSERT(renderer->isRenderBlock());
4273     return toRenderBlock(renderer)->recalcOverflowAfterStyleChange();
4274 }
4275
4276 bool RenderBlock::recalcChildOverflowAfterStyleChange()
4277 {
4278     ASSERT(childNeedsOverflowRecalcAfterStyleChange());
4279     setChildNeedsOverflowRecalcAfterStyleChange(false);
4280
4281     bool childrenOverflowChanged = false;
4282
4283     if (childrenInline()) {
4284         ListHashSet<RootInlineBox*> lineBoxes;
4285         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
4286             RenderObject* renderer = walker.current();
4287             if (recalcNormalFlowChildOverflowIfNeeded(renderer)) {
4288                 childrenOverflowChanged = true;
4289                 if (InlineBox* inlineBoxWrapper = toRenderBlock(renderer)->inlineBoxWrapper())
4290                     lineBoxes.add(&inlineBoxWrapper->root());
4291             }
4292         }
4293
4294         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
4295         GlyphOverflowAndFallbackFontsMap textBoxDataMap;
4296         for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
4297             RootInlineBox* box = *it;
4298             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
4299         }
4300     } else {
4301         for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
4302             if (recalcNormalFlowChildOverflowIfNeeded(box))
4303                 childrenOverflowChanged = true;
4304         }
4305     }
4306
4307     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
4308     if (!positionedDescendants)
4309         return childrenOverflowChanged;
4310
4311     TrackedRendererListHashSet::iterator end = positionedDescendants->end();
4312     for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
4313         RenderBox* box = *it;
4314
4315         if (!box->needsOverflowRecalcAfterStyleChange())
4316             continue;
4317         RenderBlock* block = toRenderBlock(box);
4318         if (!block->recalcOverflowAfterStyleChange() || box->style()->position() == FixedPosition)
4319             continue;
4320
4321         childrenOverflowChanged = true;
4322     }
4323     return childrenOverflowChanged;
4324 }
4325
4326 bool RenderBlock::recalcOverflowAfterStyleChange()
4327 {
4328     ASSERT(needsOverflowRecalcAfterStyleChange());
4329
4330     bool childrenOverflowChanged = false;
4331     if (childNeedsOverflowRecalcAfterStyleChange())
4332         childrenOverflowChanged = recalcChildOverflowAfterStyleChange();
4333
4334     if (!selfNeedsOverflowRecalcAfterStyleChange() && !childrenOverflowChanged)
4335         return false;
4336
4337     setSelfNeedsOverflowRecalcAfterStyleChange(false);
4338     // If the current block needs layout, overflow will be recalculated during
4339     // layout time anyway. We can safely exit here.
4340     if (needsLayout())
4341         return false;
4342
4343     LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
4344     computeOverflow(oldClientAfterEdge, true);
4345
4346     if (hasOverflowClip())
4347         layer()->scrollableArea()->updateAfterOverflowRecalc();
4348
4349     return !hasOverflowClip();
4350 }
4351
4352 #if ENABLE(ASSERT)
4353 void RenderBlock::checkPositionedObjectsNeedLayout()
4354 {
4355     if (!gPositionedDescendantsMap)
4356         return;
4357
4358     if (TrackedRendererListHashSet* positionedDescendantSet = positionedObjects()) {
4359         TrackedRendererListHashSet::const_iterator end = positionedDescendantSet->end();
4360         for (TrackedRendererListHashSet::const_iterator it = positionedDescendantSet->begin(); it != end; ++it) {
4361             RenderBox* currBox = *it;
4362             ASSERT(!currBox->needsLayout());
4363         }
4364     }
4365 }
4366
4367 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
4368 {
4369     ContinuationOutlineTableMap* table = continuationOutlineTable();
4370     if (table->isEmpty())
4371         return false;
4372
4373     ListHashSet<RenderInline*>* continuations = table->get(this);
4374     if (!continuations)
4375         return false;
4376
4377     return continuations->contains(flow);
4378 }
4379
4380 #endif
4381
4382 #ifndef NDEBUG
4383
4384 void RenderBlock::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj) const
4385 {
4386     showRenderObject();
4387     for (const RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox())
4388         root->showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj, 1);
4389 }
4390
4391 #endif
4392
4393 } // namespace blink