File: StyleBuilder.cpp

package info (click to toggle)
webkit2gtk 2.42.2-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 362,452 kB
  • sloc: cpp: 2,881,971; javascript: 282,447; ansic: 134,088; python: 43,789; ruby: 18,308; perl: 15,872; asm: 14,389; xml: 4,395; yacc: 2,350; sh: 2,074; java: 1,734; lex: 1,323; makefile: 288; pascal: 60
file content (485 lines) | stat: -rw-r--r-- 19,352 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 * Copyright (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
 * Copyright (C) 2005-2021 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2012, 2013 Google Inc. All rights reserved.
 * Copyright (C) 2014 Igalia S.L.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "StyleBuilder.h"

#include "CSSCustomPropertyValue.h"
#include "CSSFontSelector.h"
#include "CSSPaintImageValue.h"
#include "CSSPendingSubstitutionValue.h"
#include "CSSPropertyParser.h"
#include "CSSRegisteredCustomProperty.h"
#include "CSSValuePool.h"
#include "CustomPropertyRegistry.h"
#include "Document.h"
#include "HTMLElement.h"
#include "PaintWorkletGlobalScope.h"
#include "RenderStyle.h"
#include "Settings.h"
#include "StyleBuilderGenerated.h"
#include "StyleFontSizeFunctions.h"
#include "StylePropertyShorthand.h"

#include <wtf/SetForScope.h>

namespace WebCore {
namespace Style {

static const CSSPropertyID firstLowPriorityProperty = static_cast<CSSPropertyID>(lastHighPriorityProperty + 1);

inline bool isValidVisitedLinkProperty(CSSPropertyID id)
{
    switch (id) {
    case CSSPropertyBackgroundColor:
    case CSSPropertyBorderLeftColor:
    case CSSPropertyBorderRightColor:
    case CSSPropertyBorderTopColor:
    case CSSPropertyBorderBottomColor:
    case CSSPropertyCaretColor:
    case CSSPropertyColor:
    case CSSPropertyOutlineColor:
    case CSSPropertyColumnRuleColor:
    case CSSPropertyTextDecorationColor:
    case CSSPropertyTextEmphasisColor:
    case CSSPropertyWebkitTextFillColor:
    case CSSPropertyWebkitTextStrokeColor:
    case CSSPropertyFill:
    case CSSPropertyStroke:
    case CSSPropertyStrokeColor:
        return true;
    default:
        break;
    }

    return false;
}

Builder::Builder(RenderStyle& style, BuilderContext&& context, const MatchResult& matchResult, CascadeLevel cascadeLevel, OptionSet<PropertyCascade::PropertyType> includedProperties, const HashSet<AnimatableProperty>* animatedPropertes)
    : m_cascade(matchResult, cascadeLevel, includedProperties, animatedPropertes)
    , m_state(*this, style, WTFMove(context))
{
}

Builder::~Builder() = default;

void Builder::applyAllProperties()
{
    if (m_cascade.isEmpty())
        return;

    applyTopPriorityProperties();
    applyHighPriorityProperties();
    applyNonHighPriorityProperties();
}

// Top priority properties affect resolution of high priority properties.
void Builder::applyTopPriorityProperties()
{
    applyProperties(firstTopPriorityProperty, lastTopPriorityProperty);
    m_state.adjustStyleForInterCharacterRuby();
}

// High priority properties may affect resolution of other properties (they are mostly font related).
void Builder::applyHighPriorityProperties()
{
    applyProperties(firstHighPriorityProperty, lastHighPriorityProperty);
    m_state.updateFont();
}

void Builder::applyNonHighPriorityProperties()
{
    ASSERT(!m_state.fontDirty());

    applyProperties(firstLowPriorityProperty, lastLowPriorityProperty);
    applyDeferredProperties();
    // Any referenced custom properties are already resolved. This will resolve the remaining ones.
    applyCustomProperties();

    ASSERT(!m_state.fontDirty());
}

void Builder::applyDeferredProperties()
{
    for (auto id : m_cascade.deferredPropertyIDs())
        applyCascadeProperty(m_cascade.deferredProperty(id));
}

void Builder::applyProperties(int firstProperty, int lastProperty)
{
    if (LIKELY(m_cascade.customProperties().isEmpty()))
        return applyPropertiesImpl<CustomPropertyCycleTracking::Disabled>(firstProperty, lastProperty);

    return applyPropertiesImpl<CustomPropertyCycleTracking::Enabled>(firstProperty, lastProperty);
}

template<Builder::CustomPropertyCycleTracking trackCycles>
inline void Builder::applyPropertiesImpl(int firstProperty, int lastProperty)
{
    for (int id = firstProperty; id <= lastProperty; ++id) {
        CSSPropertyID propertyID = static_cast<CSSPropertyID>(id);
        if (!m_cascade.hasNormalProperty(propertyID))
            continue;
        ASSERT(propertyID != CSSPropertyCustom);
        auto& property = m_cascade.normalProperty(propertyID);

        if (trackCycles == CustomPropertyCycleTracking::Enabled) {
            m_state.m_inProgressProperties.set(propertyID);
            applyCascadeProperty(property);
            m_state.m_inProgressProperties.clear(propertyID);
            continue;
        }

        // If we don't have any custom properties, then there can't be any cycles.
        applyCascadeProperty(property);
    }
}

void Builder::applyCustomProperties()
{
    for (auto& name : m_cascade.customProperties().keys())
        applyCustomProperty(name);
}

void Builder::applyCustomProperty(const AtomString& name)
{
    if (m_state.m_appliedCustomProperties.contains(name) || !m_cascade.customProperties().contains(name))
        return;

    auto& property = m_cascade.customProperty(name);
    if (!property.cssValue[SelectorChecker::MatchDefault])
        return;

    Ref customPropertyValue = downcast<CSSCustomPropertyValue>(*property.cssValue[SelectorChecker::MatchDefault]);

    bool inCycle = !m_state.m_inProgressCustomProperties.add(name).isNewEntry;
    if (inCycle) {
        auto isNewCycle = m_state.m_inCycleCustomProperties.add(name).isNewEntry;
        if (isNewCycle) {
            // Continue resolving dependencies so we detect cycles for them as well.
            resolveCustomPropertyValueWithVariableReferences(customPropertyValue.get());
        }
        return;
    }
    
    // There may be multiple cycles through the same property. Avoid interference from any previously detected cycles.
    auto savedInCycleProperties = std::exchange(m_state.m_inCycleCustomProperties, { });

    auto createInvalidOrUnset = [&] {
        // https://drafts.csswg.org/css-variables-2/#invalid-variables
        auto* registered = m_state.document().customPropertyRegistry().get(name);
        // The property is a non-registered custom property:
        // The property is a registered custom property with universal syntax:
        // The computed value is the guaranteed-invalid value.
        if (!registered || registered->syntax.isUniversal())
            return CSSCustomPropertyValue::createWithID(name, CSSValueInvalid);
        // Otherwise:
        // ...as if the property’s value had been specified as the unset keyword.
        return CSSCustomPropertyValue::createWithID(name, CSSValueUnset);
    };

    auto resolvedValue = resolveCustomPropertyValueWithVariableReferences(customPropertyValue.get());

    if (!resolvedValue || m_state.m_inCycleCustomProperties.contains(name))
        resolvedValue = createInvalidOrUnset();

    SetForScope levelScope(m_state.m_currentProperty, &property);
    SetForScope scopedLinkMatchMutation(m_state.m_linkMatch, SelectorChecker::MatchDefault);
    applyProperty(CSSPropertyCustom, *resolvedValue, SelectorChecker::MatchDefault);

    m_state.m_inProgressCustomProperties.remove(name);
    m_state.m_appliedCustomProperties.add(name);
    m_state.m_inCycleCustomProperties.formUnion(WTFMove(savedInCycleProperties));
}

inline void Builder::applyCascadeProperty(const PropertyCascade::Property& property)
{
    SetForScope levelScope(m_state.m_currentProperty, &property);

    auto applyWithLinkMatch = [&](SelectorChecker::LinkMatchMask linkMatch) {
        if (property.cssValue[linkMatch]) {
            SetForScope scopedLinkMatchMutation(m_state.m_linkMatch, linkMatch);
            applyProperty(property.id, *property.cssValue[linkMatch], linkMatch);
        }
    };

    applyWithLinkMatch(SelectorChecker::MatchDefault);

    if (m_state.style().insideLink() == InsideLink::NotInside)
        return;

    applyWithLinkMatch(SelectorChecker::MatchLink);
    applyWithLinkMatch(SelectorChecker::MatchVisited);

    m_state.m_linkMatch = SelectorChecker::MatchDefault;
}

void Builder::applyRollbackCascadeProperty(const PropertyCascade::Property& property, SelectorChecker::LinkMatchMask linkMatchMask)
{
    auto* value = property.cssValue[linkMatchMask];
    if (!value)
        return;

    SetForScope levelScope(m_state.m_currentProperty, &property);

    applyProperty(property.id, *value, linkMatchMask);
}

void Builder::applyProperty(CSSPropertyID id, CSSValue& value, SelectorChecker::LinkMatchMask linkMatchMask)
{
    ASSERT_WITH_MESSAGE(!isShorthand(id), "Shorthand property id = %d wasn't expanded at parsing time", id);

    auto valueToApply = resolveVariableReferences(id, value);
    auto& style = m_state.style();

    if (CSSProperty::isDirectionAwareProperty(id)) {
        CSSPropertyID newId = CSSProperty::resolveDirectionAwareProperty(id, style.direction(), style.writingMode());
        ASSERT(newId != id);
        return applyProperty(newId, valueToApply.get(), linkMatchMask);
    }

    auto valueID = WebCore::valueID(valueToApply.get());

    const CSSCustomPropertyValue* customPropertyValue = nullptr;
    const CSSRegisteredCustomProperty* registeredCustomProperty = nullptr;

    if (id == CSSPropertyCustom) {
        customPropertyValue = downcast<CSSCustomPropertyValue>(valueToApply.ptr());
        ASSERT(customPropertyValue->isResolved());
        if (std::holds_alternative<CSSValueID>(customPropertyValue->value()))
            valueID = std::get<CSSValueID>(customPropertyValue->value());
        auto& name = customPropertyValue->name();
        registeredCustomProperty = m_state.document().customPropertyRegistry().get(name);
    }

    bool isInherit = valueID == CSSValueInherit;
    bool isInitial = valueID == CSSValueInitial;
    bool isUnset = valueID == CSSValueUnset;
    bool isRevert = valueID == CSSValueRevert;
    bool isRevertLayer = valueID == CSSValueRevertLayer;

    if (isRevert || isRevertLayer) {
        // In @keyframes, 'revert-layer' rolls back the cascaded value to the author level.
        // We can just not apply the property in order to keep the value from the base style.
        if (isRevertLayer && m_state.m_isBuildingKeyframeStyle)
            return;

        auto* rollbackCascade = isRevert ? ensureRollbackCascadeForRevert() : ensureRollbackCascadeForRevertLayer();

        if (rollbackCascade) {
            // With the rollback cascade built, we need to obtain the property and apply it. If the property is
            // not present, then we behave like "unset." Otherwise we apply the property instead of our own.
            if (customPropertyValue) {
                if (registeredCustomProperty && registeredCustomProperty->inherits && rollbackCascade->hasCustomProperty(customPropertyValue->name())) {
                    auto property = rollbackCascade->customProperty(customPropertyValue->name());
                    applyRollbackCascadeProperty(property, linkMatchMask);
                    return;
                }
            } else if (id < firstDeferredProperty) {
                if (rollbackCascade->hasNormalProperty(id)) {
                    auto& property = rollbackCascade->normalProperty(id);
                    applyRollbackCascadeProperty(property, linkMatchMask);
                    return;
                }
            } else if (auto* property = rollbackCascade->lastDeferredPropertyResolvingRelated(id, style.direction(), style.writingMode())) {
                applyRollbackCascadeProperty(*property, linkMatchMask);
                return;
            }
        }

        isUnset = true;
    }

    auto isInheritedProperty = [&] {
        return registeredCustomProperty ? registeredCustomProperty->inherits : CSSProperty::isInheritedProperty(id);
    };

    if (isUnset) {
        // https://drafts.csswg.org/css-cascade-4/#inherit-initial
        // The unset CSS-wide keyword acts as either inherit or initial, depending on whether the property is inherited or not.
        if (isInheritedProperty())
            isInherit = true;
        else
            isInitial = true;
    }

    ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit

    if (m_state.applyPropertyToVisitedLinkStyle() && !isValidVisitedLinkProperty(id)) {
        // Limit the properties that can be applied to only the ones honored by :visited.
        return;
    }

    if (isInherit && !isInheritedProperty())
        style.setHasExplicitlyInheritedProperties();

#if ENABLE(CSS_PAINTING_API)
    if (is<CSSPaintImageValue>(valueToApply)) {
        auto& name = downcast<CSSPaintImageValue>(valueToApply.get()).name();
        if (auto* paintWorklet = const_cast<Document&>(m_state.document()).paintWorkletGlobalScopeForName(name)) {
            Locker locker { paintWorklet->paintDefinitionLock() };
            if (auto* registration = paintWorklet->paintDefinitionMap().get(name)) {
                for (auto& property : registration->inputProperties)
                    style.addCustomPaintWatchProperty(property);
            }
        }
    }
#endif

    BuilderGenerated::applyProperty(id, m_state, valueToApply.get(), isInitial, isInherit, registeredCustomProperty);
}

Ref<CSSValue> Builder::resolveVariableReferences(CSSPropertyID propertyID, CSSValue& value)
{
    if (!value.hasVariableReferences())
        return value;

    auto variableValue = [&]() -> RefPtr<CSSValue> {
        if (is<CSSPendingSubstitutionValue>(value)) {
            auto& substitution = downcast<CSSPendingSubstitutionValue>(value);
            auto shorthandID = substitution.shorthandPropertyId();

            auto resolvedData = substitution.shorthandValue().resolveVariableReferences(m_state);
            if (!resolvedData)
                return nullptr;

            ParsedPropertyVector parsedProperties;
            if (!CSSPropertyParser::parseValue(shorthandID, false, resolvedData->tokens(), substitution.shorthandValue().context(), parsedProperties, StyleRuleType::Style))
                return nullptr;

            for (auto& property : parsedProperties) {
                if (property.id() == propertyID)
                    return property.value();
            }

            return nullptr;
        }

        auto& variableReferenceValue = downcast<CSSVariableReferenceValue>(value);
        auto resolvedData = variableReferenceValue.resolveVariableReferences(m_state);
        if (!resolvedData)
            return nullptr;

        return CSSPropertyParser::parseSingleValue(propertyID, resolvedData->tokens(), variableReferenceValue.context());
    }();

    // https://drafts.csswg.org/css-variables-2/#invalid-variables
    // ...as if the property’s value had been specified as the unset keyword.
    if (!variableValue || m_state.m_inUnitCycleProperties.get(propertyID))
        return CSSPrimitiveValue::create(CSSValueUnset);

    return *variableValue;
}

RefPtr<CSSCustomPropertyValue> Builder::resolveCustomPropertyValueWithVariableReferences(CSSCustomPropertyValue& value)
{
    if (!std::holds_alternative<Ref<CSSVariableReferenceValue>>(value.value()))
        return &value;

    auto& variableReferenceValue = std::get<Ref<CSSVariableReferenceValue>>(value.value()).get();

    auto name = value.name();
    auto* registered = m_state.document().customPropertyRegistry().get(name);
    auto& syntax = registered ? registered->syntax : CSSCustomPropertySyntax::universal();

    auto resolvedData = variableReferenceValue.resolveVariableReferences(m_state);
    if (!resolvedData)
        return nullptr;

    auto dependencies = CSSPropertyParser::collectParsedCustomPropertyValueDependencies(syntax, resolvedData->tokens(), variableReferenceValue.context());

    // https://drafts.css-houdini.org/css-properties-values-api/#dependency-cycles
    bool hasCycles = false;
    bool isFontDependent = false;

    auto checkDependencies = [&](auto& propertyDependencies) {
        for (auto property : propertyDependencies) {
            if (m_state.m_inProgressProperties.get(property)) {
                m_state.m_inUnitCycleProperties.set(property);
                hasCycles = true;
            }
            if (property == CSSPropertyFontSize)
                isFontDependent = true;
        }
    };

    checkDependencies(dependencies.properties);

    if (m_state.element() == m_state.document().documentElement())
        checkDependencies(dependencies.rootProperties);

    if (hasCycles)
        return nullptr;

    if (isFontDependent)
        m_state.updateFont();

    return CSSPropertyParser::parseTypedCustomPropertyValue(name, syntax, resolvedData->tokens(), m_state, variableReferenceValue.context());
}

const PropertyCascade* Builder::ensureRollbackCascadeForRevert()
{
    auto rollbackCascadeLevel = m_state.m_currentProperty->cascadeLevel;
    if (rollbackCascadeLevel == CascadeLevel::UserAgent)
        return nullptr;

    --rollbackCascadeLevel;

    auto key = makeRollbackCascadeKey(rollbackCascadeLevel);
    return m_rollbackCascades.ensure(key, [&] {
        return makeUnique<const PropertyCascade>(m_cascade, rollbackCascadeLevel);
    }).iterator->value.get();
}

const PropertyCascade* Builder::ensureRollbackCascadeForRevertLayer()
{
    auto& property = *m_state.m_currentProperty;
    auto rollbackLayerPriority = property.cascadeLayerPriority;
    if (!rollbackLayerPriority)
        return ensureRollbackCascadeForRevert();

    ASSERT(property.fromStyleAttribute == FromStyleAttribute::No || property.cascadeLayerPriority == RuleSet::cascadeLayerPriorityForUnlayered);

    // Style attribute reverts to the regular author style.
    if (property.fromStyleAttribute == FromStyleAttribute::No)
        --rollbackLayerPriority;

    auto key = makeRollbackCascadeKey(property.cascadeLevel, property.styleScopeOrdinal, rollbackLayerPriority);
    return m_rollbackCascades.ensure(key, [&] {
        return makeUnique<const PropertyCascade>(m_cascade, property.cascadeLevel, property.styleScopeOrdinal, rollbackLayerPriority);
    }).iterator->value.get();
}

auto Builder::makeRollbackCascadeKey(CascadeLevel cascadeLevel, ScopeOrdinal scopeOrdinal, CascadeLayerPriority cascadeLayerPriority) -> RollbackCascadeKey
{
    return { static_cast<unsigned>(cascadeLevel), static_cast<unsigned>(scopeOrdinal), static_cast<unsigned>(cascadeLayerPriority) };
}

}
}