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