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