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