2 * Copyright (C) 2017 Apple Inc. All rights reserved.
3 * Copyright (C) 2017 Igalia S.L.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
27 #include "ComplexTextController.h"
29 #include "CairoUtilities.h"
30 #include "FontCascade.h"
31 #include "HbUniquePtr.h"
32 #include "SurrogatePairAwareTextIterator.h"
37 #if ENABLE(VARIATION_FONTS)
38 #include FT_MULTIPLE_MASTERS_H
43 static inline float harfBuzzPositionToFloat(hb_position_t value)
45 return static_cast<float>(value) / (1 << 16);
48 static inline hb_position_t floatToHarfBuzzPosition(float value)
50 return static_cast<hb_position_t>(value * (1 << 16));
53 static inline hb_position_t doubleToHarfBuzzPosition(double value)
55 return static_cast<hb_position_t>(value * (1 << 16));
58 static hb_font_funcs_t* harfBuzzFontFunctions()
60 static hb_font_funcs_t* fontFunctions = nullptr;
62 // We don't set callback functions which we can't support.
63 // Harfbuzz will use the fallback implementation if they aren't set.
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);
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();
78 CairoFtFaceLocker cairoFtFaceLocker(scaledFont);
79 if (FT_Face ftFace = cairoFtFaceLocker.ftFace()) {
80 *glyph = FT_Face_GetCharVariantIndex(ftFace, unicode, variation);
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);
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();
97 cairo_text_extents_t glyphExtents;
98 cairo_glyph_t glyph = { point, 0, 0 };
99 cairo_scaled_font_glyph_extents(scaledFont, &glyph, 1, &glyphExtents);
101 bool hasVerticalGlyphs = glyphExtents.y_advance;
102 return doubleToHarfBuzzPosition(hasVerticalGlyphs ? -glyphExtents.y_advance : glyphExtents.x_advance);
103 }, nullptr, nullptr);
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.
108 }, nullptr, nullptr);
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();
115 cairo_text_extents_t glyphExtents;
116 cairo_glyph_t glyph = { point, 0, 0 };
117 cairo_scaled_font_glyph_extents(scaledFont, &glyph, 1, &glyphExtents);
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);
125 }, nullptr, nullptr);
127 hb_font_funcs_make_immutable(fontFunctions);
129 return fontFunctions;
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)
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)))
146 m_glyphs.grow(m_glyphCount);
147 m_baseAdvances.grow(m_glyphCount);
148 m_glyphOrigins.grow(m_glyphCount);
149 m_coreTextIndices.grow(m_glyphCount);
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);
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;
158 uint16_t glyph = glyphInfos[i].codepoint;
159 if (m_font.isZeroWidthSpaceGlyph(glyph) || !m_font.platformData().size()) {
161 m_baseAdvances[i] = { };
162 m_glyphOrigins[i] = { };
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);
172 m_initialAdvance = { offsetX, -offsetY };
175 m_baseAdvances[i] = { advanceX, advanceY };
176 m_glyphOrigins[i] = { offsetX, offsetY };
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);
185 static Vector<hb_feature_t, 4> fontFeatures(const FontCascade& font, FontOrientation orientation)
187 Vector<hb_feature_t, 4> features;
189 if (orientation == FontOrientation::Vertical) {
190 features.append({ s_vertTag, 1, 0, s_hbEnd });
191 features.append({ s_vrt2Tag, 1, 0, s_hbEnd });
194 hb_feature_t kerning = { s_kernTag, 0, 0, s_hbEnd };
195 if (font.enableKerning())
197 features.append(WTFMove(kerning));
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 });
207 static Optional<UScriptCode> characterScript(UChar32 character)
209 UErrorCode errorCode = U_ZERO_ERROR;
210 UScriptCode script = uscript_getScript(character, &errorCode);
211 if (U_FAILURE(errorCode))
222 static Optional<HBRun> findNextRun(const UChar* characters, unsigned length, unsigned offset)
224 SurrogatePairAwareTextIterator textIterator(characters + offset, offset, length, length);
226 unsigned clusterLength = 0;
227 if (!textIterator.consume(character, clusterLength))
230 auto currentScript = characterScript(character);
234 unsigned startIndex = offset;
235 for (textIterator.advance(clusterLength); textIterator.consume(character, clusterLength); textIterator.advance(clusterLength)) {
236 if (FontCascade::treatAsZeroWidthSpace(character))
239 auto nextScript = characterScript(character);
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.
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.
252 // If next script is inherited or common, keep using the current script.
253 if (nextScript == USCRIPT_INHERITED || nextScript == USCRIPT_COMMON)
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;
261 if (currentScript != nextScript && !uscript_hasScript(character, currentScript.value()))
262 return Optional<HBRun>({ startIndex, textIterator.currentIndex(), currentScript.value() });
265 return Optional<HBRun>({ startIndex, textIterator.currentIndex(), currentScript.value() });
268 static hb_script_t findScriptForVerticalGlyphSubstitution(hb_face_t* face)
270 static const unsigned maxCount = 32;
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]);
286 return HB_SCRIPT_INVALID;
289 void ComplexTextController::collectComplexTextRunsForCharacters(const UChar* characters, unsigned length, unsigned stringLocation, const Font* 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()));
297 Vector<HBRun> runList;
299 while (offset < length) {
300 auto run = findNextRun(characters, length, offset);
303 runList.append(run.value());
304 offset = run->endIndex;
307 size_t runCount = runList.size();
311 const auto& fontPlatformData = font->platformData();
312 auto* scaledFont = fontPlatformData.scaledFont();
313 CairoFtFaceLocker cairoFtFaceLocker(scaledFont);
314 FT_Face ftFace = cairoFtFaceLocker.ftFace();
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);
327 #if ENABLE(VARIATION_FONTS)
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;
338 hb_font_set_variations(harfBuzzFont.get(), variations.data(), variations.size());
340 FT_Done_MM_Var(ftFace->glyph->library, ftMMVar);
344 hb_font_make_immutable(harfBuzzFont.get());
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()));
351 for (unsigned i = 0; i < runCount; ++i) {
352 auto& run = runList[m_run.rtl() ? runCount - i - 1 : i];
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);
359 // Leaving direction to HarfBuzz to guess is *really* bad, but will do for now.
360 hb_buffer_guess_segment_properties(buffer.get());
362 hb_buffer_add_utf16(buffer.get(), reinterpret_cast<const uint16_t*>(characters), length, run.startIndex, run.endIndex - run.startIndex);
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());
370 } // namespace WebCore