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