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