[CSS Grid Layout] Ignore ::first-letter pseudo-element
[WebKit-https.git] / Source / WebCore / rendering / RenderBlock.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2007 David Smith (catfish.man@gmail.com)
5  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6  * Copyright (C) Research In Motion Limited 2010. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #include "config.h"
25 #include "RenderBlock.h"
26
27 #include "AXObjectCache.h"
28 #include "Document.h"
29 #include "Editor.h"
30 #include "Element.h"
31 #include "FloatQuad.h"
32 #include "Frame.h"
33 #include "FrameSelection.h"
34 #include "FrameView.h"
35 #include "GraphicsContext.h"
36 #include "HTMLInputElement.h"
37 #include "HTMLNames.h"
38 #include "HitTestLocation.h"
39 #include "HitTestResult.h"
40 #include "InlineElementBox.h"
41 #include "InlineIterator.h"
42 #include "InlineTextBox.h"
43 #include "LayoutRepainter.h"
44 #include "LogicalSelectionOffsetCaches.h"
45 #include "OverflowEvent.h"
46 #include "Page.h"
47 #include "PaintInfo.h"
48 #include "RenderBlockFlow.h"
49 #include "RenderBoxRegionInfo.h"
50 #include "RenderCombineText.h"
51 #include "RenderDeprecatedFlexibleBox.h"
52 #include "RenderFlexibleBox.h"
53 #include "RenderInline.h"
54 #include "RenderIterator.h"
55 #include "RenderLayer.h"
56 #include "RenderNamedFlowFragment.h"
57 #include "RenderNamedFlowThread.h"
58 #include "RenderRegion.h"
59 #include "RenderTableCell.h"
60 #include "RenderTextFragment.h"
61 #include "RenderTheme.h"
62 #include "RenderView.h"
63 #include "SVGTextRunRenderingContext.h"
64 #include "Settings.h"
65 #include "ShadowRoot.h"
66 #include "TextBreakIterator.h"
67 #include "TransformState.h"
68 #include <wtf/NeverDestroyed.h>
69 #include <wtf/StackStats.h>
70 #include <wtf/TemporaryChange.h>
71
72 #if ENABLE(CSS_SHAPES)
73 #include "ShapeOutsideInfo.h"
74 #endif
75
76 using namespace WTF;
77 using namespace Unicode;
78
79 namespace WebCore {
80
81 using namespace HTMLNames;
82
83 struct SameSizeAsRenderBlock : public RenderBox {
84     uint32_t bitfields;
85 };
86
87 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
88
89 static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
90 static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
91
92 static TrackedContainerMap* gPositionedContainerMap = 0;
93 static TrackedContainerMap* gPercentHeightContainerMap = 0;
94     
95 typedef HashMap<RenderBlock*, std::unique_ptr<ListHashSet<RenderInline*>>> ContinuationOutlineTableMap;
96
97 struct UpdateScrollInfoAfterLayoutTransaction {
98     UpdateScrollInfoAfterLayoutTransaction(const RenderView& view)
99         : nestedCount(0)
100         , view(&view)
101     {
102     }
103
104     int nestedCount;
105     const RenderView* view;
106     HashSet<RenderBlock*> blocks;
107 };
108
109 typedef Vector<UpdateScrollInfoAfterLayoutTransaction> DelayedUpdateScrollInfoStack;
110 static std::unique_ptr<DelayedUpdateScrollInfoStack>& updateScrollInfoAfterLayoutTransactionStack()
111 {
112     static NeverDestroyed<std::unique_ptr<DelayedUpdateScrollInfoStack>> delayedUpdatedScrollInfoStack;
113     return delayedUpdatedScrollInfoStack;
114 }
115
116 // Allocated only when some of these fields have non-default values
117
118 struct RenderBlockRareData {
119     WTF_MAKE_NONCOPYABLE(RenderBlockRareData); WTF_MAKE_FAST_ALLOCATED;
120 public:
121     RenderBlockRareData() 
122         : m_paginationStrut(0)
123         , m_pageLogicalOffset(0)
124     { 
125     }
126
127     LayoutUnit m_paginationStrut;
128     LayoutUnit m_pageLogicalOffset;
129 };
130
131 typedef HashMap<const RenderBlock*, std::unique_ptr<RenderBlockRareData>> RenderBlockRareDataMap;
132 static RenderBlockRareDataMap* gRareDataMap = 0;
133
134 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
135 // only works on RenderBlocks. If this change, this class should be shared with other RenderBoxes.
136 class OverflowEventDispatcher {
137     WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
138 public:
139     OverflowEventDispatcher(const RenderBlock* block)
140         : m_block(block)
141         , m_hadHorizontalLayoutOverflow(false)
142         , m_hadVerticalLayoutOverflow(false)
143     {
144         m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document().hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
145         if (m_shouldDispatchEvent) {
146             m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
147             m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
148         }
149     }
150
151     ~OverflowEventDispatcher()
152     {
153         if (!m_shouldDispatchEvent)
154             return;
155
156         bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
157         bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
158
159         bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
160         bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
161         if (!horizontalLayoutOverflowChanged && !verticalLayoutOverflowChanged)
162             return;
163
164         RefPtr<OverflowEvent> overflowEvent = OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow);
165         overflowEvent->setTarget(m_block->element());
166         m_block->document().enqueueOverflowEvent(overflowEvent.release());
167     }
168
169 private:
170     const RenderBlock* m_block;
171     bool m_shouldDispatchEvent;
172     bool m_hadHorizontalLayoutOverflow;
173     bool m_hadVerticalLayoutOverflow;
174 };
175
176 RenderBlock::RenderBlock(Element& element, PassRef<RenderStyle> style, unsigned baseTypeFlags)
177     : RenderBox(element, WTF::move(style), baseTypeFlags | RenderBlockFlag)
178     , m_lineHeight(-1)
179     , m_hasMarginBeforeQuirk(false)
180     , m_hasMarginAfterQuirk(false)
181     , m_beingDestroyed(false)
182     , m_hasMarkupTruncation(false)
183     , m_hasBorderOrPaddingLogicalWidthChanged(false)
184     , m_lineLayoutPath(UndeterminedPath)
185 {
186 }
187
188 RenderBlock::RenderBlock(Document& document, PassRef<RenderStyle> style, unsigned baseTypeFlags)
189     : RenderBox(document, WTF::move(style), baseTypeFlags | RenderBlockFlag)
190     , m_lineHeight(-1)
191     , m_hasMarginBeforeQuirk(false)
192     , m_hasMarginAfterQuirk(false)
193     , m_beingDestroyed(false)
194     , m_hasMarkupTruncation(false)
195     , m_hasBorderOrPaddingLogicalWidthChanged(false)
196     , m_lineLayoutPath(UndeterminedPath)
197 {
198 }
199
200 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
201 {
202     if (std::unique_ptr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
203         TrackedRendererListHashSet::iterator end = descendantSet->end();
204         for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
205             TrackedContainerMap::iterator it = containerMap->find(*descendant);
206             ASSERT(it != containerMap->end());
207             if (it == containerMap->end())
208                 continue;
209             HashSet<RenderBlock*>* containerSet = it->value.get();
210             ASSERT(containerSet->contains(block));
211             containerSet->remove(block);
212             if (containerSet->isEmpty())
213                 containerMap->remove(it);
214         }
215     }
216 }
217
218 RenderBlock::~RenderBlock()
219 {
220     if (gRareDataMap)
221         gRareDataMap->remove(this);
222     if (gPercentHeightDescendantsMap)
223         removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
224     if (gPositionedDescendantsMap)
225         removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
226 }
227
228 bool RenderBlock::hasRareData() const
229 {
230     return gRareDataMap ? gRareDataMap->contains(this) : false;
231 }
232
233 void RenderBlock::willBeDestroyed()
234 {
235     // Mark as being destroyed to avoid trouble with merges in removeChild().
236     m_beingDestroyed = true;
237
238     // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
239     // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
240     destroyLeftoverChildren();
241
242     // Destroy our continuation before anything other than anonymous children.
243     // The reason we don't destroy it before anonymous children is that they may
244     // have continuations of their own that are anonymous children of our continuation.
245     RenderBoxModelObject* continuation = this->continuation();
246     if (continuation) {
247         continuation->destroy();
248         setContinuation(0);
249     }
250     
251     if (!documentBeingDestroyed()) {
252         if (parent())
253             parent()->dirtyLinesFromChangedChild(this);
254     }
255
256     removeFromUpdateScrollInfoAfterLayoutTransaction();
257
258     RenderBox::willBeDestroyed();
259 }
260
261 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
262 {
263     const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
264
265     setReplaced(newStyle.isDisplayInlineType());
266     
267     if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle.position()) {
268         if (newStyle.position() == StaticPosition)
269             // Clear our positioned objects list. Our absolutely positioned descendants will be
270             // inserted into our containing block's positioned objects list during layout.
271             removePositionedObjects(0, NewContainingBlock);
272         else if (oldStyle->position() == StaticPosition) {
273             // Remove our absolutely positioned descendants from their current containing block.
274             // They will be inserted into our positioned objects list during layout.
275             auto cb = parent();
276             while (cb && (cb->style().position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
277                 if (cb->style().position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
278                     cb = cb->containingBlock();
279                     break;
280                 }
281                 cb = cb->parent();
282             }
283             
284             if (cb->isRenderBlock())
285                 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
286         }
287     }
288
289     RenderBox::styleWillChange(diff, newStyle);
290 }
291
292 static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
293 {
294     if (newStyle->isHorizontalWritingMode())
295         return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
296             || oldStyle->borderRightWidth() != newStyle->borderRightWidth()
297             || oldStyle->paddingLeft() != newStyle->paddingLeft()
298             || oldStyle->paddingRight() != newStyle->paddingRight();
299
300     return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
301         || oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
302         || oldStyle->paddingTop() != newStyle->paddingTop()
303         || oldStyle->paddingBottom() != newStyle->paddingBottom();
304 }
305
306 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
307 {
308     RenderBox::styleDidChange(diff, oldStyle);
309     
310     RenderStyle& newStyle = style();
311
312     if (!isAnonymousBlock()) {
313         // Ensure that all of our continuation blocks pick up the new style.
314         for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
315             RenderBoxModelObject* nextCont = currCont->continuation();
316             currCont->setContinuation(0);
317             currCont->setStyle(newStyle);
318             currCont->setContinuation(nextCont);
319         }
320     }
321
322     propagateStyleToAnonymousChildren(PropagateToBlockChildrenOnly);
323     m_lineHeight = -1;
324     
325     // It's possible for our border/padding to change, but for the overall logical width of the block to
326     // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
327     m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, &newStyle);
328 }
329
330 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
331 {
332     if (beforeChild && beforeChild->parent() == this)
333         return this;
334
335     RenderBlock* curr = toRenderBlock(continuation());
336     RenderBlock* nextToLast = this;
337     RenderBlock* last = this;
338     while (curr) {
339         if (beforeChild && beforeChild->parent() == curr) {
340             if (curr->firstChild() == beforeChild)
341                 return last;
342             return curr;
343         }
344
345         nextToLast = last;
346         last = curr;
347         curr = toRenderBlock(curr->continuation());
348     }
349
350     if (!beforeChild && !last->firstChild())
351         return nextToLast;
352     return last;
353 }
354
355 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
356 {
357     RenderBlock* flow = continuationBefore(beforeChild);
358     ASSERT(!beforeChild || beforeChild->parent()->isRenderBlock());
359     RenderBoxModelObject* beforeChildParent = 0;
360     if (beforeChild)
361         beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
362     else {
363         RenderBoxModelObject* cont = flow->continuation();
364         if (cont)
365             beforeChildParent = cont;
366         else
367             beforeChildParent = flow;
368     }
369
370     if (newChild->isFloatingOrOutOfFlowPositioned()) {
371         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
372         return;
373     }
374
375     bool childIsNormal = newChild->isInline() || !newChild->style().columnSpan();
376     bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style().columnSpan();
377     bool flowIsNormal = flow->isInline() || !flow->style().columnSpan();
378
379     if (flow == beforeChildParent) {
380         flow->addChildIgnoringContinuation(newChild, beforeChild);
381         return;
382     }
383     
384     // The goal here is to match up if we can, so that we can coalesce and create the
385     // minimal # of continuations needed for the inline.
386     if (childIsNormal == bcpIsNormal) {
387         beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
388         return;
389     }
390     if (flowIsNormal == childIsNormal) {
391         flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
392         return;
393     }
394     beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
395 }
396
397 RenderPtr<RenderBlock> RenderBlock::clone() const
398 {
399     RenderPtr<RenderBlock> cloneBlock;
400     if (isAnonymousBlock()) {
401         cloneBlock = RenderPtr<RenderBlock>(createAnonymousBlock());
402         cloneBlock->setChildrenInline(childrenInline());
403     } else {
404         cloneBlock = static_pointer_cast<RenderBlock>(element()->createElementRenderer(style()));
405         cloneBlock->initializeStyle();
406
407         // This takes care of setting the right value of childrenInline in case
408         // generated content is added to cloneBlock and 'this' does not have
409         // generated content added yet.
410         cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
411     }
412     cloneBlock->setFlowThreadState(flowThreadState());
413     return cloneBlock;
414 }
415
416 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
417                               RenderBlock* middleBlock,
418                               RenderObject* beforeChild, RenderBoxModelObject* oldCont)
419 {
420     // Create a clone of this inline.
421     RenderPtr<RenderBlock> cloneBlock = clone();
422     if (!isAnonymousBlock())
423         cloneBlock->setContinuation(oldCont);
424
425     if (!beforeChild && isAfterContent(lastChild()))
426         beforeChild = lastChild();
427
428     // If we are moving inline children from |this| to cloneBlock, then we need
429     // to clear our line box tree.
430     if (beforeChild && childrenInline())
431         deleteLines();
432
433     // Now take all of the children from beforeChild to the end and remove
434     // them from |this| and place them in the clone.
435     moveChildrenTo(cloneBlock.get(), beforeChild, 0, true);
436     
437     // Hook |clone| up as the continuation of the middle block.
438     if (!cloneBlock->isAnonymousBlock())
439         middleBlock->setContinuation(cloneBlock.get());
440
441     // We have been reparented and are now under the fromBlock.  We need
442     // to walk up our block parent chain until we hit the containing anonymous columns block.
443     // Once we hit the anonymous columns block we're done.
444     RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
445     RenderBoxModelObject* currChild = this;
446     RenderObject* currChildNextSibling = currChild->nextSibling();
447
448     while (curr && curr->isDescendantOf(fromBlock) && curr != fromBlock) {
449         RenderBlock* blockCurr = toRenderBlock(curr);
450         
451         // Create a new clone.
452         RenderPtr<RenderBlock> cloneChild = WTF::move(cloneBlock);
453         cloneBlock = blockCurr->clone();
454
455         // Insert our child clone as the first child.
456         cloneBlock->addChildIgnoringContinuation(cloneChild.leakPtr(), 0);
457
458         // Hook the clone up as a continuation of |curr|.  Note we do encounter
459         // anonymous blocks possibly as we walk up the block chain.  When we split an
460         // anonymous block, there's no need to do any continuation hookup, since we haven't
461         // actually split a real element.
462         if (!blockCurr->isAnonymousBlock()) {
463             oldCont = blockCurr->continuation();
464             blockCurr->setContinuation(cloneBlock.get());
465             cloneBlock->setContinuation(oldCont);
466         }
467
468         // Now we need to take all of the children starting from the first child
469         // *after* currChild and append them all to the clone.
470         blockCurr->moveChildrenTo(cloneBlock.get(), currChildNextSibling, 0, true);
471
472         // Keep walking up the chain.
473         currChild = curr;
474         currChildNextSibling = currChild->nextSibling();
475         curr = toRenderBoxModelObject(curr->parent());
476     }
477
478     // Now we are at the columns block level. We need to put the clone into the toBlock.
479     toBlock->insertChildInternal(cloneBlock.leakPtr(), nullptr, NotifyChildren);
480
481     // Now take all the children after currChild and remove them from the fromBlock
482     // and put them in the toBlock.
483     if (currChildNextSibling && currChildNextSibling->parent() == fromBlock)
484         fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
485 }
486
487 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
488 {
489     if (continuation() && !isAnonymousBlock())
490         addChildToContinuation(newChild, beforeChild);
491     else
492         addChildIgnoringContinuation(newChild, beforeChild);
493 }
494
495 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
496 {
497     if (beforeChild && beforeChild->parent() != this) {
498         RenderElement* beforeChildContainer = beforeChild->parent();
499         while (beforeChildContainer->parent() != this)
500             beforeChildContainer = beforeChildContainer->parent();
501         ASSERT(beforeChildContainer);
502
503         if (beforeChildContainer->isAnonymous()) {
504             // If the requested beforeChild is not one of our children, then this is because
505             // there is an anonymous container within this object that contains the beforeChild.
506             RenderElement* beforeChildAnonymousContainer = beforeChildContainer;
507             if (beforeChildAnonymousContainer->isAnonymousBlock()
508 #if ENABLE(FULLSCREEN_API)
509                 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
510                 || beforeChildAnonymousContainer->isRenderFullScreen()
511                 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
512 #endif
513                 ) {
514                 // Insert the child into the anonymous block box instead of here.
515                 if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
516                     beforeChild->parent()->addChild(newChild, beforeChild);
517                 else
518                     addChild(newChild, beforeChild->parent());
519                 return;
520             }
521
522             ASSERT(beforeChildAnonymousContainer->isTable());
523             if (newChild->isTablePart()) {
524                 // Insert into the anonymous table.
525                 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
526                 return;
527             }
528
529             beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
530
531             ASSERT(beforeChild->parent() == this);
532             if (beforeChild->parent() != this) {
533                 // We should never reach here. If we do, we need to use the
534                 // safe fallback to use the topmost beforeChild container.
535                 beforeChild = beforeChildContainer;
536             }
537         }
538     }
539
540     bool madeBoxesNonInline = false;
541
542     // A block has to either have all of its children inline, or all of its children as blocks.
543     // So, if our children are currently inline and a block child has to be inserted, we move all our
544     // inline children into anonymous block boxes.
545     if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
546         // This is a block with inline content. Wrap the inline content in anonymous blocks.
547         makeChildrenNonInline(beforeChild);
548         madeBoxesNonInline = true;
549
550         if (beforeChild && beforeChild->parent() != this) {
551             beforeChild = beforeChild->parent();
552             ASSERT(beforeChild->isAnonymousBlock());
553             ASSERT(beforeChild->parent() == this);
554         }
555     } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
556         // If we're inserting an inline child but all of our children are blocks, then we have to make sure
557         // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
558         // a new one is created and inserted into our list of children in the appropriate position.
559         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
560
561         if (afterChild && afterChild->isAnonymousBlock()) {
562             toRenderBlock(afterChild)->addChild(newChild);
563             return;
564         }
565
566         if (newChild->isInline()) {
567             // No suitable existing anonymous box - create a new one.
568             RenderBlock* newBox = createAnonymousBlock();
569             RenderBox::addChild(newBox, beforeChild);
570             newBox->addChild(newChild);
571             return;
572         }
573     }
574
575     invalidateLineLayoutPath();
576
577     RenderBox::addChild(newChild, beforeChild);
578  
579     if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
580         toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
581     // this object may be dead here
582 }
583
584 static void getInlineRun(RenderObject* start, RenderObject* boundary,
585                          RenderObject*& inlineRunStart,
586                          RenderObject*& inlineRunEnd)
587 {
588     // Beginning at |start| we find the largest contiguous run of inlines that
589     // we can.  We denote the run with start and end points, |inlineRunStart|
590     // and |inlineRunEnd|.  Note that these two values may be the same if
591     // we encounter only one inline.
592     //
593     // We skip any non-inlines we encounter as long as we haven't found any
594     // inlines yet.
595     //
596     // |boundary| indicates a non-inclusive boundary point.  Regardless of whether |boundary|
597     // is inline or not, we will not include it in a run with inlines before it.  It's as though we encountered
598     // a non-inline.
599     
600     // Start by skipping as many non-inlines as we can.
601     RenderObject * curr = start;
602     bool sawInline;
603     do {
604         while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
605             curr = curr->nextSibling();
606         
607         inlineRunStart = inlineRunEnd = curr;
608         
609         if (!curr)
610             return; // No more inline children to be found.
611         
612         sawInline = curr->isInline();
613         
614         curr = curr->nextSibling();
615         while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
616             inlineRunEnd = curr;
617             if (curr->isInline())
618                 sawInline = true;
619             curr = curr->nextSibling();
620         }
621     } while (!sawInline);
622 }
623
624 void RenderBlock::deleteLines()
625 {
626     if (AXObjectCache* cache = document().existingAXObjectCache())
627         cache->recomputeIsIgnored(this);
628 }
629
630 void RenderBlock::makeChildrenNonInline(RenderObject* insertionPoint)
631 {    
632     // makeChildrenNonInline takes a block whose children are *all* inline and it
633     // makes sure that inline children are coalesced under anonymous
634     // blocks.  If |insertionPoint| is defined, then it represents the insertion point for
635     // the new block child that is causing us to have to wrap all the inlines.  This
636     // means that we cannot coalesce inlines before |insertionPoint| with inlines following
637     // |insertionPoint|, because the new child is going to be inserted in between the inlines,
638     // splitting them.
639     ASSERT(isInlineBlockOrInlineTable() || !isInline());
640     ASSERT(!insertionPoint || insertionPoint->parent() == this);
641
642     setChildrenInline(false);
643
644     RenderObject* child = firstChild();
645     if (!child)
646         return;
647
648     deleteLines();
649
650     while (child) {
651         RenderObject* inlineRunStart;
652         RenderObject* inlineRunEnd;
653         getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
654
655         if (!inlineRunStart)
656             break;
657
658         child = inlineRunEnd->nextSibling();
659
660         RenderBlock* block = createAnonymousBlock();
661         insertChildInternal(block, inlineRunStart, NotifyChildren);
662         moveChildrenTo(block, inlineRunStart, child);
663     }
664
665 #ifndef NDEBUG
666     for (RenderObject* c = firstChild(); c; c = c->nextSibling())
667         ASSERT(!c->isInline());
668 #endif
669
670     repaint();
671 }
672
673 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
674 {
675     ASSERT(child->isAnonymousBlock());
676     ASSERT(!child->childrenInline());
677     
678     if (child->continuation())
679         return;
680     
681     RenderObject* firstAnChild = child->firstChild();
682     RenderObject* lastAnChild = child->lastChild();
683     if (firstAnChild) {
684         RenderObject* o = firstAnChild;
685         while (o) {
686             o->setParent(this);
687             o = o->nextSibling();
688         }
689         firstAnChild->setPreviousSibling(child->previousSibling());
690         lastAnChild->setNextSibling(child->nextSibling());
691         if (child->previousSibling())
692             child->previousSibling()->setNextSibling(firstAnChild);
693         if (child->nextSibling())
694             child->nextSibling()->setPreviousSibling(lastAnChild);
695             
696         if (child == firstChild())
697             setFirstChild(firstAnChild);
698         if (child == lastChild())
699             setLastChild(lastAnChild);
700     } else {
701         if (child == firstChild())
702             setFirstChild(child->nextSibling());
703         if (child == lastChild())
704             setLastChild(child->previousSibling());
705
706         if (child->previousSibling())
707             child->previousSibling()->setNextSibling(child->nextSibling());
708         if (child->nextSibling())
709             child->nextSibling()->setPreviousSibling(child->previousSibling());
710     }
711
712     child->setFirstChild(0);
713     child->m_next = 0;
714
715     // Remove all the information in the flow thread associated with the leftover anonymous block.
716     child->removeFromRenderFlowThread();
717
718     child->setParent(0);
719     child->setPreviousSibling(0);
720     child->setNextSibling(0);
721
722     child->destroy();
723 }
724
725 static bool canMergeAnonymousBlock(RenderBlock* anonymousBlock)
726 {
727     if (anonymousBlock->beingDestroyed() || anonymousBlock->continuation())
728         return false;
729     if (anonymousBlock->isRubyRun() || anonymousBlock->isRubyBase())
730         return false;
731     return true;
732 }
733
734 static bool canMergeContiguousAnonymousBlocks(RenderObject& oldChild, RenderObject* previous, RenderObject* next)
735 {
736     if (oldChild.documentBeingDestroyed() || oldChild.isInline() || oldChild.virtualContinuation())
737         return false;
738
739     if (previous) {
740         if (!previous->isAnonymousBlock())
741             return false;
742         RenderBlock* previousAnonymousBlock = toRenderBlock(previous);
743         if (!canMergeAnonymousBlock(previousAnonymousBlock))
744             return false;
745     }
746     if (next) {
747         if (!next->isAnonymousBlock())
748             return false;
749         RenderBlock* nextAnonymousBlock = toRenderBlock(next);
750         if (!canMergeAnonymousBlock(nextAnonymousBlock))
751             return false;
752     }
753     return true;
754 }
755
756 void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderBlock* child)
757 {
758     parent->setNeedsLayoutAndPrefWidthsRecalc();
759     parent->setChildrenInline(child->childrenInline());
760     RenderObject* nextSibling = child->nextSibling();
761
762     RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
763     CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
764     if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
765         toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(child);
766
767     parent->removeChildInternal(*child, child->hasLayer() ? NotifyChildren : DontNotifyChildren);
768     child->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
769     // Delete the now-empty block's lines and nuke it.
770     child->deleteLines();
771     child->destroy();
772 }
773
774 RenderObject* RenderBlock::removeChild(RenderObject& oldChild)
775 {
776     // No need to waste time in merging or removing empty anonymous blocks.
777     // We can just bail out if our document is getting destroyed.
778     if (documentBeingDestroyed())
779         return RenderBox::removeChild(oldChild);
780
781     // If this child is a block, and if our previous and next siblings are
782     // both anonymous blocks with inline content, then we can go ahead and
783     // fold the inline content back together.
784     RenderObject* prev = oldChild.previousSibling();
785     RenderObject* next = oldChild.nextSibling();
786     bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
787     if (canMergeAnonymousBlocks && prev && next) {
788         prev->setNeedsLayoutAndPrefWidthsRecalc();
789         RenderBlock* nextBlock = toRenderBlock(next);
790         RenderBlock* prevBlock = toRenderBlock(prev);
791        
792         if (prev->childrenInline() != next->childrenInline()) {
793             RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
794             RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
795             
796             // Place the inline children block inside of the block children block instead of deleting it.
797             // In order to reuse it, we have to reset it to just be a generic anonymous block.  Make sure
798             // to clear out inherited column properties by just making a new style, and to also clear the
799             // column span flag if it is set.
800             ASSERT(!inlineChildrenBlock->continuation());
801             // Cache this value as it might get changed in setStyle() call.
802             bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
803             inlineChildrenBlock->setStyle(RenderStyle::createAnonymousStyleWithDisplay(&style(), BLOCK));
804             removeChildInternal(*inlineChildrenBlock, inlineChildrenBlockHasLayer ? NotifyChildren : DontNotifyChildren);
805             
806             // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
807             RenderObject* beforeChild = prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : nullptr;
808             blockChildrenBlock->insertChildInternal(inlineChildrenBlock, beforeChild,
809                 (inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer()) ? NotifyChildren : DontNotifyChildren);
810             next->setNeedsLayoutAndPrefWidthsRecalc();
811             
812             // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
813             // of "this". we null out prev or next so that is not used later in the function.
814             if (inlineChildrenBlock == prevBlock)
815                 prev = 0;
816             else
817                 next = 0;
818         } else {
819             // Take all the children out of the |next| block and put them in
820             // the |prev| block.
821             nextBlock->moveAllChildrenIncludingFloatsTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
822             
823             // Delete the now-empty block's lines and nuke it.
824             nextBlock->deleteLines();
825             nextBlock->destroy();
826             next = 0;
827         }
828     }
829
830     invalidateLineLayoutPath();
831
832     RenderObject* nextSibling = RenderBox::removeChild(oldChild);
833
834     RenderObject* child = prev ? prev : next;
835     if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
836         // The removal has knocked us down to containing only a single anonymous
837         // box.  We can go ahead and pull the content right back up into our
838         // box.
839         collapseAnonymousBoxChild(this, toRenderBlock(child));
840         nextSibling = nullptr;
841     } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
842         // It's possible that the removal has knocked us down to a single anonymous
843         // block with pseudo-style element siblings (e.g. first-letter). If these
844         // are floating, then we need to pull the content up also.
845         RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
846         if ((anonBlock->previousSibling() || anonBlock->nextSibling())
847             && (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style().styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
848             && (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style().styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
849             collapseAnonymousBoxChild(this, anonBlock);
850             nextSibling = nullptr;
851         }
852     }
853
854     if (!firstChild()) {
855         nextSibling = nullptr;
856
857         // If this was our last child be sure to clear out our line boxes.
858         if (childrenInline())
859             deleteLines();
860
861         // If we are an empty anonymous block in the continuation chain,
862         // we need to remove ourself and fix the continuation chain.
863         if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild.isListMarker()) {
864             auto containingBlockIgnoringAnonymous = containingBlock();
865             while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymousBlock())
866                 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
867             for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
868                 if (curr->virtualContinuation() != this)
869                     continue;
870
871                 // Found our previous continuation. We just need to point it to
872                 // |this|'s next continuation.
873                 RenderBoxModelObject* nextContinuation = continuation();
874                 if (curr->isRenderInline())
875                     toRenderInline(curr)->setContinuation(nextContinuation);
876                 else if (curr->isRenderBlock())
877                     toRenderBlock(curr)->setContinuation(nextContinuation);
878                 else
879                     ASSERT_NOT_REACHED();
880
881                 break;
882             }
883             setContinuation(0);
884             destroy();
885         }
886     }
887     
888     return nextSibling;
889 }
890
891 bool RenderBlock::isSelfCollapsingBlock() const
892 {
893     // We are not self-collapsing if we
894     // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
895     // (b) are a table,
896     // (c) have border/padding,
897     // (d) have a min-height
898     // (e) have specified that one of our margins can't collapse using a CSS extension
899     if (logicalHeight() > 0
900         || isTable() || borderAndPaddingLogicalHeight()
901         || style().logicalMinHeight().isPositive()
902         || style().marginBeforeCollapse() == MSEPARATE || style().marginAfterCollapse() == MSEPARATE)
903         return false;
904
905     Length logicalHeightLength = style().logicalHeight();
906     bool hasAutoHeight = logicalHeightLength.isAuto();
907     if (logicalHeightLength.isPercent() && !document().inQuirksMode()) {
908         hasAutoHeight = true;
909         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
910             if (cb->style().logicalHeight().isFixed() || cb->isTableCell())
911                 hasAutoHeight = false;
912         }
913     }
914
915     // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
916     // on whether we have content that is all self-collapsing or not.
917     if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
918         // If the block has inline children, see if we generated any line boxes.  If we have any
919         // line boxes, then we can't be self-collapsing, since we have content.
920         if (childrenInline())
921             return !hasLines();
922         
923         // Whether or not we collapse is dependent on whether all our normal flow children
924         // are also self-collapsing.
925         for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
926             if (child->isFloatingOrOutOfFlowPositioned())
927                 continue;
928             if (!child->isSelfCollapsingBlock())
929                 return false;
930         }
931         return true;
932     }
933     return false;
934 }
935
936 static inline UpdateScrollInfoAfterLayoutTransaction* currentUpdateScrollInfoAfterLayoutTransaction()
937 {
938     if (!updateScrollInfoAfterLayoutTransactionStack())
939         return nullptr;
940     return &updateScrollInfoAfterLayoutTransactionStack()->last();
941 }
942
943 void RenderBlock::beginUpdateScrollInfoAfterLayoutTransaction()
944 {
945     if (!updateScrollInfoAfterLayoutTransactionStack())
946         updateScrollInfoAfterLayoutTransactionStack() = std::make_unique<DelayedUpdateScrollInfoStack>();
947     if (updateScrollInfoAfterLayoutTransactionStack()->isEmpty() || currentUpdateScrollInfoAfterLayoutTransaction()->view != &view())
948         updateScrollInfoAfterLayoutTransactionStack()->append(UpdateScrollInfoAfterLayoutTransaction(view()));
949     ++currentUpdateScrollInfoAfterLayoutTransaction()->nestedCount;
950 }
951
952 void RenderBlock::endAndCommitUpdateScrollInfoAfterLayoutTransaction()
953 {
954     UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
955     ASSERT(transaction);
956     ASSERT(transaction->view == &view());
957     if (--transaction->nestedCount)
958         return;
959
960     // Calling RenderLayer::updateScrollInfoAfterLayout() may cause its associated block to layout again and
961     // updates its scroll info (i.e. call RenderBlock::updateScrollInfoAfterLayout()). We remove |transaction|
962     // from the transaction stack to ensure that all subsequent calls to RenderBlock::updateScrollInfoAfterLayout()
963     // are dispatched immediately. That is, to ensure that such subsequent calls aren't added to |transaction|
964     // while we are processing it.
965     Vector<RenderBlock*> blocksToUpdate;
966     copyToVector(transaction->blocks, blocksToUpdate);
967     updateScrollInfoAfterLayoutTransactionStack()->removeLast();
968     if (updateScrollInfoAfterLayoutTransactionStack()->isEmpty())
969         updateScrollInfoAfterLayoutTransactionStack() = nullptr;
970
971     for (auto* block : blocksToUpdate) {
972         ASSERT(block->hasOverflowClip());
973         block->layer()->updateScrollInfoAfterLayout();
974         block->clearLayoutOverflow();
975     }
976 }
977
978 void RenderBlock::removeFromUpdateScrollInfoAfterLayoutTransaction()
979 {
980     if (UNLIKELY(updateScrollInfoAfterLayoutTransactionStack().get() != 0)) {
981         UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
982         ASSERT(transaction);
983         ASSERT(transaction->view == &view());
984         transaction->blocks.remove(this);
985     }
986 }
987
988 void RenderBlock::updateScrollInfoAfterLayout()
989 {
990     if (hasOverflowClip()) {
991         if (style().isFlippedBlocksWritingMode()) {
992             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=97937
993             // Workaround for now. We cannot delay the scroll info for overflow
994             // for items with opposite writing directions, as the contents needs
995             // to overflow in that direction
996             layer()->updateScrollInfoAfterLayout();
997             return;
998         }
999
1000         UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
1001         if (transaction && transaction->view == &view()) {
1002             transaction->blocks.add(this);
1003             return;
1004         }
1005         layer()->updateScrollInfoAfterLayout();
1006     }
1007 }
1008
1009 void RenderBlock::layout()
1010 {
1011     StackStats::LayoutCheckPoint layoutCheckPoint;
1012     OverflowEventDispatcher dispatcher(this);
1013
1014     // Update our first letter info now.
1015     updateFirstLetter();
1016
1017     // Table cells call layoutBlock directly, so don't add any logic here.  Put code into
1018     // layoutBlock().
1019     layoutBlock(false);
1020     
1021     // It's safe to check for control clip here, since controls can never be table cells.
1022     // If we have a lightweight clip, there can never be any overflow from children.
1023     UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
1024     bool isDelayingUpdateScrollInfoAfterLayoutInView = transaction && transaction->view == &view();
1025     if (hasControlClip() && m_overflow && !isDelayingUpdateScrollInfoAfterLayoutInView)
1026         clearLayoutOverflow();
1027
1028     invalidateBackgroundObscurationStatus();
1029 }
1030
1031 static RenderBlockRareData* getRareData(const RenderBlock* block)
1032 {
1033     return gRareDataMap ? gRareDataMap->get(block) : 0;
1034 }
1035
1036 static RenderBlockRareData& ensureRareData(const RenderBlock* block)
1037 {
1038     if (!gRareDataMap)
1039         gRareDataMap = new RenderBlockRareDataMap;
1040     
1041     auto& rareData = gRareDataMap->add(block, nullptr).iterator->value;
1042     if (!rareData)
1043         rareData = std::make_unique<RenderBlockRareData>();
1044     return *rareData.get();
1045 }
1046
1047 #if ENABLE(CSS_SHAPES)
1048 void RenderBlock::imageChanged(WrappedImagePtr image, const IntRect*)
1049 {
1050     RenderBox::imageChanged(image);
1051
1052     if (!parent() || !everHadLayout())
1053         return;
1054 }
1055 #endif
1056
1057 void RenderBlock::preparePaginationBeforeBlockLayout(bool& relayoutChildren)
1058 {
1059     // Regions changing widths can force us to relayout our children.
1060     RenderFlowThread* flowThread = flowThreadContainingBlock();
1061     if (flowThread)
1062         flowThread->logicalWidthChangedInRegionsForBlock(this, relayoutChildren);
1063 }
1064
1065 bool RenderBlock::recomputeLogicalWidth()
1066 {
1067     LayoutUnit oldWidth = logicalWidth();
1068     
1069     updateLogicalWidth();
1070     
1071     bool hasBorderOrPaddingLogicalWidthChanged = m_hasBorderOrPaddingLogicalWidthChanged;
1072     m_hasBorderOrPaddingLogicalWidthChanged = false;
1073
1074     return oldWidth != logicalWidth() || hasBorderOrPaddingLogicalWidthChanged;
1075 }
1076
1077 void RenderBlock::layoutBlock(bool, LayoutUnit)
1078 {
1079     ASSERT_NOT_REACHED();
1080     clearNeedsLayout();
1081 }
1082
1083 void RenderBlock::addOverflowFromChildren()
1084 {
1085     if (childrenInline())
1086         addOverflowFromInlineChildren();
1087     else
1088         addOverflowFromBlockChildren();
1089     
1090     // If this block is flowed inside a flow thread, make sure its overflow is propagated to the containing regions.
1091     if (m_overflow) {
1092         if (RenderFlowThread* containingFlowThread = flowThreadContainingBlock())
1093             containingFlowThread->addRegionsVisualOverflow(this, m_overflow->visualOverflowRect());
1094     }
1095 }
1096
1097 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool)
1098 {
1099     clearOverflow();
1100
1101     // Add overflow from children.
1102     addOverflowFromChildren();
1103
1104     // Add in the overflow from positioned objects.
1105     addOverflowFromPositionedObjects();
1106
1107     if (hasOverflowClip()) {
1108         // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1109         // and bottom padding.  Set the axis we don't care about to be 1, since we want this overflow to always
1110         // be considered reachable.
1111         LayoutRect clientRect(flippedClientBoxRect());
1112         LayoutRect rectToApply;
1113         if (isHorizontalWritingMode())
1114             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1115         else
1116             rectToApply = LayoutRect(clientRect.x(), clientRect.y(), std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1117         addLayoutOverflow(rectToApply);
1118         if (hasRenderOverflow())
1119             m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
1120     }
1121         
1122     // Add visual overflow from box-shadow and border-image-outset.
1123     addVisualEffectOverflow();
1124
1125     // Add visual overflow from theme.
1126     addVisualOverflowFromTheme();
1127 }
1128
1129 void RenderBlock::clearLayoutOverflow()
1130 {
1131     if (!m_overflow)
1132         return;
1133     
1134     if (visualOverflowRect() == borderBoxRect()) {
1135         // FIXME: Implement complete solution for regions overflow.
1136         clearOverflow();
1137         return;
1138     }
1139     
1140     m_overflow->setLayoutOverflow(borderBoxRect());
1141 }
1142
1143 void RenderBlock::addOverflowFromBlockChildren()
1144 {
1145     for (auto child = firstChildBox(); child; child = child->nextSiblingBox()) {
1146         if (!child->isFloatingOrOutOfFlowPositioned())
1147             addOverflowFromChild(child);
1148     }
1149 }
1150
1151 void RenderBlock::addOverflowFromPositionedObjects()
1152 {
1153     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1154     if (!positionedDescendants)
1155         return;
1156
1157     for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
1158         RenderBox* positionedObject = *it;
1159         
1160         // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1161         if (positionedObject->style().position() != FixedPosition) {
1162             LayoutUnit x = positionedObject->x();
1163             if (style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1164                 x -= verticalScrollbarWidth();
1165             addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
1166         }
1167     }
1168 }
1169
1170 void RenderBlock::addVisualOverflowFromTheme()
1171 {
1172     if (!style().hasAppearance())
1173         return;
1174
1175     FloatRect inflatedRect = borderBoxRect();
1176     theme().adjustRepaintRect(*this, inflatedRect);
1177     addVisualOverflow(snappedIntRect(LayoutRect(inflatedRect)));
1178
1179     if (RenderFlowThread* flowThread = flowThreadContainingBlock())
1180         flowThread->addRegionsVisualOverflowFromTheme(this);
1181 }
1182
1183 bool RenderBlock::expandsToEncloseOverhangingFloats() const
1184 {
1185     return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBoxIncludingDeprecated())
1186         || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot() || isRenderFlowThread();
1187 }
1188
1189 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox& child, LayoutUnit childMarginStart, RenderRegion* region)
1190 {
1191     LayoutUnit startPosition = startOffsetForContent(region);
1192
1193     // Add in our start margin.
1194     LayoutUnit oldPosition = startPosition + childMarginStart;
1195     LayoutUnit newPosition = oldPosition;
1196
1197     LayoutUnit blockOffset = logicalTopForChild(child);
1198     if (region)
1199         blockOffset = std::max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
1200
1201     LayoutUnit startOff = startOffsetForLineInRegion(blockOffset, false, region, logicalHeightForChild(child));
1202
1203     if (style().textAlign() != WEBKIT_CENTER && !child.style().marginStartUsing(&style()).isAuto()) {
1204         if (childMarginStart < 0)
1205             startOff += childMarginStart;
1206         newPosition = std::max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
1207     } else if (startOff != startPosition)
1208         newPosition = startOff + childMarginStart;
1209
1210     return newPosition - oldPosition;
1211 }
1212
1213 void RenderBlock::setLogicalLeftForChild(RenderBox& child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
1214 {
1215     if (isHorizontalWritingMode()) {
1216         if (applyDelta == ApplyLayoutDelta)
1217             view().addLayoutDelta(LayoutSize(child.x() - logicalLeft, 0));
1218         child.setX(logicalLeft);
1219     } else {
1220         if (applyDelta == ApplyLayoutDelta)
1221             view().addLayoutDelta(LayoutSize(0, child.y() - logicalLeft));
1222         child.setY(logicalLeft);
1223     }
1224 }
1225
1226 void RenderBlock::setLogicalTopForChild(RenderBox& child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
1227 {
1228     if (isHorizontalWritingMode()) {
1229         if (applyDelta == ApplyLayoutDelta)
1230             view().addLayoutDelta(LayoutSize(0, child.y() - logicalTop));
1231         child.setY(logicalTop);
1232     } else {
1233         if (applyDelta == ApplyLayoutDelta)
1234             view().addLayoutDelta(LayoutSize(child.x() - logicalTop, 0));
1235         child.setX(logicalTop);
1236     }
1237 }
1238
1239 void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox& child)
1240 {
1241     // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
1242     // an auto value. Add a method to determine this, so that we can avoid the relayout.
1243     if (relayoutChildren || (child.hasRelativeLogicalHeight() && !isRenderView()))
1244         child.setChildNeedsLayout(MarkOnlyThis);
1245
1246     // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1247     if (relayoutChildren && child.needsPreferredWidthsRecalculation())
1248         child.setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
1249 }
1250
1251 void RenderBlock::dirtyForLayoutFromPercentageHeightDescendants()
1252 {
1253     if (!gPercentHeightDescendantsMap)
1254         return;
1255
1256     TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this);
1257     if (!descendants)
1258         return;
1259
1260     for (auto it = descendants->begin(), end = descendants->end(); it != end; ++it) {
1261         RenderBox* box = *it;
1262         while (box != this) {
1263             if (box->normalChildNeedsLayout())
1264                 break;
1265             box->setChildNeedsLayout(MarkOnlyThis);
1266             
1267             // If the width of an image is affected by the height of a child (e.g., an image with an aspect ratio),
1268             // then we have to dirty preferred widths, since even enclosing blocks can become dirty as a result.
1269             // (A horizontal flexbox that contains an inline image wrapped in an anonymous block for example.)
1270             if (box->hasAspectRatio()) 
1271                 box->setPreferredLogicalWidthsDirty(true);
1272             
1273             box = box->containingBlock();
1274             ASSERT(box);
1275             if (!box)
1276                 break;
1277         }
1278     }
1279 }
1280
1281 void RenderBlock::simplifiedNormalFlowLayout()
1282 {
1283     if (childrenInline()) {
1284         ListHashSet<RootInlineBox*> lineBoxes;
1285         for (InlineWalker walker(*this); !walker.atEnd(); walker.advance()) {
1286             RenderObject* o = walker.current();
1287             if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
1288                 RenderBox& box = toRenderBox(*o);
1289                 box.layoutIfNeeded();
1290                 if (box.inlineBoxWrapper())
1291                     lineBoxes.add(&box.inlineBoxWrapper()->root());
1292             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
1293                 o->clearNeedsLayout();
1294         }
1295
1296         // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
1297         // FIXME: Find a way to invalidate the knownToHaveNoOverflow flag on the InlineBoxes.
1298         GlyphOverflowAndFallbackFontsMap textBoxDataMap;                  
1299         for (auto it = lineBoxes.begin(), end = lineBoxes.end(); it != end; ++it) {
1300             RootInlineBox* box = *it;
1301             box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
1302         }
1303     } else {
1304         for (auto box = firstChildBox(); box; box = box->nextSiblingBox()) {
1305             if (!box->isOutOfFlowPositioned())
1306                 box->layoutIfNeeded();
1307         }
1308     }
1309 }
1310
1311 bool RenderBlock::simplifiedLayout()
1312 {
1313     if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
1314         return false;
1315
1316     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
1317     
1318     if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
1319         return false;
1320
1321     // Lay out positioned descendants or objects that just need to recompute overflow.
1322     if (needsSimplifiedNormalFlowLayout())
1323         simplifiedNormalFlowLayout();
1324
1325     // Make sure a forced break is applied after the content if we are a flow thread in a simplified layout.
1326     // This ensures the size information is correctly computed for the last auto-height region receiving content.
1327     if (isRenderFlowThread())
1328         toRenderFlowThread(this)->applyBreakAfterContent(clientLogicalBottom());
1329
1330     // Lay out our positioned objects if our positioned child bit is set.
1331     // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
1332     // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the 
1333     // relative positioned container. So if we can have fixed pos objects in our positioned objects list check if any of them
1334     // are statically positioned and thus need to move with their absolute ancestors.
1335     bool canContainFixedPosObjects = canContainFixedPositionObjects();
1336     if (posChildNeedsLayout() || canContainFixedPosObjects)
1337         layoutPositionedObjects(false, !posChildNeedsLayout() && canContainFixedPosObjects);
1338
1339     // Recompute our overflow information.
1340     // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
1341     // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
1342     // For now just always recompute overflow.  This is no worse performance-wise than the old code that called rightmostPosition and
1343     // lowestPosition on every relayout so it's not a regression.
1344     // computeOverflow expects the bottom edge before we clamp our height. Since this information isn't available during
1345     // simplifiedLayout, we cache the value in m_overflow.
1346     LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
1347     computeOverflow(oldClientAfterEdge, true);
1348
1349     statePusher.pop();
1350     
1351     updateLayerTransform();
1352
1353     updateScrollInfoAfterLayout();
1354
1355     clearNeedsLayout();
1356     return true;
1357 }
1358
1359 void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject& child)
1360 {
1361     if (child.style().position() != FixedPosition)
1362         return;
1363
1364     bool hasStaticBlockPosition = child.style().hasStaticBlockPosition(isHorizontalWritingMode());
1365     bool hasStaticInlinePosition = child.style().hasStaticInlinePosition(isHorizontalWritingMode());
1366     if (!hasStaticBlockPosition && !hasStaticInlinePosition)
1367         return;
1368
1369     auto o = child.parent();
1370     while (o && !o->isRenderView() && o->style().position() != AbsolutePosition)
1371         o = o->parent();
1372     if (o->style().position() != AbsolutePosition)
1373         return;
1374
1375     RenderBox& box = toRenderBox(child);
1376     if (hasStaticInlinePosition) {
1377         LogicalExtentComputedValues computedValues;
1378         box.computeLogicalWidthInRegion(computedValues);
1379         LayoutUnit newLeft = computedValues.m_position;
1380         if (newLeft != box.logicalLeft())
1381             box.setChildNeedsLayout(MarkOnlyThis);
1382     } else if (hasStaticBlockPosition) {
1383         LayoutUnit oldTop = box.logicalTop();
1384         box.updateLogicalHeight();
1385         if (box.logicalTop() != oldTop)
1386             box.setChildNeedsLayout(MarkOnlyThis);
1387     }
1388 }
1389
1390 LayoutUnit RenderBlock::marginIntrinsicLogicalWidthForChild(RenderBox& child) const
1391 {
1392     // A margin has three types: fixed, percentage, and auto (variable).
1393     // Auto and percentage margins become 0 when computing min/max width.
1394     // Fixed margins can be added in as is.
1395     Length marginLeft = child.style().marginStartUsing(&style());
1396     Length marginRight = child.style().marginEndUsing(&style());
1397     LayoutUnit margin = 0;
1398     if (marginLeft.isFixed())
1399         margin += marginLeft.value();
1400     if (marginRight.isFixed())
1401         margin += marginRight.value();
1402     return margin;
1403 }
1404
1405 void RenderBlock::layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly)
1406 {
1407     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1408     if (!positionedDescendants)
1409         return;
1410
1411     for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
1412         RenderBox& r = **it;
1413         
1414         estimateRegionRangeForBoxChild(r);
1415
1416         // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
1417         // 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. 
1418         // it has static position.
1419         markFixedPositionObjectForLayoutIfNeeded(r);
1420         if (fixedPositionObjectsOnly) {
1421             r.layoutIfNeeded();
1422             continue;
1423         }
1424
1425         // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
1426         // non-positioned block.  Rather than trying to detect all of these movement cases, we just always lay out positioned
1427         // objects that are positioned implicitly like this.  Such objects are rare, and so in typical DHTML menu usage (where everything is
1428         // positioned explicitly) this should not incur a performance penalty.
1429         if (relayoutChildren || (r.style().hasStaticBlockPosition(isHorizontalWritingMode()) && r.parent() != this))
1430             r.setChildNeedsLayout(MarkOnlyThis);
1431             
1432         // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1433         if (relayoutChildren && r.needsPreferredWidthsRecalculation())
1434             r.setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
1435         
1436         if (!r.needsLayout())
1437             r.markForPaginationRelayoutIfNeeded();
1438         
1439         // We don't have to do a full layout.  We just have to update our position. Try that first. If we have shrink-to-fit width
1440         // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
1441         if (r.needsPositionedMovementLayoutOnly() && r.tryLayoutDoingPositionedMovementOnly())
1442             r.clearNeedsLayout();
1443             
1444         // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
1445         // If it's wrong we'll lay out again.
1446         LayoutUnit oldLogicalTop = 0;
1447         bool needsBlockDirectionLocationSetBeforeLayout = r.needsLayout() && view().layoutState()->needsBlockDirectionLocationSetBeforeLayout();
1448         if (needsBlockDirectionLocationSetBeforeLayout) {
1449             if (isHorizontalWritingMode() == r.isHorizontalWritingMode())
1450                 r.updateLogicalHeight();
1451             else
1452                 r.updateLogicalWidth();
1453             oldLogicalTop = logicalTopForChild(r);
1454         }
1455
1456         r.layoutIfNeeded();
1457
1458         // Lay out again if our estimate was wrong.
1459         if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
1460             r.setChildNeedsLayout(MarkOnlyThis);
1461             r.layoutIfNeeded();
1462         }
1463
1464         if (updateRegionRangeForBoxChild(r)) {
1465             r.setNeedsLayout(MarkOnlyThis);
1466             r.layoutIfNeeded();
1467         }
1468     }
1469 }
1470
1471 void RenderBlock::markPositionedObjectsForLayout()
1472 {
1473     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1474     if (!positionedDescendants)
1475         return;
1476
1477     for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
1478         RenderBox* r = *it;
1479         r->setChildNeedsLayout();
1480     }
1481 }
1482
1483 void RenderBlock::markForPaginationRelayoutIfNeeded()
1484 {
1485     ASSERT(!needsLayout());
1486     if (needsLayout())
1487         return;
1488
1489     if (view().layoutState()->pageLogicalHeightChanged() || (view().layoutState()->pageLogicalHeight() && view().layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()))
1490         setChildNeedsLayout(MarkOnlyThis);
1491 }
1492
1493 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1494 {
1495     LayoutPoint adjustedPaintOffset = paintOffset + location();
1496     
1497     PaintPhase phase = paintInfo.phase;
1498
1499     RenderNamedFlowFragment* namedFlowFragment = currentRenderNamedFlowFragment();
1500     // Check our region range to make sure we need to be painting in this region.
1501     if (namedFlowFragment && !namedFlowFragment->flowThread()->objectShouldFragmentInFlowRegion(this, namedFlowFragment))
1502         return;
1503
1504     // Check if we need to do anything at all.
1505     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
1506     // paints the root's background.
1507     if (!isRoot()) {
1508         LayoutRect overflowBox = overflowRectForPaintRejection(namedFlowFragment);
1509         flipForWritingMode(overflowBox);
1510         overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
1511         overflowBox.moveBy(adjustedPaintOffset);
1512         if (!overflowBox.intersects(paintInfo.rect)
1513 #if PLATFORM(IOS)
1514             // FIXME: This may be applicable to non-iOS ports.
1515             && (!hasLayer() || !layer()->isComposited())
1516 #endif
1517         )
1518             return;
1519     }
1520
1521     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
1522     paintObject(paintInfo, adjustedPaintOffset);
1523     if (pushedClip)
1524         popContentsClip(paintInfo, phase, adjustedPaintOffset);
1525
1526     // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
1527     // z-index.  We paint after we painted the background/border, so that the scrollbars will
1528     // sit above the background/border.
1529     if (hasOverflowClip() && style().visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(*this) && !paintInfo.paintRootBackgroundOnly())
1530         layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), snappedIntRect(paintInfo.rect));
1531 }
1532
1533 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1534 {
1535     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
1536     // It's ok not to draw, because later on, when all the stylesheets do load, styleResolverChanged() on the Document
1537     // will do a full repaint.
1538     if (document().didLayoutWithPendingStylesheets() && !isRenderView())
1539         return;
1540
1541     if (childrenInline())
1542         paintInlineChildren(paintInfo, paintOffset);
1543     else {
1544         PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
1545         newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
1546
1547         // We don't paint our own background, but we do let the kids paint their backgrounds.
1548         PaintInfo paintInfoForChild(paintInfo);
1549         paintInfoForChild.phase = newPhase;
1550         paintInfoForChild.updateSubtreePaintRootForChildren(this);
1551
1552         // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
1553         // NSViews. Do not add any more code for this.
1554         bool usePrintRect = !view().printRect().isEmpty();
1555         paintChildren(paintInfo, paintOffset, paintInfoForChild, usePrintRect);
1556     }
1557 }
1558
1559 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
1560 {
1561     for (auto child = firstChildBox(); child; child = child->nextSiblingBox()) {
1562         if (!paintChild(*child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
1563             return;
1564     }
1565 }
1566
1567 bool RenderBlock::paintChild(RenderBox& child, PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
1568 {
1569     // Check for page-break-before: always, and if it's set, break and bail.
1570     bool checkBeforeAlways = !childrenInline() && (usePrintRect && child.style().pageBreakBefore() == PBALWAYS);
1571     LayoutUnit absoluteChildY = paintOffset.y() + child.y();
1572     if (checkBeforeAlways
1573         && absoluteChildY > paintInfo.rect.y()
1574         && absoluteChildY < paintInfo.rect.maxY()) {
1575         view().setBestTruncatedAt(absoluteChildY, this, true);
1576         return false;
1577     }
1578
1579     if (!child.isFloating() && child.isReplaced() && usePrintRect && child.height() <= view().printRect().height()) {
1580         // Paginate block-level replaced elements.
1581         if (absoluteChildY + child.height() > view().printRect().maxY()) {
1582             if (absoluteChildY < view().truncatedAt())
1583                 view().setBestTruncatedAt(absoluteChildY, &child);
1584             // If we were able to truncate, don't paint.
1585             if (absoluteChildY >= view().truncatedAt())
1586                 return false;
1587         }
1588     }
1589
1590     LayoutPoint childPoint = flipForWritingModeForChild(&child, paintOffset);
1591     if (!child.hasSelfPaintingLayer() && !child.isFloating())
1592         child.paint(paintInfoForChild, childPoint);
1593
1594     // Check for page-break-after: always, and if it's set, break and bail.
1595     bool checkAfterAlways = !childrenInline() && (usePrintRect && child.style().pageBreakAfter() == PBALWAYS);
1596     if (checkAfterAlways
1597         && (absoluteChildY + child.height()) > paintInfo.rect.y()
1598         && (absoluteChildY + child.height()) < paintInfo.rect.maxY()) {
1599         view().setBestTruncatedAt(absoluteChildY + child.height() + std::max<LayoutUnit>(0, child.collapsedMarginAfter()), this, true);
1600         return false;
1601     }
1602
1603     return true;
1604 }
1605
1606
1607 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
1608 {
1609     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
1610     bool caretBrowsing = frame().settings().caretBrowsingEnabled();
1611     RenderObject* caretPainter;
1612     bool isContentEditable;
1613     if (type == CursorCaret) {
1614         caretPainter = frame().selection().caretRendererWithoutUpdatingLayout();
1615         isContentEditable = frame().selection().selection().hasEditableStyle();
1616     } else {
1617         caretPainter = frame().page()->dragCaretController().caretRenderer();
1618         isContentEditable = frame().page()->dragCaretController().isContentEditable();
1619     }
1620
1621     if (caretPainter == this && (isContentEditable || caretBrowsing)) {
1622         if (type == CursorCaret)
1623             frame().selection().paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
1624         else
1625             frame().page()->dragCaretController().paintDragCaret(&frame(), paintInfo.context, paintOffset, paintInfo.rect);
1626     }
1627 }
1628
1629 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1630 {
1631     PaintPhase paintPhase = paintInfo.phase;
1632
1633     // 1. paint background, borders etc
1634     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style().visibility() == VISIBLE) {
1635         if (hasBoxDecorations()) {
1636             bool didClipToRegion = false;
1637             
1638             RenderNamedFlowFragment* namedFlowFragment = currentRenderNamedFlowFragment();
1639             if (paintInfo.paintContainer && namedFlowFragment && paintInfo.paintContainer->isRenderNamedFlowThread()) {
1640                 // If this box goes beyond the current region, then make sure not to overflow the region.
1641                 // This (overflowing region X altough also fragmented to region X+1) could happen when one of this box's children
1642                 // overflows region X and is an unsplittable element (like an image).
1643                 // The same applies for a box overflowing the top of region X when that box is also fragmented in region X-1.
1644
1645                 paintInfo.context->save();
1646                 didClipToRegion = true;
1647
1648                 paintInfo.context->clip(toRenderNamedFlowThread(paintInfo.paintContainer)->decorationsClipRectForBoxInNamedFlowFragment(*this, *namedFlowFragment));
1649             }
1650
1651             paintBoxDecorations(paintInfo, paintOffset);
1652             
1653             if (didClipToRegion)
1654                 paintInfo.context->restore();
1655         }
1656     }
1657
1658     if (paintPhase == PaintPhaseMask && style().visibility() == VISIBLE) {
1659         paintMask(paintInfo, paintOffset);
1660         return;
1661     }
1662
1663     // If just painting the root background, then return.
1664     if (paintInfo.paintRootBackgroundOnly())
1665         return;
1666
1667     // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
1668     LayoutPoint scrolledOffset = paintOffset;
1669     scrolledOffset.move(-scrolledContentOffset());
1670
1671     // Column rules need to account for scrolling and clipping.
1672     // FIXME: Clipping of column rules does not work. We will need a separate paint phase for column rules I suspect in order to get
1673     // clipping correct (since it has to paint as background but is still considered "contents").
1674     if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style().visibility() == VISIBLE)
1675         paintColumnRules(paintInfo, scrolledOffset);
1676
1677     // Done with backgrounds, borders and column rules.
1678     if (paintPhase == PaintPhaseBlockBackground)
1679         return;
1680     
1681     // 2. paint contents
1682     if (paintPhase != PaintPhaseSelfOutline)
1683         paintContents(paintInfo, scrolledOffset);
1684
1685     // 3. paint selection
1686     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
1687     bool isPrinting = document().printing();
1688     if (!isPrinting)
1689         paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
1690
1691     // 4. paint floats.
1692     if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip)
1693         paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
1694
1695     // 5. paint outline.
1696     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style().visibility() == VISIBLE)
1697         paintOutline(paintInfo, LayoutRect(paintOffset, size()));
1698
1699     // 6. paint continuation outlines.
1700     if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
1701         RenderInline* inlineCont = inlineElementContinuation();
1702         if (inlineCont && inlineCont->hasOutline() && inlineCont->style().visibility() == VISIBLE) {
1703             RenderInline* inlineRenderer = toRenderInline(inlineCont->element()->renderer());
1704             RenderBlock* cb = containingBlock();
1705
1706             bool inlineEnclosedInSelfPaintingLayer = false;
1707             for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = &box->parent()->enclosingBoxModelObject()) {
1708                 if (box->hasSelfPaintingLayer()) {
1709                     inlineEnclosedInSelfPaintingLayer = true;
1710                     break;
1711                 }
1712             }
1713
1714             // Do not add continuations for outline painting by our containing block if we are a relative positioned
1715             // anonymous block (i.e. have our own layer), paint them straightaway instead. This is because a block depends on renderers in its continuation table being
1716             // in the same layer. 
1717             if (!inlineEnclosedInSelfPaintingLayer && !hasLayer())
1718                 cb->addContinuationWithOutline(inlineRenderer);
1719             else if (!inlineRenderer->firstLineBox() || (!inlineEnclosedInSelfPaintingLayer && hasLayer()))
1720                 inlineRenderer->paintOutline(paintInfo, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
1721         }
1722         paintContinuationOutlines(paintInfo, paintOffset);
1723     }
1724
1725     // 7. paint caret.
1726     // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
1727     // then paint the caret.
1728     if (paintPhase == PaintPhaseForeground) {        
1729         paintCaret(paintInfo, paintOffset, CursorCaret);
1730         paintCaret(paintInfo, paintOffset, DragCaret);
1731     }
1732 }
1733
1734 RenderInline* RenderBlock::inlineElementContinuation() const
1735
1736     RenderBoxModelObject* continuation = this->continuation();
1737     return continuation && continuation->isRenderInline() ? toRenderInline(continuation) : 0;
1738 }
1739
1740 RenderBlock* RenderBlock::blockElementContinuation() const
1741 {
1742     RenderBoxModelObject* currentContinuation = continuation();
1743     if (!currentContinuation || currentContinuation->isInline())
1744         return 0;
1745     RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
1746     if (nextContinuation->isAnonymousBlock())
1747         return nextContinuation->blockElementContinuation();
1748     return nextContinuation;
1749 }
1750     
1751 static ContinuationOutlineTableMap* continuationOutlineTable()
1752 {
1753     DEPRECATED_DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
1754     return &table;
1755 }
1756
1757 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
1758 {
1759     // We can't make this work if the inline is in a layer.  We'll just rely on the broken
1760     // way of painting.
1761     ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
1762     
1763     ContinuationOutlineTableMap* table = continuationOutlineTable();
1764     ListHashSet<RenderInline*>* continuations = table->get(this);
1765     if (!continuations) {
1766         continuations = new ListHashSet<RenderInline*>;
1767         table->set(this, std::unique_ptr<ListHashSet<RenderInline*>>(continuations));
1768     }
1769     
1770     continuations->add(flow);
1771 }
1772
1773 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
1774 {
1775     ContinuationOutlineTableMap* table = continuationOutlineTable();
1776     if (table->isEmpty())
1777         return false;
1778         
1779     ListHashSet<RenderInline*>* continuations = table->get(this);
1780     if (!continuations)
1781         return false;
1782
1783     return continuations->contains(flow);
1784 }
1785
1786 void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
1787 {
1788     ContinuationOutlineTableMap* table = continuationOutlineTable();
1789     if (table->isEmpty())
1790         return;
1791         
1792     std::unique_ptr<ListHashSet<RenderInline*>> continuations = table->take(this);
1793     if (!continuations)
1794         return;
1795
1796     LayoutPoint accumulatedPaintOffset = paintOffset;
1797     // Paint each continuation outline.
1798     ListHashSet<RenderInline*>::iterator end = continuations->end();
1799     for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
1800         // Need to add in the coordinates of the intervening blocks.
1801         RenderInline* flow = *it;
1802         RenderBlock* block = flow->containingBlock();
1803         for ( ; block && block != this; block = block->containingBlock())
1804             accumulatedPaintOffset.moveBy(block->location());
1805         ASSERT(block);   
1806         flow->paintOutline(info, accumulatedPaintOffset);
1807     }
1808 }
1809
1810 bool RenderBlock::shouldPaintSelectionGaps() const
1811 {
1812     return selectionState() != SelectionNone && style().visibility() == VISIBLE && isSelectionRoot();
1813 }
1814
1815 bool RenderBlock::isSelectionRoot() const
1816 {
1817     if (isPseudoElement())
1818         return false;
1819     ASSERT(element() || isAnonymous());
1820         
1821     // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
1822     if (isTable())
1823         return false;
1824         
1825     if (isBody() || isRoot() || hasOverflowClip()
1826         || isPositioned() || isFloating()
1827         || isTableCell() || isInlineBlockOrInlineTable()
1828         || hasTransform() || hasReflection() || hasMask() || isWritingModeRoot()
1829         || isRenderFlowThread() || style().columnSpan() == ColumnSpanAll)
1830         return true;
1831     
1832     if (view().selectionUnsplitStart()) {
1833         Node* startElement = view().selectionUnsplitStart()->node();
1834         if (startElement && startElement->rootEditableElement() == element())
1835             return true;
1836     }
1837     
1838     return false;
1839 }
1840
1841 GapRects RenderBlock::selectionGapRectsForRepaint(const RenderLayerModelObject* repaintContainer)
1842 {
1843     ASSERT(!needsLayout());
1844
1845     if (!shouldPaintSelectionGaps())
1846         return GapRects();
1847
1848     TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
1849     mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip | UseTransforms);
1850     LayoutPoint offsetFromRepaintContainer(transformState.mappedPoint() - scrolledContentOffset());
1851
1852     LogicalSelectionOffsetCaches cache(*this);
1853     LayoutUnit lastTop = 0;
1854     LayoutUnit lastLeft = logicalLeftSelectionOffset(*this, lastTop, cache);
1855     LayoutUnit lastRight = logicalRightSelectionOffset(*this, lastTop, cache);
1856     
1857     return selectionGaps(*this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight, cache);
1858 }
1859
1860 void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1861 {
1862 #if ENABLE(TEXT_SELECTION)
1863     if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
1864         LogicalSelectionOffsetCaches cache(*this);
1865         LayoutUnit lastTop = 0;
1866         LayoutUnit lastLeft = logicalLeftSelectionOffset(*this, lastTop, cache);
1867         LayoutUnit lastRight = logicalRightSelectionOffset(*this, lastTop, cache);
1868         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1869
1870         LayoutRect gapRectsBounds = selectionGaps(*this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, cache, &paintInfo);
1871         if (!gapRectsBounds.isEmpty()) {
1872             if (RenderLayer* layer = enclosingLayer()) {
1873                 gapRectsBounds.moveBy(-paintOffset);
1874                 if (!hasLayer()) {
1875                     LayoutRect localBounds(gapRectsBounds);
1876                     flipForWritingMode(localBounds);
1877                     gapRectsBounds = localToContainerQuad(FloatRect(localBounds), &layer->renderer()).enclosingBoundingBox();
1878                     if (layer->renderer().isBox())
1879                         gapRectsBounds.move(layer->renderBox()->scrolledContentOffset());
1880                 }
1881                 layer->addBlockSelectionGapsBounds(gapRectsBounds);
1882             }
1883         }
1884     }
1885 #else
1886     UNUSED_PARAM(paintInfo);
1887     UNUSED_PARAM(paintOffset);
1888 #endif
1889 }
1890
1891 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, TrackedRendererListHashSet* positionedObjects)
1892 {
1893     if (!positionedObjects)
1894         return;
1895     
1896     TrackedRendererListHashSet::const_iterator end = positionedObjects->end();
1897     for (TrackedRendererListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
1898         RenderBox* r = *it;
1899         paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
1900     }
1901 }
1902
1903 LayoutUnit blockDirectionOffset(RenderBlock& rootBlock, const LayoutSize& offsetFromRootBlock)
1904 {
1905     return rootBlock.isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
1906 }
1907
1908 LayoutUnit inlineDirectionOffset(RenderBlock& rootBlock, const LayoutSize& offsetFromRootBlock)
1909 {
1910     return rootBlock.isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
1911 }
1912
1913 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
1914 {
1915     LayoutRect result;
1916     if (isHorizontalWritingMode())
1917         result = logicalRect;
1918     else
1919         result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
1920     flipForWritingMode(result);
1921     result.moveBy(rootBlockPhysicalPosition);
1922     return result;
1923 }
1924
1925 GapRects RenderBlock::selectionGaps(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
1926     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
1927 {
1928     // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
1929     // Clip out floating and positioned objects when painting selection gaps.
1930     if (paintInfo) {
1931         // Note that we don't clip out overflow for positioned objects.  We just stick to the border box.
1932         LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
1933         rootBlock.flipForWritingMode(flippedBlockRect);
1934         flippedBlockRect.moveBy(rootBlockPhysicalPosition);
1935         clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), positionedObjects());
1936         if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
1937             for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
1938                 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
1939         clipOutFloatingObjects(rootBlock, paintInfo, rootBlockPhysicalPosition, offsetFromRootBlock);
1940     }
1941
1942     // 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
1943     // fixed).
1944     GapRects result;
1945     if (!isRenderBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
1946         return result;
1947
1948     if (hasTransform() || style().columnSpan() == ColumnSpanAll || isInFlowRenderFlowThread()) {
1949         // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
1950         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
1951         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
1952         lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
1953         return result;
1954     }
1955     
1956     RenderNamedFlowFragment* namedFlowFragment = currentRenderNamedFlowFragment();
1957     if (paintInfo && namedFlowFragment && paintInfo->paintContainer->isRenderFlowThread()) {
1958         // Make sure the current object is actually flowed into the region being painted.
1959         if (!toRenderFlowThread(paintInfo->paintContainer)->objectShouldFragmentInFlowRegion(this, namedFlowFragment))
1960             return result;
1961     }
1962
1963     if (childrenInline())
1964         result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
1965     else
1966         result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
1967
1968     // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
1969     if (&rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd)) {
1970         result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
1971             lastLogicalTop, lastLogicalLeft, lastLogicalRight, logicalHeight(), cache, paintInfo));
1972     }
1973
1974     return result;
1975 }
1976
1977 GapRects RenderBlock::inlineSelectionGaps(RenderBlock&, const LayoutPoint&, const LayoutSize&, LayoutUnit&, LayoutUnit&, LayoutUnit&, const LogicalSelectionOffsetCaches&, const PaintInfo*)
1978 {
1979     ASSERT_NOT_REACHED();
1980     return GapRects();
1981 }
1982
1983 GapRects RenderBlock::blockSelectionGaps(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
1984     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
1985 {
1986     GapRects result;
1987
1988     // Go ahead and jump right to the first block child that contains some selected objects.
1989     RenderBox* curr;
1990     for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
1991     
1992     if (!curr)
1993         return result;
1994
1995     LogicalSelectionOffsetCaches childCache(*this, cache);
1996
1997     for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
1998         SelectionState childState = curr->selectionState();
1999         if (childState == SelectionBoth || childState == SelectionEnd)
2000             sawSelectionEnd = true;
2001
2002         if (curr->isFloatingOrOutOfFlowPositioned())
2003             continue; // We must be a normal flow object in order to even be considered.
2004
2005         if (curr->isInFlowPositioned() && curr->hasLayer()) {
2006             // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
2007             // Just disregard it completely.
2008             LayoutSize relOffset = curr->layer()->offsetForInFlowPosition();
2009             if (relOffset.width() || relOffset.height())
2010                 continue;
2011         }
2012
2013         bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
2014         bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
2015         if (fillBlockGaps) {
2016             // We need to fill the vertical gap above this object.
2017             if (childState == SelectionEnd || childState == SelectionInside) {
2018                 // Fill the gap above the object.
2019                 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
2020                     lastLogicalTop, lastLogicalLeft, lastLogicalRight, curr->logicalTop(), cache, paintInfo));
2021             }
2022
2023             // 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*
2024             // our object.  We know this if the selection did not end inside our object.
2025             if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
2026                 childState = SelectionNone;
2027
2028             // Fill side gaps on this object based off its state.
2029             bool leftGap, rightGap;
2030             getSelectionGapInfo(childState, leftGap, rightGap);
2031
2032             if (leftGap)
2033                 result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), cache, paintInfo));
2034             if (rightGap)
2035                 result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), cache, paintInfo));
2036
2037             // Update lastLogicalTop to be just underneath the object.  lastLogicalLeft and lastLogicalRight extend as far as
2038             // they can without bumping into floating or positioned objects.  Ideally they will go right up
2039             // to the border of the root selection block.
2040             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
2041             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom(), cache);
2042             lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom(), cache);
2043         } else if (childState != SelectionNone) {
2044             // We must be a block that has some selected object inside it.  Go ahead and recur.
2045             result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()), 
2046                 lastLogicalTop, lastLogicalLeft, lastLogicalRight, childCache, paintInfo));
2047         }
2048     }
2049     return result;
2050 }
2051
2052 LayoutRect RenderBlock::blockSelectionGap(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2053     LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
2054 {
2055     LayoutUnit logicalTop = lastLogicalTop;
2056     LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
2057     if (logicalHeight <= 0)
2058         return LayoutRect();
2059
2060     // Get the selection offsets for the bottom of the gap
2061     LayoutUnit logicalLeft = std::max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom, cache));
2062     LayoutUnit logicalRight = std::min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom, cache));
2063     LayoutUnit logicalWidth = logicalRight - logicalLeft;
2064     if (logicalWidth <= 0)
2065         return LayoutRect();
2066
2067     LayoutRect gapRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
2068     if (paintInfo)
2069         paintInfo->context->fillRect(snapRectToDevicePixels(gapRect, document().deviceScaleFactor()), selectionBackgroundColor(), style().colorSpace());
2070     return gapRect;
2071 }
2072
2073 LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2074     RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
2075 {
2076     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
2077     LayoutUnit rootBlockLogicalLeft = std::max(logicalLeftSelectionOffset(rootBlock, logicalTop, cache), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight, cache));
2078     LayoutUnit rootBlockLogicalRight = std::min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalLeft,
2079         std::min(logicalRightSelectionOffset(rootBlock, logicalTop, cache), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight, cache)));
2080     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2081     if (rootBlockLogicalWidth <= 0)
2082         return LayoutRect();
2083
2084     LayoutRect gapRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2085     if (paintInfo)
2086         paintInfo->context->fillRect(snapRectToDevicePixels(gapRect, document().deviceScaleFactor()), selObj->selectionBackgroundColor(), selObj->style().colorSpace());
2087     return gapRect;
2088 }
2089
2090 LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2091     RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
2092 {
2093     LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
2094     LayoutUnit rootBlockLogicalLeft = std::max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalRight,
2095         std::max(logicalLeftSelectionOffset(rootBlock, logicalTop, cache), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight, cache)));
2096     LayoutUnit rootBlockLogicalRight = std::min(logicalRightSelectionOffset(rootBlock, logicalTop, cache), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight, cache));
2097     LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2098     if (rootBlockLogicalWidth <= 0)
2099         return LayoutRect();
2100
2101     LayoutRect gapRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2102     if (paintInfo)
2103         paintInfo->context->fillRect(snapRectToDevicePixels(gapRect, document().deviceScaleFactor()), selObj->selectionBackgroundColor(), selObj->style().colorSpace());
2104     return gapRect;
2105 }
2106
2107 void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap)
2108 {
2109     bool ltr = style().isLeftToRightDirection();
2110     leftGap = (state == RenderObject::SelectionInside) ||
2111               (state == RenderObject::SelectionEnd && ltr) ||
2112               (state == RenderObject::SelectionStart && !ltr);
2113     rightGap = (state == RenderObject::SelectionInside) ||
2114                (state == RenderObject::SelectionStart && ltr) ||
2115                (state == RenderObject::SelectionEnd && !ltr);
2116 }
2117
2118 LayoutUnit RenderBlock::logicalLeftSelectionOffset(RenderBlock& rootBlock, LayoutUnit position, const LogicalSelectionOffsetCaches& cache)
2119 {
2120     LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
2121     if (logicalLeft == logicalLeftOffsetForContent()) {
2122         if (&rootBlock != this) // The border can potentially be further extended by our containingBlock().
2123             return cache.containingBlockInfo(*this).logicalLeftSelectionOffset(rootBlock, position + logicalTop());
2124         return logicalLeft;
2125     }
2126
2127     RenderBlock* cb = this;
2128     const LogicalSelectionOffsetCaches* currentCache = &cache;
2129     while (cb != &rootBlock) {
2130         logicalLeft += cb->logicalLeft();
2131
2132         ASSERT(currentCache);
2133         auto info = currentCache->containingBlockInfo(*cb);
2134         cb = info.block();
2135         currentCache = info.cache();
2136     }
2137     return logicalLeft;
2138 }
2139
2140 LayoutUnit RenderBlock::logicalRightSelectionOffset(RenderBlock& rootBlock, LayoutUnit position, const LogicalSelectionOffsetCaches& cache)
2141 {
2142     LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
2143     if (logicalRight == logicalRightOffsetForContent()) {
2144         if (&rootBlock != this) // The border can potentially be further extended by our containingBlock().
2145             return cache.containingBlockInfo(*this).logicalRightSelectionOffset(rootBlock, position + logicalTop());
2146         return logicalRight;
2147     }
2148
2149     RenderBlock* cb = this;
2150     const LogicalSelectionOffsetCaches* currentCache = &cache;
2151     while (cb != &rootBlock) {
2152         logicalRight += cb->logicalLeft();
2153
2154         ASSERT(currentCache);
2155         auto info = currentCache->containingBlockInfo(*cb);
2156         cb = info.block();
2157         currentCache = info.cache();
2158     }
2159     return logicalRight;
2160 }
2161
2162 RenderBlock* RenderBlock::blockBeforeWithinSelectionRoot(LayoutSize& offset) const
2163 {
2164     if (isSelectionRoot())
2165         return 0;
2166
2167     const RenderElement* object = this;
2168     RenderObject* sibling;
2169     do {
2170         sibling = object->previousSibling();
2171         while (sibling && (!sibling->isRenderBlock() || toRenderBlock(sibling)->isSelectionRoot()))
2172             sibling = sibling->previousSibling();
2173
2174         offset -= LayoutSize(toRenderBlock(object)->logicalLeft(), toRenderBlock(object)->logicalTop());
2175         object = object->parent();
2176     } while (!sibling && object && object->isRenderBlock() && !toRenderBlock(object)->isSelectionRoot());
2177
2178     if (!sibling)
2179         return 0;
2180
2181     RenderBlock* beforeBlock = toRenderBlock(sibling);
2182
2183     offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
2184
2185     RenderObject* child = beforeBlock->lastChild();
2186     while (child && child->isRenderBlock()) {
2187         beforeBlock = toRenderBlock(child);
2188         offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
2189         child = beforeBlock->lastChild();
2190     }
2191     return beforeBlock;
2192 }
2193
2194 void RenderBlock::insertIntoTrackedRendererMaps(RenderBox& descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
2195 {
2196     if (!descendantsMap) {
2197         descendantsMap = new TrackedDescendantsMap;
2198         containerMap = new TrackedContainerMap;
2199     }
2200     
2201     TrackedRendererListHashSet* descendantSet = descendantsMap->get(this);
2202     if (!descendantSet) {
2203         descendantSet = new TrackedRendererListHashSet;
2204         descendantsMap->set(this, std::unique_ptr<TrackedRendererListHashSet>(descendantSet));
2205     }
2206     bool added = descendantSet->add(&descendant).isNewEntry;
2207     if (!added) {
2208         ASSERT(containerMap->get(&descendant));
2209         ASSERT(containerMap->get(&descendant)->contains(this));
2210         return;
2211     }
2212     
2213     HashSet<RenderBlock*>* containerSet = containerMap->get(&descendant);
2214     if (!containerSet) {
2215         containerSet = new HashSet<RenderBlock*>;
2216         containerMap->set(&descendant, std::unique_ptr<HashSet<RenderBlock*>>(containerSet));
2217     }
2218     ASSERT(!containerSet->contains(this));
2219     containerSet->add(this);
2220 }
2221
2222 void RenderBlock::removeFromTrackedRendererMaps(RenderBox& descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
2223 {
2224     if (!descendantsMap)
2225         return;
2226     
2227     std::unique_ptr<HashSet<RenderBlock*>> containerSet = containerMap->take(&descendant);
2228     if (!containerSet)
2229         return;
2230     
2231     for (auto it = containerSet->begin(), end = containerSet->end(); it != end; ++it) {
2232         RenderBlock* container = *it;
2233
2234         // FIXME: Disabling this assert temporarily until we fix the layout
2235         // bugs associated with positioned objects not properly cleared from
2236         // their ancestor chain before being moved. See webkit bug 93766.
2237         // ASSERT(descendant->isDescendantOf(container));
2238
2239         TrackedDescendantsMap::iterator descendantsMapIterator = descendantsMap->find(container);
2240         ASSERT(descendantsMapIterator != descendantsMap->end());
2241         if (descendantsMapIterator == descendantsMap->end())
2242             continue;
2243         TrackedRendererListHashSet* descendantSet = descendantsMapIterator->value.get();
2244         ASSERT(descendantSet->contains(&descendant));
2245         descendantSet->remove(&descendant);
2246         if (descendantSet->isEmpty())
2247             descendantsMap->remove(descendantsMapIterator);
2248     }
2249 }
2250
2251 TrackedRendererListHashSet* RenderBlock::positionedObjects() const
2252 {
2253     if (gPositionedDescendantsMap)
2254         return gPositionedDescendantsMap->get(this);
2255     return 0;
2256 }
2257
2258 void RenderBlock::insertPositionedObject(RenderBox& o)
2259 {
2260     ASSERT(!isAnonymousBlock());
2261
2262     if (o.isRenderFlowThread())
2263         return;
2264     
2265     insertIntoTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
2266 }
2267
2268 void RenderBlock::removePositionedObject(RenderBox& o)
2269 {
2270     removeFromTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
2271 }
2272
2273 void RenderBlock::removePositionedObjects(RenderBlock* o, ContainingBlockState containingBlockState)
2274 {
2275     TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2276     if (!positionedDescendants)
2277         return;
2278     
2279     Vector<RenderBox*, 16> deadObjects;
2280
2281     for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
2282         RenderBox* r = *it;
2283         if (!o || r->isDescendantOf(o)) {
2284             if (containingBlockState == NewContainingBlock)
2285                 r->setChildNeedsLayout(MarkOnlyThis);
2286             
2287             // It is parent blocks job to add positioned child to positioned objects list of its containing block
2288             // Parent layout needs to be invalidated to ensure this happens.
2289             RenderElement* p = r->parent();
2290             while (p && !p->isRenderBlock())
2291                 p = p->parent();
2292             if (p)
2293                 p->setChildNeedsLayout();
2294             
2295             deadObjects.append(r);
2296         }
2297     }
2298     
2299     for (unsigned i = 0; i < deadObjects.size(); i++)
2300         removePositionedObject(*deadObjects.at(i));
2301 }
2302
2303 void RenderBlock::addPercentHeightDescendant(RenderBox& descendant)
2304 {
2305     insertIntoTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
2306 }
2307
2308 void RenderBlock::removePercentHeightDescendant(RenderBox& descendant)
2309 {
2310     removeFromTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
2311 }
2312
2313 TrackedRendererListHashSet* RenderBlock::percentHeightDescendants() const
2314 {
2315     return gPercentHeightDescendantsMap ? gPercentHeightDescendantsMap->get(this) : 0;
2316 }
2317
2318 bool RenderBlock::hasPercentHeightContainerMap()
2319 {
2320     return gPercentHeightContainerMap;
2321 }
2322
2323 bool RenderBlock::hasPercentHeightDescendant(RenderBox& descendant)
2324 {
2325     // We don't null check gPercentHeightContainerMap since the caller
2326     // already ensures this and we need to call this function on every
2327     // descendant in clearPercentHeightDescendantsFrom().
2328     ASSERT(gPercentHeightContainerMap);
2329     return gPercentHeightContainerMap->contains(&descendant);
2330 }
2331
2332 void RenderBlock::removePercentHeightDescendantIfNeeded(RenderBox& descendant)
2333 {
2334     // We query the map directly, rather than looking at style's
2335     // logicalHeight()/logicalMinHeight()/logicalMaxHeight() since those
2336     // can change with writing mode/directional changes.
2337     if (!hasPercentHeightContainerMap())
2338         return;
2339
2340     if (!hasPercentHeightDescendant(descendant))
2341         return;
2342
2343     removePercentHeightDescendant(descendant);
2344 }
2345
2346 void RenderBlock::clearPercentHeightDescendantsFrom(RenderBox& parent)
2347 {
2348     ASSERT(gPercentHeightContainerMap);
2349     for (RenderObject* curr = parent.firstChild(); curr; curr = curr->nextInPreOrder(&parent)) {
2350         if (!curr->isBox())
2351             continue;
2352  
2353         RenderBox& box = toRenderBox(*curr);
2354         if (!hasPercentHeightDescendant(box))
2355             continue;
2356
2357         removePercentHeightDescendant(box);
2358     }
2359 }
2360
2361 LayoutUnit RenderBlock::textIndentOffset() const
2362 {
2363     LayoutUnit cw = 0;
2364     if (style().textIndent().isPercent())
2365         cw = containingBlock()->availableLogicalWidth();
2366     return minimumValueForLength(style().textIndent(), cw);
2367 }
2368
2369 LayoutUnit RenderBlock::logicalLeftOffsetForContent(RenderRegion* region) const
2370 {
2371     LayoutUnit logicalLeftOffset = style().isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
2372     if (!region)
2373         return logicalLeftOffset;
2374     LayoutRect boxRect = borderBoxRectInRegion(region);
2375     return logicalLeftOffset + (isHorizontalWritingMode() ? boxRect.x() : boxRect.y());
2376 }
2377
2378 LayoutUnit RenderBlock::logicalRightOffsetForContent(RenderRegion* region) const
2379 {
2380     LayoutUnit logicalRightOffset = style().isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
2381     logicalRightOffset += availableLogicalWidth();
2382     if (!region)
2383         return logicalRightOffset;
2384     LayoutRect boxRect = borderBoxRectInRegion(region);
2385     return logicalRightOffset - (logicalWidth() - (isHorizontalWritingMode() ? boxRect.maxX() : boxRect.maxY()));
2386 }
2387
2388 LayoutUnit RenderBlock::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2389 {
2390     LayoutUnit left = offsetFromFloats;
2391
2392     if (applyTextIndent && style().isLeftToRightDirection())
2393         left += textIndentOffset();
2394
2395     if (style().lineAlign() == LineAlignNone)
2396         return left;
2397     
2398     // Push in our left offset so that it is aligned with the character grid.
2399     LayoutState* layoutState = view().layoutState();
2400     if (!layoutState)
2401         return left;
2402
2403     RenderBlock* lineGrid = layoutState->lineGrid();
2404     if (!lineGrid || lineGrid->style().writingMode() != style().writingMode())
2405         return left;
2406
2407     // FIXME: Should letter-spacing apply? This is complicated since it doesn't apply at the edge?
2408     float maxCharWidth = lineGrid->style().font().primaryFont()->maxCharWidth();
2409     if (!maxCharWidth)
2410         return left;
2411
2412     LayoutUnit lineGridOffset = lineGrid->isHorizontalWritingMode() ? layoutState->lineGridOffset().width(): layoutState->lineGridOffset().height();
2413     LayoutUnit layoutOffset = lineGrid->isHorizontalWritingMode() ? layoutState->layoutOffset().width() : layoutState->layoutOffset().height();
2414     
2415     // Push in to the nearest character width (truncated so that we pixel snap left).
2416     // FIXME: Should be patched when subpixel layout lands, since this calculation doesn't have to pixel snap
2417     // any more (https://bugs.webkit.org/show_bug.cgi?id=79946).
2418     // FIXME: This is wrong for RTL (https://bugs.webkit.org/show_bug.cgi?id=79945).
2419     // FIXME: This doesn't work with columns or regions (https://bugs.webkit.org/show_bug.cgi?id=79942).
2420     // FIXME: This doesn't work when the inline position of the object isn't set ahead of time.
2421     // FIXME: Dynamic changes to the font or to the inline position need to result in a deep relayout.
2422     // (https://bugs.webkit.org/show_bug.cgi?id=79944)
2423     float remainder = fmodf(maxCharWidth - fmodf(left + layoutOffset - lineGridOffset, maxCharWidth), maxCharWidth);
2424     left += remainder;
2425     return left;
2426 }
2427
2428 LayoutUnit RenderBlock::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2429 {
2430     LayoutUnit right = offsetFromFloats;
2431     
2432     if (applyTextIndent && !style().isLeftToRightDirection())
2433         right -= textIndentOffset();
2434     
2435     if (style().lineAlign() == LineAlignNone)
2436         return right;
2437     
2438     // Push in our right offset so that it is aligned with the character grid.
2439     LayoutState* layoutState = view().layoutState();
2440     if (!layoutState)
2441         return right;
2442
2443     RenderBlock* lineGrid = layoutState->lineGrid();
2444     if (!lineGrid || lineGrid->style().writingMode() != style().writingMode())
2445         return right;
2446
2447     // FIXME: Should letter-spacing apply? This is complicated since it doesn't apply at the edge?
2448     float maxCharWidth = lineGrid->style().font().primaryFont()->maxCharWidth();
2449     if (!maxCharWidth)
2450         return right;
2451
2452     LayoutUnit lineGridOffset = lineGrid->isHorizontalWritingMode() ? layoutState->lineGridOffset().width(): layoutState->lineGridOffset().height();
2453     LayoutUnit layoutOffset = lineGrid->isHorizontalWritingMode() ? layoutState->layoutOffset().width() : layoutState->layoutOffset().height();
2454     
2455     // Push in to the nearest character width (truncated so that we pixel snap right).
2456     // FIXME: Should be patched when subpixel layout lands, since this calculation doesn't have to pixel snap
2457     // any more (https://bugs.webkit.org/show_bug.cgi?id=79946).
2458     // FIXME: This is wrong for RTL (https://bugs.webkit.org/show_bug.cgi?id=79945).
2459     // FIXME: This doesn't work with columns or regions (https://bugs.webkit.org/show_bug.cgi?id=79942).
2460     // FIXME: This doesn't work when the inline position of the object isn't set ahead of time.
2461     // FIXME: Dynamic changes to the font or to the inline position need to result in a deep relayout.
2462     // (https://bugs.webkit.org/show_bug.cgi?id=79944)
2463     float remainder = fmodf(fmodf(right + layoutOffset - lineGridOffset, maxCharWidth), maxCharWidth);
2464     right -= ceilf(remainder);
2465     return right;
2466 }
2467
2468 bool RenderBlock::avoidsFloats() const
2469 {
2470     // Floats can't intrude into our box if we have a non-auto column count or width.
2471     return RenderBox::avoidsFloats()
2472         || !style().hasAutoColumnCount()
2473         || !style().hasAutoColumnWidth()
2474         || style().hasFlowFrom();
2475 }
2476
2477 bool RenderBlock::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset)
2478 {
2479     if (!scrollsOverflow())
2480         return false;
2481
2482     return layer()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
2483 }
2484
2485 Node* RenderBlock::nodeForHitTest() const
2486 {
2487     // If we are in the margins of block elements that are part of a
2488     // continuation we're actually still inside the enclosing element
2489     // that was split. Use the appropriate inner node.
2490     if (isRenderView())
2491         return &document();
2492     return isAnonymousBlockContinuation() ? continuation()->element() : element();
2493 }
2494
2495 bool RenderBlock::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2496 {
2497     LayoutPoint adjustedLocation(accumulatedOffset + location());
2498     LayoutSize localOffset = toLayoutSize(adjustedLocation);
2499
2500     RenderFlowThread* flowThread = flowThreadContainingBlock();
2501     RenderNamedFlowFragment* namedFlowFragment = flowThread ? toRenderNamedFlowFragment(flowThread->currentRegion()) : nullptr;
2502     // If we are now searching inside a region, make sure this element
2503     // is being fragmented into this region.
2504     if (namedFlowFragment && !flowThread->objectShouldFragmentInFlowRegion(this, namedFlowFragment))
2505         return false;
2506
2507     if (!isRenderView()) {
2508         // Check if we need to do anything at all.
2509         LayoutRect overflowBox = visualOverflowRect();
2510         flipForWritingMode(overflowBox);
2511         overflowBox.moveBy(adjustedLocation);
2512         if (!locationInContainer.intersects(overflowBox))
2513             return false;
2514     }
2515
2516     if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && isPointInOverflowControl(result, locationInContainer.point(), adjustedLocation)) {
2517         updateHitTestResult(result, locationInContainer.point() - localOffset);
2518         // FIXME: isPointInOverflowControl() doesn't handle rect-based tests yet.
2519         if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer))
2520            return true;
2521     }
2522
2523     if (style().clipPath()) {
2524         switch (style().clipPath()->type()) {
2525         case ClipPathOperation::Shape: {
2526             ShapeClipPathOperation* clipPath = toShapeClipPathOperation(style().clipPath());
2527
2528             LayoutRect referenceBoxRect;
2529             switch (clipPath->referenceBox()) {
2530             case CSSBoxType::MarginBox:
2531                 referenceBoxRect = marginBoxRect();
2532                 break;
2533             case CSSBoxType::BorderBox:
2534                 referenceBoxRect = borderBoxRect();
2535                 break;
2536             case CSSBoxType::PaddingBox:
2537                 referenceBoxRect = paddingBoxRect();
2538                 break;
2539             case CSSBoxType::ContentBox:
2540                 referenceBoxRect = contentBoxRect();
2541                 break;
2542             case CSSBoxType::BoxMissing:
2543             case CSSBoxType::Fill:
2544             case CSSBoxType::Stroke:
2545             case CSSBoxType::ViewBox:
2546                 referenceBoxRect = borderBoxRect();
2547             }
2548             if (!clipPath->pathForReferenceRect(referenceBoxRect).contains(locationInContainer.point() - localOffset, clipPath->windRule()))
2549                 return false;
2550             break;
2551         }
2552         // FIXME: handle Reference/Box
2553         case ClipPathOperation::Reference:
2554         case ClipPathOperation::Box:
2555             break;
2556         }
2557     }
2558
2559     // If we have clipping, then we can't have any spillout.
2560     bool useOverflowClip = hasOverflowClip() && !hasSelfPaintingLayer();
2561     bool useClip = (hasControlClip() || useOverflowClip);
2562     bool checkChildren = !useClip || (hasControlClip() ? locationInContainer.intersects(controlClipRect(adjustedLocation)) : locationInContainer.intersects(overflowClipRect(adjustedLocation, namedFlowFragment, IncludeOverlayScrollbarSize)));
2563     if (checkChildren) {
2564         // Hit test descendants first.
2565         LayoutSize scrolledOffset(localOffset - scrolledContentOffset());
2566
2567         if (hitTestContents(request, result, locationInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
2568             updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2569             return true;
2570         }
2571         if (hitTestAction == HitTestFloat && hitTestFloats(request, result, locationInContainer, toLayoutPoint(scrolledOffset)))
2572             return true;
2573     }
2574
2575     // Check if the point is outside radii.
2576     if (!isRenderView() && style().hasBorderRadius()) {
2577         LayoutRect borderRect = borderBoxRect();
2578         borderRect.moveBy(adjustedLocation);
2579         RoundedRect border = style().getRoundedBorderFor(borderRect);
2580         if (!locationInContainer.intersects(border))
2581             return false;
2582     }
2583
2584     // Now hit test our background
2585     if (hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) {
2586         LayoutRect boundsRect(adjustedLocation, size());
2587         if (visibleToHitTesting() && locationInContainer.intersects(boundsRect)) {
2588             updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2589             if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer, boundsRect))
2590                 return true;
2591         }
2592     }
2593
2594     return false;
2595 }
2596
2597 bool RenderBlock::hitTestContents(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2598 {
2599     if (childrenInline() && !isTable())
2600         return hitTestInlineChildren(request, result, locationInContainer, accumulatedOffset, hitTestAction);
2601
2602     // Hit test our children.
2603     HitTestAction childHitTest = hitTestAction;
2604     if (hitTestAction == HitTestChildBlockBackgrounds)
2605         childHitTest = HitTestChildBlockBackground;
2606     for (auto child = lastChildBox(); child; child = child->previousSiblingBox()) {
2607         LayoutPoint childPoint = flipForWritingModeForChild(child, accumulatedOffset);
2608         if (!child->hasSelfPaintingLayer() && !child->isFloating() && child->nodeAtPoint(request, result, locationInContainer, childPoint, childHitTest))
2609             return true;
2610     }
2611
2612     return false;
2613 }
2614
2615 static inline bool isEditingBoundary(RenderElement* ancestor, RenderObject& child)
2616 {
2617     ASSERT(!ancestor || ancestor->nonPseudoElement());
2618     ASSERT(child.nonPseudoNode());
2619     return !ancestor || !ancestor->parent() || (ancestor->hasLayer() && ancestor->parent()->isRenderView())
2620         || ancestor->nonPseudoElement()->hasEditableStyle() == child.nonPseudoNode()->hasEditableStyle();
2621 }
2622
2623 // FIXME: This function should go on RenderObject as an instance method. Then
2624 // all cases in which positionForPoint recurs could call this instead to
2625 // prevent crossing editable boundaries. This would require many tests.
2626 VisiblePosition positionForPointRespectingEditingBoundaries(RenderBlock& parent, RenderBox& child, const LayoutPoint& pointInParentCoordinates)
2627 {
2628     LayoutPoint childLocation = child.location();
2629     if (child.isInFlowPositioned())
2630         childLocation += child.offsetForInFlowPosition();
2631
2632     // FIXME: This is wrong if the child's writing-mode is different from the parent's.
2633     LayoutPoint pointInChildCoordinates(toLayoutPoint(pointInParentCoordinates - childLocation));
2634
2635     // If this is an anonymous renderer, we just recur normally
2636     Element* childElement= child.nonPseudoElement();
2637     if (!childElement)
2638         return child.positionForPoint(pointInChildCoordinates, nullptr);
2639
2640     // Otherwise, first make sure that the editability of the parent and child agree.
2641     // If they don't agree, then we return a visible position just before or after the child
2642     RenderElement* ancestor = &parent;
2643     while (ancestor && !ancestor->nonPseudoElement())
2644         ancestor = ancestor->parent();
2645
2646     // If we can't find an ancestor to check editability on, or editability is unchanged, we recur like normal
2647     if (isEditingBoundary(ancestor, child))
2648         return child.positionForPoint(pointInChildCoordinates, nullptr);
2649     
2650 #if PLATFORM(IOS)
2651     // On iOS we want to constrain VisiblePositions to the editable region closest to the input position, so
2652     // we will allow descent from non-editable to editable content.
2653     // FIXME: This constraining must be done at a higher level once we implement contentEditable. For now, if something
2654     // is editable, the whole document will be.
2655     if (childElement->isContentEditable() && !ancestor->element()->isContentEditable())
2656         return child.positionForPoint(pointInChildCoordinates, nullptr);
2657 #endif
2658
2659     // Otherwise return before or after the child, depending on if the click was to the logical left or logical right of the child
2660     LayoutUnit childMiddle = parent.logicalWidthForChild(child) / 2;
2661     LayoutUnit logicalLeft = parent.isHorizontalWritingMode() ? pointInChildCoordinates.x() : pointInChildCoordinates.y();
2662     if (logicalLeft < childMiddle)
2663         return ancestor->createVisiblePosition(childElement->nodeIndex(), DOWNSTREAM);
2664     return ancestor->createVisiblePosition(childElement->nodeIndex() + 1, UPSTREAM);
2665 }
2666
2667 VisiblePosition RenderBlock::positionForPointWithInlineChildren(const LayoutPoint&, const RenderRegion*)
2668 {
2669     ASSERT_NOT_REACHED();
2670     return VisiblePosition();
2671 }
2672
2673 static inline bool isChildHitTestCandidate(const RenderBox& box)
2674 {
2675     return box.height() && box.style().visibility() == VISIBLE && !box.isFloatingOrOutOfFlowPositioned() && !box.isInFlowRenderFlowThread();
2676 }
2677
2678 // Valid candidates in a FlowThread must be rendered by the region.
2679 static inline bool isChildHitTestCandidate(const RenderBox& box, const RenderRegion* region, const LayoutPoint& point)
2680 {
2681     if (!isChildHitTestCandidate(box))
2682         return false;
2683     if (!region)
2684         return true;
2685     const RenderBlock& block = box.isRenderBlock() ? toRenderBlock(box) : *box.containingBlock();
2686     return block.regionAtBlockOffset(point.y()) == region;
2687 }
2688
2689 VisiblePosition RenderBlock::positionForPoint(const LayoutPoint& point, const RenderRegion* region)
2690 {
2691     if (isTable())
2692         return RenderBox::positionForPoint(point, region);
2693
2694     if (isReplaced()) {
2695         // FIXME: This seems wrong when the object's writing-mode doesn't match the line's writing-mode.
2696         LayoutUnit pointLogicalLeft = isHorizontalWritingMode() ? point.x() : point.y();
2697         LayoutUnit pointLogicalTop = isHorizontalWritingMode() ? point.y() : point.x();
2698
2699         if (pointLogicalTop < 0 || (pointLogicalTop < logicalHeight() && pointLogicalLeft < 0))
2700             return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
2701         if (pointLogicalTop >= logicalHeight() || (pointLogicalTop >= 0 && pointLogicalLeft >= logicalWidth()))
2702             return createVisiblePosition(caretMaxOffset(), DOWNSTREAM);
2703     } 
2704
2705     LayoutPoint pointInContents = point;
2706     offsetForContents(pointInContents);
2707     LayoutPoint pointInLogicalContents(pointInContents);
2708     if (!isHorizontalWritingMode())
2709         pointInLogicalContents = pointInLogicalContents.transposedPoint();
2710
2711     if (childrenInline())
2712         return positionForPointWithInlineChildren(pointInLogicalContents, region);
2713
2714     RenderBox* lastCandidateBox = lastChildBox();
2715
2716     if (!region)
2717         region = regionAtBlockOffset(pointInLogicalContents.y());
2718
2719     while (lastCandidateBox && !isChildHitTestCandidate(*lastCandidateBox, region, pointInLogicalContents))
2720         lastCandidateBox = lastCandidateBox->previousSiblingBox();
2721
2722     bool blocksAreFlipped = style().isFlippedBlocksWritingMode();
2723     if (lastCandidateBox) {
2724         if (pointInLogicalContents.y() > logicalTopForChild(*lastCandidateBox)
2725             || (!blocksAreFlipped && pointInLogicalContents.y() == logicalTopForChild(*lastCandidateBox)))
2726             return positionForPointRespectingEditingBoundaries(*this, *lastCandidateBox, pointInContents);
2727
2728         for (auto childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
2729             if (!isChildHitTestCandidate(*childBox, region, pointInLogicalContents))
2730                 continue;
2731             LayoutUnit childLogicalBottom = logicalTopForChild(*childBox) + logicalHeightForChild(*childBox);
2732             // We hit child if our click is above the bottom of its padding box (like IE6/7 and FF3).
2733             if (isChildHitTestCandidate(*childBox, region, pointInLogicalContents) && (pointInLogicalContents.y() < childLogicalBottom
2734                 || (blocksAreFlipped && pointInLogicalContents.y() == childLogicalBottom)))
2735                 return positionForPointRespectingEditingBoundaries(*this, *childBox, pointInContents);
2736         }
2737     }
2738
2739     // We only get here if there are no hit test candidate children below the click.
2740     return RenderBox::positionForPoint(point, region);
2741 }
2742
2743 void RenderBlock::offsetForContents(LayoutPoint& offset) const
2744 {
2745     offset = flipForWritingMode(offset);
2746     offset += scrolledContentOffset();
2747     offset = flipForWritingMode(offset);
2748 }
2749
2750 void RenderBlock::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
2751 {
2752     ASSERT(!childrenInline());
2753     
2754     computeBlockPreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
2755
2756     maxLogicalWidth = std::max(minLogicalWidth, maxLogicalWidth);
2757
2758     int scrollbarWidth = instrinsicScrollbarLogicalWidth();
2759     maxLogicalWidth += scrollbarWidth;
2760     minLogicalWidth += scrollbarWidth;
2761 }
2762
2763 void RenderBlock::computePreferredLogicalWidths()
2764 {
2765     ASSERT(preferredLogicalWidthsDirty());
2766
2767     updateFirstLetter();
2768
2769     m_minPreferredLogicalWidth = 0;
2770     m_maxPreferredLogicalWidth = 0;
2771
2772     const RenderStyle& styleToUse = style();
2773     if (!isTableCell() && styleToUse.logicalWidth().isFixed() && styleToUse.logicalWidth().value() >= 0
2774         && !(isDeprecatedFlexItem() && !styleToUse.logicalWidth().intValue()))
2775         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalWidth().value());
2776     else
2777         computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
2778     
2779     if (styleToUse.logicalMinWidth().isFixed() && styleToUse.logicalMinWidth().value() > 0) {
2780         m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMinWidth().value()));
2781         m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMinWidth().value()));
2782     }
2783     
2784     if (styleToUse.logicalMaxWidth().isFixed()) {
2785         m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMaxWidth().value()));
2786         m_minPreferredLogicalWidth = std::min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMaxWidth().value()));
2787     }
2788     
2789     // Table layout uses integers, ceil the preferred widths to ensure that they can contain the contents.
2790     if (isTableCell()) {
2791         m_minPreferredLogicalWidth = m_minPreferredLogicalWidth.ceil();
2792         m_maxPreferredLogicalWidth = m_maxPreferredLogicalWidth.ceil();
2793     }
2794
2795     LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
2796     m_minPreferredLogicalWidth += borderAndPadding;
2797     m_maxPreferredLogicalWidth += borderAndPadding;
2798
2799     setPreferredLogicalWidthsDirty(false);
2800 }
2801
2802 void RenderBlock::computeBlockPreferredLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
2803 {
2804     const RenderStyle& styleToUse = style();
2805     bool nowrap = styleToUse.whiteSpace() == NOWRAP;
2806
2807     RenderObject* child = firstChild();
2808     RenderBlock* containingBlock = this->containingBlock();
2809     LayoutUnit floatLeftWidth = 0, floatRightWidth = 0;
2810     while (child) {
2811         // Positioned children don't affect the min/max width
2812         if (child->isOutOfFlowPositioned()) {
2813             child = child->nextSibling();
2814             continue;
2815         }
2816
2817         const RenderStyle& childStyle = child->style();
2818         if (child->isFloating() || (child->isBox() && toRenderBox(child)->avoidsFloats())) {
2819             LayoutUnit floatTotalWidth = floatLeftWidth + floatRightWidth;
2820             if (childStyle.clear() & CLEFT) {
2821                 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
2822                 floatLeftWidth = 0;
2823             }
2824             if (childStyle.clear() & CRIGHT) {
2825                 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
2826                 floatRightWidth = 0;
2827             }
2828         }
2829
2830         // A margin basically has three types: fixed, percentage, and auto (variable).
2831         // Auto and percentage margins simply become 0 when computing min/max width.
2832         // Fixed margins can be added in as is.
2833         Length startMarginLength = childStyle.marginStartUsing(&styleToUse);
2834         Length endMarginLength = childStyle.marginEndUsing(&styleToUse);
2835         LayoutUnit margin = 0;
2836         LayoutUnit marginStart = 0;
2837         LayoutUnit marginEnd = 0;
2838         if (startMarginLength.isFixed())
2839             marginStart += startMarginLength.value();
2840         if (endMarginLength.isFixed())
2841             marginEnd += endMarginLength.value();
2842         margin = marginStart + marginEnd;
2843
2844         LayoutUnit childMinPreferredLogicalWidth, childMaxPreferredLogicalWidth;
2845         if (child->isBox() && child->isHorizontalWritingMode() != isHorizontalWritingMode()) {
2846             RenderBox* childBox = toRenderBox(child);
2847             LogicalExtentComputedValues computedValues;
2848             childBox->computeLogicalHeight(childBox->borderAndPaddingLogicalHeight(), 0, computedValues);
2849             childMinPreferredLogicalWidth = childMaxPreferredLogicalWidth = computedValues.m_extent;
2850         } else {
2851             childMinPreferredLogicalWidth = child->minPreferredLogicalWidth();
2852             childMaxPreferredLogicalWidth = child->maxPreferredLogicalWidth();
2853         }
2854
2855         LayoutUnit w = childMinPreferredLogicalWidth + margin;
2856         minLogicalWidth = std::max(w, minLogicalWidth);
2857         
2858         // IE ignores tables for calculation of nowrap. Makes some sense.
2859         if (nowrap && !child->isTable())
2860             maxLogicalWidth = std::max(w, maxLogicalWidth);
2861
2862         w = childMaxPreferredLogicalWidth + margin;
2863
2864         if (!child->isFloating()) {
2865             if (child->isBox() && toRenderBox(child)->avoidsFloats()) {
2866                 // Determine a left and right max value based off whether or not the floats can fit in the
2867                 // margins of the object.  For negative margins, we will attempt to overlap the float if the negative margin
2868                 // is smaller than the float width.
2869                 bool ltr = containingBlock ? containingBlock->style().isLeftToRightDirection() : styleToUse.isLeftToRightDirection();
2870                 LayoutUnit marginLogicalLeft = ltr ? marginStart : marginEnd;
2871                 LayoutUnit marginLogicalRight = ltr ? marginEnd : marginStart;
2872                 LayoutUnit maxLeft = marginLogicalLeft > 0 ? std::max(floatLeftWidth, marginLogicalLeft) : floatLeftWidth + marginLogicalLeft;
2873                 LayoutUnit maxRight = marginLogicalRight > 0 ? std::max(floatRightWidth, marginLogicalRight) : floatRightWidth + marginLogicalRight;
2874                 w = childMaxPreferredLogicalWidth + maxLeft + maxRight;
2875                 w = std::max(w, floatLeftWidth + floatRightWidth);
2876             }
2877             else
2878                 maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
2879             floatLeftWidth = floatRightWidth = 0;
2880         }
2881         
2882         if (child->isFloating()) {
2883             if (childStyle.floating() == LeftFloat)
2884                 floatLeftWidth += w;
2885             else
2886                 floatRightWidth += w;
2887         } else
2888             maxLogicalWidth = std::max(w, maxLogicalWidth);
2889         
2890         child = child->nextSibling();
2891     }
2892
2893     // Always make sure these values are non-negative.
2894     minLogicalWidth = std::max<LayoutUnit>(0, minLogicalWidth);
2895     maxLogicalWidth = std::max<LayoutUnit>(0, maxLogicalWidth);
2896
2897     maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
2898 }
2899
2900 bool RenderBlock::hasLineIfEmpty() const
2901 {
2902     if (!element())
2903         return false;
2904     
2905     if (element()->isRootEditableElement())
2906         return true;
2907     
2908     return false;
2909 }
2910
2911 LayoutUnit RenderBlock::lineHeight(bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
2912 {
2913     // Inline blocks are replaced elements. Otherwise, just pass off to
2914     // the base class.  If we're being queried as though we're the root line
2915     // box, then the fact that we're an inline-block is irrelevant, and we behave
2916     // just like a block.
2917     if (isReplaced() && linePositionMode == PositionOnContainingLine)
2918         return RenderBox::lineHeight(firstLine, direction, linePositionMode);
2919
2920     if (firstLine && document().styleSheetCollection().usesFirstLineRules()) {
2921         RenderStyle& s = firstLine ? firstLineStyle() : style();
2922         if (&s != &style())
2923             return s.computedLineHeight();
2924     }
2925     
2926     if (m_lineHeight == -1)
2927         m_lineHeight = style().computedLineHeight();
2928
2929     return m_lineHeight;
2930 }
2931
2932 int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
2933 {
2934     // Inline blocks are replaced elements. Otherwise, just pass off to
2935     // the base class.  If we're being queried as though we're the root line
2936     // box, then the fact that we're an inline-block is irrelevant, and we behave
2937     // just like a block.
2938     if (isReplaced() && linePositionMode == PositionOnContainingLine) {
2939         // For "leaf" theme objects, let the theme decide what the baseline position is.
2940         // FIXME: Might be better to have a custom CSS property instead, so that if the theme
2941         // is turned off, checkboxes/radios will still have decent baselines.
2942         // FIXME: Need to patch form controls to deal with vertical lines.
2943         if (style().hasAppearance() && !theme().isControlContainer(style().appearance()))
2944             return theme().baselinePosition(*this);
2945             
2946         // CSS2.1 states that the baseline of an inline block is the baseline of the last line box in
2947         // the normal flow.  We make an exception for marquees, since their baselines are meaningless
2948         // (the content inside them moves).  This matches WinIE as well, which just bottom-aligns them.
2949         // We also give up on finding a baseline if we have a vertical scrollbar, or if we are scrolled
2950         // vertically (e.g., an overflow:hidden block that has had scrollTop moved) or if the baseline is outside
2951         // of our content box.
2952         bool ignoreBaseline = (layer() && (layer()->marquee() || (direction == HorizontalLine ? (layer()->verticalScrollbar() || layer()->scrollYOffset() != 0)
2953             : (layer()->horizontalScrollbar() || layer()->scrollXOffset() != 0)))) || (isWritingModeRoot() && !isRubyRun());
2954         
2955         int baselinePos = ignoreBaseline ? -1 : inlineBlockBaseline(direction);
2956         
2957         LayoutUnit bottomOfContent = direction == HorizontalLine ? borderTop() + paddingTop() + contentHeight() : borderRight() + paddingRight() + contentWidth();
2958         if (baselinePos != -1 && baselinePos <= bottomOfContent)
2959             return direction == HorizontalLine ? marginTop() + baselinePos : marginRight() + baselinePos;
2960             
2961         return RenderBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
2962     }
2963
2964     const RenderStyle& style = firstLine ? firstLineStyle() : this->style();
2965     const FontMetrics& fontMetrics = style.fontMetrics();
2966     return fontMetrics.ascent(baselineType) + (lineHeight(firstLine, direction, linePositionMode) - fontMetrics.height()) / 2;
2967 }
2968
2969 LayoutUnit RenderBlock::minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const
2970 {
2971     if (!document().inNoQuirksMode() && replacedHeight)
2972         return replacedHeight;
2973
2974     const RenderStyle& style = isFirstLine ? firstLineStyle() : this->style();
2975     if (!(style.lineBoxContain() & LineBoxContainBlock))
2976         return 0;
2977
2978     return std::max<LayoutUnit>(replacedHeight, lineHeight(isFirstLine, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
2979 }
2980
2981 int RenderBlock::firstLineBaseline() const
2982 {
2983     if (isWritingModeRoot() && !isRubyRun())
2984         return -1;
2985
2986     for (RenderBox* curr = firstChildBox(); curr; curr = curr->nextSiblingBox()) {
2987         if (!curr->isFloatingOrOutOfFlowPositioned()) {
2988             int result = curr->firstLineBaseline();
2989             if (result != -1)
2990                 return curr->logicalTop() + result; // Translate to our coordinate space.
2991         }
2992     }
2993
2994     return -1;
2995 }
2996
2997 int RenderBlock::inlineBlockBaseline(LineDirectionMode lineDirection) const
2998 {
2999     if (isWritingModeRoot() && !isRubyRun())
3000         return -1;
3001
3002     bool haveNormalFlowChild = false;
3003     for (auto box = lastChildBox(); box; box = box->previousSiblingBox()) {
3004         if (box->isFloatingOrOutOfFlowPositioned())
3005             continue;
3006         haveNormalFlowChild = true;
3007         int result = box->inlineBlockBaseline(lineDirection);
3008         if (result != -1)
3009             return box->logicalTop() + result; // Translate to our coordinate space.
3010     }
3011
3012     if (!haveNormalFlowChild && hasLineIfEmpty()) {
3013         auto& fontMetrics = firstLineStyle().fontMetrics();
3014         return fontMetrics.ascent()
3015              + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3016              + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
3017     }
3018
3019     return -1;
3020 }
3021
3022 static inline bool isRenderBlockFlowOrRenderButton(RenderElement& renderElement)
3023 {
3024     // We include isRenderButton in this check because buttons are implemented
3025     // using flex box but should still support first-line|first-letter.
3026     // The flex box and specs require that flex box and grid do not support
3027     // first-line|first-letter, though.
3028     // FIXME: Remove when buttons are implemented with align-items instead of
3029     // flex box.
3030     return renderElement.isRenderBlockFlow() || renderElement.isRenderButton();
3031 }
3032
3033 RenderBlock* RenderBlock::firstLineBlock() const
3034 {
3035     RenderBlock* firstLineBlock = const_cast<RenderBlock*>(this);
3036     bool hasPseudo = false;
3037     while (true) {
3038         hasPseudo = firstLineBlock->style().hasPseudoStyle(FIRST_LINE);
3039         if (hasPseudo)
3040             break;
3041         RenderElement* parentBlock = firstLineBlock->parent();
3042         if (firstLineBlock->isReplaced() || firstLineBlock->isFloating()
3043             || !parentBlock || parentBlock->firstChild() != firstLineBlock || !isRenderBlockFlowOrRenderButton(*parentBlock))
3044             break;
3045         firstLineBlock = toRenderBlock(parentBlock);
3046     } 
3047     
3048     if (!hasPseudo)
3049         return 0;
3050     
3051     return firstLineBlock;
3052 }
3053
3054 static RenderStyle* styleForFirstLetter(RenderObject* firstLetterBlock, RenderObject* firstLetterContainer)
3055 {
3056     RenderStyle* pseudoStyle = firstLetterBlock->getCachedPseudoStyle(FIRST_LETTER, &firstLetterContainer->firstLineStyle());
3057     
3058     // If we have an initial letter drop that is >= 1, then we need to force floating to be on.
3059     if (pseudoStyle->initialLetterDrop() >= 1 && !pseudoStyle->isFloating())
3060         pseudoStyle->setFloating(pseudoStyle->isLeftToRightDirection() ? LeftFloat : RightFloat);
3061
3062     // We have to compute the correct font-size for the first-letter if it has an initial letter height set.
3063     RenderObject* paragraph = firstLetterContainer->isRenderBlockFlow() ? firstLetterContainer : firstLetterContainer->containingBlock();
3064     if (pseudoStyle->initialLetterHeight() >= 1 && pseudoStyle->fontMetrics().hasCapHeight() && paragraph->style().fontMetrics().hasCapHeight()) {
3065         // FIXME: For ideographic baselines, we want to go from line edge to line edge. This is equivalent to (N-1)*line-height + the font height.
3066         // We don't yet support ideographic baselines.
3067         // For an N-line first-letter and for alphabetic baselines, the cap-height of the first letter needs to equal (N-1)*line-height of paragraph lines + cap-height of the paragraph
3068         // Mathematically we can't rely on font-size, since font().height() doesn't necessarily match. For reliability, the best approach is simply to
3069         // compare the final measured cap-heights of the two fonts in order to get to the closest possible value.
3070         pseudoStyle->setLineBoxContain(LineBoxContainInitialLetter);
3071         int lineHeight = paragraph->style().computedLineHeight();
3072         
3073         // Set the font to be one line too big and then ratchet back to get to a precise fit. We can't just set the desired font size based off font height metrics
3074         // because many fonts bake ascent into the font metrics. Therefore we have to look at actual measured cap height values in order to know when we have a good fit.
3075         FontDescription newFontDescription = pseudoStyle->fontDescription();
3076         float capRatio = pseudoStyle->fontMetrics().floatCapHeight() / pseudoStyle->fontSize();
3077         float startingFontSize = ((pseudoStyle->initialLetterHeight() - 1) * lineHeight + paragraph->style().fontMetrics().capHeight()) / capRatio;
3078         newFontDescription.setSpecifiedSize(startingFontSize);
3079         newFontDescription.setComputedSize(startingFontSize);
3080         pseudoStyle->setFontDescription(newFontDescription);
3081         pseudoStyle->font().update(pseudoStyle->font().fontSelector());
3082         
3083         int desiredCapHeight = (pseudoStyle->initialLetterHeight() - 1) * lineHeight + paragraph->style().fontMetrics().capHeight();
3084         int actualCapHeight = pseudoStyle->fontMetrics().capHeight();
3085         while (actualCapHeight > desiredCapHeight) {
3086             FontDescription newFontDescription = pseudoStyle->fontDescription();
3087             newFontDescription.setSpecifiedSize(newFontDescription.specifiedSize() - 1);
3088             newFontDescription.setComputedSize(newFontDescription.computedSize() -1);
3089             pseudoStyle->setFontDescription(newFontDescription);
3090             pseudoStyle->font().update(pseudoStyle->font().fontSelector());
3091             actualCapHeight = pseudoStyle->fontMetrics().capHeight();
3092         }
3093     }
3094     
3095     // Force inline display (except for floating first-letters).
3096     pseudoStyle->setDisplay(pseudoStyle->isFloating() ? BLOCK : INLINE);
3097     // CSS2 says first-letter can't be positioned.
3098     pseudoStyle->setPosition(StaticPosition);
3099     return pseudoStyle;
3100 }
3101
3102 // CSS 2.1 http://www.w3.org/TR/CSS21/selector.html#first-letter
3103 // "Punctuation (i.e, characters defined in Unicode [UNICODE] in the "open" (Ps), "close" (Pe),
3104 // "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes), that precedes or follows the first letter should be included"
3105 static inline bool isPunctuationForFirstLetter(UChar c)
3106 {
3107     return U_GET_GC_MASK(c) & (U_GC_PS_MASK | U_GC_PE_MASK | U_GC_PI_MASK | U_GC_PF_MASK | U_GC_PO_MASK);
3108 }
3109
3110 static inline bool shouldSkipForFirstLetter(UChar c)
3111 {
3112     return isSpaceOrNewline(c) || c == noBreakSpace || isPunctuationForFirstLetter(c);
3113 }
3114
3115 static inline RenderBlock* findFirstLetterBlock(RenderBlock* start)
3116 {
3117     RenderBlock* firstLetterBlock = start;
3118     while (true) {
3119         bool canHaveFirstLetterRenderer = firstLetterBlock->style().hasPseudoStyle(FIRST_LETTER)
3120             && firstLetterBlock->canHaveGeneratedChildren()
3121             && isRenderBlockFlowOrRenderButton(*firstLetterBlock);
3122         if (canHaveFirstLetterRenderer)
3123             return firstLetterBlock;
3124
3125         RenderElement* parentBlock = firstLetterBlock->parent();
3126         if (firstLetterBlock->isReplaced() || !parentBlock || parentBlock->firstChild() != firstLetterBlock
3127             || !isRenderBlockFlowOrRenderButton(*parentBlock))
3128             return 0;
3129         firstLetterBlock = toRenderBlock(parentBlock);
3130     } 
3131
3132     return 0;
3133 }
3134
3135 void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderObject* currentChild)
3136 {
3137     RenderElement* firstLetter = currentChild->parent();
3138     RenderElement* firstLetterContainer = firstLetter->parent();
3139     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3140     ASSERT(firstLetter->isFloating() || firstLetter->isInline());
3141
3142     if (Style::determineChange(&firstLetter->style(), pseudoStyle) == Style::Detach) {
3143         // The first-letter renderer needs to be replaced. Create a new renderer of the right type.
3144         RenderBoxModelObject* newFirstLetter;
3145         if (pseudoStyle->display() == INLINE)
3146             newFirstLetter = new RenderInline(document(), *pseudoStyle);
3147         else
3148             newFirstLetter = new RenderBlockFlow(document(), *pseudoStyle);
3149         newFirstLetter->initializeStyle();
3150
3151         // Move the first letter into the new renderer.
3152         LayoutStateDisabler layoutStateDisabler(&view());
3153         while (RenderObject* child = firstLetter->firstChild()) {
3154             if (child->isText())
3155                 toRenderText(child)->removeAndDestroyTextBoxes();
3156             firstLetter->removeChild(*child);
3157             newFirstLetter->addChild(child, 0);
3158         }
3159
3160         RenderObject* nextSibling = firstLetter->nextSibling();
3161         if (RenderTextFragment* remainingText = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText()) {
3162             ASSERT(remainingText->isAnonymous() || remainingText->textNode()->renderer() == remainingText);
3163             // Replace the old renderer with the new one.
3164             remainingText->setFirstLetter(*newFirstLetter);
3165             newFirstLetter->setFirstLetterRemainingText(remainingText);
3166         }
3167         // To prevent removal of single anonymous block in RenderBlock::removeChild and causing
3168         // |nextSibling| to go stale, we remove the old first letter using removeChildNode first.
3169         firstLetterContainer->removeChildInternal(*firstLetter, NotifyChildren);
3170         firstLetter->destroy();
3171         firstLetter = newFirstLetter;
3172         firstLetterContainer->addChild(firstLetter, nextSibling);
3173     } else
3174         firstLetter->setStyle(*pseudoStyle);
3175 }
3176
3177 void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderText* currentTextChild)
3178 {
3179     RenderElement* firstLetterContainer = currentTextChild->parent();
3180     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3181     RenderBoxModelObject* firstLetter = 0;
3182     if (pseudoStyle->display() == INLINE)
3183         firstLetter = new RenderInline(document(), *pseudoStyle);
3184     else
3185         firstLetter = new RenderBlockFlow(document(), *pseudoStyle);
3186     firstLetter->initializeStyle();
3187     firstLetterContainer->addChild(firstLetter, currentTextChild);
3188
3189     // The original string is going to be either a generated content string or a DOM node's
3190     // string.  We want the original string before it got transformed in case first-letter has
3191     // no text-transform or a different text-transform applied to it.
3192     String oldText = currentTextChild->originalText();
3193     ASSERT(!oldText.isNull());
3194
3195     if (!oldText.isEmpty()) {
3196         unsigned length = 0;
3197
3198         // Account for leading spaces and punctuation.
3199         while (length < oldText.length() && shouldSkipForFirstLetter(oldText[length]))
3200             length++;
3201
3202         // Account for first grapheme cluster.
3203         length += numCharactersInGraphemeClusters(StringView(oldText).substring(length), 1);
3204         
3205         // Keep looking for whitespace and allowed punctuation, but avoid
3206         // accumulating just whitespace into the :first-letter.
3207         for (unsigned scanLength = length; scanLength < oldText.length(); ++scanLength) {
3208             UChar c = oldText[scanLength];
3209             
3210             if (!shouldSkipForFirstLetter(c))
3211                 break;
3212
3213             if (isPunctuationForFirstLetter(c))
3214                 length = scanLength + 1;
3215          }
3216          
3217         // Construct a text fragment for the text after the first letter.
3218         // This text fragment might be empty.
3219         RenderTextFragment* remainingText;
3220         if (currentTextChild->textNode())
3221             remainingText = new RenderTextFragment(*currentTextChild->textNode(), oldText, length, oldText.length() - length);
3222         else
3223             remainingText = new RenderTextFragment(document(), oldText, length, oldText.length() - length);
3224
3225         if (remainingText->textNode())
3226             remainingText->textNode()->setRenderer(remainingText);
3227
3228         firstLetterContainer->addChild(remainingText, currentTextChild);
3229         firstLetterContainer->removeChild(*currentTextChild);
3230         remainingText->setFirstLetter(*firstLetter);
3231         firstLetter->setFirstLetterRemainingText(remainingText);
3232         
3233         // construct text fragment for the first letter
3234         RenderTextFragment* letter;
3235         if (remainingText->textNode())
3236             letter = new RenderTextFragment(*remainingText->textNode(), oldText, 0, length);
3237         else
3238             letter = new RenderTextFragment(document(), oldText, 0, length);
3239
3240         firstLetter->addChild(letter);
3241
3242         currentTextChild->destroy();
3243     }
3244 }
3245     
3246 void RenderBlock::getFirstLetter(RenderObject*& firstLetter, RenderElement*& firstLetterContainer, RenderObject* skipObject)
3247 {
3248     firstLetter = nullptr;
3249     firstLetterContainer = nullptr;
3250
3251     if (!document().styleSheetCollection().usesFirstLetterRules())
3252         return;
3253
3254     // Don't recur
3255     if (style().styleType() == FIRST_LETTER)
3256         return;
3257     
3258     // FIXME: We need to destroy the first-letter object if it is no longer the first child. Need to find
3259     // an efficient way to check for that situation though before implementing anything.
3260     firstLetterContainer = findFirstLetterBlock(this);
3261     if (!firstLetterContainer)
3262         return;
3263     
3264     // Drill into inlines looking for our first text descendant.
3265     firstLetter = firstLetterContainer->firstChild();
3266     while (firstLetter) {
3267         if (firstLetter->isText()) {
3268             if (firstLetter == skipObject) {
3269                 firstLetter = firstLetter->nextSibling();
3270                 continue;
3271             }
3272             
3273             break;