File: TextBreakIterator.h

package info (click to toggle)
webkit2gtk 2.48.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 429,620 kB
  • sloc: cpp: 3,696,936; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,276; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (389 lines) | stat: -rw-r--r-- 13,160 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (C) 2006 Lars Knoll <lars@trolltech.com>
 * Copyright (C) 2007-2023 Apple Inc. All rights reserved.
 *
 * 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.
 *
 */

#pragma once

#include <mutex>
#include <optional>
#include <variant>
#include <wtf/NeverDestroyed.h>
#include <wtf/text/StringView.h>
#include <wtf/text/icu/TextBreakIteratorICU.h>

#if PLATFORM(COCOA)
#include <wtf/text/cf/TextBreakIteratorCF.h>
#else
#include <wtf/text/NullTextBreakIterator.h>
#endif

namespace WTF {

#if PLATFORM(COCOA)
typedef TextBreakIteratorCF TextBreakIteratorPlatform;
#else
typedef NullTextBreakIterator TextBreakIteratorPlatform;
#endif

class TextBreakIteratorCache;

class TextBreakIterator {
    WTF_MAKE_FAST_ALLOCATED;
public:
    struct LineMode {
        using Behavior = TextBreakIteratorICU::LineMode::Behavior;
        Behavior behavior;
        friend bool operator==(LineMode, LineMode) = default;
    };
    struct CaretMode {
        friend bool operator==(CaretMode, CaretMode) = default;
    };
    struct DeleteMode {
        friend bool operator==(DeleteMode, DeleteMode) = default;
    };
    struct CharacterMode {
        friend bool operator==(CharacterMode, CharacterMode) = default;
    };
    using Mode = std::variant<LineMode, CaretMode, DeleteMode, CharacterMode>;

    enum class ContentAnalysis : bool {
        Linguistic,
        Mechanical,
    };

    TextBreakIterator() = delete;
    TextBreakIterator(const TextBreakIterator&) = delete;
    TextBreakIterator(TextBreakIterator&&) = default;
    TextBreakIterator& operator=(const TextBreakIterator&) = delete;
    TextBreakIterator& operator=(TextBreakIterator&&) = default;

    std::optional<unsigned> preceding(unsigned location) const
    {
        return switchOn(m_backing, [&](const auto& iterator) {
            return iterator.preceding(location);
        });
    }

    std::optional<unsigned> following(unsigned location) const
    {
        return switchOn(m_backing, [&](const auto& iterator) {
            return iterator.following(location);
        });
    }

    bool isBoundary(unsigned location) const
    {
        return switchOn(m_backing, [&](const auto& iterator) {
            return iterator.isBoundary(location);
        });
    }

private:
    friend class CachedTextBreakIterator;
    friend class TextBreakIteratorCache;

    using Backing = std::variant<TextBreakIteratorICU, TextBreakIteratorPlatform>;

    static Backing mapModeToBackingIterator(StringView, std::span<const UChar> priorContext, Mode, ContentAnalysis, const AtomString& locale);

    // Use CachedTextBreakIterator instead of constructing one of these directly.
    WTF_EXPORT_PRIVATE TextBreakIterator(StringView, std::span<const UChar> priorContext, Mode, ContentAnalysis, const AtomString& locale);

    void setText(StringView string, std::span<const UChar> priorContext)
    {
        return switchOn(m_backing, [&](auto& iterator) {
            return iterator.setText(string, priorContext);
        });
    }

    Mode mode() const
    {
        return m_mode;
    }

    ContentAnalysis contentAnalysis() const
    {
        return m_contentAnalysis;
    }

    const AtomString& locale() const
    {
        return m_locale;
    }

    Backing m_backing;
    Mode m_mode;
    ContentAnalysis m_contentAnalysis { ContentAnalysis::Mechanical };
    AtomString m_locale;
};

class CachedTextBreakIterator;

class TextBreakIteratorCache {
    WTF_MAKE_FAST_ALLOCATED;
// Use CachedTextBreakIterator instead of dealing with the cache directly.
private:
    friend class LazyNeverDestroyed<TextBreakIteratorCache>;
    friend class CachedTextBreakIterator;

    WTF_EXPORT_PRIVATE static TextBreakIteratorCache& singleton();

    TextBreakIteratorCache(const TextBreakIteratorCache&) = delete;
    TextBreakIteratorCache(TextBreakIteratorCache&&) = delete;
    TextBreakIteratorCache& operator=(const TextBreakIteratorCache&) = delete;
    TextBreakIteratorCache& operator=(TextBreakIteratorCache&&) = delete;

