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