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