    TextBreakIterator take(StringView string, std::span<const UChar> priorContext, TextBreakIterator::Mode mode, TextBreakIterator::ContentAnalysis contentAnalysis, const AtomString& locale)
    {
        ASSERT(isMainThread());
        auto iter = std::find_if(m_unused.begin(), m_unused.end(), [&](TextBreakIterator& candidate) {
            return candidate.mode() == mode && candidate.contentAnalysis() == contentAnalysis && candidate.locale() == locale;
        });
        if (iter == m_unused.end())
            return TextBreakIterator(string, priorContext, mode, contentAnalysis, locale);
        auto result = WTFMove(*iter);
        m_unused.remove(iter - m_unused.begin());
        result.setText(string, priorContext);
        return result;
    }

    void put(TextBreakIterator&& iterator)
    {
        ASSERT(isMainThread());
        m_unused.append(WTFMove(iterator));
        if (m_unused.size() > capacity)
            m_unused.remove(0);
    }

    TextBreakIteratorCache() = default;

    static constexpr int capacity = 2;
    // FIXME: Break this up into different Vectors per mode.
    Vector<TextBreakIterator, capacity> m_unused;
};

// RAII for TextBreakIterator and TextBreakIteratorCache.
class CachedTextBreakIterator {
    WTF_MAKE_FAST_ALLOCATED;
public:
    CachedTextBreakIterator(StringView string, std::span<const UChar> priorContext, TextBreakIterator::Mode mode, const AtomString& locale, TextBreakIterator::ContentAnalysis contentAnalysis = TextBreakIterator::ContentAnalysis::Mechanical)
        : m_backing(isMainThread() ? TextBreakIteratorCache::singleton().take(string, priorContext, mode, contentAnalysis, locale) : TextBreakIterator(string, priorContext, mode, contentAnalysis, locale))
    {
    }

    ~CachedTextBreakIterator()
    {
        if (m_backing && isMainThread())
            TextBreakIteratorCache::singleton().put(WTFMove(*m_backing));
    }

    CachedTextBreakIterator() = delete;
    CachedTextBreakIterator(const CachedTextBreakIterator&) = delete;
    CachedTextBreakIterator(CachedTextBreakIterator&& other)
        : m_backing(std::exchange(other.m_backing, { }))
    {
        other.m_backing = std::nullopt;
    }
    CachedTextBreakIterator& operator=(const CachedTextBreakIterator&) = delete;
    CachedTextBreakIterator& operator=(CachedTextBreakIterator&& other)
    {
        m_backing = std::exchange(other.m_backing, { });
        return *this;
    }

    std::optional<unsigned> preceding(unsigned location) const
    {
        return m_backing->preceding(location);
    }

    std::optional<unsigned> following(unsigned location) const
    {
        return m_backing->following(location);
    }

    bool isBoundary(unsigned location) const
    {
        return m_backing->isBoundary(location);
    }

private:
    std::optional<TextBreakIterator> m_backing;
};

WTF_EXPORT_PRIVATE UBreakIterator* wordBreakIterator(StringView);
WTF_EXPORT_PRIVATE UBreakIterator* sentenceBreakIterator(StringView);

WTF_EXPORT_PRIVATE bool isWordTextBreak(UBreakIterator*);

class CachedLineBreakIteratorFactory {
    WTF_MAKE_FAST_ALLOCATED;
public:
    class PriorContext {
    public:
        static constexpr size_t Length = 2;

        PriorContext()
        {
            reset();
        }

        UChar lastCharacter() const
        {
            static_assert(Length >= 1);
            return m_priorContext[m_priorContext.size() - 1];
        }

        UChar secondToLastCharacter() const
        {
            static_assert(Length >= 2);
            return m_priorContext[m_priorContext.size() - 2];
        }

        void set(std::array<UChar, Length>&& newPriorContext)
        {
            m_priorContext = WTFMove(newPriorContext);
        }

        void update(UChar last)
        {
            for (size_t i = 0; i < m_priorContext.size() - 1; ++i)
                m_priorContext[i] = m_priorContext[i + 1];
            m_priorContext[m_priorContext.size() - 1] = last;
        }

        void reset()
        {
            std::fill(std::begin(m_priorContext), std::end(m_priorContext), 0);
        }

