File: SVGTextMetricsBuilder.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 (292 lines) | stat: -rw-r--r-- 12,666 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
/*
 * Copyright (C) Research In Motion Limited 2010-2012. 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.
 */

#include "config.h"
#include "SVGTextMetricsBuilder.h"

#include "ComplexTextController.h"
#include "FontCascadeCache.h"
#include "RenderChildIterator.h"
#include "RenderSVGInline.h"
#include "RenderSVGInlineText.h"
#include "RenderSVGText.h"
#include "RenderStyleInlines.h"
#include "WidthIterator.h"
#include <wtf/WeakPtr.h>

namespace WebCore {

SVGTextMetricsBuilder::SVGTextMetricsBuilder()
    : m_run(StringView())
    , m_textPosition(0)
    , m_isComplexText(false)
    , m_totalWidth(0)
{
}

inline bool SVGTextMetricsBuilder::currentCharacterStartsSurrogatePair() const
{
    return U16_IS_LEAD(m_run[m_textPosition]) && (m_textPosition + 1) < m_run.length() && U16_IS_TRAIL(m_run[m_textPosition + 1]);
}

template<typename Iterator>
bool SVGTextMetricsBuilder::advance(Iterator& iterator)
{
    m_textPosition += m_currentMetrics.length();
    if (m_textPosition >= m_run.length())
        return false;

    advanceIterator(iterator);
    return m_currentMetrics.length() > 0;
}

void SVGTextMetricsBuilder::advanceIterator(WidthIterator& simpleWidthIterator)
{
    GlyphBuffer glyphBuffer;
    auto before = simpleWidthIterator.currentCharacterIndex();
    simpleWidthIterator.advance(m_textPosition + 1, glyphBuffer);
    auto after = simpleWidthIterator.currentCharacterIndex();
    if (before == after) {
        m_currentMetrics = SVGTextMetrics();
        return;
    }

    float currentWidth = simpleWidthIterator.runWidthSoFar() - m_totalWidth;
    m_totalWidth = simpleWidthIterator.runWidthSoFar();

    m_currentMetrics = SVGTextMetrics(*m_text, after - before, currentWidth);
}

void SVGTextMetricsBuilder::advanceIterator(ComplexTextController& complexTextController)
{
    unsigned metricsLength = currentCharacterStartsSurrogatePair() ? 2 : 1;
    float beforeWidth = 0;
    float afterWidth = 0;

    complexTextController.advance(m_textPosition, nullptr);
    beforeWidth = complexTextController.runWidthSoFar();

    complexTextController.advance(m_textPosition + metricsLength, nullptr);
    afterWidth = complexTextController.runWidthSoFar();

    m_currentMetrics = SVGTextMetrics(*m_text, metricsLength, afterWidth - beforeWidth);
    m_complexStartToCurrentMetrics = SVGTextMetrics(*m_text, m_textPosition + metricsLength, afterWidth);

    ASSERT(m_currentMetrics.length() == metricsLength);

    // Frequent case for Arabic text: when measuring a single character the arabic isolated form is taken
    // when rendering the glyph "in context" (with it's surrounding characters) it changes due to shaping.
    // So whenever currentWidth != currentMetrics.width(), we are processing a text run whose length is
    // not equal to the sum of the individual lengths of the glyphs, when measuring them isolated.
    float currentWidth = m_complexStartToCurrentMetrics.width() - m_totalWidth;
    if (currentWidth != m_currentMetrics.width())
        m_currentMetrics.setWidth(currentWidth);

    m_totalWidth = m_complexStartToCurrentMetrics.width();
}

static inline bool shouldUseComplexTextController(FontCascade::CodePath codePathToUse, const FontCascade& scaledFont)
{
#if PLATFORM(GTK) || PLATFORM(WPE)
    if (codePathToUse != FontCascade::CodePath::Complex && scaledFont.shouldUseComplexTextControllerForSimpleText())
        return true;
#else
    UNUSED_PARAM(scaledFont);
#endif
    return codePathToUse == FontCascade::CodePath::Complex;
}

void SVGTextMetricsBuilder::initializeMeasurementWithTextRenderer(RenderSVGInlineText& text)
{
    m_text = text;
    m_textPosition = 0;
    m_currentMetrics = SVGTextMetrics();
    m_complexStartToCurrentMetrics = SVGTextMetrics();
    m_totalWidth = 0;

    const FontCascade& scaledFont = text.scaledFont();
    m_run = SVGTextMetrics::constructTextRun(text);
    m_isComplexText = shouldUseComplexTextController(scaledFont.codePath(m_run), scaledFont);

    if (m_isComplexText)
        FontCascadeCache::forCurrentThread().invalidate();

    m_canUseSimplifiedTextMeasuring = false;
    if (!m_isComplexText) {
        if (auto cachedValue = text.canUseSimplifiedTextMeasuring())
            m_canUseSimplifiedTextMeasuring = cachedValue.value();
        else {
            // Currently SVG implementation does not support first-line, so we always pass nullptr for firstLineStyle.
            // When supporting first-line, we also need to update firstLineStyle's FontCascade to be aligned with scaledFont in RenderSVGInlineText.
            m_canUseSimplifiedTextMeasuring = Layout::TextUtil::canUseSimplifiedTextMeasuring(m_run.text(), scaledFont, text.style().collapseWhiteSpace(), nullptr);
            text.setCanUseSimplifiedTextMeasuring(m_canUseSimplifiedTextMeasuring);
        }
    }
}

struct MeasureTextData {
    MeasureTextData(SVGCharacterDataMap* characterDataMap)
        : allCharactersMap(characterDataMap)
    {
    }

