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