        unsigned length() const
        {
            unsigned result = 0;
            for (auto iterator = std::rbegin(m_priorContext); iterator != std::rend(m_priorContext) && *iterator; ++iterator)
                ++result;
            return result;
        }

        std::span<const UChar> characters() const
        {
            return std::span<const UChar>(m_priorContext).last(length());
        }

        friend bool operator==(const PriorContext&, const PriorContext&) = default;

    private:
        std::array<UChar, Length> m_priorContext;
    };

    CachedLineBreakIteratorFactory() = default;

    explicit CachedLineBreakIteratorFactory(StringView stringView, const AtomString& locale = AtomString(), TextBreakIterator::LineMode::Behavior mode = TextBreakIterator::LineMode::Behavior::Default, TextBreakIterator::ContentAnalysis contentAnalysis = TextBreakIterator::ContentAnalysis::Mechanical)
        : m_stringView(stringView)
        , m_locale(locale)
        , m_mode(mode)
        , m_contentAnalysis(contentAnalysis)
    {
    }

    StringView stringView() const { return m_stringView; }
    TextBreakIterator::LineMode::Behavior mode() const { return m_mode; }
    TextBreakIterator::ContentAnalysis contentAnalysis() const { return m_contentAnalysis; }

    CachedTextBreakIterator& get()
    {
        auto priorContext = m_priorContext.characters();
        if (!m_iterator) {
            m_iterator = CachedTextBreakIterator(m_stringView, priorContext, WTF::TextBreakIterator::LineMode { m_mode }, m_locale, m_contentAnalysis);
            m_cachedPriorContext = priorContext.data();
        } else if (priorContext.data() != m_cachedPriorContext) {
            resetStringAndReleaseIterator(m_stringView, m_locale, m_mode, m_contentAnalysis);
            return get();
        }
        return *m_iterator;
    }

    void resetStringAndReleaseIterator(StringView stringView, const AtomString& locale, TextBreakIterator::LineMode::Behavior mode, TextBreakIterator::ContentAnalysis contentAnalysis = TextBreakIterator::ContentAnalysis::Mechanical)
    {
        m_stringView = stringView;
        m_locale = locale;
        m_iterator = std::nullopt;
        m_cachedPriorContext = nullptr;
        m_mode = mode;
        m_contentAnalysis = contentAnalysis;
    }

    const PriorContext& priorContext() const
    {
        return m_priorContext;
    }

    PriorContext& priorContext()
    {
        return m_priorContext;
    }

private:
    StringView m_stringView;
    AtomString m_locale;
    std::optional<CachedTextBreakIterator> m_iterator;
    const UChar* m_cachedPriorContext { nullptr };
    TextBreakIterator::LineMode::Behavior m_mode { TextBreakIterator::LineMode::Behavior::Default };
    TextBreakIterator::ContentAnalysis m_contentAnalysis { TextBreakIterator::ContentAnalysis::Mechanical };
    PriorContext m_priorContext;
};

// Iterates over "extended grapheme clusters", as defined in UAX #29.
// Note that platform implementations may be less sophisticated - e.g. ICU prior to
// version 4.0 only supports "legacy grapheme clusters".
// Use this for general text processing, e.g. string truncation.

class NonSharedCharacterBreakIterator {
    WTF_MAKE_FAST_ALLOCATED;
    WTF_MAKE_NONCOPYABLE(NonSharedCharacterBreakIterator);
public:
    WTF_EXPORT_PRIVATE NonSharedCharacterBreakIterator(StringView);
    WTF_EXPORT_PRIVATE ~NonSharedCharacterBreakIterator();

    NonSharedCharacterBreakIterator(NonSharedCharacterBreakIterator&&);

    operator UBreakIterator*() const { return m_iterator; }

private:
    UBreakIterator* m_iterator;
};

// Counts the number of grapheme clusters. A surrogate pair or a sequence
// of a non-combining character and following combining characters is
// counted as 1 grapheme cluster.
WTF_EXPORT_PRIVATE unsigned numGraphemeClusters(StringView);

// Returns the number of code units that create the specified number of
// grapheme clusters. If there are fewer clusters in the string than specified,
// the length of the string is returned.
WTF_EXPORT_PRIVATE unsigned numCodeUnitsInGraphemeClusters(StringView, unsigned);

}

using WTF::CachedTextBreakIterator;
using WTF::CachedLineBreakIteratorFactory;
using WTF::NonSharedCharacterBreakIterator;
using WTF::TextBreakIterator;
using WTF::TextBreakIteratorCache;
using WTF::isWordTextBreak;