d7770db1d21a6b43343d4959d8a6b681dc3d73dc
[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(pixelSnappedIntRect(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), pixelSnappedIntRect(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 = roundedLayoutPoint(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(pixelSnappedForPainting(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(pixelSnappedForPainting(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(pixelSnappedForPainting(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 struct InlineMinMaxIterator {
2803 /* InlineMinMaxIterator is a class that will iterate over all render objects that contribute to
2804    inline min/max width calculations.  Note the following about the way it walks:
2805    (1) Positioned content is skipped (since it does not contribute to min/max width of a block)
2806    (2) We do not drill into the children of floats or replaced elements, since you can't break
2807        in the middle of such an element.
2808    (3) Inline flows (e.g., <a>, <span>, <i>) are walked twice, since each side can have
2809        distinct borders/margin/padding that contribute to the min/max width.
2810 */
2811     RenderObject* parent;
2812     RenderObject* current;
2813     bool endOfInline;
2814
2815     InlineMinMaxIterator(RenderObject* p, bool end = false)
2816         :parent(p), current(p), endOfInline(end) {}
2817
2818     RenderObject* next();
2819 };
2820
2821 RenderObject* InlineMinMaxIterator::next()
2822 {
2823     RenderObject* result = 0;
2824     bool oldEndOfInline = endOfInline;
2825     endOfInline = false;
2826     while (current || current == parent) {
2827         if (!oldEndOfInline &&
2828             (current == parent ||
2829              (!current->isFloating() && !current->isReplaced() && !current->isOutOfFlowPositioned())))
2830             result = current->firstChildSlow();
2831         if (!result) {
2832             // We hit the end of our inline. (It was empty, e.g., <span></span>.)
2833             if (!oldEndOfInline && current->isRenderInline()) {
2834                 result = current;
2835                 endOfInline = true;
2836                 break;
2837             }
2838
2839             while (current && current != parent) {
2840                 result = current->nextSibling();
2841                 if (result) break;
2842                 current = current->parent();
2843                 if (current && current != parent && current->isRenderInline()) {
2844                     result = current;
2845                     endOfInline = true;
2846                     break;
2847                 }
2848             }
2849         }
2850
2851         if (!result)
2852             break;
2853
2854         if (!result->isOutOfFlowPositioned() && (result->isTextOrLineBreak() || result->isFloating() || result->isReplaced() || result->isRenderInline()))
2855              break;
2856         
2857         current = result;
2858         result = 0;
2859     }
2860
2861     // Update our position.
2862     current = result;
2863     return current;
2864 }
2865
2866 static LayoutUnit getBPMWidth(LayoutUnit childValue, Length cssUnit)
2867 {
2868     if (cssUnit.type() != Auto)
2869         return (cssUnit.isFixed() ? LayoutUnit(cssUnit.value()) : childValue);
2870     return 0;
2871 }
2872
2873 static LayoutUnit getBorderPaddingMargin(const RenderBoxModelObject* child, bool endOfInline)
2874 {
2875     const RenderStyle& childStyle = child->style();
2876     if (endOfInline)
2877         return getBPMWidth(child->marginEnd(), childStyle.marginEnd()) +
2878                getBPMWidth(child->paddingEnd(), childStyle.paddingEnd()) +
2879                child->borderEnd();
2880     return getBPMWidth(child->marginStart(), childStyle.marginStart()) +
2881                getBPMWidth(child->paddingStart(), childStyle.paddingStart()) +
2882                child->borderStart();
2883 }
2884
2885 static inline void stripTrailingSpace(float& inlineMax, float& inlineMin,
2886                                       RenderObject* trailingSpaceChild)
2887 {
2888     if (trailingSpaceChild && trailingSpaceChild->isText()) {
2889         // Collapse away the trailing space at the end of a block.
2890         RenderText* t = toRenderText(trailingSpaceChild);
2891         const UChar space = ' ';
2892         const Font& font = t->style().font(); // FIXME: This ignores first-line.
2893         float spaceWidth = font.width(RenderBlock::constructTextRun(t, font, &space, 1, t->style()));
2894         inlineMax -= spaceWidth + font.wordSpacing();
2895         if (inlineMin > inlineMax)
2896             inlineMin = inlineMax;
2897     }
2898 }
2899
2900 static inline void updatePreferredWidth(LayoutUnit& preferredWidth, float& result)
2901 {
2902     LayoutUnit snappedResult = ceiledLayoutUnit(result);
2903     preferredWidth = std::max(snappedResult, preferredWidth);
2904 }
2905
2906 // With sub-pixel enabled: When converting between floating point and LayoutUnits
2907 // we risk losing precision with each conversion. When this occurs while
2908 // accumulating our preferred widths, we can wind up with a line width that's
2909 // larger than our maxPreferredWidth due to pure float accumulation.
2910 //
2911 // With sub-pixel disabled: values from Lengths or the render tree aren't subject
2912 // to the same loss of precision, as they're always truncated and stored as
2913 // integers. We mirror that behavior here to prevent over-allocating our preferred
2914 // width.
2915 static inline LayoutUnit adjustFloatForSubPixelLayout(float value)
2916 {
2917     return ceiledLayoutUnit(value);
2918 }
2919
2920
2921 void RenderBlock::computeInlinePreferredLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth)
2922 {
2923     float inlineMax = 0;
2924     float inlineMin = 0;
2925
2926     const RenderStyle& styleToUse = style();
2927     RenderBlock* containingBlock = this->containingBlock();
2928     LayoutUnit cw = containingBlock ? containingBlock->contentLogicalWidth() : LayoutUnit();
2929
2930     // If we are at the start of a line, we want to ignore all white-space.
2931     // Also strip spaces if we previously had text that ended in a trailing space.
2932     bool stripFrontSpaces = true;
2933     RenderObject* trailingSpaceChild = 0;
2934
2935     // Firefox and Opera will allow a table cell to grow to fit an image inside it under
2936     // very specific cirucumstances (in order to match common WinIE renderings). 
2937     // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.) 
2938     bool allowImagesToBreak = !document().inQuirksMode() || !isTableCell() || !styleToUse.logicalWidth().isIntrinsicOrAuto();
2939
2940     bool autoWrap, oldAutoWrap;
2941     autoWrap = oldAutoWrap = styleToUse.autoWrap();
2942
2943     InlineMinMaxIterator childIterator(this);
2944
2945     // Only gets added to the max preffered width once.
2946     bool addedTextIndent = false;
2947     // Signals the text indent was more negative than the min preferred width
2948     bool hasRemainingNegativeTextIndent = false;
2949
2950     LayoutUnit textIndent = minimumValueForLength(styleToUse.textIndent(), cw);
2951     RenderObject* prevFloat = 0;
2952     bool isPrevChildInlineFlow = false;
2953     bool shouldBreakLineAfterText = false;
2954     while (RenderObject* child = childIterator.next()) {
2955         autoWrap = child->isReplaced() ? child->parent()->style().autoWrap() : 
2956             child->style().autoWrap();
2957
2958         if (!child->isBR()) {
2959             // Step One: determine whether or not we need to go ahead and
2960             // terminate our current line.  Each discrete chunk can become
2961             // the new min-width, if it is the widest chunk seen so far, and
2962             // it can also become the max-width.
2963
2964             // Children fall into three categories:
2965             // (1) An inline flow object.  These objects always have a min/max of 0,
2966             // and are included in the iteration solely so that their margins can
2967             // be added in.
2968             //
2969             // (2) An inline non-text non-flow object, e.g., an inline replaced element.
2970             // These objects can always be on a line by themselves, so in this situation
2971             // we need to go ahead and break the current line, and then add in our own
2972             // margins and min/max width on its own line, and then terminate the line.
2973             //
2974             // (3) A text object.  Text runs can have breakable characters at the start,
2975             // the middle or the end.  They may also lose whitespace off the front if
2976             // we're already ignoring whitespace.  In order to compute accurate min-width
2977             // information, we need three pieces of information.
2978             // (a) the min-width of the first non-breakable run.  Should be 0 if the text string
2979             // starts with whitespace.
2980             // (b) the min-width of the last non-breakable run. Should be 0 if the text string
2981             // ends with whitespace.
2982             // (c) the min/max width of the string (trimmed for whitespace).
2983             //
2984             // If the text string starts with whitespace, then we need to go ahead and
2985             // terminate our current line (unless we're already in a whitespace stripping
2986             // mode.
2987             //
2988             // If the text string has a breakable character in the middle, but didn't start
2989             // with whitespace, then we add the width of the first non-breakable run and
2990             // then end the current line.  We then need to use the intermediate min/max width
2991             // values (if any of them are larger than our current min/max).  We then look at
2992             // the width of the last non-breakable run and use that to start a new line
2993             // (unless we end in whitespace).
2994             const RenderStyle& childStyle = child->style();
2995             float childMin = 0;
2996             float childMax = 0;
2997
2998             if (!child->isText()) {
2999                 if (child->isLineBreakOpportunity()) {
3000                     updatePreferredWidth(minLogicalWidth, inlineMin);
3001                     inlineMin = 0;
3002                     continue;
3003                 }
3004                 // Case (1) and (2).  Inline replaced and inline flow elements.
3005                 if (child->isRenderInline()) {
3006                     // Add in padding/border/margin from the appropriate side of
3007                     // the element.
3008                     float bpm = getBorderPaddingMargin(toRenderInline(child), childIterator.endOfInline);
3009                     childMin += bpm;
3010                     childMax += bpm;
3011
3012                     inlineMin += childMin;
3013                     inlineMax += childMax;
3014                     
3015                     child->setPreferredLogicalWidthsDirty(false);
3016                 } else {
3017                     // Inline replaced elts add in their margins to their min/max values.
3018                     LayoutUnit margins = 0;
3019                     Length startMargin = childStyle.marginStart();
3020                     Length endMargin = childStyle.marginEnd();
3021                     if (startMargin.isFixed())
3022                         margins += adjustFloatForSubPixelLayout(startMargin.value());
3023                     if (endMargin.isFixed())
3024                         margins += adjustFloatForSubPixelLayout(endMargin.value());
3025                     childMin += margins.ceilToFloat();
3026                     childMax += margins.ceilToFloat();
3027                 }
3028             }
3029
3030             if (!child->isRenderInline() && !child->isText()) {
3031                 // Case (2). Inline replaced elements and floats.
3032                 // Go ahead and terminate the current line as far as
3033                 // minwidth is concerned.
3034                 childMin += child->minPreferredLogicalWidth().ceilToFloat();
3035                 childMax += child->maxPreferredLogicalWidth().ceilToFloat();
3036
3037                 bool clearPreviousFloat;
3038                 if (child->isFloating()) {
3039                     clearPreviousFloat = (prevFloat
3040                         && ((prevFloat->style().floating() == LeftFloat && (childStyle.clear() & CLEFT))
3041                             || (prevFloat->style().floating() == RightFloat && (childStyle.clear() & CRIGHT))));
3042                     prevFloat = child;
3043                 } else
3044                     clearPreviousFloat = false;
3045
3046                 bool canBreakReplacedElement = !child->isImage() || allowImagesToBreak;
3047                 if ((canBreakReplacedElement && (autoWrap || oldAutoWrap) && (!isPrevChildInlineFlow || shouldBreakLineAfterText)) || clearPreviousFloat) {
3048                     updatePreferredWidth(minLogicalWidth, inlineMin);
3049                     inlineMin = 0;
3050                 }
3051
3052                 // If we're supposed to clear the previous float, then terminate maxwidth as well.
3053                 if (clearPreviousFloat) {
3054                     updatePreferredWidth(maxLogicalWidth, inlineMax);
3055                     inlineMax = 0;
3056                 }
3057
3058                 // Add in text-indent.  This is added in only once.
3059                 if (!addedTextIndent && !child->isFloating()) {
3060                     LayoutUnit ceiledIndent = textIndent.ceilToFloat();
3061                     childMin += ceiledIndent;
3062                     childMax += ceiledIndent;
3063
3064                     if (childMin < 0)
3065                         textIndent = adjustFloatForSubPixelLayout(childMin);
3066                     else
3067                         addedTextIndent = true;
3068                 }
3069
3070                 // Add our width to the max.
3071                 inlineMax += std::max<float>(0, childMax);
3072
3073                 if (!autoWrap || !canBreakReplacedElement || (isPrevChildInlineFlow && !shouldBreakLineAfterText)) {
3074                     if (child->isFloating())
3075                         updatePreferredWidth(minLogicalWidth, childMin);
3076                     else
3077                         inlineMin += childMin;
3078                 } else {
3079                     // Now check our line.
3080                     updatePreferredWidth(minLogicalWidth, childMin);
3081
3082                     // Now start a new line.
3083                     inlineMin = 0;
3084                 }
3085
3086                 if (autoWrap && canBreakReplacedElement && isPrevChildInlineFlow) {
3087                     updatePreferredWidth(minLogicalWidth, inlineMin);
3088                     inlineMin = 0;
3089                 }
3090
3091                 // We are no longer stripping whitespace at the start of
3092                 // a line.
3093                 if (!child->isFloating()) {
3094                     stripFrontSpaces = false;
3095                     trailingSpaceChild = 0;
3096                 }
3097             } else if (child->isText()) {
3098                 // Case (3). Text.
3099                 RenderText* t = toRenderText(child);
3100
3101                 if (t->style().hasTextCombine() && t->isCombineText())
3102                     toRenderCombineText(*t).combineText();
3103
3104                 // Determine if we have a breakable character.  Pass in
3105                 // whether or not we should ignore any spaces at the front
3106                 // of the string.  If those are going to be stripped out,
3107                 // then they shouldn't be considered in the breakable char
3108                 // check.
3109                 bool hasBreakableChar, hasBreak;
3110                 float beginMin, endMin;
3111                 bool beginWS, endWS;
3112                 float beginMax, endMax;
3113                 t->trimmedPrefWidths(inlineMax, beginMin, beginWS, endMin, endWS,
3114                                      hasBreakableChar, hasBreak, beginMax, endMax,
3115                                      childMin, childMax, stripFrontSpaces);
3116
3117                 // This text object will not be rendered, but it may still provide a breaking opportunity.
3118                 if (!hasBreak && childMax == 0) {
3119                     if (autoWrap && (beginWS || endWS)) {
3120                         updatePreferredWidth(minLogicalWidth, inlineMin);
3121                         inlineMin = 0;
3122                     }
3123                     continue;
3124                 }
3125                 
3126                 if (stripFrontSpaces)
3127                     trailingSpaceChild = child;
3128                 else
3129                     trailingSpaceChild = 0;
3130
3131                 // Add in text-indent.  This is added in only once.
3132                 float ti = 0;
3133                 if (!addedTextIndent || hasRemainingNegativeTextIndent) {
3134                     ti = textIndent.ceilToFloat();
3135                     childMin += ti;
3136                     beginMin += ti;
3137                     
3138                     // It the text indent negative and larger than the child minimum, we re-use the remainder
3139                     // in future minimum calculations, but using the negative value again on the maximum
3140                     // will lead to under-counting the max pref width.
3141                     if (!addedTextIndent) {
3142                         childMax += ti;
3143                         beginMax += ti;
3144                         addedTextIndent = true;
3145                     }
3146                     
3147                     if (childMin < 0) {
3148                         textIndent = childMin;
3149                         hasRemainingNegativeTextIndent = true;
3150                     }
3151                 }
3152                 
3153                 // If we have no breakable characters at all,
3154                 // then this is the easy case. We add ourselves to the current
3155                 // min and max and continue.
3156                 if (!hasBreakableChar) {
3157                     inlineMin += childMin;
3158                 } else {
3159                     // We have a breakable character.  Now we need to know if
3160                     // we start and end with whitespace.
3161                     if (beginWS)
3162                         // Go ahead and end the current line.
3163                         updatePreferredWidth(minLogicalWidth, inlineMin);
3164                     else {
3165                         inlineMin += beginMin;
3166                         updatePreferredWidth(minLogicalWidth, inlineMin);
3167                         childMin -= ti;
3168                     }
3169
3170                     inlineMin = childMin;
3171
3172                     if (endWS) {
3173                         // We end in whitespace, which means we can go ahead
3174                         // and end our current line.
3175                         updatePreferredWidth(minLogicalWidth, inlineMin);
3176                         inlineMin = 0;
3177                         shouldBreakLineAfterText = false;
3178                     } else {
3179                         updatePreferredWidth(minLogicalWidth, inlineMin);
3180                         inlineMin = endMin;
3181                         shouldBreakLineAfterText = true;
3182                     }
3183                 }
3184
3185                 if (hasBreak) {
3186                     inlineMax += beginMax;
3187                     updatePreferredWidth(maxLogicalWidth, inlineMax);
3188                     updatePreferredWidth(maxLogicalWidth, childMax);
3189                     inlineMax = endMax;
3190                     addedTextIndent = true;
3191                 } else
3192                     inlineMax += std::max<float>(0, childMax);
3193             }
3194
3195             // Ignore spaces after a list marker.
3196             if (child->isListMarker())
3197                 stripFrontSpaces = true;
3198         } else {
3199             updatePreferredWidth(minLogicalWidth, inlineMin);
3200             updatePreferredWidth(maxLogicalWidth, inlineMax);
3201             inlineMin = inlineMax = 0;
3202             stripFrontSpaces = true;
3203             trailingSpaceChild = 0;
3204             addedTextIndent = true;
3205         }
3206
3207         if (!child->isText() && child->isRenderInline())
3208             isPrevChildInlineFlow = true;
3209         else
3210             isPrevChildInlineFlow = false;
3211
3212         oldAutoWrap = autoWrap;
3213     }
3214
3215     if (styleToUse.collapseWhiteSpace())
3216         stripTrailingSpace(inlineMax, inlineMin, trailingSpaceChild);
3217
3218     updatePreferredWidth(minLogicalWidth, inlineMin);
3219     updatePreferredWidth(maxLogicalWidth, inlineMax);
3220 }
3221
3222 void RenderBlock::computeBlockPreferredLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
3223 {
3224     const RenderStyle& styleToUse = style();
3225     bool nowrap = styleToUse.whiteSpace() == NOWRAP;
3226
3227     RenderObject* child = firstChild();
3228     RenderBlock* containingBlock = this->containingBlock();
3229     LayoutUnit floatLeftWidth = 0, floatRightWidth = 0;
3230     while (child) {
3231         // Positioned children don't affect the min/max width
3232         if (child->isOutOfFlowPositioned()) {
3233             child = child->nextSibling();
3234             continue;
3235         }
3236
3237         const RenderStyle& childStyle = child->style();
3238         if (child->isFloating() || (child->isBox() && toRenderBox(child)->avoidsFloats())) {
3239             LayoutUnit floatTotalWidth = floatLeftWidth + floatRightWidth;
3240             if (childStyle.clear() & CLEFT) {
3241                 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
3242                 floatLeftWidth = 0;
3243             }
3244             if (childStyle.clear() & CRIGHT) {
3245                 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
3246                 floatRightWidth = 0;
3247             }
3248         }
3249
3250         // A margin basically has three types: fixed, percentage, and auto (variable).
3251         // Auto and percentage margins simply become 0 when computing min/max width.
3252         // Fixed margins can be added in as is.
3253         Length startMarginLength = childStyle.marginStartUsing(&styleToUse);
3254         Length endMarginLength = childStyle.marginEndUsing(&styleToUse);
3255         LayoutUnit margin = 0;
3256         LayoutUnit marginStart = 0;
3257         LayoutUnit marginEnd = 0;
3258         if (startMarginLength.isFixed())
3259             marginStart += startMarginLength.value();
3260         if (endMarginLength.isFixed())
3261             marginEnd += endMarginLength.value();
3262         margin = marginStart + marginEnd;
3263
3264         LayoutUnit childMinPreferredLogicalWidth, childMaxPreferredLogicalWidth;
3265         if (child->isBox() && child->isHorizontalWritingMode() != isHorizontalWritingMode()) {
3266             RenderBox* childBox = toRenderBox(child);
3267             LogicalExtentComputedValues computedValues;
3268             childBox->computeLogicalHeight(childBox->borderAndPaddingLogicalHeight(), 0, computedValues);
3269             childMinPreferredLogicalWidth = childMaxPreferredLogicalWidth = computedValues.m_extent;
3270         } else {
3271             childMinPreferredLogicalWidth = child->minPreferredLogicalWidth();
3272             childMaxPreferredLogicalWidth = child->maxPreferredLogicalWidth();
3273         }
3274
3275         LayoutUnit w = childMinPreferredLogicalWidth + margin;
3276         minLogicalWidth = std::max(w, minLogicalWidth);
3277         
3278         // IE ignores tables for calculation of nowrap. Makes some sense.
3279         if (nowrap && !child->isTable())
3280             maxLogicalWidth = std::max(w, maxLogicalWidth);
3281
3282         w = childMaxPreferredLogicalWidth + margin;
3283
3284         if (!child->isFloating()) {
3285             if (child->isBox() && toRenderBox(child)->avoidsFloats()) {
3286                 // Determine a left and right max value based off whether or not the floats can fit in the
3287                 // margins of the object.  For negative margins, we will attempt to overlap the float if the negative margin
3288                 // is smaller than the float width.
3289                 bool ltr = containingBlock ? containingBlock->style().isLeftToRightDirection() : styleToUse.isLeftToRightDirection();
3290                 LayoutUnit marginLogicalLeft = ltr ? marginStart : marginEnd;
3291                 LayoutUnit marginLogicalRight = ltr ? marginEnd : marginStart;
3292                 LayoutUnit maxLeft = marginLogicalLeft > 0 ? std::max(floatLeftWidth, marginLogicalLeft) : floatLeftWidth + marginLogicalLeft;
3293                 LayoutUnit maxRight = marginLogicalRight > 0 ? std::max(floatRightWidth, marginLogicalRight) : floatRightWidth + marginLogicalRight;
3294                 w = childMaxPreferredLogicalWidth + maxLeft + maxRight;
3295                 w = std::max(w, floatLeftWidth + floatRightWidth);
3296             }
3297             else
3298                 maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
3299             floatLeftWidth = floatRightWidth = 0;
3300         }
3301         
3302         if (child->isFloating()) {
3303             if (childStyle.floating() == LeftFloat)
3304                 floatLeftWidth += w;
3305             else
3306                 floatRightWidth += w;
3307         } else
3308             maxLogicalWidth = std::max(w, maxLogicalWidth);
3309         
3310         child = child->nextSibling();
3311     }
3312
3313     // Always make sure these values are non-negative.
3314     minLogicalWidth = std::max<LayoutUnit>(0, minLogicalWidth);
3315     maxLogicalWidth = std::max<LayoutUnit>(0, maxLogicalWidth);
3316
3317     maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
3318 }
3319
3320 bool RenderBlock::hasLineIfEmpty() const
3321 {
3322     if (!element())
3323         return false;
3324     
3325     if (element()->isRootEditableElement())
3326         return true;
3327     
3328     return false;
3329 }
3330
3331 LayoutUnit RenderBlock::lineHeight(bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
3332 {
3333     // Inline blocks are replaced elements. Otherwise, just pass off to
3334     // the base class.  If we're being queried as though we're the root line
3335     // box, then the fact that we're an inline-block is irrelevant, and we behave
3336     // just like a block.
3337     if (isReplaced() && linePositionMode == PositionOnContainingLine)
3338         return RenderBox::lineHeight(firstLine, direction, linePositionMode);
3339
3340     if (firstLine && document().styleSheetCollection().usesFirstLineRules()) {
3341         RenderStyle& s = firstLine ? firstLineStyle() : style();
3342         if (&s != &style())
3343             return s.computedLineHeight();
3344     }
3345     
3346     if (m_lineHeight == -1)
3347         m_lineHeight = style().computedLineHeight();
3348
3349     return m_lineHeight;
3350 }
3351
3352 int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
3353 {
3354     // Inline blocks are replaced elements. Otherwise, just pass off to
3355     // the base class.  If we're being queried as though we're the root line
3356     // box, then the fact that we're an inline-block is irrelevant, and we behave
3357     // just like a block.
3358     if (isReplaced() && linePositionMode == PositionOnContainingLine) {
3359         // For "leaf" theme objects, let the theme decide what the baseline position is.
3360         // FIXME: Might be better to have a custom CSS property instead, so that if the theme
3361         // is turned off, checkboxes/radios will still have decent baselines.
3362         // FIXME: Need to patch form controls to deal with vertical lines.
3363         if (style().hasAppearance() && !theme().isControlContainer(style().appearance()))
3364             return theme().baselinePosition(*this);
3365             
3366         // CSS2.1 states that the baseline of an inline block is the baseline of the last line box in
3367         // the normal flow.  We make an exception for marquees, since their baselines are meaningless
3368         // (the content inside them moves).  This matches WinIE as well, which just bottom-aligns them.
3369         // We also give up on finding a baseline if we have a vertical scrollbar, or if we are scrolled
3370         // vertically (e.g., an overflow:hidden block that has had scrollTop moved) or if the baseline is outside
3371         // of our content box.
3372         bool ignoreBaseline = (layer() && (layer()->marquee() || (direction == HorizontalLine ? (layer()->verticalScrollbar() || layer()->scrollYOffset() != 0)
3373             : (layer()->horizontalScrollbar() || layer()->scrollXOffset() != 0)))) || (isWritingModeRoot() && !isRubyRun());
3374         
3375         int baselinePos = ignoreBaseline ? -1 : inlineBlockBaseline(direction);
3376         
3377         LayoutUnit bottomOfContent = direction == HorizontalLine ? borderTop() + paddingTop() + contentHeight() : borderRight() + paddingRight() + contentWidth();
3378         if (baselinePos != -1 && baselinePos <= bottomOfContent)
3379             return direction == HorizontalLine ? marginTop() + baselinePos : marginRight() + baselinePos;
3380             
3381         return RenderBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
3382     }
3383
3384     const RenderStyle& style = firstLine ? firstLineStyle() : this->style();
3385     const FontMetrics& fontMetrics = style.fontMetrics();
3386     return fontMetrics.ascent(baselineType) + (lineHeight(firstLine, direction, linePositionMode) - fontMetrics.height()) / 2;
3387 }
3388
3389 LayoutUnit RenderBlock::minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const
3390 {
3391     if (!document().inNoQuirksMode() && replacedHeight)
3392         return replacedHeight;
3393
3394     const RenderStyle& style = isFirstLine ? firstLineStyle() : this->style();
3395     if (!(style.lineBoxContain() & LineBoxContainBlock))
3396         return 0;
3397
3398     return std::max<LayoutUnit>(replacedHeight, lineHeight(isFirstLine, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
3399 }
3400
3401 int RenderBlock::firstLineBaseline() const
3402 {
3403     if (isWritingModeRoot() && !isRubyRun())
3404         return -1;
3405
3406     for (RenderBox* curr = firstChildBox(); curr; curr = curr->nextSiblingBox()) {
3407         if (!curr->isFloatingOrOutOfFlowPositioned()) {
3408             int result = curr->firstLineBaseline();
3409             if (result != -1)
3410                 return curr->logicalTop() + result; // Translate to our coordinate space.
3411         }
3412     }
3413
3414     return -1;
3415 }
3416
3417 int RenderBlock::inlineBlockBaseline(LineDirectionMode lineDirection) const
3418 {
3419     if (isWritingModeRoot() && !isRubyRun())
3420         return -1;
3421
3422     bool haveNormalFlowChild = false;
3423     for (auto box = lastChildBox(); box; box = box->previousSiblingBox()) {
3424         if (box->isFloatingOrOutOfFlowPositioned())
3425             continue;
3426         haveNormalFlowChild = true;
3427         int result = box->inlineBlockBaseline(lineDirection);
3428         if (result != -1)
3429             return box->logicalTop() + result; // Translate to our coordinate space.
3430     }
3431
3432     if (!haveNormalFlowChild && hasLineIfEmpty()) {
3433         auto& fontMetrics = firstLineStyle().fontMetrics();
3434         return fontMetrics.ascent()
3435              + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3436              + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
3437     }
3438
3439     return -1;
3440 }
3441
3442 RenderBlock* RenderBlock::firstLineBlock() const
3443 {
3444     RenderBlock* firstLineBlock = const_cast<RenderBlock*>(this);
3445     bool hasPseudo = false;
3446     while (true) {
3447         hasPseudo = firstLineBlock->style().hasPseudoStyle(FIRST_LINE);
3448         if (hasPseudo)
3449             break;
3450         RenderElement* parentBlock = firstLineBlock->parent();
3451         // We include isRenderButton in this check because buttons are
3452         // implemented using flex box but should still support first-line. The
3453         // flex box spec requires that flex box does not support first-line,
3454         // though.
3455         // FIXME: Remove when buttons are implemented with align-items instead
3456         // of flexbox.
3457         if (firstLineBlock->isReplaced() || firstLineBlock->isFloating()
3458             || !parentBlock || parentBlock->firstChild() != firstLineBlock || (!parentBlock->isRenderBlockFlow() && !parentBlock->isRenderButton()))
3459             break;
3460         firstLineBlock = toRenderBlock(parentBlock);
3461     } 
3462     
3463     if (!hasPseudo)
3464         return 0;
3465     
3466     return firstLineBlock;
3467 }
3468
3469 static RenderStyle* styleForFirstLetter(RenderObject* firstLetterBlock, RenderObject* firstLetterContainer)
3470 {
3471     RenderStyle* pseudoStyle = firstLetterBlock->getCachedPseudoStyle(FIRST_LETTER, &firstLetterContainer->firstLineStyle());
3472     // Force inline display (except for floating first-letters).
3473     pseudoStyle->setDisplay(pseudoStyle->isFloating() ? BLOCK : INLINE);
3474     // CSS2 says first-letter can't be positioned.
3475     pseudoStyle->setPosition(StaticPosition);
3476     return pseudoStyle;
3477 }
3478
3479 // CSS 2.1 http://www.w3.org/TR/CSS21/selector.html#first-letter
3480 // "Punctuation (i.e, characters defined in Unicode [UNICODE] in the "open" (Ps), "close" (Pe),
3481 // "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes), that precedes or follows the first letter should be included"
3482 static inline bool isPunctuationForFirstLetter(UChar c)
3483 {
3484     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);
3485 }
3486
3487 static inline bool shouldSkipForFirstLetter(UChar c)
3488 {
3489     return isSpaceOrNewline(c) || c == noBreakSpace || isPunctuationForFirstLetter(c);
3490 }
3491
3492 static inline RenderBlock* findFirstLetterBlock(RenderBlock* start)
3493 {
3494     RenderBlock* firstLetterBlock = start;
3495     while (true) {
3496         // We include isRenderButton in these two checks because buttons are
3497         // implemented using flex box but should still support first-letter.
3498         // The flex box spec requires that flex box does not support
3499         // first-letter, though.
3500         // FIXME: Remove when buttons are implemented with align-items instead
3501         // of flexbox.
3502         bool canHaveFirstLetterRenderer = firstLetterBlock->style().hasPseudoStyle(FIRST_LETTER)
3503             && firstLetterBlock->canHaveGeneratedChildren()
3504             && (!firstLetterBlock->isFlexibleBox() || firstLetterBlock->isRenderButton());
3505         if (canHaveFirstLetterRenderer)
3506             return firstLetterBlock;
3507
3508         RenderElement* parentBlock = firstLetterBlock->parent();
3509         if (firstLetterBlock->isReplaced() || !parentBlock || parentBlock->firstChild() != firstLetterBlock
3510             || (!parentBlock->isRenderBlockFlow() && !parentBlock->isRenderButton()))
3511             return 0;
3512         firstLetterBlock = toRenderBlock(parentBlock);
3513     } 
3514
3515     return 0;
3516 }
3517
3518 void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderObject* currentChild)
3519 {
3520     RenderElement* firstLetter = currentChild->parent();
3521     RenderElement* firstLetterContainer = firstLetter->parent();
3522     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3523     ASSERT(firstLetter->isFloating() || firstLetter->isInline());
3524
3525     if (Style::determineChange(&firstLetter->style(), pseudoStyle) == Style::Detach) {
3526         // The first-letter renderer needs to be replaced. Create a new renderer of the right type.
3527         RenderBoxModelObject* newFirstLetter;
3528         if (pseudoStyle->display() == INLINE)
3529             newFirstLetter = new RenderInline(document(), *pseudoStyle);
3530         else
3531             newFirstLetter = new RenderBlockFlow(document(), *pseudoStyle);
3532         newFirstLetter->initializeStyle();
3533
3534         // Move the first letter into the new renderer.
3535         LayoutStateDisabler layoutStateDisabler(&view());
3536         while (RenderObject* child = firstLetter->firstChild()) {
3537             if (child->isText())
3538                 toRenderText(child)->removeAndDestroyTextBoxes();
3539             firstLetter->removeChild(*child);
3540             newFirstLetter->addChild(child, 0);
3541         }
3542
3543         RenderObject* nextSibling = firstLetter->nextSibling();
3544         if (RenderTextFragment* remainingText = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText()) {
3545             ASSERT(remainingText->isAnonymous() || remainingText->textNode()->renderer() == remainingText);
3546             // Replace the old renderer with the new one.
3547             remainingText->setFirstLetter(*newFirstLetter);
3548             newFirstLetter->setFirstLetterRemainingText(remainingText);
3549         }
3550         // To prevent removal of single anonymous block in RenderBlock::removeChild and causing
3551         // |nextSibling| to go stale, we remove the old first letter using removeChildNode first.
3552         firstLetterContainer->removeChildInternal(*firstLetter, NotifyChildren);
3553         firstLetter->destroy();
3554         firstLetter = newFirstLetter;
3555         firstLetterContainer->addChild(firstLetter, nextSibling);
3556     } else
3557         firstLetter->setStyle(*pseudoStyle);
3558 }
3559
3560 void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderText* currentTextChild)
3561 {
3562     RenderElement* firstLetterContainer = currentTextChild->parent();
3563     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3564     RenderBoxModelObject* firstLetter = 0;
3565     if (pseudoStyle->display() == INLINE)
3566         firstLetter = new RenderInline(document(), *pseudoStyle);
3567     else
3568         firstLetter = new RenderBlockFlow(document(), *pseudoStyle);
3569     firstLetter->initializeStyle();
3570     firstLetterContainer->addChild(firstLetter, currentTextChild);
3571
3572     // The original string is going to be either a generated content string or a DOM node's
3573     // string.  We want the original string before it got transformed in case first-letter has
3574     // no text-transform or a different text-transform applied to it.
3575     String oldText = currentTextChild->originalText();
3576     ASSERT(!oldText.isNull());
3577
3578     if (!oldText.isEmpty()) {
3579         unsigned length = 0;
3580
3581         // Account for leading spaces and punctuation.
3582         while (length < oldText.length() && shouldSkipForFirstLetter(oldText[length]))
3583             length++;
3584
3585         // Account for first grapheme cluster.
3586         length += numCharactersInGraphemeClusters(StringView(oldText).substring(length), 1);
3587         
3588         // Keep looking for whitespace and allowed punctuation, but avoid
3589         // accumulating just whitespace into the :first-letter.
3590         for (unsigned scanLength = length; scanLength < oldText.length(); ++scanLength) {
3591             UChar c = oldText[scanLength];
3592             
3593             if (!shouldSkipForFirstLetter(c))
3594                 break;
3595
3596             if (isPunctuationForFirstLetter(c))
3597                 length = scanLength + 1;
3598          }
3599          
3600         // Construct a text fragment for the text after the first letter.
3601         // This text fragment might be empty.
3602         RenderTextFragment* remainingText;
3603         if (currentTextChild->textNode())
3604             remainingText = new RenderTextFragment(*currentTextChild->textNode(), oldText, length, oldText.length() - length);
3605         else
3606             remainingText = new RenderTextFragment(document(), oldText, length, oldText.length() - length);
3607
3608         if (remainingText->textNode())
3609             remainingText->textNode()->setRenderer(remainingText);
3610
3611         firstLetterContainer->addChild(remainingText, currentTextChild);
3612         firstLetterContainer->removeChild(*currentTextChild);
3613         remainingText->setFirstLetter(*firstLetter);
3614         firstLetter->setFirstLetterRemainingText(remainingText);
3615         
3616         // construct text fragment for the first letter
3617         RenderTextFragment* letter;
3618         if (remainingText->textNode())
3619             letter = new RenderTextFragment(*remainingText->textNode(), oldText, 0, length);
3620         else
3621             letter = new RenderTextFragment(document(), oldText, 0, length);
3622
3623         firstLetter->addChild(letter);
3624
3625         currentTextChild->destroy();
3626     }
3627 }
3628     
3629 void RenderBlock::getFirstLetter(RenderObject*& firstLetter, RenderElement*& firstLetterContainer, RenderObject* skipObject)
3630 {
3631     firstLetter = nullptr;
3632     firstLetterContainer = nullptr;
3633
3634     if (!document().styleSheetCollection().usesFirstLetterRules())
3635         return;
3636
3637     // Don't recur
3638     if (style().styleType() == FIRST_LETTER)
3639         return;
3640     
3641     // FIXME: We need to destroy the first-letter object if it is no longer the first child. Need to find
3642     // an efficient way to check for that situation though before implementing anything.
3643     firstLetterContainer = findFirstLetterBlock(this);
3644     if (!firstLetterContainer)
3645         return;
3646     
3647     // Drill into inlines looking for our first text descendant.
3648     firstLetter = firstLetterContainer->firstChild();
3649     while (firstLetter) {
3650         if (firstLetter->isText()) {
3651             if (firstLetter == skipObject) {
3652                 firstLetter = firstLetter->nextSibling();
3653                 continue;
3654             }
3655             
3656             break;
3657         }
3658
3659         RenderElement& current = toRenderElement(*firstLetter);
3660         if (current.isListMarker())
3661             firstLetter = current.nextSibling();
3662         else if (current.isFloatingOrOutOfFlowPositioned()) {
3663             if (current.style().styleType() == FIRST_LETTER) {
3664                 firstLetter = current.firstChild();
3665                 break;
3666             }
3667             firstLetter = current.nextSibling();
3668         } else if (current.isReplaced() || current.isRenderButton() || current.isMenuList())
3669             break;
3670         else if (current.style().hasPseudoStyle(FIRST_LETTER) && current.canHaveGeneratedChildren())  {
3671             // We found a lower-level node with first-letter, which supersedes the higher-level style
3672             firstLetterContainer = &current;
3673             firstLetter = current.firstChild();
3674         } else
3675             firstLetter = current.firstChild();
3676     }
3677     
3678     if (!firstLetter)
3679         firstLetterContainer = nullptr;
3680 }
3681
3682 void RenderBlock::updateFirstLetter()
3683 {
3684     RenderObject* firstLetterObj;
3685     RenderElement* firstLetterContainer;
3686     // FIXME: The first letter might be composed of a variety of code units, and therefore might
3687     // be contained within multiple RenderElements.
3688     getFirstLetter(firstLetterObj, firstLetterContainer);
3689
3690     if (!firstLetterObj)
3691         return;
3692
3693     // If the child already has style, then it has already been created, so we just want
3694     // to update it.
3695     if (firstLetterObj->parent()->style().styleType() == FIRST_LETTER) {
3696         updateFirstLetterStyle(firstLetterContainer, firstLetterObj);
3697         return;
3698     }
3699
3700     if (!firstLetterObj->isText())
3701         return;
3702
3703     // Our layout state is not valid for the repaints we are going to trigger by
3704     // adding and removing children of firstLetterContainer.
3705     LayoutStateDisabler layoutStateDisabler(&view());
3706
3707     createFirstLetterRenderer(firstLetterContainer, toRenderText(firstLetterObj));
3708 }
3709
3710 LayoutUnit RenderBlock::paginationStrut() const
3711 {
3712     RenderBlockRareData* rareData = getRareData(this);
3713     return rareData ? rareData->m_paginationStrut : LayoutUnit();
3714 }
3715
3716 LayoutUnit RenderBlock::pageLogicalOffset() const
3717 {
3718     RenderBlockRareData* rareData = getRareData(this);
3719     return rareData ? rareData->m_pageLogicalOffset : LayoutUnit();
3720 }
3721
3722 void RenderBlock::setPaginationStrut(LayoutUnit strut)
3723 {
3724     RenderBlockRareData* rareData = getRareData(this);
3725     if (!rareData) {
3726         if (!strut)
3727             return;
3728         rareData = &ensureRareData(this);
3729     }
3730     rareData->m_paginationStrut = strut;
3731 }
3732
3733 void RenderBlock::setPageLogicalOffset(LayoutUnit logicalOffset)
3734 {
3735     RenderBlockRareData* rareData = getRareData(this);
3736     if (!rareData) {
3737         if (!logicalOffset)
3738             return;
3739         rareData = &ensureRareData(this);
3740     }
3741     rareData->m_pageLogicalOffset = logicalOffset;
3742 }
3743
3744 void RenderBlock::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
3745 {
3746     // For blocks inside inlines, we go ahead and include margins so that we run right up to the
3747     // inline boxes above and below us (thus getting merged with them to form a single irregular
3748     // shape).
3749     if (isAnonymousBlockContinuation()) {
3750         // FIXME: This is wrong for block-flows that are horizontal.
3751         // https://bugs.webkit.org/show_bug.cgi?id=46781
3752         rects.append(pixelSnappedIntRect(accumulatedOffset.x(), accumulatedOffset.y() - collapsedMarginBefore(),
3753                                 width(), height() + collapsedMarginBefore() + collapsedMarginAfter()));
3754         continuation()->absoluteRects(rects, accumulatedOffset - toLayoutSize(location() +
3755                 inlineElementContinuation()->containingBlock()->location()));
3756     } else
3757         rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
3758 }
3759
3760 void RenderBlock::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
3761 {
3762     // For blocks inside inlines, we go ahead and include margins so that we run right up to the