1 | /* |
2 | * Copyright (C) 2017 Apple Inc. All rights reserved. |
3 | * Copyright (C) 2017 Igalia S.L. |
4 | * |
5 | * Redistribution and use in source and binary forms, with or without |
6 | * modification, are permitted provided that the following conditions |
7 | * are met: |
8 | * 1. Redistributions of source code must retain the above copyright |
9 | * notice, this list of conditions and the following disclaimer. |
10 | * 2. Redistributions in binary form must reproduce the above copyright |
11 | * notice, this list of conditions and the following disclaimer in the |
12 | * documentation and/or other materials provided with the distribution. |
13 | * |
14 | * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY |
15 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
16 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
17 | * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY |
18 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
19 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
20 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON |
21 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
22 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
23 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
24 | */ |
25 | |
26 | #include "config.h" |
27 | #include "ComplexTextController.h" |
28 | |
29 | #include "CairoUtilities.h" |
30 | #include "FontCascade.h" |
31 | #include "HbUniquePtr.h" |
32 | #include "SurrogatePairAwareTextIterator.h" |
33 | #include <hb-ft.h> |
34 | #include <hb-icu.h> |
35 | #include <hb-ot.h> |
36 | |
37 | #if ENABLE(VARIATION_FONTS) |
38 | #include FT_MULTIPLE_MASTERS_H |
39 | #endif |
40 | |
41 | namespace WebCore { |
42 | |
43 | static inline float harfBuzzPositionToFloat(hb_position_t value) |
44 | { |
45 | return static_cast<float>(value) / (1 << 16); |
46 | } |
47 | |
48 | static inline hb_position_t floatToHarfBuzzPosition(float value) |
49 | { |
50 | return static_cast<hb_position_t>(value * (1 << 16)); |
51 | } |
52 | |
53 | static inline hb_position_t doubleToHarfBuzzPosition(double value) |
54 | { |
55 | return static_cast<hb_position_t>(value * (1 << 16)); |
56 | } |
57 | |
58 | static hb_font_funcs_t* harfBuzzFontFunctions() |
59 | { |
60 | static hb_font_funcs_t* fontFunctions = nullptr; |
61 | |
62 | // We don't set callback functions which we can't support. |
63 | // Harfbuzz will use the fallback implementation if they aren't set. |
64 | if (!fontFunctions) { |
65 | fontFunctions = hb_font_funcs_create(); |
66 | #if HB_VERSION_ATLEAST(1, 2, 3) |
67 | hb_font_funcs_set_nominal_glyph_func(fontFunctions, [](hb_font_t*, void* context, hb_codepoint_t unicode, hb_codepoint_t* glyph, void*) -> hb_bool_t { |
68 | auto& font = *static_cast<Font*>(context); |
69 | *glyph = font.glyphForCharacter(unicode); |
70 | return !!*glyph; |
71 | }, nullptr, nullptr); |
72 | |
73 | hb_font_funcs_set_variation_glyph_func(fontFunctions, [](hb_font_t*, void* context, hb_codepoint_t unicode, hb_codepoint_t variation, hb_codepoint_t* glyph, void*) -> hb_bool_t { |
74 | auto& font = *static_cast<Font*>(context); |
75 | auto* scaledFont = font.platformData().scaledFont(); |
76 | ASSERT(scaledFont); |
77 | |
78 | CairoFtFaceLocker cairoFtFaceLocker(scaledFont); |
79 | if (FT_Face ftFace = cairoFtFaceLocker.ftFace()) { |
80 | *glyph = FT_Face_GetCharVariantIndex(ftFace, unicode, variation); |
81 | return !!*glyph; |
82 | } |
83 | return false; |
84 | }, nullptr, nullptr); |
85 | #else |
86 | hb_font_funcs_set_glyph_func(fontFunctions, [](hb_font_t*, void* context, hb_codepoint_t unicode, hb_codepoint_t, hb_codepoint_t* glyph, void*) -> hb_bool_t { |
87 | auto& font = *static_cast<Font*>(context); |
88 | *glyph = font.glyphForCharacter(unicode); |
89 | return !!*glyph; |
90 | }, nullptr, nullptr); |
91 | #endif |
92 | hb_font_funcs_set_glyph_h_advance_func(fontFunctions, [](hb_font_t*, void* context, hb_codepoint_t point, void*) -> hb_bool_t { |
93 | auto& font = *static_cast<Font*>(context); |
94 | auto* scaledFont = font.platformData().scaledFont(); |
95 | ASSERT(scaledFont); |
96 | |
97 | cairo_text_extents_t glyphExtents; |
98 | cairo_glyph_t glyph = { point, 0, 0 }; |
99 | cairo_scaled_font_glyph_extents(scaledFont, &glyph, 1, &glyphExtents); |
100 | |
101 | bool hasVerticalGlyphs = glyphExtents.y_advance; |
102 | return doubleToHarfBuzzPosition(hasVerticalGlyphs ? -glyphExtents.y_advance : glyphExtents.x_advance); |
103 | }, nullptr, nullptr); |
104 | |
105 | hb_font_funcs_set_glyph_h_origin_func(fontFunctions, [](hb_font_t*, void*, hb_codepoint_t, hb_position_t*, hb_position_t*, void*) -> hb_bool_t { |
106 | // Just return true, following the way that Harfbuzz-FreeType implementation does. |
107 | return true; |
108 | }, nullptr, nullptr); |
109 | |
110 | hb_font_funcs_set_glyph_extents_func(fontFunctions, [](hb_font_t*, void* context, hb_codepoint_t point, hb_glyph_extents_t* extents, void*) -> hb_bool_t { |
111 | auto& font = *static_cast<Font*>(context); |
112 | auto* scaledFont = font.platformData().scaledFont(); |
113 | ASSERT(scaledFont); |
114 | |
115 | cairo_text_extents_t glyphExtents; |
116 | cairo_glyph_t glyph = { point, 0, 0 }; |
117 | cairo_scaled_font_glyph_extents(scaledFont, &glyph, 1, &glyphExtents); |
118 | |
119 | bool hasVerticalGlyphs = glyphExtents.y_advance; |
120 | extents->x_bearing = doubleToHarfBuzzPosition(glyphExtents.x_bearing); |
121 | extents->y_bearing = doubleToHarfBuzzPosition(hasVerticalGlyphs ? -glyphExtents.y_bearing : glyphExtents.y_bearing); |
122 | extents->width = doubleToHarfBuzzPosition(hasVerticalGlyphs ? -glyphExtents.height : glyphExtents.width); |
123 | extents->height = doubleToHarfBuzzPosition(hasVerticalGlyphs ? glyphExtents.width : glyphExtents.height); |
124 | return true; |
125 | }, nullptr, nullptr); |
126 | |
127 | hb_font_funcs_make_immutable(fontFunctions); |
128 | } |
129 | return fontFunctions; |
130 | } |
131 | |
132 | ComplexTextController::ComplexTextRun::ComplexTextRun(hb_buffer_t* buffer, const Font& font, const UChar* characters, unsigned stringLocation, unsigned stringLength, unsigned indexBegin, unsigned indexEnd) |
133 | : m_initialAdvance(0, 0) |
134 | , m_font(font) |
135 | , m_characters(characters) |
136 | , m_stringLength(stringLength) |
137 | , m_indexBegin(indexBegin) |
138 | , m_indexEnd(indexEnd) |
139 | , m_glyphCount(hb_buffer_get_length(buffer)) |
140 | , m_stringLocation(stringLocation) |
141 | , m_isLTR(HB_DIRECTION_IS_FORWARD(hb_buffer_get_direction(buffer))) |
142 | { |
143 | if (!m_glyphCount) |
144 | return; |
145 | |
146 | m_glyphs.grow(m_glyphCount); |
147 | m_baseAdvances.grow(m_glyphCount); |
148 | m_glyphOrigins.grow(m_glyphCount); |
149 | m_coreTextIndices.grow(m_glyphCount); |
150 | |
151 | hb_glyph_info_t* glyphInfos = hb_buffer_get_glyph_infos(buffer, nullptr); |
152 | hb_glyph_position_t* glyphPositions = hb_buffer_get_glyph_positions(buffer, nullptr); |
153 | |
154 | // HarfBuzz returns the shaping result in visual order. We don't need to flip for RTL. |
155 | for (unsigned i = 0; i < m_glyphCount; ++i) { |
156 | m_coreTextIndices[i] = glyphInfos[i].cluster; |
157 | |
158 | uint16_t glyph = glyphInfos[i].codepoint; |
159 | if (m_font.isZeroWidthSpaceGlyph(glyph) || !m_font.platformData().size()) { |
160 | m_glyphs[i] = glyph; |
161 | m_baseAdvances[i] = { }; |
162 | m_glyphOrigins[i] = { }; |
163 | continue; |
164 | } |
165 | |
166 | float offsetX = harfBuzzPositionToFloat(glyphPositions[i].x_offset); |
167 | float offsetY = -harfBuzzPositionToFloat(glyphPositions[i].y_offset); |
168 | float advanceX = harfBuzzPositionToFloat(glyphPositions[i].x_advance); |
169 | float advanceY = harfBuzzPositionToFloat(glyphPositions[i].y_advance); |
170 | |
171 | if (!i) |
172 | m_initialAdvance = { offsetX, -offsetY }; |
173 | |
174 | m_glyphs[i] = glyph; |
175 | m_baseAdvances[i] = { advanceX, advanceY }; |
176 | m_glyphOrigins[i] = { offsetX, offsetY }; |
177 | } |
178 | } |
179 | |
180 | static const hb_tag_t s_vertTag = HB_TAG('v', 'e', 'r', 't'); |
181 | static const hb_tag_t s_vrt2Tag = HB_TAG('v', 'r', 't', '2'); |
182 | static const hb_tag_t s_kernTag = HB_TAG('k', 'e', 'r', 'n'); |
183 | static const unsigned s_hbEnd = static_cast<unsigned>(-1); |
184 | |
185 | static Vector<hb_feature_t, 4> fontFeatures(const FontCascade& font, FontOrientation orientation) |
186 | { |
187 | Vector<hb_feature_t, 4> features; |
188 | |
189 | if (orientation == FontOrientation::Vertical) { |
190 | features.append({ s_vertTag, 1, 0, s_hbEnd }); |
191 | features.append({ s_vrt2Tag, 1, 0, s_hbEnd }); |
192 | } |
193 | |
194 | hb_feature_t kerning = { s_kernTag, 0, 0, s_hbEnd }; |
195 | if (font.enableKerning()) |
196 | kerning.value = 1; |
197 | features.append(WTFMove(kerning)); |
198 | |
199 | for (auto& feature : font.fontDescription().featureSettings()) { |
200 | auto& tag = feature.tag(); |
201 | features.append({ HB_TAG(tag[0], tag[1], tag[2], tag[3]), static_cast<uint32_t>(feature.value()), 0, s_hbEnd }); |
202 | } |
203 | |
204 | return features; |
205 | } |
206 | |
207 | static Optional<UScriptCode> characterScript(UChar32 character) |
208 | { |
209 | UErrorCode errorCode = U_ZERO_ERROR; |
210 | UScriptCode script = uscript_getScript(character, &errorCode); |
211 | if (U_FAILURE(errorCode)) |
212 | return WTF::nullopt; |
213 | return script; |
214 | } |
215 | |
216 | struct HBRun { |
217 | unsigned startIndex; |
218 | unsigned endIndex; |
219 | UScriptCode script; |
220 | }; |
221 | |
222 | static Optional<HBRun> findNextRun(const UChar* characters, unsigned length, unsigned offset) |
223 | { |
224 | SurrogatePairAwareTextIterator textIterator(characters + offset, offset, length, length); |
225 | UChar32 character; |
226 | unsigned clusterLength = 0; |
227 | if (!textIterator.consume(character, clusterLength)) |
228 | return WTF::nullopt; |
229 | |
230 | auto currentScript = characterScript(character); |
231 | if (!currentScript) |
232 | return WTF::nullopt; |
233 | |
234 | unsigned startIndex = offset; |
235 | for (textIterator.advance(clusterLength); textIterator.consume(character, clusterLength); textIterator.advance(clusterLength)) { |
236 | if (FontCascade::treatAsZeroWidthSpace(character)) |
237 | continue; |
238 | |
239 | auto nextScript = characterScript(character); |
240 | if (!nextScript) |
241 | return WTF::nullopt; |
242 | |
243 | // §5.1 Handling Characters with the Common Script Property. |
244 | // Programs must resolve any of the special Script property values, such as Common, |
245 | // based on the context of the surrounding characters. A simple heuristic uses the |
246 | // script of the preceding character, which works well in many cases. |
247 | // http://www.unicode.org/reports/tr24/#Common. |
248 | // |
249 | // FIXME: cover all other cases mentioned in the spec (ie. brackets or quotation marks). |
250 | // https://bugs.webkit.org/show_bug.cgi?id=177003. |
251 | // |
252 | // If next script is inherited or common, keep using the current script. |
253 | if (nextScript == USCRIPT_INHERITED || nextScript == USCRIPT_COMMON) |
254 | continue; |
255 | // If current script is inherited or common, set the next script as current. |
256 | if (currentScript == USCRIPT_INHERITED || currentScript == USCRIPT_COMMON) { |
257 | currentScript = nextScript; |
258 | continue; |
259 | } |
260 | |
261 | if (currentScript != nextScript && !uscript_hasScript(character, currentScript.value())) |
262 | return Optional<HBRun>({ startIndex, textIterator.currentIndex(), currentScript.value() }); |
263 | } |
264 | |
265 | return Optional<HBRun>({ startIndex, textIterator.currentIndex(), currentScript.value() }); |
266 | } |
267 | |
268 | static hb_script_t findScriptForVerticalGlyphSubstitution(hb_face_t* face) |
269 | { |
270 | static const unsigned maxCount = 32; |
271 | |
272 | unsigned scriptCount = maxCount; |
273 | hb_tag_t scriptTags[maxCount]; |
274 | hb_ot_layout_table_get_script_tags(face, HB_OT_TAG_GSUB, 0, &scriptCount, scriptTags); |
275 | for (unsigned scriptIndex = 0; scriptIndex < scriptCount; ++scriptIndex) { |
276 | unsigned languageCount = maxCount; |
277 | hb_tag_t languageTags[maxCount]; |
278 | hb_ot_layout_script_get_language_tags(face, HB_OT_TAG_GSUB, scriptIndex, 0, &languageCount, languageTags); |
279 | for (unsigned languageIndex = 0; languageIndex < languageCount; ++languageIndex) { |
280 | unsigned featureIndex; |
281 | if (hb_ot_layout_language_find_feature(face, HB_OT_TAG_GSUB, scriptIndex, languageIndex, s_vertTag, &featureIndex) |
282 | || hb_ot_layout_language_find_feature(face, HB_OT_TAG_GSUB, scriptIndex, languageIndex, s_vrt2Tag, &featureIndex)) |
283 | return hb_ot_tag_to_script(scriptTags[scriptIndex]); |
284 | } |
285 | } |
286 | return HB_SCRIPT_INVALID; |
287 | } |
288 | |
289 | void ComplexTextController::collectComplexTextRunsForCharacters(const UChar* characters, unsigned length, unsigned stringLocation, const Font* font) |
290 | { |
291 | if (!font) { |
292 | // Create a run of missing glyphs from the primary font. |
293 | m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), characters, stringLocation, length, 0, length, m_run.ltr())); |
294 | return; |
295 | } |
296 | |
297 | Vector<HBRun> runList; |
298 | unsigned offset = 0; |
299 | while (offset < length) { |
300 | auto run = findNextRun(characters, length, offset); |
301 | if (!run) |
302 | break; |
303 | runList.append(run.value()); |
304 | offset = run->endIndex; |
305 | } |
306 | |
307 | size_t runCount = runList.size(); |
308 | if (!runCount) |
309 | return; |
310 | |
311 | const auto& fontPlatformData = font->platformData(); |
312 | auto* scaledFont = fontPlatformData.scaledFont(); |
313 | CairoFtFaceLocker cairoFtFaceLocker(scaledFont); |
314 | FT_Face ftFace = cairoFtFaceLocker.ftFace(); |
315 | if (!ftFace) |
316 | return; |
317 | |
318 | HbUniquePtr<hb_face_t> face(hb_ft_face_create_cached(ftFace)); |
319 | HbUniquePtr<hb_font_t> harfBuzzFont(hb_font_create(face.get())); |
320 | hb_font_set_funcs(harfBuzzFont.get(), harfBuzzFontFunctions(), const_cast<Font*>(font), nullptr); |
321 | const float size = fontPlatformData.size(); |
322 | if (floorf(size) == size) |
323 | hb_font_set_ppem(harfBuzzFont.get(), size, size); |
324 | int scale = floatToHarfBuzzPosition(size); |
325 | hb_font_set_scale(harfBuzzFont.get(), scale, scale); |
326 | |
327 | #if ENABLE(VARIATION_FONTS) |
328 | FT_MM_Var* ftMMVar; |
329 | if (!FT_Get_MM_Var(ftFace, &ftMMVar)) { |
330 | Vector<FT_Fixed, 4> coords; |
331 | coords.resize(ftMMVar->num_axis); |
332 | if (!FT_Get_Var_Design_Coordinates(ftFace, coords.size(), coords.data())) { |
333 | Vector<hb_variation_t, 4> variations(coords.size()); |
334 | for (FT_UInt i = 0; i < ftMMVar->num_axis; ++i) { |
335 | variations[i].tag = ftMMVar->axis[i].tag; |
336 | variations[i].value = coords[i] / 65536.0; |
337 | } |
338 | hb_font_set_variations(harfBuzzFont.get(), variations.data(), variations.size()); |
339 | } |
340 | FT_Done_MM_Var(ftFace->glyph->library, ftMMVar); |
341 | } |
342 | #endif |
343 | |
344 | hb_font_make_immutable(harfBuzzFont.get()); |
345 | |
346 | auto features = fontFeatures(m_font, fontPlatformData.orientation()); |
347 | HbUniquePtr<hb_buffer_t> buffer(hb_buffer_create()); |
348 | if (fontPlatformData.orientation() == FontOrientation::Vertical) |
349 | hb_buffer_set_script(buffer.get(), findScriptForVerticalGlyphSubstitution(face.get())); |
350 | |
351 | for (unsigned i = 0; i < runCount; ++i) { |
352 | auto& run = runList[m_run.rtl() ? runCount - i - 1 : i]; |
353 | |
354 | if (fontPlatformData.orientation() != FontOrientation::Vertical) |
355 | hb_buffer_set_script(buffer.get(), hb_icu_script_to_script(run.script)); |
356 | if (!m_mayUseNaturalWritingDirection || m_run.directionalOverride()) |
357 | hb_buffer_set_direction(buffer.get(), m_run.rtl() ? HB_DIRECTION_RTL : HB_DIRECTION_LTR); |
358 | else { |
359 | // Leaving direction to HarfBuzz to guess is *really* bad, but will do for now. |
360 | hb_buffer_guess_segment_properties(buffer.get()); |
361 | } |
362 | hb_buffer_add_utf16(buffer.get(), reinterpret_cast<const uint16_t*>(characters), length, run.startIndex, run.endIndex - run.startIndex); |
363 | |
364 | hb_shape(harfBuzzFont.get(), buffer.get(), features.isEmpty() ? nullptr : features.data(), features.size()); |
365 | m_complexTextRuns.append(ComplexTextRun::create(buffer.get(), *font, characters, stringLocation, length, run.startIndex, run.endIndex)); |
366 | hb_buffer_reset(buffer.get()); |
367 | } |
368 | } |
369 | |
370 | } // namespace WebCore |
371 | |