324cfba80cfd2a61ec677d94320c65599a875d7f
[WebKit-https.git] / Source / WebCore / style / StyleResolveTree.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Peter Kelly (pmk@post.com)
5  *           (C) 2001 Dirk Mueller (mueller@kde.org)
6  *           (C) 2007 David Smith (catfish.man@gmail.com)
7  * Copyright (C) 2004-2010, 2012-2014 Apple Inc. All rights reserved.
8  *           (C) 2007 Eric Seidel (eric@webkit.org)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 #include "config.h"
27 #include "StyleResolveTree.h"
28
29 #include "AXObjectCache.h"
30 #include "AnimationController.h"
31 #include "CSSFontSelector.h"
32 #include "ElementIterator.h"
33 #include "ElementRareData.h"
34 #include "FlowThreadController.h"
35 #include "InsertionPoint.h"
36 #include "LoaderStrategy.h"
37 #include "MainFrame.h"
38 #include "NodeRenderStyle.h"
39 #include "NodeRenderingTraversal.h"
40 #include "NodeTraversal.h"
41 #include "PlatformStrategies.h"
42 #include "RenderFullScreen.h"
43 #include "RenderNamedFlowThread.h"
44 #include "RenderText.h"
45 #include "RenderTreePosition.h"
46 #include "RenderWidget.h"
47 #include "ResourceLoadScheduler.h"
48 #include "Settings.h"
49 #include "ShadowRoot.h"
50 #include "StyleResolveForDocument.h"
51 #include "StyleResolver.h"
52 #include "Text.h"
53
54 #if PLATFORM(IOS)
55 #include "CSSFontSelector.h"
56 #include "WKContentObservation.h"
57 #endif
58
59 namespace WebCore {
60
61 namespace Style {
62
63 enum DetachType { NormalDetach, ReattachDetach };
64
65 static void attachRenderTree(Element&, RenderStyle& inheritedStyle, RenderTreePosition&, PassRefPtr<RenderStyle>);
66 static void attachTextRenderer(Text&, RenderTreePosition&);
67 static void detachRenderTree(Element&, DetachType);
68 static void resolveTextNode(Text&, RenderTreePosition&);
69 static void resolveTree(Element&, RenderStyle& inheritedStyle, RenderTreePosition&, Change);
70
71 Change determineChange(const RenderStyle& s1, const RenderStyle& s2)
72 {
73     if (s1.display() != s2.display())
74         return Detach;
75     if (s1.hasPseudoStyle(FIRST_LETTER) != s2.hasPseudoStyle(FIRST_LETTER))
76         return Detach;
77     // We just detach if a renderer acquires or loses a column-span, since spanning elements
78     // typically won't contain much content.
79     if (s1.columnSpan() != s2.columnSpan())
80         return Detach;
81     if (!s1.contentDataEquivalent(&s2))
82         return Detach;
83     // When text-combine property has been changed, we need to prepare a separate renderer object.
84     // When text-combine is on, we use RenderCombineText, otherwise RenderText.
85     // https://bugs.webkit.org/show_bug.cgi?id=55069
86     if (s1.hasTextCombine() != s2.hasTextCombine())
87         return Detach;
88     // We need to reattach the node, so that it is moved to the correct RenderFlowThread.
89     if (s1.flowThread() != s2.flowThread())
90         return Detach;
91     // When the region thread has changed, we need to prepare a separate render region object.
92     if (s1.regionThread() != s2.regionThread())
93         return Detach;
94     // FIXME: Multicolumn regions not yet supported (http://dev.w3.org/csswg/css-regions/#multi-column-regions)
95     // When the node has region style and changed its multicol style, we have to prepare
96     // a separate render region object.
97     if (s1.hasFlowFrom() && (s1.specifiesColumns() != s2.specifiesColumns()))
98         return Detach;
99     if (s1.alignItems() != s2.alignItems())
100         return Detach;
101
102     if (s1 != s2) {
103         if (s1.inheritedNotEqual(&s2))
104             return Inherit;
105         if (s1.hasExplicitlyInheritedProperties() || s2.hasExplicitlyInheritedProperties())
106             return Inherit;
107
108         return NoInherit;
109     }
110     // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
111     // because setStyle will do the right thing with anything else.
112     if (s1.hasAnyPublicPseudoStyles()) {
113         for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
114             if (s1.hasPseudoStyle(pseudoId)) {
115                 RenderStyle* ps2 = s2.getCachedPseudoStyle(pseudoId);
116                 if (!ps2)
117                     return NoInherit;
118                 RenderStyle* ps1 = s1.getCachedPseudoStyle(pseudoId);
119                 if (!ps1 || *ps1 != *ps2)
120                     return NoInherit;
121             }
122         }
123     }
124
125     return NoChange;
126 }
127
128 static bool shouldCreateRenderer(const Element& element, const RenderElement& parentRenderer)
129 {
130     if (!element.document().shouldCreateRenderers())
131         return false;
132     if (!parentRenderer.canHaveChildren() && !(element.isPseudoElement() && parentRenderer.canHaveGeneratedChildren()))
133         return false;
134     if (parentRenderer.element() && !parentRenderer.element()->childShouldCreateRenderer(element))
135         return false;
136     return true;
137 }
138
139 static Ref<RenderStyle> styleForElement(Element& element, RenderStyle& inheritedStyle)
140 {
141     if (element.hasCustomStyleResolveCallbacks()) {
142         if (RefPtr<RenderStyle> style = element.customStyleForRenderer(inheritedStyle))
143             return style.releaseNonNull();
144     }
145     return element.document().ensureStyleResolver().styleForElement(&element, &inheritedStyle);
146 }
147
148 #if ENABLE(CSS_REGIONS)
149 static RenderNamedFlowThread* moveToFlowThreadIfNeeded(Element& element, const RenderStyle& style)
150 {
151     if (!element.shouldMoveToFlowThread(style))
152         return 0;
153
154     FlowThreadController& flowThreadController = element.document().renderView()->flowThreadController();
155     RenderNamedFlowThread& parentFlowRenderer = flowThreadController.ensureRenderFlowThreadWithName(style.flowThread());
156     flowThreadController.registerNamedFlowContentElement(element, parentFlowRenderer);
157     return &parentFlowRenderer;
158 }
159 #endif
160
161 static void createRendererIfNeeded(Element& element, RenderStyle& inheritedStyle, RenderTreePosition& renderTreePosition, PassRefPtr<RenderStyle> resolvedStyle)
162 {
163     ASSERT(!element.renderer());
164
165     RefPtr<RenderStyle> style = resolvedStyle;
166
167     if (!shouldCreateRenderer(element, renderTreePosition.parent()))
168         return;
169
170     if (!style)
171         style = styleForElement(element, inheritedStyle);
172
173     RenderNamedFlowThread* parentFlowRenderer = 0;
174 #if ENABLE(CSS_REGIONS)
175     parentFlowRenderer = moveToFlowThreadIfNeeded(element, *style);
176 #endif
177
178     if (!element.rendererIsNeeded(*style))
179         return;
180
181     renderTreePosition.computeNextSibling(element);
182
183     RenderTreePosition insertionPosition = parentFlowRenderer
184         ? RenderTreePosition(*parentFlowRenderer, parentFlowRenderer->nextRendererForElement(element))
185         : renderTreePosition;
186
187     RenderElement* newRenderer = element.createElementRenderer(style.releaseNonNull(), insertionPosition).leakPtr();
188     if (!newRenderer)
189         return;
190     if (!insertionPosition.canInsert(*newRenderer)) {
191         newRenderer->destroy();
192         return;
193     }
194
195     // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style
196     // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail.
197     newRenderer->setFlowThreadState(insertionPosition.parent().flowThreadState());
198
199     // Code below updateAnimations() can depend on Element::renderer() already being set.
200     element.setRenderer(newRenderer);
201
202     // FIXME: There's probably a better way to factor this.
203     // This just does what setAnimatedStyle() does, except with setStyleInternal() instead of setStyle().
204     newRenderer->setStyleInternal(newRenderer->animation().updateAnimations(*newRenderer, newRenderer->style()));
205
206     newRenderer->initializeStyle();
207
208 #if ENABLE(FULLSCREEN_API)
209     Document& document = element.document();
210     if (document.webkitIsFullScreen() && document.webkitCurrentFullScreenElement() == &element) {
211         newRenderer = RenderFullScreen::wrapRenderer(newRenderer, &insertionPosition.parent(), document);
212         if (!newRenderer)
213             return;
214     }
215 #endif
216     // Note: Adding newRenderer instead of renderer(). renderer() may be a child of newRenderer.
217     insertionPosition.insert(*newRenderer);
218 }
219
220 static void invalidateWhitespaceOnlyTextSiblingsAfterAttachIfNeeded(Node& current)
221 {
222     if (is<InsertionPoint>(current))
223         return;
224     // This function finds sibling text renderers where the results of textRendererIsNeeded may have changed as a result of
225     // the current node gaining or losing the renderer. This can only affect white space text nodes.
226     for (Node* sibling = current.nextSibling(); sibling; sibling = sibling->nextSibling()) {
227         if (sibling->needsStyleRecalc())
228             return;
229         if (is<Element>(*sibling)) {
230             // Text renderers beyond rendered elements can't be affected.
231             if (!sibling->renderer() || RenderTreePosition::isRendererReparented(*sibling->renderer()))
232                 continue;
233             return;
234         }
235         if (!is<Text>(*sibling))
236             continue;
237         Text& textSibling = downcast<Text>(*sibling);
238         if (!textSibling.containsOnlyWhitespace())
239             continue;
240         textSibling.setNeedsStyleRecalc();
241     }
242 }
243
244 static bool textRendererIsNeeded(const Text& textNode, const RenderTreePosition& renderTreePosition)
245 {
246     const RenderElement& parentRenderer = renderTreePosition.parent();
247     if (!parentRenderer.canHaveChildren())
248         return false;
249     if (parentRenderer.element() && !parentRenderer.element()->childShouldCreateRenderer(textNode))
250         return false;
251     if (textNode.isEditingText())
252         return true;
253     if (!textNode.length())
254         return false;
255     if (!textNode.containsOnlyWhitespace())
256         return true;
257     // This text node has nothing but white space. We may still need a renderer in some cases.
258     if (parentRenderer.isTable() || parentRenderer.isTableRow() || parentRenderer.isTableSection() || parentRenderer.isRenderTableCol() || parentRenderer.isFrameSet())
259         return false;
260     if (parentRenderer.style().preserveNewline()) // pre/pre-wrap/pre-line always make renderers.
261         return true;
262
263     RenderObject* previousRenderer = RenderTreePosition::previousSiblingRenderer(textNode);
264     if (previousRenderer && previousRenderer->isBR()) // <span><br/> <br/></span>
265         return false;
266         
267     if (parentRenderer.isRenderInline()) {
268         // <span><div/> <div/></span>
269         if (previousRenderer && !previousRenderer->isInline())
270             return false;
271     } else {
272         if (parentRenderer.isRenderBlock() && !parentRenderer.childrenInline() && (!previousRenderer || !previousRenderer->isInline()))
273             return false;
274         
275         RenderObject* first = parentRenderer.firstChild();
276         while (first && first->isFloatingOrOutOfFlowPositioned())
277             first = first->nextSibling();
278         RenderObject* nextRenderer = RenderTreePosition::nextSiblingRenderer(textNode, parentRenderer);
279         if (!first || nextRenderer == first) {
280             // Whitespace at the start of a block just goes away. Don't even make a render object for this text.
281             return false;
282         }
283     }
284     return true;
285 }
286
287 static void createTextRendererIfNeeded(Text& textNode, RenderTreePosition& renderTreePosition)
288 {
289     ASSERT(!textNode.renderer());
290
291     if (!textRendererIsNeeded(textNode, renderTreePosition))
292         return;
293
294     auto newRenderer = textNode.createTextRenderer(renderTreePosition.parent().style());
295     ASSERT(newRenderer);
296
297     renderTreePosition.computeNextSibling(textNode);
298
299     if (!renderTreePosition.canInsert(*newRenderer))
300         return;
301
302     // Make sure the RenderObject already knows it is going to be added to a RenderFlowThread before we set the style
303     // for the first time. Otherwise code using inRenderFlowThread() in the styleWillChange and styleDidChange will fail.
304     newRenderer->setFlowThreadState(renderTreePosition.parent().flowThreadState());
305
306     textNode.setRenderer(newRenderer.get());
307     // Parent takes care of the animations, no need to call setAnimatableStyle.
308     renderTreePosition.insert(*newRenderer.leakPtr());
309 }
310
311 void attachTextRenderer(Text& textNode, RenderTreePosition& renderTreePosition)
312 {
313     createTextRendererIfNeeded(textNode, renderTreePosition);
314
315     textNode.clearNeedsStyleRecalc();
316 }
317
318 void detachTextRenderer(Text& textNode)
319 {
320     if (textNode.renderer())
321         textNode.renderer()->destroyAndCleanupAnonymousWrappers();
322     textNode.setRenderer(0);
323 }
324
325 void updateTextRendererAfterContentChange(Text& textNode, unsigned offsetOfReplacedData, unsigned lengthOfReplacedData)
326 {
327     ContainerNode* renderingParentNode = NodeRenderingTraversal::parent(&textNode);
328     if (!renderingParentNode || !renderingParentNode->renderer())
329         return;
330
331     bool hadRenderer = textNode.renderer();
332
333     RenderTreePosition renderTreePosition(*renderingParentNode->renderer());
334     resolveTextNode(textNode, renderTreePosition);
335
336     if (hadRenderer && textNode.renderer())
337         textNode.renderer()->setTextWithOffset(textNode.data(), offsetOfReplacedData, lengthOfReplacedData);
338 }
339
340 static void attachChildren(ContainerNode& current, RenderStyle& inheritedStyle, RenderTreePosition& renderTreePosition)
341 {
342     for (Node* child = current.firstChild(); child; child = child->nextSibling()) {
343         ASSERT((!child->renderer() || child->isNamedFlowContentNode()) || current.shadowRoot());
344         if (child->renderer()) {
345             renderTreePosition.invalidateNextSibling(*child->renderer());
346             continue;
347         }
348         if (is<Text>(*child)) {
349             attachTextRenderer(downcast<Text>(*child), renderTreePosition);
350             continue;
351         }
352         if (is<Element>(*child))
353             attachRenderTree(downcast<Element>(*child), inheritedStyle, renderTreePosition, nullptr);
354     }
355 }
356
357 static void attachDistributedChildren(InsertionPoint& insertionPoint, RenderStyle& inheritedStyle, RenderTreePosition& renderTreePosition)
358 {
359     if (ShadowRoot* shadowRoot = insertionPoint.containingShadowRoot())
360         ContentDistributor::ensureDistribution(shadowRoot);
361
362     for (Node* current = insertionPoint.firstDistributed(); current; current = insertionPoint.nextDistributedTo(current)) {
363         if (current->renderer())
364             renderTreePosition.invalidateNextSibling(*current->renderer());
365         if (is<Text>(*current)) {
366             if (current->renderer())
367                 continue;
368             attachTextRenderer(downcast<Text>(*current), renderTreePosition);
369             continue;
370         }
371         if (is<Element>(*current)) {
372             Element& currentElement = downcast<Element>(*current);
373             if (currentElement.renderer())
374                 detachRenderTree(currentElement);
375             attachRenderTree(currentElement, inheritedStyle, renderTreePosition, nullptr);
376         }
377     }
378     // Use actual children as fallback content.
379     if (!insertionPoint.hasDistribution())
380         attachChildren(insertionPoint, inheritedStyle, renderTreePosition);
381 }
382
383 static void attachShadowRoot(ShadowRoot& shadowRoot)
384 {
385     ASSERT(shadowRoot.hostElement());
386     ASSERT(shadowRoot.hostElement()->renderer());
387
388     auto& renderer = *shadowRoot.hostElement()->renderer();
389     RenderTreePosition renderTreePosition(renderer);
390     attachChildren(shadowRoot, renderer.style(), renderTreePosition);
391
392     shadowRoot.clearNeedsStyleRecalc();
393     shadowRoot.clearChildNeedsStyleRecalc();
394 }
395
396 static PseudoElement* beforeOrAfterPseudoElement(Element& current, PseudoId pseudoId)
397 {
398     ASSERT(pseudoId == BEFORE || pseudoId == AFTER);
399     if (pseudoId == BEFORE)
400         return current.beforePseudoElement();
401     return current.afterPseudoElement();
402 }
403
404 static void setBeforeOrAfterPseudoElement(Element& current, Ref<PseudoElement>&& pseudoElement, PseudoId pseudoId)
405 {
406     ASSERT(pseudoId == BEFORE || pseudoId == AFTER);
407     if (pseudoId == BEFORE) {
408         current.setBeforePseudoElement(WTF::move(pseudoElement));
409         return;
410     }
411     current.setAfterPseudoElement(WTF::move(pseudoElement));
412 }
413
414 static void clearBeforeOrAfterPseudoElement(Element& current, PseudoId pseudoId)
415 {
416     ASSERT(pseudoId == BEFORE || pseudoId == AFTER);
417     if (pseudoId == BEFORE) {
418         current.clearBeforePseudoElement();
419         return;
420     }
421     current.clearAfterPseudoElement();
422 }
423
424 static void resetStyleForNonRenderedDescendants(Element& current)
425 {
426     ASSERT(!current.renderer());
427     bool elementNeedingStyleRecalcAffectsNextSiblingElementStyle = false;
428     for (auto& child : childrenOfType<Element>(current)) {
429         ASSERT(!child.renderer());
430         if (elementNeedingStyleRecalcAffectsNextSiblingElementStyle) {
431             if (child.styleIsAffectedByPreviousSibling())
432                 child.setNeedsStyleRecalc();
433             elementNeedingStyleRecalcAffectsNextSiblingElementStyle = child.affectsNextSiblingElementStyle();
434         }
435
436         if (child.needsStyleRecalc()) {
437             child.resetComputedStyle();
438             child.clearNeedsStyleRecalc();
439             elementNeedingStyleRecalcAffectsNextSiblingElementStyle = child.affectsNextSiblingElementStyle();
440         }
441
442         if (child.childNeedsStyleRecalc()) {
443             resetStyleForNonRenderedDescendants(child);
444             child.clearChildNeedsStyleRecalc();
445         }
446     }
447 }
448
449 static bool needsPseudoElement(Element& current, PseudoId pseudoId)
450 {
451     if (!current.renderer() || !current.renderer()->canHaveGeneratedChildren())
452         return false;
453     if (current.isPseudoElement())
454         return false;
455     if (!pseudoElementRendererIsNeeded(current.renderer()->getCachedPseudoStyle(pseudoId)))
456         return false;
457     return true;
458 }
459
460 static void attachBeforeOrAfterPseudoElementIfNeeded(Element& current, PseudoId pseudoId, RenderTreePosition& renderTreePosition)
461 {
462     if (!needsPseudoElement(current, pseudoId))
463         return;
464     Ref<PseudoElement> pseudoElement = PseudoElement::create(current, pseudoId);
465     setBeforeOrAfterPseudoElement(current, pseudoElement.copyRef(), pseudoId);
466     attachRenderTree(pseudoElement.get(), *current.renderStyle(), renderTreePosition, nullptr);
467 }
468
469 static void attachRenderTree(Element& current, RenderStyle& inheritedStyle, RenderTreePosition& renderTreePosition, PassRefPtr<RenderStyle> resolvedStyle)
470 {
471     PostResolutionCallbackDisabler callbackDisabler(current.document());
472     WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
473
474     if (is<InsertionPoint>(current)) {
475         attachDistributedChildren(downcast<InsertionPoint>(current), inheritedStyle, renderTreePosition);
476         current.clearNeedsStyleRecalc();
477         current.clearChildNeedsStyleRecalc();
478         return;
479     }
480
481     if (current.hasCustomStyleResolveCallbacks())
482         current.willAttachRenderers();
483
484     createRendererIfNeeded(current, inheritedStyle, renderTreePosition, resolvedStyle);
485
486     if (auto* renderer = current.renderer()) {
487         StyleResolverParentPusher parentPusher(&current);
488
489         RenderTreePosition childRenderTreePosition(*renderer);
490         attachBeforeOrAfterPseudoElementIfNeeded(current, BEFORE, childRenderTreePosition);
491
492         if (ShadowRoot* shadowRoot = current.shadowRoot()) {
493             parentPusher.push();
494             attachShadowRoot(*shadowRoot);
495         } else if (current.firstChild())
496             parentPusher.push();
497
498         attachChildren(current, renderer->style(), childRenderTreePosition);
499
500         if (AXObjectCache* cache = current.document().axObjectCache())
501             cache->updateCacheAfterNodeIsAttached(&current);
502
503         attachBeforeOrAfterPseudoElementIfNeeded(current, AFTER, childRenderTreePosition);
504
505         current.updateFocusAppearanceAfterAttachIfNeeded();
506     } else
507         resetStyleForNonRenderedDescendants(current);
508
509     current.clearNeedsStyleRecalc();
510     current.clearChildNeedsStyleRecalc();
511
512     if (current.hasCustomStyleResolveCallbacks())
513         current.didAttachRenderers();
514 }
515
516 static void detachDistributedChildren(InsertionPoint& insertionPoint)
517 {
518     for (Node* current = insertionPoint.firstDistributed(); current; current = insertionPoint.nextDistributedTo(current)) {
519         if (is<Text>(*current)) {
520             detachTextRenderer(downcast<Text>(*current));
521             continue;
522         }
523         if (is<Element>(*current))
524             detachRenderTree(downcast<Element>(*current));
525     }
526 }
527
528 static void detachChildren(ContainerNode& current, DetachType detachType)
529 {
530     if (is<InsertionPoint>(current))
531         detachDistributedChildren(downcast<InsertionPoint>(current));
532
533     for (Node* child = current.firstChild(); child; child = child->nextSibling()) {
534         if (is<Text>(*child)) {
535             Style::detachTextRenderer(downcast<Text>(*child));
536             continue;
537         }
538         if (is<Element>(*child))
539             detachRenderTree(downcast<Element>(*child), detachType);
540     }
541     current.clearChildNeedsStyleRecalc();
542 }
543
544 static void detachShadowRoot(ShadowRoot& shadowRoot, DetachType detachType)
545 {
546     detachChildren(shadowRoot, detachType);
547 }
548
549 static void detachRenderTree(Element& current, DetachType detachType)
550 {
551     WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
552
553     if (current.hasCustomStyleResolveCallbacks())
554         current.willDetachRenderers();
555
556     current.clearStyleDerivedDataBeforeDetachingRenderer();
557
558     // Do not remove the element's hovered and active status
559     // if performing a reattach.
560     if (detachType != ReattachDetach)
561         current.clearHoverAndActiveStatusBeforeDetachingRenderer();
562
563     if (ShadowRoot* shadowRoot = current.shadowRoot())
564         detachShadowRoot(*shadowRoot, detachType);
565
566     detachChildren(current, detachType);
567
568     if (current.renderer())
569         current.renderer()->destroyAndCleanupAnonymousWrappers();
570     current.setRenderer(0);
571
572     if (current.hasCustomStyleResolveCallbacks())
573         current.didDetachRenderers();
574 }
575
576 static bool pseudoStyleCacheIsInvalid(RenderElement* renderer, RenderStyle* newStyle)
577 {
578     const RenderStyle& currentStyle = renderer->style();
579
580     const PseudoStyleCache* pseudoStyleCache = currentStyle.cachedPseudoStyles();
581     if (!pseudoStyleCache)
582         return false;
583
584     size_t cacheSize = pseudoStyleCache->size();
585     for (size_t i = 0; i < cacheSize; ++i) {
586         RefPtr<RenderStyle> newPseudoStyle;
587         PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
588         if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
589             newPseudoStyle = renderer->uncachedFirstLineStyle(newStyle);
590         else
591             newPseudoStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
592         if (!newPseudoStyle)
593             return true;
594         if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
595             if (pseudoId < FIRST_INTERNAL_PSEUDOID)
596                 newStyle->setHasPseudoStyle(pseudoId);
597             newStyle->addCachedPseudoStyle(newPseudoStyle);
598             if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
599                 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
600                 // is needed, but for now just assume a layout will be required. The diff code
601                 // in RenderObject::setStyle would need to be factored out so that it could be reused.
602                 renderer->setNeedsLayoutAndPrefWidthsRecalc();
603             }
604             return true;
605         }
606     }
607     return false;
608 }
609
610 static Change resolveLocal(Element& current, RenderStyle& inheritedStyle, RenderTreePosition& renderTreePosition, Change inheritedChange)
611 {
612     Change localChange = Detach;
613     RefPtr<RenderStyle> newStyle;
614     RefPtr<RenderStyle> currentStyle = current.renderStyle();
615
616     Document& document = current.document();
617     if (currentStyle && current.styleChangeType() != ReconstructRenderTree) {
618         Ref<RenderStyle> style(styleForElement(current, inheritedStyle));
619         newStyle = style.ptr();
620         localChange = determineChange(*currentStyle, style);
621     }
622     if (localChange == Detach) {
623         if (current.renderer() || current.isNamedFlowContentNode())
624             detachRenderTree(current, ReattachDetach);
625         attachRenderTree(current, inheritedStyle, renderTreePosition, newStyle.release());
626         invalidateWhitespaceOnlyTextSiblingsAfterAttachIfNeeded(current);
627
628         return Detach;
629     }
630
631     if (RenderElement* renderer = current.renderer()) {
632         if (localChange != NoChange || pseudoStyleCacheIsInvalid(renderer, newStyle.get()) || (inheritedChange == Force && renderer->requiresForcedStyleRecalcPropagation()) || current.styleChangeType() == SyntheticStyleChange)
633             renderer->setAnimatableStyle(*newStyle);
634         else if (current.needsStyleRecalc()) {
635             // Although no change occurred, we use the new style so that the cousin style sharing code won't get
636             // fooled into believing this style is the same.
637             renderer->setStyleInternal(*newStyle);
638         }
639     }
640
641     // If "rem" units are used anywhere in the document, and if the document element's font size changes, then force font updating
642     // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
643     if (document.styleSheetCollection().usesRemUnits() && document.documentElement() == &current && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
644         // Cached RenderStyles may depend on the re units.
645         if (StyleResolver* styleResolver = document.styleResolverIfExists())
646             styleResolver->invalidateMatchedPropertiesCache();
647         return Force;
648     }
649     if (inheritedChange == Force)
650         return Force;
651     if (current.styleChangeType() >= FullStyleChange)
652         return Force;
653
654     return localChange;
655 }
656
657 void resolveTextNode(Text& text, RenderTreePosition& renderTreePosition)
658 {
659     text.clearNeedsStyleRecalc();
660
661     bool hasRenderer = text.renderer();
662     bool needsRenderer = textRendererIsNeeded(text, renderTreePosition);
663     if (hasRenderer) {
664         if (needsRenderer)
665             return;
666         detachTextRenderer(text);
667         invalidateWhitespaceOnlyTextSiblingsAfterAttachIfNeeded(text);
668         return;
669     }
670     if (!needsRenderer)
671         return;
672     attachTextRenderer(text, renderTreePosition);
673     invalidateWhitespaceOnlyTextSiblingsAfterAttachIfNeeded(text);
674 }
675
676 static void resolveShadowTree(ShadowRoot& shadowRoot, Element& host, Style::Change change)
677 {
678     ASSERT(shadowRoot.hostElement() == &host);
679     ASSERT(host.renderer());
680     RenderTreePosition renderTreePosition(*host.renderer());
681     for (Node* child = shadowRoot.firstChild(); child; child = child->nextSibling()) {
682         if (child->renderer())
683             renderTreePosition.invalidateNextSibling(*child->renderer());
684         if (is<Text>(*child) && child->needsStyleRecalc()) {
685             resolveTextNode(downcast<Text>(*child), renderTreePosition);
686             continue;
687         }
688         if (is<Element>(*child))
689             resolveTree(downcast<Element>(*child), host.renderer()->style(), renderTreePosition, change);
690     }
691
692     shadowRoot.clearNeedsStyleRecalc();
693     shadowRoot.clearChildNeedsStyleRecalc();
694 }
695
696 static void updateBeforeOrAfterPseudoElement(Element& current, Change change, PseudoId pseudoId, RenderTreePosition& renderTreePosition)
697 {
698     ASSERT(current.renderer());
699     if (PseudoElement* existingPseudoElement = beforeOrAfterPseudoElement(current, pseudoId)) {
700         if (existingPseudoElement->renderer())
701             renderTreePosition.invalidateNextSibling(*existingPseudoElement->renderer());
702
703         if (needsPseudoElement(current, pseudoId))
704             resolveTree(*existingPseudoElement, current.renderer()->style(), renderTreePosition, current.needsStyleRecalc() ? Force : change);
705         else
706             clearBeforeOrAfterPseudoElement(current, pseudoId);
707         return;
708     }
709     attachBeforeOrAfterPseudoElementIfNeeded(current, pseudoId, renderTreePosition);
710 }
711
712 #if PLATFORM(IOS)
713 static EVisibility elementImplicitVisibility(const Element* element)
714 {
715     RenderObject* renderer = element->renderer();
716     if (!renderer)
717         return VISIBLE;
718
719     RenderStyle& style = renderer->style();
720
721     Length width(style.width());
722     Length height(style.height());
723     if ((width.isFixed() && width.value() <= 0) || (height.isFixed() && height.value() <= 0))
724         return HIDDEN;
725
726     Length top(style.top());
727     Length left(style.left());
728     if (left.isFixed() && width.isFixed() && -left.value() >= width.value())
729         return HIDDEN;
730
731     if (top.isFixed() && height.isFixed() && -top.value() >= height.value())
732         return HIDDEN;
733     return VISIBLE;
734 }
735
736 class CheckForVisibilityChangeOnRecalcStyle {
737 public:
738     CheckForVisibilityChangeOnRecalcStyle(Element* element, RenderStyle* currentStyle)
739         : m_element(element)
740         , m_previousDisplay(currentStyle ? currentStyle->display() : NONE)
741         , m_previousVisibility(currentStyle ? currentStyle->visibility() : HIDDEN)
742         , m_previousImplicitVisibility(WKObservingContentChanges() && WKContentChange() != WKContentVisibilityChange ? elementImplicitVisibility(element) : VISIBLE)
743     {
744     }
745     ~CheckForVisibilityChangeOnRecalcStyle()
746     {
747         if (!WKObservingContentChanges())
748             return;
749         RenderStyle* style = m_element->renderStyle();
750         if (!style)
751             return;
752         if ((m_previousDisplay == NONE && style->display() != NONE) || (m_previousVisibility == HIDDEN && style->visibility() != HIDDEN)
753             || (m_previousImplicitVisibility == HIDDEN && elementImplicitVisibility(m_element.get()) == VISIBLE))
754             WKSetObservedContentChange(WKContentVisibilityChange);
755     }
756 private:
757     RefPtr<Element> m_element;
758     EDisplay m_previousDisplay;
759     EVisibility m_previousVisibility;
760     EVisibility m_previousImplicitVisibility;
761 };
762 #endif // PLATFORM(IOS)
763
764 void resolveTree(Element& current, RenderStyle& inheritedStyle, RenderTreePosition& renderTreePosition, Change change)
765 {
766     ASSERT(change != Detach);
767
768     if (is<InsertionPoint>(current)) {
769         current.clearNeedsStyleRecalc();
770         current.clearChildNeedsStyleRecalc();
771         return;
772     }
773
774     if (current.hasCustomStyleResolveCallbacks()) {
775         if (!current.willRecalcStyle(change))
776             return;
777     }
778
779 #if PLATFORM(IOS)
780     CheckForVisibilityChangeOnRecalcStyle checkForVisibilityChange(&current, current.renderStyle());
781 #endif
782
783     if (change > NoChange || current.needsStyleRecalc())
784         current.resetComputedStyle();
785
786     if (change >= Inherit || current.needsStyleRecalc())
787         change = resolveLocal(current, inheritedStyle, renderTreePosition, change);
788
789     auto* renderer = current.renderer();
790
791     if (change != Detach && renderer) {
792         StyleResolverParentPusher parentPusher(&current);
793
794         if (ShadowRoot* shadowRoot = current.shadowRoot()) {
795             if (change >= Inherit || shadowRoot->childNeedsStyleRecalc() || shadowRoot->needsStyleRecalc()) {
796                 parentPusher.push();
797                 resolveShadowTree(*shadowRoot, current, change);
798             }
799         }
800
801         RenderTreePosition childRenderTreePosition(*renderer);
802         updateBeforeOrAfterPseudoElement(current, change, BEFORE, childRenderTreePosition);
803
804         bool elementNeedingStyleRecalcAffectsNextSiblingElementStyle = false;
805         for (Node* child = current.firstChild(); child; child = child->nextSibling()) {
806             if (RenderObject* childRenderer = child->renderer())
807                 childRenderTreePosition.invalidateNextSibling(*childRenderer);
808             if (is<Text>(*child) && child->needsStyleRecalc()) {
809                 resolveTextNode(downcast<Text>(*child), childRenderTreePosition);
810                 continue;
811             }
812             if (!is<Element>(*child))
813                 continue;
814
815             Element& childElement = downcast<Element>(*child);
816             if (elementNeedingStyleRecalcAffectsNextSiblingElementStyle) {
817                 if (childElement.styleIsAffectedByPreviousSibling())
818                     childElement.setNeedsStyleRecalc();
819                 elementNeedingStyleRecalcAffectsNextSiblingElementStyle = childElement.affectsNextSiblingElementStyle();
820             } else if (childElement.styleChangeType() >= FullStyleChange)
821                 elementNeedingStyleRecalcAffectsNextSiblingElementStyle = childElement.affectsNextSiblingElementStyle();
822             if (change >= Inherit || childElement.childNeedsStyleRecalc() || childElement.needsStyleRecalc()) {
823                 parentPusher.push();
824                 resolveTree(childElement, renderer->style(), childRenderTreePosition, change);
825             }
826         }
827
828         updateBeforeOrAfterPseudoElement(current, change, AFTER, childRenderTreePosition);
829     }
830     if (change != Detach && !renderer)
831         resetStyleForNonRenderedDescendants(current);
832
833     current.clearNeedsStyleRecalc();
834     current.clearChildNeedsStyleRecalc();
835     
836     if (current.hasCustomStyleResolveCallbacks())
837         current.didRecalcStyle(change);
838 }
839
840 void resolveTree(Document& document, Change change)
841 {
842     if (change == Force) {
843         auto documentStyle = resolveForDocument(document);
844
845         // Inserting the pictograph font at the end of the font fallback list is done by the
846         // font selector, so set a font selector if needed.
847         if (Settings* settings = document.settings()) {
848             if (settings->fontFallbackPrefersPictographs())
849                 documentStyle.get().fontCascade().update(&document.fontSelector());
850         }
851
852         Style::Change documentChange = determineChange(documentStyle.get(), document.renderView()->style());
853         if (documentChange != NoChange)
854             document.renderView()->setStyle(WTF::move(documentStyle));
855     }
856
857     Element* documentElement = document.documentElement();
858     if (!documentElement)
859         return;
860     if (change < Inherit && !documentElement->childNeedsStyleRecalc() && !documentElement->needsStyleRecalc())
861         return;
862     RenderTreePosition renderTreePosition(*document.renderView());
863     resolveTree(*documentElement, *document.renderStyle(), renderTreePosition, change);
864 }
865
866 void detachRenderTree(Element& element)
867 {
868     detachRenderTree(element, NormalDetach);
869 }
870
871 static Vector<std::function<void ()>>& postResolutionCallbackQueue()
872 {
873     static NeverDestroyed<Vector<std::function<void ()>>> vector;
874     return vector;
875 }
876
877 void queuePostResolutionCallback(std::function<void ()> callback)
878 {
879     postResolutionCallbackQueue().append(callback);
880 }
881
882 static void suspendMemoryCacheClientCalls(Document& document)
883 {
884     Page* page = document.page();
885     if (!page || !page->areMemoryCacheClientCallsEnabled())
886         return;
887
888     page->setMemoryCacheClientCallsEnabled(false);
889
890     RefPtr<MainFrame> protectedMainFrame = &page->mainFrame();
891     postResolutionCallbackQueue().append([protectedMainFrame]{
892         if (Page* page = protectedMainFrame->page())
893             page->setMemoryCacheClientCallsEnabled(true);
894     });
895 }
896
897 static unsigned resolutionNestingDepth;
898
899 PostResolutionCallbackDisabler::PostResolutionCallbackDisabler(Document& document)
900 {
901     ++resolutionNestingDepth;
902
903     if (resolutionNestingDepth == 1)
904         platformStrategies()->loaderStrategy()->resourceLoadScheduler()->suspendPendingRequests();
905
906     // FIXME: It's strange to build this into the disabler.
907     suspendMemoryCacheClientCalls(document);
908 }
909
910 PostResolutionCallbackDisabler::~PostResolutionCallbackDisabler()
911 {
912     if (resolutionNestingDepth == 1) {
913         // Get size each time through the loop because a callback can add more callbacks to the end of the queue.
914         auto& queue = postResolutionCallbackQueue();
915         for (size_t i = 0; i < queue.size(); ++i)
916             queue[i]();
917         queue.clear();
918
919         platformStrategies()->loaderStrategy()->resourceLoadScheduler()->resumePendingRequests();
920     }
921
922     --resolutionNestingDepth;
923 }
924
925 bool postResolutionCallbacksAreSuspended()
926 {
927     return resolutionNestingDepth;
928 }
929
930 }
931 }