File: TextListParser.cpp

package info (click to toggle)
webkit2gtk 2.51.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 455,340 kB
  • sloc: cpp: 3,865,253; javascript: 197,710; ansic: 165,177; python: 49,241; asm: 21,868; ruby: 18,095; perl: 16,926; xml: 4,623; sh: 2,409; yacc: 2,356; java: 2,019; lex: 1,330; pascal: 372; makefile: 210
file content (265 lines) | stat: -rw-r--r-- 9,191 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
/*
 * Copyright (C) 2025 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "TextListParser.h"

#include <WebCore/CSSSerializationContext.h>
#include <WebCore/CSSValueKeywords.h>
#include <WebCore/CSSValuePool.h>
#include <WebCore/ContainerNodeInlines.h>
#include <WebCore/Document.h>
#include <WebCore/Editing.h>
#include <WebCore/Editor.h>
#include <WebCore/ElementInlines.h>
#include <WebCore/FontAttributes.h>
#include <WebCore/HTMLElement.h>
#include <WebCore/HTMLNames.h>
#include <WebCore/MutableStyleProperties.h>
#include <WebCore/RenderElement.h>
#include <WebCore/StyleProperties.h>
#include <WebCore/StylePropertiesInlines.h>
#include <WebCore/StyledElement.h>
#include <WebCore/VisibleSelection.h>
#include <span>
#include <wtf/ASCIICType.h>
#include <wtf/CheckedArithmetic.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/AtomString.h>
#include <wtf/text/ParsingUtilities.h>
#include <wtf/text/StringParsingBuffer.h>
#include <wtf/unicode/CharacterNames.h>

namespace WebCore {

// MARK: Helpers

template<typename Character>
constexpr int consumeNumber(StringParsingBuffer<Character>& input)
{
    // Parse the digits until there is no more input left or a non-ASCII digit character has been encountered.
    Checked<int> value;
    do {
        auto c = input.consume();
        int digitValue = c - '0';
        value = (value * 10) + digitValue;
    } while (!input.atEnd() && WTF::isASCIIDigit(*input));

    ASSERT(value.value() > 0);
    return value.value();
}

template<typename Character>
void skipToEnd(StringParsingBuffer<Character>& input)
{
    input.advanceBy(input.lengthRemaining());
}

// MARK: Primary consumers

template<typename Character>
std::optional<TextList> tryConsumeUnorderedDiscTextList(StringParsingBuffer<Character>& input)
{
    if (WTF::skipExactly(input, '*') ||  WTF::skipCharactersExactly(input, WTF::spanReinterpretCast<const Character>(WTF::span(WTF::Unicode::bullet)))) {
        if (input.atEnd())
            return { { { CSS::Keyword::Disc { } }, 0, false } };

        skipToEnd(input);
    }

    return std::nullopt;
}

template<typename Character>
std::optional<TextList> tryConsumeUnorderedDashTextList(StringParsingBuffer<Character>& input)
{
    static constexpr std::array marker { WTF::Unicode::emDash, WTF::Unicode::noBreakSpace, WTF::Unicode::noBreakSpace };

    if (WTF::skipExactly(input, WTF::Unicode::hyphenMinus)) {
        if (input.atEnd())
            return { { Style::ListStyleType { AtomString { std::span { marker } } }, 0, false } };

        skipToEnd(input);
    }

    return std::nullopt;
}

template<typename Character>
std::optional<TextList> tryConsumeOrderedDecimalTextList(StringParsingBuffer<Character>& input)
{
    // This algorithm is similar to the one in StringToIntegerConversion.h, but is stricter and simpler; specifically:
    //
    //   - only base 10 is allowed
    //   - whitespace is not allowed anywhere
    //   - the "-" and "+" signs are not allowed (which consequently restricts the output to non-negative values)
    //   - prefixed "0"s are not allowed (which consequently restricts the output to non-zero values)
    //   - "trailing junk" is only allowed if it is either "." or ")"

    // Must start with an ASCII digit that is not 0.
    if (input.atEnd() || !WTF::isASCIIDigit(*input) || *input == '0')
        return std::nullopt;

    auto start = consumeNumber(input);

    // The format is valid iff there is a "." or a ")" immediately after the digits, and nothing afterwards.
    if (WTF::skipExactly(input, '.') || WTF::skipExactly(input, ')')) {
        if (input.atEnd())
            return { { { CSS::Keyword::Decimal { } }, start, true } };

        skipToEnd(input);
    }

    skipToEnd(input);
    return std::nullopt;
}

template<typename Character>
inline std::optional<TextList> consumeTextList(StringParsingBuffer<Character>& input)
{
    if (auto result = tryConsumeUnorderedDiscTextList(input))
        return result;

    if (auto result = tryConsumeUnorderedDashTextList(input))
        return result;

    if (auto result = tryConsumeOrderedDecimalTextList(input))
        return result;

    return std::nullopt;
}

static AtomString inlineStyleForListStyleType(const StyledElement& element, Style::ListStyleType styleType)
{
    CheckedPtr renderer = element.renderer();
    if (!renderer) {
        ASSERT_NOT_REACHED();
        return WTF::nullAtom();
    }

    CheckedRef style = renderer->style();
    auto& pool = CSSValuePool::singleton();

    Ref value = Style::createCSSValue(pool, style, styleType);

    RefPtr inlineStyle = MutableStyleProperties::create();
    if (RefPtr existingInlineStyle = element.inlineStyle())
        inlineStyle = existingInlineStyle->mutableCopy();

    inlineStyle->setProperty(CSSPropertyListStyleType, WTFMove(value));

    return inlineStyle->asTextAtom(CSS::defaultSerializationContext());
}

static AtomString classNameForSmartList(const TextList& textList)
{
    if (textList.ordered) {
        ASSERT(textList.styleType.isDecimal());
        return "Apple-decimal-list"_s;
    }

    if (textList.styleType.isDisc())
        return "Apple-disc-list"_s;

    ASSERT(textList.styleType.isString());
    return "Apple-dash-list"_s;
}

static AtomString startingOrdinalForList(const StyledElement& element, const TextList& textList)
{
    if (!textList.ordered)
        return WTF::nullAtom();

    ASSERT(textList.styleType.isDecimal());
    ASSERT(textList.startingItemNumber > 0);

    // This is either a newly created list, or an existing list that was just appended to.
    // In the case of the latter, the existing list's ordering takes precedent over any new elements.
    if (element.hasAttributeWithoutSynchronization(HTMLNames::startAttr))
        return WTF::nullAtom();

    return AtomString::number(textList.startingItemNumber);
}

// MARK: Entry points

std::optional<TextList> parseTextList(StringView input)
{
    // The input is parsed to a TextList using these rules:
    //
    //  <U+002A | U+2022>EOF                        |= <U+2022>          (unordered, disc)
    //  <U+2010>EOF                                 |= <U+2014  >        (unordered, dash)
    //  <ordinal><U+002E | U+0029>EOF , ordinal > 0 |= <ordinal><U+002E> (ordered, start=ordinal)
    //  otherwise                                   |= invalid

    return WTF::readCharactersForParsing(input, [](auto buffer) -> std::optional<TextList> {
        return consumeTextList(buffer);
    });
}

Vector<std::pair<const QualifiedName&, AtomString>> nodeAttributesForSmartList(const StyledElement& element, const TextList& list)
{
    Vector<std::pair<const QualifiedName&, AtomString>> result;

    if (auto start = startingOrdinalForList(element, list); !start.isNull())
        result.append({ HTMLNames::startAttr, start });

    if (auto style = inlineStyleForListStyleType(element, list.styleType); !style.isNull())
        result.append({ HTMLNames::styleAttr, style });

    if (auto className = classNameForSmartList(list); !className.isNull())
        result.append({ HTMLNames::classAttr, className });

    return result;
}

bool selectionAllowsSmartLists(const String& text, const VisibleSelection& selection)
{
    RefPtr document = selection.document();
    if (!document)
        return false;

    if (!document->protectedEditor()->isSmartListsEnabled())
        return false;

    if (text != " "_s) {
        // Smart Lists can only be "activated" by a space character.
        return false;
    }

    if (!selection.isCaret()) {
        // Smart Lists can only be "activated" if the selection does not contain any content.
        return false;
    }

    if (enclosingList(selection.base().protectedAnchorNode().get())) {
        // Smart Lists can not be "activated" if the selection is already within a list.
        return false;
    }

    return true;
}

} // namespace WebCore