2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include <dali/integration-api/debug.h>
21 #include <dali/devel-api/adaptor-framework/environment-variable.h>
22 #include <dali/internal/text/text-abstraction/plugin/font-client-utils.h>
23 #include <dali/internal/text/text-abstraction/plugin/font-face-cache-item.h>
25 #if defined(DEBUG_ENABLED)
26 extern Dali::Integration::Log::Filter* gFontClientLogFilter;
29 namespace Dali::TextAbstraction::Internal
33 const float FROM_266 = 1.0f / 64.0f;
34 const float POINTS_PER_INCH = 72.f;
37 * @brief Maximum size of glyph cache per each font face.
39 constexpr std::size_t DEFAULT_GLYPH_CACHE_MAX = 128;
40 constexpr std::size_t MINIMUM_SIZE_OF_GLYPH_CACHE_MAX = 2u;
42 constexpr auto MAX_NUMBER_OF_GLYPH_CACHE_ENV = "DALI_GLYPH_CACHE_MAX";
45 * @brief Get maximum size of glyph cache size from environment.
46 * If not settuped, default as 128.
47 * @note This value fixed when we call it first time.
48 * @return The max size of glyph cache.
50 size_t GetMaxNumberOfGlyphCache()
52 using Dali::EnvironmentVariable::GetEnvironmentVariable;
53 static auto numberString = GetEnvironmentVariable(MAX_NUMBER_OF_GLYPH_CACHE_ENV);
54 static auto number = numberString ? std::strtoul(numberString, nullptr, 10) : DEFAULT_GLYPH_CACHE_MAX;
55 return (number < MINIMUM_SIZE_OF_GLYPH_CACHE_MAX) ? MINIMUM_SIZE_OF_GLYPH_CACHE_MAX : number;
59 FontFaceCacheItem::FontFaceCacheItem(FT_Library& freeTypeLibrary,
62 PointSize26Dot6 requestedPointSize,
64 const FontMetrics& metrics)
65 : mFreeTypeLibrary(freeTypeLibrary),
66 mFreeTypeFace(ftFace),
67 mGlyphCacheManager(new GlyphCacheManager(mFreeTypeFace, GetMaxNumberOfGlyphCache())),
69 mRequestedPointSize(requestedPointSize),
72 mCharacterSet(nullptr),
74 mFixedWidthPixels(0.f),
75 mFixedHeightPixels(0.f),
78 mIsFixedSizeBitmap(false),
79 mHasColorTables(false)
83 FontFaceCacheItem::FontFaceCacheItem(FT_Library& freeTypeLibrary,
86 PointSize26Dot6 requestedPointSize,
88 const FontMetrics& metrics,
93 : mFreeTypeLibrary(freeTypeLibrary),
94 mFreeTypeFace(ftFace),
95 mGlyphCacheManager(new GlyphCacheManager(mFreeTypeFace, GetMaxNumberOfGlyphCache())),
97 mRequestedPointSize(requestedPointSize),
100 mCharacterSet(nullptr),
101 mFixedSizeIndex(fixedSizeIndex),
102 mFixedWidthPixels(fixedWidth),
103 mFixedHeightPixels(fixedHeight),
106 mIsFixedSizeBitmap(true),
107 mHasColorTables(hasColorTables)
111 // Move constructor. font client plugin container may call this.
112 // Note that we make nullptr of some reference sensitive values here.
113 FontFaceCacheItem::FontFaceCacheItem(FontFaceCacheItem&& rhs)
114 : mFreeTypeLibrary(rhs.mFreeTypeLibrary)
116 mFreeTypeFace = rhs.mFreeTypeFace;
117 mGlyphCacheManager = rhs.mGlyphCacheManager;
118 mPath = std::move(rhs.mPath);
119 mRequestedPointSize = rhs.mRequestedPointSize;
120 mFaceIndex = rhs.mFaceIndex;
121 mMetrics = rhs.mMetrics;
122 mCharacterSet = rhs.mCharacterSet;
123 mFixedSizeIndex = rhs.mFixedSizeIndex;
124 mFixedWidthPixels = rhs.mFixedWidthPixels;
125 mFixedHeightPixels = rhs.mFixedWidthPixels;
126 mVectorFontId = rhs.mVectorFontId;
127 mFontId = rhs.mFontId;
128 mIsFixedSizeBitmap = rhs.mIsFixedSizeBitmap;
129 mHasColorTables = rhs.mHasColorTables;
131 rhs.mGlyphCacheManager = nullptr;
132 rhs.mFreeTypeFace = nullptr;
135 FontFaceCacheItem::~FontFaceCacheItem()
137 // delete glyph cache manager before free face.
138 if(mGlyphCacheManager)
140 delete mGlyphCacheManager;
146 FT_Done_Face(mFreeTypeFace);
150 void FontFaceCacheItem::GetFontMetrics(FontMetrics& metrics, unsigned int dpiVertical) const
154 // Adjust the metrics if the fixed-size font should be down-scaled
155 if(mIsFixedSizeBitmap)
157 const float desiredFixedSize = static_cast<float>(mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * dpiVertical;
159 if(desiredFixedSize > 0.f)
161 const float scaleFactor = desiredFixedSize / mFixedHeightPixels;
163 metrics.ascender = round(metrics.ascender * scaleFactor);
164 metrics.descender = round(metrics.descender * scaleFactor);
165 metrics.height = round(metrics.height * scaleFactor);
166 metrics.underlinePosition = metrics.underlinePosition * scaleFactor;
167 metrics.underlineThickness = metrics.underlineThickness * scaleFactor;
172 bool FontFaceCacheItem::GetGlyphMetrics(GlyphInfo& glyphInfo, unsigned int dpiVertical, bool horizontal) const
176 GlyphCacheManager::GlyphCacheData glyphData;
179 #ifdef FREETYPE_BITMAP_SUPPORT
180 // Check to see if we should be loading a Fixed Size bitmap?
181 if(mIsFixedSizeBitmap)
183 FT_Select_Size(mFreeTypeFace, mFixedSizeIndex); ///< @todo: needs to be investigated why it's needed to select the size again.
184 mGlyphCacheManager->GetGlyphCacheDataFromIndex(glyphInfo.index, FT_LOAD_COLOR, false, glyphData, error);
186 if(FT_Err_Ok == error)
188 glyphInfo.width = mFixedWidthPixels;
189 glyphInfo.height = mFixedHeightPixels;
190 glyphInfo.advance = mFixedWidthPixels;
191 glyphInfo.xBearing = 0.0f;
193 const auto& metrics = glyphData.mGlyphMetrics;
197 glyphInfo.yBearing += static_cast<float>(metrics.horiBearingY) * FROM_266;
201 glyphInfo.yBearing += static_cast<float>(metrics.vertBearingY) * FROM_266;
204 // Adjust the metrics if the fixed-size font should be down-scaled
205 const float desiredFixedSize = static_cast<float>(mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * dpiVertical;
207 if(desiredFixedSize > 0.f)
209 const float scaleFactor = desiredFixedSize / mFixedHeightPixels;
210 glyphInfo.width = round(glyphInfo.width * scaleFactor);
211 glyphInfo.height = round(glyphInfo.height * scaleFactor);
212 glyphInfo.advance = round(glyphInfo.advance * scaleFactor);
213 glyphInfo.xBearing = round(glyphInfo.xBearing * scaleFactor);
214 glyphInfo.yBearing = round(glyphInfo.yBearing * scaleFactor);
216 glyphInfo.scaleFactor = scaleFactor;
221 DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::GetBitmapMetrics. FreeType Bitmap Load_Glyph error %d\n", error);
228 // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap.
229 // i.e. with the SNum-3R font.
230 // @todo: add an option to use the FT_LOAD_DEFAULT if required?
231 mGlyphCacheManager->GetGlyphCacheDataFromIndex(glyphInfo.index, FT_LOAD_NO_AUTOHINT, glyphInfo.isBoldRequired, glyphData, error);
233 // Keep the width of the glyph before doing the software emboldening.
234 // It will be used to calculate a scale factor to be applied to the
235 // advance as Harfbuzz doesn't apply any SW emboldening to calculate
236 // the advance of the glyph.
238 if(FT_Err_Ok == error)
240 const auto& metrics = glyphData.mGlyphMetrics;
242 glyphInfo.width = static_cast<float>(metrics.width) * FROM_266;
243 glyphInfo.height = static_cast<float>(metrics.height) * FROM_266;
246 glyphInfo.xBearing += static_cast<float>(metrics.horiBearingX) * FROM_266;
247 glyphInfo.yBearing += static_cast<float>(metrics.horiBearingY) * FROM_266;
251 glyphInfo.xBearing += static_cast<float>(metrics.vertBearingX) * FROM_266;
252 glyphInfo.yBearing += static_cast<float>(metrics.vertBearingY) * FROM_266;
255 const bool isEmboldeningRequired = glyphInfo.isBoldRequired && !(glyphData.mStyleFlags & FT_STYLE_FLAG_BOLD);
256 if(isEmboldeningRequired)
258 // Get dummy glyph data without embolden.
259 GlyphCacheManager::GlyphCacheData dummyData;
260 if(mGlyphCacheManager->GetGlyphCacheDataFromIndex(glyphInfo.index, FT_LOAD_NO_AUTOHINT, false, dummyData, error))
262 // If the glyph is emboldened by software, the advance is multiplied by a
263 // scale factor to make it slightly bigger.
264 const float width = static_cast<float>(dummyData.mGlyphMetrics.width) * FROM_266;
265 if(!EqualsZero(width))
267 glyphInfo.advance *= (glyphInfo.width / width);
272 // Use the bounding box of the bitmap to correct the metrics.
273 // For some fonts i.e the SNum-3R the metrics need to be corrected,
274 // otherwise the glyphs 'dance' up and down depending on the
275 // font's point size.
276 FT_Glyph glyph = glyphData.mGlyph;
279 FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_GRIDFIT, &bbox);
281 const float descender = glyphInfo.height - glyphInfo.yBearing;
282 glyphInfo.height = (bbox.yMax - bbox.yMin) * FROM_266;
283 glyphInfo.yBearing = glyphInfo.height - round(descender);
294 * @brief Create a bitmap representation of a glyph from a face font
296 * @param[in] glyphIndex The index of a glyph within the specified font.
297 * @param[in] isItalicRequired Whether the glyph requires italic style.
298 * @param[in] isBoldRequired Whether the glyph requires bold style.
299 * @param[out] data The bitmap data.
300 * @param[in] outlineWidth The width of the glyph outline in pixels.
302 void FontFaceCacheItem::CreateBitmap(
303 GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth, bool isItalicRequired, bool isBoldRequired) const
305 GlyphCacheManager::GlyphCacheData glyphData;
307 // For the software italics.
308 bool isShearRequired = false;
310 #ifdef FREETYPE_BITMAP_SUPPORT
311 // Check to see if this is fixed size bitmap
312 if(mIsFixedSizeBitmap)
314 mGlyphCacheManager->GetGlyphCacheDataFromIndex(glyphIndex, FT_LOAD_COLOR, isBoldRequired, glyphData, error);
319 // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap.
320 // i.e. with the SNum-3R font.
321 // @todo: add an option to use the FT_LOAD_DEFAULT if required?
322 mGlyphCacheManager->GetGlyphCacheDataFromIndex(glyphIndex, FT_LOAD_NO_AUTOHINT, isBoldRequired, glyphData, error);
324 if(FT_Err_Ok == error)
326 if(isItalicRequired && !(glyphData.mStyleFlags & FT_STYLE_FLAG_ITALIC))
328 // Will do the software italic.
329 isShearRequired = true;
332 // Convert to bitmap if necessary
333 if(!glyphData.mIsBitmap)
335 FT_Glyph glyph = glyphData.mGlyph;
337 DALI_ASSERT_ALWAYS(glyph->format != FT_GLYPH_FORMAT_BITMAP && "Something wrong with cashing. Some bitmap glyph cached failed.");
339 int offsetX = 0, offsetY = 0;
340 bool isOutlineGlyph = (glyph->format == FT_GLYPH_FORMAT_OUTLINE && outlineWidth > 0);
341 bool isStrokeGlyphSuccess = false;
343 // Create a bitmap for the outline
346 // Retrieve the horizontal and vertical distance from the current pen position to the
347 // left and top border of the glyph bitmap for a normal glyph before applying the outline.
348 if(FT_Err_Ok == error)
350 // Copy new glyph, and keep original cached glyph.
351 error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 0);
352 if(FT_Err_Ok == error)
354 FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(glyph);
356 offsetX = bitmapGlyph->left;
357 offsetY = bitmapGlyph->top;
359 // Copied FT_Glyph object must be released with FT_Done_Glyph
360 FT_Done_Glyph(glyph);
363 // Replace as original glyph
364 glyph = glyphData.mGlyph;
367 // Now apply the outline
371 error = FT_Stroker_New(mFreeTypeLibrary, &stroker);
373 if(FT_Err_Ok == error)
375 // Copy glyph pointer for release memory.
376 FT_Stroker_Set(stroker, outlineWidth * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0);
377 error = FT_Glyph_StrokeBorder(&glyph, stroker, 0, 0);
379 if(FT_Err_Ok == error)
381 FT_Stroker_Done(stroker);
382 isStrokeGlyphSuccess = true;
386 DALI_LOG_ERROR("FT_Glyph_StrokeBorder Failed with error: %d\n", error);
391 DALI_LOG_ERROR("FT_Stroker_New Failed with error: %d\n", error);
395 // Copy new glyph, and keep original cached glyph.
396 // If we already copy new glyph by stroke, just re-use that.
397 error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, isStrokeGlyphSuccess);
398 if(FT_Err_Ok == error)
400 FT_BitmapGlyph bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(glyph);
404 // Calculate the additional horizontal and vertical offsets needed for the position of the outline glyph
405 data.outlineOffsetX = offsetX - bitmapGlyph->left - outlineWidth;
406 data.outlineOffsetY = bitmapGlyph->top - offsetY - outlineWidth;
409 ConvertBitmap(data, bitmapGlyph->bitmap, isShearRequired);
411 // Copied FT_Glyph object must be released with FT_Done_Glyph
412 FT_Done_Glyph(glyph);
416 DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Get_Glyph Failed with error: %d\n", error);
421 ConvertBitmap(data, *glyphData.mBitmap, isShearRequired);
424 data.isColorEmoji = mIsFixedSizeBitmap;
428 DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Load_Glyph Failed with error: %d\n", error);
432 bool FontFaceCacheItem::IsColorGlyph(GlyphIndex glyphIndex) const
436 #ifdef FREETYPE_BITMAP_SUPPORT
437 // Check to see if this is fixed size bitmap
440 GlyphCacheManager::GlyphCacheData dummyData;
441 mGlyphCacheManager->GetGlyphCacheDataFromIndex(glyphIndex, FT_LOAD_COLOR, false, dummyData, error);
444 return FT_Err_Ok == error;
448 * Check if the character is supported by this font
449 * @param[in] character The character to test
451 bool FontFaceCacheItem::IsCharacterSupported(Character character)
453 if(nullptr == mCharacterSet)
455 // Create again the character set.
456 // It can be null if the ResetSystemDefaults() method has been called.
458 FontDescription description;
459 description.path = mPath;
460 description.family = std::move(FontFamily(mFreeTypeFace->family_name));
461 description.weight = FontWeight::NONE;
462 description.width = FontWidth::NONE;
463 description.slant = FontSlant::NONE;
465 // Note FreeType doesn't give too much info to build a proper font style.
466 if(mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC)
468 description.slant = FontSlant::ITALIC;
470 if(mFreeTypeFace->style_flags & FT_STYLE_FLAG_BOLD)
472 description.weight = FontWeight::BOLD;
475 mCharacterSet = FcCharSetCopy(CreateCharacterSetFromDescription(description));
478 return FcCharSetHasChar(mCharacterSet, character);
481 GlyphIndex FontFaceCacheItem::GetGlyphIndex(Character character) const
483 return FT_Get_Char_Index(mFreeTypeFace, character);
486 GlyphIndex FontFaceCacheItem::GetGlyphIndex(Character character, Character variantSelector) const
488 return FT_Face_GetCharVariantIndex(mFreeTypeFace, character, variantSelector);
491 } // namespace Dali::TextAbstraction::Internal