    SVGCharacterDataMap* allCharactersMap;
    bool processRenderer { false };
};

std::tuple<unsigned, char16_t> SVGTextMetricsBuilder::measureTextRenderer(RenderSVGInlineText& text, const MeasureTextData& data, std::tuple<unsigned, char16_t> state)
{
    SVGTextLayoutAttributes* attributes = text.layoutAttributes();
    ASSERT(attributes);
    Vector<SVGTextMetrics>& textMetricsValues = attributes->textMetricsValues();
    if (data.processRenderer) {
        if (data.allCharactersMap)
            attributes->clear();
        else
            textMetricsValues.shrink(0);
    }

    initializeMeasurementWithTextRenderer(text);

    auto& scaledFont = text.scaledFont();
    if (m_canUseSimplifiedTextMeasuring && data.processRenderer) {
        // If we are not specifying specific configuration for characters, data.allCharactersMap has only 1 entry for default case.
        // This is extremely common, and that's why we crafted a fast path here.
        // FIXME: For any cases, we are handling one character by one character in SVGTextMetrics. But many texts do not have
        // characterDataMap. We should handle multiple characters in one SVGTextMetrics. This also makes RTL work.
        // FIXME: This function is called even though width information is not changed at all. RenderSVGText / RenderSVGInlineText
        // should track the potential changes to width etc. and invoke this function only when it is actually changed.
        if (data.allCharactersMap && m_run.direction() == TextDirection::LTR && data.allCharactersMap->size() == 1) {
            constexpr unsigned defaultPosition = 1;
            ASSERT(data.allCharactersMap->contains(defaultPosition)); // "1" is the default value and always exists.
            auto characterData = data.allCharactersMap->get(defaultPosition);

            auto [valueListPosition, lastCharacter] = state;
            bool preserveWhiteSpace = text.style().whiteSpaceCollapse() == WhiteSpaceCollapse::Preserve;
            auto view = m_run.text();
            unsigned length = view.length();
            unsigned skippedCharacters = 0;
            float scalingFactor = text.scalingFactor();
            ASSERT(scalingFactor);
            float scaledHeight = scaledFont.metricsOfPrimaryFont().height() / scalingFactor;

            // m_canUseSimplifiedTextMeasuring ensures that this does not include surrogate pairs. So we do not need to consider about them.
            for (unsigned i = 0; i < length; ++i) {
                char16_t currentCharacter = view.characterAt(i);
                ASSERT(!U16_IS_LEAD(currentCharacter));
                if (currentCharacter == space && !preserveWhiteSpace && (!lastCharacter || lastCharacter == space)) {
                    if (data.processRenderer)
                        textMetricsValues.append(SVGTextMetrics(SVGTextMetrics::SkippedSpaceMetrics));
                    ++skippedCharacters;
                    continue;
                }

                if ((valueListPosition + i - skippedCharacters + 1) == defaultPosition)
                    attributes->characterDataMap().set(i + 1, characterData);

                float width = scaledFont.widthForTextUsingSimplifiedMeasuring(view.substring(i, 1), TextDirection::LTR);
                float scaledWidth = width / scalingFactor;
                textMetricsValues.append(SVGTextMetrics(1, scaledWidth, scaledHeight));
                lastCharacter = currentCharacter;
            }

            return std::tuple { valueListPosition + length - skippedCharacters, lastCharacter };
        }
    }

    if (m_isComplexText) {
        ComplexTextController iterator(scaledFont, m_run, true);
        return measureTextRendererWithIterator(iterator, text, data, state);
    }

    WidthIterator iterator(scaledFont, m_run);
    return measureTextRendererWithIterator(iterator, text, data, state);
}

template<typename Iterator>
std::tuple<unsigned, char16_t> SVGTextMetricsBuilder::measureTextRendererWithIterator(Iterator& iterator, RenderSVGInlineText& text, const MeasureTextData& data, std::tuple<unsigned, char16_t> state)
{
    auto [valueListPosition, lastCharacter] = state;
    bool preserveWhiteSpace = text.style().whiteSpaceCollapse() == WhiteSpaceCollapse::Preserve;
    auto* attributes = text.layoutAttributes();
    auto& textMetricsValues = attributes->textMetricsValues();
    int surrogatePairCharacters = 0;
    unsigned skippedCharacters = 0;
    while (advance(iterator)) {
        char16_t currentCharacter = m_run[m_textPosition];
        if (currentCharacter == space && !preserveWhiteSpace && (!lastCharacter || lastCharacter == space)) {
            if (data.processRenderer)
                textMetricsValues.append(SVGTextMetrics(SVGTextMetrics::SkippedSpaceMetrics));
            skippedCharacters += m_currentMetrics.length();
            continue;
        }

        if (data.processRenderer) {
            if (data.allCharactersMap) {
                auto it = data.allCharactersMap->find(valueListPosition + m_textPosition - skippedCharacters - surrogatePairCharacters + 1);
                if (it != data.allCharactersMap->end())
                    attributes->characterDataMap().set(m_textPosition + 1, it->value);
            }
            textMetricsValues.append(m_currentMetrics);
        }

        if (data.allCharactersMap && currentCharacterStartsSurrogatePair())
            surrogatePairCharacters++;

        lastCharacter = currentCharacter;
    }

    return std::tuple { valueListPosition + m_textPosition - skippedCharacters, lastCharacter };
}

void SVGTextMetricsBuilder::walkTree(RenderElement& start, RenderSVGInlineText* stopAtLeaf, MeasureTextData& data)
{
    unsigned valueListPosition = 0;
    char16_t lastCharacter = 0;
    CheckedPtr child = start.firstChild();
    while (child) {
        if (auto* text = dynamicDowncast<RenderSVGInlineText>(*child)) {
            data.processRenderer = !stopAtLeaf || stopAtLeaf == text;
            std::tie(valueListPosition, lastCharacter) = measureTextRenderer(*text, data, std::tuple { valueListPosition, lastCharacter });
            if (stopAtLeaf && stopAtLeaf == text)
                return;
        } else if (auto* renderer = dynamicDowncast<RenderSVGInline>(*child)) {
            // Visit children of text content elements.
            if (auto* inlineChild = renderer->firstChild()) {
                child = inlineChild;
                continue;
            }
        }
        child = child->nextInPreOrderAfterChildren(&start);
    }
}

void SVGTextMetricsBuilder::measureTextRenderer(RenderSVGText& textRoot, RenderSVGInlineText* stopAtLeaf)
{
    MeasureTextData data(nullptr);
    walkTree(textRoot, stopAtLeaf, data);
}

void SVGTextMetricsBuilder::buildMetricsAndLayoutAttributes(RenderSVGText& textRoot, RenderSVGInlineText* stopAtLeaf, SVGCharacterDataMap& allCharactersMap)
{
    MeasureTextData data(&allCharactersMap);
    walkTree(textRoot, stopAtLeaf, data);
}

}