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