b2e5cddf1c73757c49a7ef6b17e31876d1b3d61c
[WebKit-https.git] / Source / WebCore / rendering / updating / RenderTreeBuilder.cpp
1 /*
2  * Copyright (C) 2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "RenderTreeBuilder.h"
28
29 #include "AXObjectCache.h"
30 #include "Frame.h"
31 #include "FrameSelection.h"
32 #include "RenderButton.h"
33 #include "RenderCounter.h"
34 #include "RenderElement.h"
35 #include "RenderFullScreen.h"
36 #include "RenderGrid.h"
37 #include "RenderLineBreak.h"
38 #include "RenderMathMLFenced.h"
39 #include "RenderMenuList.h"
40 #include "RenderRuby.h"
41 #include "RenderRubyBase.h"
42 #include "RenderRubyRun.h"
43 #include "RenderSVGContainer.h"
44 #include "RenderSVGInline.h"
45 #include "RenderSVGRoot.h"
46 #include "RenderTable.h"
47 #include "RenderTableRow.h"
48 #include "RenderTableSection.h"
49 #include "RenderText.h"
50 #include "RenderTextFragment.h"
51 #include "RenderTreeBuilderBlock.h"
52 #include "RenderTreeBuilderBlockFlow.h"
53 #include "RenderTreeBuilderContinuation.h"
54 #include "RenderTreeBuilderFirstLetter.h"
55 #include "RenderTreeBuilderFormControls.h"
56 #include "RenderTreeBuilderFullScreen.h"
57 #include "RenderTreeBuilderInline.h"
58 #include "RenderTreeBuilderList.h"
59 #include "RenderTreeBuilderMathML.h"
60 #include "RenderTreeBuilderMultiColumn.h"
61 #include "RenderTreeBuilderRuby.h"
62 #include "RenderTreeBuilderSVG.h"
63 #include "RenderTreeBuilderTable.h"
64
65 namespace WebCore {
66
67 RenderTreeBuilder* RenderTreeBuilder::s_current;
68
69 static void markBoxForRelayoutAfterSplit(RenderBox& box)
70 {
71     // FIXME: The table code should handle that automatically. If not,
72     // we should fix it and remove the table part checks.
73     if (is<RenderTable>(box)) {
74         // Because we may have added some sections with already computed column structures, we need to
75         // sync the table structure with them now. This avoids crashes when adding new cells to the table.
76         downcast<RenderTable>(box).forceSectionsRecalc();
77     } else if (is<RenderTableSection>(box))
78         downcast<RenderTableSection>(box).setNeedsCellRecalc();
79
80     box.setNeedsLayoutAndPrefWidthsRecalc();
81 }
82
83 static void getInlineRun(RenderObject* start, RenderObject* boundary, RenderObject*& inlineRunStart, RenderObject*& inlineRunEnd)
84 {
85     // Beginning at |start| we find the largest contiguous run of inlines that
86     // we can. We denote the run with start and end points, |inlineRunStart|
87     // and |inlineRunEnd|. Note that these two values may be the same if
88     // we encounter only one inline.
89     //
90     // We skip any non-inlines we encounter as long as we haven't found any
91     // inlines yet.
92     //
93     // |boundary| indicates a non-inclusive boundary point. Regardless of whether |boundary|
94     // is inline or not, we will not include it in a run with inlines before it. It's as though we encountered
95     // a non-inline.
96
97     // Start by skipping as many non-inlines as we can.
98     auto* curr = start;
99     bool sawInline;
100     do {
101         while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
102             curr = curr->nextSibling();
103
104         inlineRunStart = inlineRunEnd = curr;
105
106         if (!curr)
107             return; // No more inline children to be found.
108
109         sawInline = curr->isInline();
110
111         curr = curr->nextSibling();
112         while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
113             inlineRunEnd = curr;
114             if (curr->isInline())
115                 sawInline = true;
116             curr = curr->nextSibling();
117         }
118     } while (!sawInline);
119 }
120
121 RenderTreeBuilder::RenderTreeBuilder(RenderView& view)
122     : m_view(view)
123     , m_firstLetterBuilder(std::make_unique<FirstLetter>(*this))
124     , m_listBuilder(std::make_unique<List>(*this))
125     , m_multiColumnBuilder(std::make_unique<MultiColumn>(*this))
126     , m_tableBuilder(std::make_unique<Table>(*this))
127     , m_rubyBuilder(std::make_unique<Ruby>(*this))
128     , m_formControlsBuilder(std::make_unique<FormControls>(*this))
129     , m_blockBuilder(std::make_unique<Block>(*this))
130     , m_blockFlowBuilder(std::make_unique<BlockFlow>(*this))
131     , m_inlineBuilder(std::make_unique<Inline>(*this))
132     , m_svgBuilder(std::make_unique<SVG>(*this))
133     , m_mathMLBuilder(std::make_unique<MathML>(*this))
134     , m_continuationBuilder(std::make_unique<Continuation>(*this))
135 #if ENABLE(FULLSCREEN_API)
136     , m_fullScreenBuilder(std::make_unique<FullScreen>(*this))
137 #endif
138 {
139     RELEASE_ASSERT(!s_current || &m_view != &s_current->m_view);
140     m_previous = s_current;
141     s_current = this;
142 }
143
144 RenderTreeBuilder::~RenderTreeBuilder()
145 {
146     s_current = m_previous;
147 }
148
149 void RenderTreeBuilder::destroy(RenderObject& renderer)
150 {
151     ASSERT(renderer.parent());
152     auto toDestroy = detach(*renderer.parent(), renderer);
153
154 #if ENABLE(FULLSCREEN_API)
155     if (is<RenderFullScreen>(renderer))
156         fullScreenBuilder().cleanupOnDestroy(downcast<RenderFullScreen>(renderer));
157 #endif
158
159     if (is<RenderTextFragment>(renderer))
160         firstLetterBuilder().cleanupOnDestroy(downcast<RenderTextFragment>(renderer));
161
162     if (is<RenderBoxModelObject>(renderer))
163         continuationBuilder().cleanupOnDestroy(downcast<RenderBoxModelObject>(renderer));
164
165     // We need to detach the subtree first so that the descendants don't have
166     // access to previous/next sublings at detach().
167     // FIXME: webkit.org/b/182909.
168     if (!is<RenderElement>(toDestroy.get()))
169         return;
170
171     auto& childToDestroy = downcast<RenderElement>(*toDestroy.get());
172     while (childToDestroy.firstChild()) {
173         auto& firstChild = *childToDestroy.firstChild();
174         if (auto* node = firstChild.node())
175             node->setRenderer(nullptr);
176         destroy(firstChild);
177     }
178 }
179
180 void RenderTreeBuilder::attach(RenderElement& parent, RenderPtr<RenderObject> child, RenderObject* beforeChild)
181 {
182     auto insertRecursiveIfNeeded = [&](RenderElement& parentCandidate) {
183         if (&parent == &parentCandidate) {
184             attachToRenderElement(parent, WTFMove(child), beforeChild);
185             return;
186         }
187         attach(parentCandidate, WTFMove(child), beforeChild);
188     };
189
190     ASSERT(&parent.view() == &m_view);
191
192     if (is<RenderText>(beforeChild)) {
193         if (auto* wrapperInline = downcast<RenderText>(*beforeChild).inlineWrapperForDisplayContents())
194             beforeChild = wrapperInline;
195     }
196
197     if (is<RenderTableRow>(parent)) {
198         auto& parentCandidate = tableBuilder().findOrCreateParentForChild(downcast<RenderTableRow>(parent), *child, beforeChild);
199         if (&parentCandidate == &parent) {
200             tableBuilder().attach(downcast<RenderTableRow>(parentCandidate), WTFMove(child), beforeChild);
201             return;
202         }
203         insertRecursiveIfNeeded(parentCandidate);
204         return;
205     }
206
207     if (is<RenderTableSection>(parent)) {
208         auto& parentCandidate = tableBuilder().findOrCreateParentForChild(downcast<RenderTableSection>(parent), *child, beforeChild);
209         if (&parent == &parentCandidate) {
210             tableBuilder().attach(downcast<RenderTableSection>(parent), WTFMove(child), beforeChild);
211             return;
212         }
213         insertRecursiveIfNeeded(parentCandidate);
214         return;
215     }
216
217     if (is<RenderTable>(parent)) {
218         auto& parentCandidate = tableBuilder().findOrCreateParentForChild(downcast<RenderTable>(parent), *child, beforeChild);
219         if (&parentCandidate == &parent) {
220             tableBuilder().attach(downcast<RenderTable>(parentCandidate), WTFMove(child), beforeChild);
221             return;
222         }
223         insertRecursiveIfNeeded(parentCandidate);
224         return;
225     }
226
227     if (is<RenderRubyAsBlock>(parent)) {
228         insertRecursiveIfNeeded(rubyBuilder().findOrCreateParentForChild(downcast<RenderRubyAsBlock>(parent), *child, beforeChild));
229         return;
230     }
231
232     if (is<RenderRubyAsInline>(parent)) {
233         insertRecursiveIfNeeded(rubyBuilder().findOrCreateParentForChild(downcast<RenderRubyAsInline>(parent), *child, beforeChild));
234         return;
235     }
236
237     if (is<RenderRubyRun>(parent)) {
238         rubyBuilder().attach(downcast<RenderRubyRun>(parent), WTFMove(child), beforeChild);
239         return;
240     }
241
242     if (is<RenderButton>(parent)) {
243         formControlsBuilder().attach(downcast<RenderButton>(parent), WTFMove(child), beforeChild);
244         return;
245     }
246
247     if (is<RenderMenuList>(parent)) {
248         formControlsBuilder().attach(downcast<RenderMenuList>(parent), WTFMove(child), beforeChild);
249         return;
250     }
251
252     if (is<RenderSVGContainer>(parent)) {
253         svgBuilder().attach(downcast<RenderSVGContainer>(parent), WTFMove(child), beforeChild);
254         return;
255     }
256
257     if (is<RenderSVGInline>(parent)) {
258         svgBuilder().attach(downcast<RenderSVGInline>(parent), WTFMove(child), beforeChild);
259         return;
260     }
261
262     if (is<RenderSVGRoot>(parent)) {
263         svgBuilder().attach(downcast<RenderSVGRoot>(parent), WTFMove(child), beforeChild);
264         return;
265     }
266
267     if (is<RenderSVGText>(parent)) {
268         svgBuilder().attach(downcast<RenderSVGText>(parent), WTFMove(child), beforeChild);
269         return;
270     }
271
272     if (is<RenderMathMLFenced>(parent)) {
273         mathMLBuilder().attach(downcast<RenderMathMLFenced>(parent), WTFMove(child), beforeChild);
274         return;
275     }
276
277     if (is<RenderGrid>(parent)) {
278         attachToRenderGrid(downcast<RenderGrid>(parent), WTFMove(child), beforeChild);
279         return;
280     }
281
282     if (is<RenderBlockFlow>(parent)) {
283         blockFlowBuilder().attach(downcast<RenderBlockFlow>(parent), WTFMove(child), beforeChild);
284         return;
285     }
286
287     if (is<RenderBlock>(parent)) {
288         blockBuilder().attach(downcast<RenderBlock>(parent), WTFMove(child), beforeChild);
289         return;
290     }
291
292     if (is<RenderInline>(parent)) {
293         inlineBuilder().attach(downcast<RenderInline>(parent), WTFMove(child), beforeChild);
294         return;
295     }
296
297     attachToRenderElement(parent, WTFMove(child), beforeChild);
298 }
299
300 void RenderTreeBuilder::attachIgnoringContinuation(RenderElement& parent, RenderPtr<RenderObject> child, RenderObject* beforeChild)
301 {
302     if (is<RenderInline>(parent)) {
303         inlineBuilder().attachIgnoringContinuation(downcast<RenderInline>(parent), WTFMove(child), beforeChild);
304         return;
305     }
306
307     if (is<RenderBlock>(parent)) {
308         blockBuilder().attachIgnoringContinuation(downcast<RenderBlock>(parent), WTFMove(child), beforeChild);
309         return;
310     }
311
312     attach(parent, WTFMove(child), beforeChild);
313 }
314
315 RenderPtr<RenderObject> RenderTreeBuilder::detach(RenderElement& parent, RenderObject& child)
316 {
317     if (is<RenderRubyAsInline>(parent))
318         return rubyBuilder().detach(downcast<RenderRubyAsInline>(parent), child);
319
320     if (is<RenderRubyAsBlock>(parent))
321         return rubyBuilder().detach(downcast<RenderRubyAsBlock>(parent), child);
322
323     if (is<RenderRubyRun>(parent))
324         return rubyBuilder().detach(downcast<RenderRubyRun>(parent), child);
325
326     if (is<RenderMenuList>(parent))
327         return formControlsBuilder().detach(downcast<RenderMenuList>(parent), child);
328
329     if (is<RenderButton>(parent))
330         return formControlsBuilder().detach(downcast<RenderButton>(parent), child);
331
332     if (is<RenderGrid>(parent))
333         return detachFromRenderGrid(downcast<RenderGrid>(parent), child);
334
335     if (is<RenderSVGText>(parent))
336         return svgBuilder().detach(downcast<RenderSVGText>(parent), child);
337
338     if (is<RenderSVGInline>(parent))
339         return svgBuilder().detach(downcast<RenderSVGInline>(parent), child);
340
341     if (is<RenderSVGContainer>(parent))
342         return svgBuilder().detach(downcast<RenderSVGContainer>(parent), child);
343
344     if (is<RenderSVGRoot>(parent))
345         return svgBuilder().detach(downcast<RenderSVGRoot>(parent), child);
346
347     if (is<RenderBlockFlow>(parent))
348         return blockBuilder().detach(downcast<RenderBlockFlow>(parent), child);
349
350     if (is<RenderBlock>(parent))
351         return blockBuilder().detach(downcast<RenderBlock>(parent), child);
352
353     return detachFromRenderElement(parent, child);
354 }
355
356 void RenderTreeBuilder::attach(RenderTreePosition& position, RenderPtr<RenderObject> child)
357 {
358     attach(position.parent(), WTFMove(child), position.nextSibling());
359 }
360
361 #if ENABLE(FULLSCREEN_API)
362 void RenderTreeBuilder::createPlaceholderForFullScreen(RenderFullScreen& renderer, std::unique_ptr<RenderStyle> style, const LayoutRect& frameRect)
363 {
364     fullScreenBuilder().createPlaceholder(renderer, WTFMove(style), frameRect);
365 }
366 #endif
367
368 void RenderTreeBuilder::attachToRenderElement(RenderElement& parent, RenderPtr<RenderObject> child, RenderObject* beforeChild)
369 {
370     if (tableBuilder().childRequiresTable(parent, *child)) {
371         RenderTable* table;
372         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : parent.lastChild();
373         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
374             table = downcast<RenderTable>(afterChild);
375         else {
376             auto newTable = RenderTable::createAnonymousWithParentRenderer(parent);
377             table = newTable.get();
378             attach(parent, WTFMove(newTable), beforeChild);
379         }
380
381         attach(*table, WTFMove(child));
382         return;
383     }
384     auto& newChild = *child.get();
385     attachToRenderElementInternal(parent, WTFMove(child), beforeChild);
386     parent.didAttachChild(newChild, beforeChild);
387 }
388
389 void RenderTreeBuilder::attachToRenderElementInternal(RenderElement& parent, RenderPtr<RenderObject> child, RenderObject* beforeChild)
390 {
391     RELEASE_ASSERT_WITH_MESSAGE(!parent.view().frameView().layoutContext().layoutState(), "Layout must not mutate render tree");
392     ASSERT(parent.canHaveChildren() || parent.canHaveGeneratedChildren());
393     ASSERT(!child->parent());
394     ASSERT(!parent.isRenderBlockFlow() || (!child->isTableSection() && !child->isTableRow() && !child->isTableCell()));
395
396     while (beforeChild && beforeChild->parent() && beforeChild->parent() != &parent)
397         beforeChild = beforeChild->parent();
398
399     ASSERT(!beforeChild || beforeChild->parent() == &parent);
400     ASSERT(!is<RenderText>(beforeChild) || !downcast<RenderText>(*beforeChild).inlineWrapperForDisplayContents());
401
402     // Take the ownership.
403     auto* newChild = parent.attachRendererInternal(WTFMove(child), beforeChild);
404
405     newChild->initializeFragmentedFlowStateOnInsertion();
406     if (!parent.renderTreeBeingDestroyed()) {
407         newChild->insertedIntoTree();
408
409         auto* fragmentedFlow = newChild->enclosingFragmentedFlow();
410         if (is<RenderMultiColumnFlow>(fragmentedFlow))
411             multiColumnBuilder().multiColumnDescendantInserted(downcast<RenderMultiColumnFlow>(*fragmentedFlow), *newChild);
412
413         if (is<RenderElement>(*newChild))
414             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
415     }
416
417     newChild->setNeedsLayoutAndPrefWidthsRecalc();
418     parent.setPreferredLogicalWidthsDirty(true);
419     if (!parent.normalChildNeedsLayout())
420         parent.setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
421
422     if (AXObjectCache* cache = parent.document().axObjectCache())
423         cache->childrenChanged(&parent, newChild);
424     if (is<RenderBlockFlow>(parent))
425         downcast<RenderBlockFlow>(parent).invalidateLineLayoutPath();
426     if (parent.hasOutlineAutoAncestor() || parent.outlineStyleForRepaint().outlineStyleIsAuto())
427         newChild->setHasOutlineAutoAncestor();
428 }
429
430 void RenderTreeBuilder::move(RenderBoxModelObject& from, RenderBoxModelObject& to, RenderObject& child, RenderObject* beforeChild, NormalizeAfterInsertion normalizeAfterInsertion)
431 {
432     // We assume that callers have cleared their positioned objects list for child moves so the
433     // positioned renderer maps don't become stale. It would be too slow to do the map lookup on each call.
434     ASSERT(normalizeAfterInsertion == NormalizeAfterInsertion::No || !is<RenderBlock>(from) || !downcast<RenderBlock>(from).hasPositionedObjects());
435
436     ASSERT(&from == child.parent());
437     ASSERT(!beforeChild || &to == beforeChild->parent());
438     if (normalizeAfterInsertion == NormalizeAfterInsertion::Yes && (to.isRenderBlock() || to.isRenderInline())) {
439         // Takes care of adding the new child correctly if toBlock and fromBlock
440         // have different kind of children (block vs inline).
441         auto childToMove = detachFromRenderElement(from, child);
442         attach(to, WTFMove(childToMove), beforeChild);
443     } else {
444         auto childToMove = detachFromRenderElement(from, child);
445         attachToRenderElementInternal(to, WTFMove(childToMove), beforeChild);
446     }
447 }
448
449 void RenderTreeBuilder::move(RenderBoxModelObject& from, RenderBoxModelObject& to, RenderObject& child, NormalizeAfterInsertion normalizeAfterInsertion)
450 {
451     move(from, to, child, nullptr, normalizeAfterInsertion);
452 }
453
454 void RenderTreeBuilder::moveAllChildren(RenderBoxModelObject& from, RenderBoxModelObject& to, NormalizeAfterInsertion normalizeAfterInsertion)
455 {
456     moveAllChildren(from, to, nullptr, normalizeAfterInsertion);
457 }
458
459 void RenderTreeBuilder::moveAllChildren(RenderBoxModelObject& from, RenderBoxModelObject& to, RenderObject* beforeChild, NormalizeAfterInsertion normalizeAfterInsertion)
460 {
461     moveChildren(from, to, from.firstChild(), nullptr, beforeChild, normalizeAfterInsertion);
462 }
463
464 void RenderTreeBuilder::moveChildren(RenderBoxModelObject& from, RenderBoxModelObject& to, RenderObject* startChild, RenderObject* endChild, NormalizeAfterInsertion normalizeAfterInsertion)
465 {
466     moveChildren(from, to, startChild, endChild, nullptr, normalizeAfterInsertion);
467 }
468
469 void RenderTreeBuilder::moveChildren(RenderBoxModelObject& from, RenderBoxModelObject& to, RenderObject* startChild, RenderObject* endChild, RenderObject* beforeChild, NormalizeAfterInsertion normalizeAfterInsertion)
470 {
471     // This condition is rarely hit since this function is usually called on
472     // anonymous blocks which can no longer carry positioned objects (see r120761)
473     // or when fullRemoveInsert is false.
474     if (normalizeAfterInsertion == NormalizeAfterInsertion::Yes && is<RenderBlock>(from)) {
475         downcast<RenderBlock>(from).removePositionedObjects(nullptr);
476         if (is<RenderBlockFlow>(from))
477             downcast<RenderBlockFlow>(from).removeFloatingObjects();
478     }
479
480     ASSERT(!beforeChild || &to == beforeChild->parent());
481     for (RenderObject* child = startChild; child && child != endChild; ) {
482         // Save our next sibling as moveChildTo will clear it.
483         RenderObject* nextSibling = child->nextSibling();
484
485         // FIXME: This logic here fails to detect the first letter in certain cases
486         // and skips a valid sibling renderer (see webkit.org/b/163737).
487         // Check to make sure we're not saving the firstLetter as the nextSibling.
488         // When the |child| object will be moved, its firstLetter will be recreated,
489         // so saving it now in nextSibling would leave us with a stale object.
490         if (is<RenderTextFragment>(*child) && is<RenderText>(nextSibling)) {
491             RenderObject* firstLetterObj = nullptr;
492             if (RenderBlock* block = downcast<RenderTextFragment>(*child).blockForAccompanyingFirstLetter()) {
493                 RenderElement* firstLetterContainer = nullptr;
494                 block->getFirstLetter(firstLetterObj, firstLetterContainer, child);
495             }
496
497             // This is the first letter, skip it.
498             if (firstLetterObj == nextSibling)
499                 nextSibling = nextSibling->nextSibling();
500         }
501
502         move(from, to, *child, beforeChild, normalizeAfterInsertion);
503         child = nextSibling;
504     }
505 }
506
507 void RenderTreeBuilder::moveAllChildrenIncludingFloats(RenderBlock& from, RenderBlock& to, RenderTreeBuilder::NormalizeAfterInsertion normalizeAfterInsertion)
508 {
509     if (is<RenderBlockFlow>(from)) {
510         blockFlowBuilder().moveAllChildrenIncludingFloats(downcast<RenderBlockFlow>(from), to, normalizeAfterInsertion);
511         return;
512     }
513     moveAllChildren(from, to, normalizeAfterInsertion);
514 }
515
516 void RenderTreeBuilder::makeChildrenNonInline(RenderBlock& parent, RenderObject* insertionPoint)
517 {
518     // makeChildrenNonInline takes a block whose children are *all* inline and it
519     // makes sure that inline children are coalesced under anonymous
520     // blocks. If |insertionPoint| is defined, then it represents the insertion point for
521     // the new block child that is causing us to have to wrap all the inlines. This
522     // means that we cannot coalesce inlines before |insertionPoint| with inlines following
523     // |insertionPoint|, because the new child is going to be inserted in between the inlines,
524     // splitting them.
525     ASSERT(parent.isInlineBlockOrInlineTable() || !parent.isInline());
526     ASSERT(!insertionPoint || insertionPoint->parent() == &parent);
527
528     parent.setChildrenInline(false);
529
530     auto* child = parent.firstChild();
531     if (!child)
532         return;
533
534     parent.deleteLines();
535
536     while (child) {
537         RenderObject* inlineRunStart = nullptr;
538         RenderObject* inlineRunEnd = nullptr;
539         getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
540
541         if (!inlineRunStart)
542             break;
543
544         child = inlineRunEnd->nextSibling();
545
546         auto newBlock = parent.createAnonymousBlock();
547         auto& block = *newBlock;
548         attachToRenderElementInternal(parent, WTFMove(newBlock), inlineRunStart);
549         moveChildren(parent, block, inlineRunStart, child, RenderTreeBuilder::NormalizeAfterInsertion::No);
550     }
551 #ifndef NDEBUG
552     for (RenderObject* c = parent.firstChild(); c; c = c->nextSibling())
553         ASSERT(!c->isInline());
554 #endif
555     parent.repaint();
556 }
557
558 RenderObject* RenderTreeBuilder::splitAnonymousBoxesAroundChild(RenderBox& parent, RenderObject* beforeChild)
559 {
560     bool didSplitParentAnonymousBoxes = false;
561
562     while (beforeChild->parent() != &parent) {
563         auto& boxToSplit = downcast<RenderBox>(*beforeChild->parent());
564         if (boxToSplit.firstChild() != beforeChild && boxToSplit.isAnonymous()) {
565             didSplitParentAnonymousBoxes = true;
566
567             // We have to split the parent box into two boxes and move children
568             // from |beforeChild| to end into the new post box.
569             auto newPostBox = boxToSplit.createAnonymousBoxWithSameTypeAs(parent);
570             auto& postBox = *newPostBox;
571             postBox.setChildrenInline(boxToSplit.childrenInline());
572             RenderBox* parentBox = downcast<RenderBox>(boxToSplit.parent());
573             // We need to invalidate the |parentBox| before inserting the new node
574             // so that the table repainting logic knows the structure is dirty.
575             // See for example RenderTableCell:clippedOverflowRectForRepaint.
576             markBoxForRelayoutAfterSplit(*parentBox);
577             attachToRenderElementInternal(*parentBox, WTFMove(newPostBox), boxToSplit.nextSibling());
578             moveChildren(boxToSplit, postBox, beforeChild, nullptr, RenderTreeBuilder::NormalizeAfterInsertion::Yes);
579
580             markBoxForRelayoutAfterSplit(boxToSplit);
581             markBoxForRelayoutAfterSplit(postBox);
582
583             beforeChild = &postBox;
584         } else
585             beforeChild = &boxToSplit;
586     }
587
588     if (didSplitParentAnonymousBoxes)
589         markBoxForRelayoutAfterSplit(parent);
590
591     ASSERT(beforeChild->parent() == &parent);
592     return beforeChild;
593 }
594
595 void RenderTreeBuilder::childFlowStateChangesAndAffectsParentBlock(RenderElement& child)
596 {
597     auto* parent = child.parent();
598     if (!child.isInline()) {
599         if (is<RenderBlock>(parent))
600             blockBuilder().childBecameNonInline(downcast<RenderBlock>(*parent), child);
601         else if (is<RenderInline>(*parent))
602             inlineBuilder().childBecameNonInline(downcast<RenderInline>(*parent), child);
603     } else {
604         // An anonymous block must be made to wrap this inline.
605         auto newBlock = downcast<RenderBlock>(*parent).createAnonymousBlock();
606         auto& block = *newBlock;
607         attachToRenderElementInternal(*parent, WTFMove(newBlock), &child);
608         auto thisToMove = detachFromRenderElement(*parent, child);
609         attachToRenderElementInternal(block, WTFMove(thisToMove));
610     }
611 }
612
613 void RenderTreeBuilder::removeAnonymousWrappersForInlineChildrenIfNeeded(RenderElement& parent)
614 {
615     if (!is<RenderBlock>(parent))
616         return;
617     auto& blockParent = downcast<RenderBlock>(parent);
618     if (!blockParent.canDropAnonymousBlockChild())
619         return;
620
621     // We have changed to floated or out-of-flow positioning so maybe all our parent's
622     // children can be inline now. Bail if there are any block children left on the line,
623     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
624     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
625     // if we find a continuation.
626     auto* current = blockParent.firstChild();
627     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
628         current = current->nextSibling();
629
630     if (current)
631         return;
632
633     RenderObject* next;
634     for (current = blockParent.firstChild(); current; current = next) {
635         next = current->nextSibling();
636         if (current->isAnonymousBlock())
637             blockBuilder().dropAnonymousBoxChild(blockParent, downcast<RenderBlock>(*current));
638     }
639 }
640
641 void RenderTreeBuilder::childFlowStateChangesAndNoLongerAffectsParentBlock(RenderElement& child)
642 {
643     ASSERT(child.parent());
644     removeAnonymousWrappersForInlineChildrenIfNeeded(*child.parent());
645 }
646
647 static bool isAnonymousAndSafeToDelete(RenderElement& element)
648 {
649     if (!element.isAnonymous())
650         return false;
651     if (element.isRenderView() || element.isRenderFragmentedFlow())
652         return false;
653     return true;
654 }
655
656 static RenderObject& findDestroyRootIncludingAnonymous(RenderObject& renderer)
657 {
658     auto* destroyRoot = &renderer;
659     while (true) {
660         auto& destroyRootParent = *destroyRoot->parent();
661         if (!isAnonymousAndSafeToDelete(destroyRootParent))
662             break;
663         bool destroyingOnlyChild = destroyRootParent.firstChild() == destroyRoot && destroyRootParent.lastChild() == destroyRoot;
664         if (!destroyingOnlyChild)
665             break;
666         destroyRoot = &destroyRootParent;
667     }
668     return *destroyRoot;
669 }
670
671 void RenderTreeBuilder::destroyAndCleanUpAnonymousWrappers(RenderObject& child)
672 {
673     // If the tree is destroyed, there is no need for a clean-up phase.
674     if (child.renderTreeBeingDestroyed()) {
675         destroy(child);
676         return;
677     }
678
679     // Remove intruding floats from sibling blocks before detaching.
680     if (is<RenderBox>(child) && child.isFloatingOrOutOfFlowPositioned())
681         downcast<RenderBox>(child).removeFloatingOrPositionedChildFromBlockLists();
682     auto& destroyRoot = findDestroyRootIncludingAnonymous(child);
683     if (is<RenderTableRow>(destroyRoot))
684         tableBuilder().collapseAndDestroyAnonymousSiblingRows(downcast<RenderTableRow>(destroyRoot));
685
686     auto& destroyRootParent = *destroyRoot.parent();
687     destroy(destroyRoot);
688     removeAnonymousWrappersForInlineChildrenIfNeeded(destroyRootParent);
689
690     // Anonymous parent might have become empty, try to delete it too.
691     if (isAnonymousAndSafeToDelete(destroyRootParent) && !destroyRootParent.firstChild())
692         destroyAndCleanUpAnonymousWrappers(destroyRootParent);
693     // WARNING: child is deleted here.
694 }
695
696 void RenderTreeBuilder::updateAfterDescendants(RenderElement& renderer)
697 {
698     if (is<RenderBlock>(renderer))
699         firstLetterBuilder().updateAfterDescendants(downcast<RenderBlock>(renderer));
700     if (is<RenderListItem>(renderer))
701         listBuilder().updateItemMarker(downcast<RenderListItem>(renderer));
702     if (is<RenderBlockFlow>(renderer))
703         multiColumnBuilder().updateAfterDescendants(downcast<RenderBlockFlow>(renderer));
704 }
705
706 RenderPtr<RenderObject> RenderTreeBuilder::detachFromRenderGrid(RenderGrid& parent, RenderObject& child)
707 {
708     auto takenChild = blockBuilder().detach(parent, child);
709     // Positioned grid items do not take up space or otherwise participate in the layout of the grid,
710     // for that reason we don't need to mark the grid as dirty when they are removed.
711     if (child.isOutOfFlowPositioned())
712         return takenChild;
713
714     // The grid needs to be recomputed as it might contain auto-placed items that will change their position.
715     parent.dirtyGrid();
716     return takenChild;
717 }
718
719 RenderPtr<RenderObject> RenderTreeBuilder::detachFromRenderElement(RenderElement& parent, RenderObject& child)
720 {
721     RELEASE_ASSERT_WITH_MESSAGE(!parent.view().frameView().layoutContext().layoutState(), "Layout must not mutate render tree");
722
723     ASSERT(parent.canHaveChildren() || parent.canHaveGeneratedChildren());
724     ASSERT(child.parent() == &parent);
725
726     if (child.isFloatingOrOutOfFlowPositioned())
727         downcast<RenderBox>(child).removeFloatingOrPositionedChildFromBlockLists();
728
729     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
730     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
731     // disappears gets repainted properly.
732     if (!parent.renderTreeBeingDestroyed() && child.everHadLayout()) {
733         child.setNeedsLayoutAndPrefWidthsRecalc();
734         // We only repaint |child| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
735         if (child.isBody())
736             parent.view().repaintRootContents();
737         else
738             child.repaint();
739     }
740
741     // If we have a line box wrapper, delete it.
742     if (is<RenderBox>(child))
743         downcast<RenderBox>(child).deleteLineBoxWrapper();
744     else if (is<RenderLineBreak>(child))
745         downcast<RenderLineBreak>(child).deleteInlineBoxWrapper();
746
747     if (!parent.renderTreeBeingDestroyed() && is<RenderFlexibleBox>(parent) && !child.isFloatingOrOutOfFlowPositioned() && child.isBox())
748         downcast<RenderFlexibleBox>(parent).clearCachedChildIntrinsicContentLogicalHeight(downcast<RenderBox>(child));
749
750     // If child is the start or end of the selection, then clear the selection to
751     // avoid problems of invalid pointers.
752     if (!parent.renderTreeBeingDestroyed() && child.isSelectionBorder())
753         parent.frame().selection().setNeedsSelectionUpdate();
754
755     if (!parent.renderTreeBeingDestroyed())
756         child.willBeRemovedFromTree();
757
758     child.resetFragmentedFlowStateOnRemoval();
759
760     // WARNING: There should be no code running between willBeRemovedFromTree() and the actual removal below.
761     // This is needed to avoid race conditions where willBeRemovedFromTree() would dirty the tree's structure
762     // and the code running here would force an untimely rebuilding, leaving |child| dangling.
763     auto childToTake = parent.detachRendererInternal(child);
764
765     // rendererRemovedFromTree() walks the whole subtree. We can improve performance
766     // by skipping this step when destroying the entire tree.
767     if (!parent.renderTreeBeingDestroyed() && is<RenderElement>(*childToTake))
768         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(*childToTake));
769
770     if (!parent.renderTreeBeingDestroyed()) {
771         if (AXObjectCache* cache = parent.document().existingAXObjectCache())
772             cache->childrenChanged(&parent);
773     }
774
775     return childToTake;
776 }
777
778 void RenderTreeBuilder::attachToRenderGrid(RenderGrid& parent, RenderPtr<RenderObject> child, RenderObject* beforeChild)
779 {
780     auto& newChild = *child;
781     blockBuilder().attach(parent, WTFMove(child), beforeChild);
782
783     // Positioned grid items do not take up space or otherwise participate in the layout of the grid,
784     // for that reason we don't need to mark the grid as dirty when they are added.
785     if (newChild.isOutOfFlowPositioned())
786         return;
787
788     // The grid needs to be recomputed as it might contain auto-placed items that
789     // will change their position.
790     parent.dirtyGrid();
791 }
792
793 }