d6904058dcf51802d4d425ca8506993e12e0a9c4
[platform/core/uifw/dali-adaptor.git] / dali / internal / text / text-abstraction / plugin / font-client-plugin-impl.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/text/text-abstraction/plugin/font-client-plugin-impl.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/devel-api/text-abstraction/font-list.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/integration-api/trace.h>
25 #include <dali/integration-api/platform-abstraction.h>
26 #include <dali/internal/adaptor/common/adaptor-impl.h>
27 #include <dali/internal/imaging/common/image-operations.h>
28 #include <dali/internal/text/text-abstraction/plugin/bitmap-font-cache-item.h>
29 #include <dali/internal/text/text-abstraction/plugin/embedded-item.h>
30 #include <dali/internal/text/text-abstraction/plugin/font-client-plugin-cache-handler.h>
31 #include <dali/internal/text/text-abstraction/plugin/font-client-utils.h>
32 #include <dali/internal/text/text-abstraction/plugin/font-face-cache-item.h>
33 #include <dali/public-api/common/dali-vector.h>
34 #include <dali/public-api/common/vector-wrapper.h>
35
36 // EXTERNAL INCLUDES
37 #include <fontconfig/fontconfig.h>
38 #include <algorithm>
39 #include <iterator>
40
41 #if defined(DEBUG_ENABLED)
42
43 // Note, to turn on trace and verbose logging, use "export LOG_FONT_CLIENT=3,true"
44 // Or re-define the following filter using Verbose,true instead of NoLogging,false,
45 // Or, add DALI_LOG_FILTER_ENABLE_TRACE(gFontClientLogFilter) in the code below.
46
47 Dali::Integration::Log::Filter* gFontClientLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT");
48
49 #define FONT_LOG_DESCRIPTION(fontDescription, prefix)                                                                            \
50   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, #prefix "  description; family : [%s]\n", fontDescription.family.c_str()); \
51   DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose,                                                                            \
52                 "                 path : [%s]\n"                                                                                 \
53                 "                width : [%s]\n"                                                                                 \
54                 "               weight : [%s]\n"                                                                                 \
55                 "                slant : [%s]\n\n",                                                                              \
56                 fontDescription.path.c_str(),                                                                                    \
57                 FontWidth::Name[fontDescription.width],                                                                          \
58                 FontWeight::Name[fontDescription.weight],                                                                        \
59                 FontSlant::Name[fontDescription.slant])
60
61 #define FONT_LOG_REQUEST(charcode, requestedPointSize, preferColor) \
62   DALI_LOG_INFO(gFontClientLogFilter, Debug::General,               \
63                 "           character : %p\n"                       \
64                 "  requestedPointSize : %d\n"                       \
65                 "         preferColor : %s\n",                      \
66                 charcode,                                           \
67                 requestedPointSize,                                 \
68                 (preferColor ? "true" : "false"))
69
70 #else
71
72 #define FONT_LOG_DESCRIPTION(fontDescription, prefix)
73 #define FONT_LOG_REQUEST(charcode, requestedPointSize, preferColor)
74
75 #endif
76
77 namespace
78 {
79
80 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_FONT_PERFORMANCE_MARKER, false);
81
82 /**
83  * Conversion from Fractional26.6 to float
84  */
85 const float FROM_266        = 1.0f / 64.0f;
86 const float POINTS_PER_INCH = 72.f;
87
88 const uint32_t ELLIPSIS_CHARACTER = 0x2026;
89
90 } // namespace
91
92 using Dali::Vector;
93
94 namespace Dali::TextAbstraction::Internal
95 {
96 namespace
97 {
98 /**
99  * @brief Check if @p ftFace and @p requestedPointSize produces block that fit into atlas block
100  *
101  * @param[in/out] ftFace Face type object.
102  * @param[in] horizontalDpi The horizontal dpi.
103  * @param[in] verticalDpi The vertical dpi.
104  * @param[in] maxSizeFitInAtlas The maximum size of block to fit into atlas
105  * @param[in] requestedPointSize The requested point-size.
106  * @return whether the  ftFace's block can fit into atlas
107  */
108 bool IsFitIntoAtlas(FT_Face& ftFace, int& error, const unsigned int& horizontalDpi, const unsigned int& verticalDpi, const Size& maxSizeFitInAtlas, const uint32_t& requestedPointSize)
109 {
110   bool isFit = false;
111
112   error = FT_Set_Char_Size(ftFace,
113                            0,
114                            requestedPointSize,
115                            horizontalDpi,
116                            verticalDpi);
117
118   if(error == FT_Err_Ok)
119   {
120     //Check width and height of block for requestedPointSize
121     //If the width or height is greater than the maximum-size then decrement by one unit of point-size.
122     if(static_cast<float>(ftFace->size->metrics.height) * FROM_266 <= maxSizeFitInAtlas.height && (static_cast<float>(ftFace->size->metrics.ascender) - static_cast<float>(ftFace->size->metrics.descender)) * FROM_266 <= maxSizeFitInAtlas.width)
123     {
124       isFit = true;
125     }
126   }
127
128   return isFit;
129 }
130
131 /**
132  * @brief Search on proper @p requestedPointSize that produces block that fit into atlas block considering on @p ftFace, @p horizontalDpi, and @p verticalDpi
133  *
134  * @param[in/out] ftFace Face type object.
135  * @param[in] horizontalDpi The horizontal dpi.
136  * @param[in] verticalDpi The vertical dpi.
137  * @param[in] maxSizeFitInAtlas The maximum size of block to fit into atlas
138  * @param[in/out] requestedPointSize The requested point-size.
139  * @return FreeType error code. 0 means success when requesting the nominal size (in points).
140  */
141 int SearchOnProperPointSize(FT_Face& ftFace, const unsigned int& horizontalDpi, const unsigned int& verticalDpi, const Size& maxSizeFitInAtlas, uint32_t& requestedPointSize)
142 {
143   //To improve performance of sequential search. This code is applying Exponential search then followed by Binary search.
144   const uint32_t& pointSizePerOneUnit = TextAbstraction::FontClient::NUMBER_OF_POINTS_PER_ONE_UNIT_OF_POINT_SIZE;
145   bool            canFitInAtlas;
146   int             error; // FreeType error code.
147
148   canFitInAtlas = IsFitIntoAtlas(ftFace, error, horizontalDpi, verticalDpi, maxSizeFitInAtlas, requestedPointSize);
149   if(FT_Err_Ok != error)
150   {
151     return error;
152   }
153
154   if(!canFitInAtlas)
155   {
156     //Exponential search
157     uint32_t exponentialDecrement = 1;
158
159     while(!canFitInAtlas && requestedPointSize > pointSizePerOneUnit * exponentialDecrement)
160     {
161       requestedPointSize -= (pointSizePerOneUnit * exponentialDecrement);
162       canFitInAtlas = IsFitIntoAtlas(ftFace, error, horizontalDpi, verticalDpi, maxSizeFitInAtlas, requestedPointSize);
163       if(FT_Err_Ok != error)
164       {
165         return error;
166       }
167
168       exponentialDecrement *= 2;
169     }
170
171     //Binary search
172     uint32_t minPointSize;
173     uint32_t maxPointSize;
174
175     if(canFitInAtlas)
176     {
177       exponentialDecrement /= 2;
178       minPointSize = requestedPointSize;
179       maxPointSize = requestedPointSize + (pointSizePerOneUnit * exponentialDecrement);
180     }
181     else
182     {
183       minPointSize = 0;
184       maxPointSize = requestedPointSize;
185     }
186
187     while(minPointSize < maxPointSize)
188     {
189       requestedPointSize = ((maxPointSize / pointSizePerOneUnit - minPointSize / pointSizePerOneUnit) / 2) * pointSizePerOneUnit + minPointSize;
190       canFitInAtlas      = IsFitIntoAtlas(ftFace, error, horizontalDpi, verticalDpi, maxSizeFitInAtlas, requestedPointSize);
191       if(FT_Err_Ok != error)
192       {
193         return error;
194       }
195
196       if(canFitInAtlas)
197       {
198         if(minPointSize == requestedPointSize)
199         {
200           //Found targeted point-size
201           return error;
202         }
203
204         minPointSize = requestedPointSize;
205       }
206       else
207       {
208         maxPointSize = requestedPointSize;
209       }
210     }
211   }
212
213   return error;
214 }
215
216 } // namespace
217
218 FontClient::Plugin::Plugin(unsigned int horizontalDpi,
219                            unsigned int verticalDpi)
220 : mFreeTypeLibrary(nullptr),
221   mDpiHorizontal(horizontalDpi),
222   mDpiVertical(verticalDpi),
223   mIsAtlasLimitationEnabled(TextAbstraction::FontClient::DEFAULT_ATLAS_LIMITATION_ENABLED),
224   mCurrentMaximumBlockSizeFitInAtlas(TextAbstraction::FontClient::MAX_SIZE_FIT_IN_ATLAS),
225   mVectorFontCache(nullptr),
226   mCacheHandler(new CacheHandler())
227 {
228   int error = FT_Init_FreeType(&mFreeTypeLibrary);
229   if(FT_Err_Ok != error)
230   {
231     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FreeType Init error: %d\n", error);
232   }
233
234 #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
235   mVectorFontCache = new VectorFontCache(mFreeTypeLibrary);
236 #endif
237 }
238
239 FontClient::Plugin::~Plugin()
240 {
241   // Delete cache hanlder before remove mFreeTypeLibrary
242   delete mCacheHandler;
243
244 #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
245   delete mVectorFontCache;
246 #endif
247
248   FT_Done_FreeType(mFreeTypeLibrary);
249 }
250
251 void FontClient::Plugin::ClearCache() const
252 {
253   mCacheHandler->ClearCache();
254 }
255
256 void FontClient::Plugin::SetDpi(unsigned int horizontalDpi,
257                                 unsigned int verticalDpi)
258 {
259   mDpiHorizontal = horizontalDpi;
260   mDpiVertical   = verticalDpi;
261 }
262
263 void FontClient::Plugin::ResetSystemDefaults() const
264 {
265   mCacheHandler->ResetSystemDefaults();
266 }
267
268 void FontClient::Plugin::FontPreCache(const FontFamilyList& fallbackFamilyList, const FontFamilyList& extraFamilyList, const FontFamily& localeFamily) const
269 {
270   mCacheHandler->InitDefaultFontDescription();
271
272   FontFamilyList familyList;
273   familyList.reserve(extraFamilyList.size() + 1);
274
275   for (const auto& fallbackFont : fallbackFamilyList)
276   {
277     FontList*         fontList         = nullptr;
278     CharacterSetList* characterSetList = nullptr;
279     FontDescriptionId fontDescriptionId = 0u;
280     FontDescription fontDescription;
281     fontDescription.family = FontFamily(fallbackFont);
282     fontDescription.weight = DefaultFontWeight();
283     fontDescription.width  = DefaultFontWidth();
284     fontDescription.slant  = DefaultFontSlant();
285
286     if(!mCacheHandler->FindFallbackFontList(fontDescription, fontList, characterSetList))
287     {
288       mCacheHandler->CacheFallbackFontList(std::move(fontDescription), fontList, characterSetList);
289     }
290     if(!mCacheHandler->FindValidatedFont(fontDescription, fontDescriptionId))
291     {
292       mCacheHandler->ValidateFont(fontDescription, fontDescriptionId);
293     }
294
295     if(extraFamilyList.empty() && localeFamily.empty())
296     {
297       continue;
298     }
299
300     familyList.clear();
301     familyList.insert(familyList.end(), extraFamilyList.begin(), extraFamilyList.end());
302     if(!localeFamily.empty())
303     {
304       familyList.push_back(localeFamily);
305     }
306
307     for(const auto& font : *fontList)
308     {
309       auto it = std::find(familyList.begin(), familyList.end(), font.family);
310       if(it != familyList.end())
311       {
312         if(!mCacheHandler->FindValidatedFont(font, fontDescriptionId))
313         {
314           mCacheHandler->ValidateFont(font, fontDescriptionId);
315         }
316         familyList.erase(it);
317       }
318     }
319   }
320 }
321
322 void FontClient::Plugin::GetDefaultPlatformFontDescription(FontDescription& fontDescription) const
323 {
324   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
325
326   mCacheHandler->InitDefaultFontDescription();
327   fontDescription = mCacheHandler->mDefaultFontDescription;
328
329   FONT_LOG_DESCRIPTION(fontDescription, "");
330 }
331
332 void FontClient::Plugin::GetDefaultFonts(FontList& defaultFonts) const
333 {
334   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
335
336   mCacheHandler->InitDefaultFonts();
337   defaultFonts = mCacheHandler->mDefaultFonts;
338
339   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  number of default fonts : [%d]\n", mCacheHandler->mDefaultFonts.size());
340 }
341
342 void FontClient::Plugin::GetSystemFonts(FontList& systemFonts) const
343 {
344   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
345
346   mCacheHandler->InitSystemFonts();
347   systemFonts = mCacheHandler->mSystemFonts;
348
349   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  number of system fonts : [%d]\n", mCacheHandler->mSystemFonts.size());
350 }
351
352 void FontClient::Plugin::GetDescription(FontId           fontId,
353                                         FontDescription& fontDescription) const
354 {
355   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
356   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", fontId);
357
358   if((fontId > 0u) && (fontId - 1u < mCacheHandler->mFontIdCache.size()))
359   {
360     const auto& fontIdCacheItem = mCacheHandler->mFontIdCache[fontId - 1u];
361     switch(fontIdCacheItem.type)
362     {
363       case FontDescription::FACE_FONT:
364       {
365         for(const auto& item : mCacheHandler->mFontDescriptionSizeCache)
366         {
367           if(item.second == fontIdCacheItem.index)
368           {
369             fontDescription = *(mCacheHandler->mFontDescriptionCache.begin() + item.first.fontDescriptionId - 1u);
370
371             FONT_LOG_DESCRIPTION(fontDescription, "");
372             return;
373           }
374         }
375         break;
376       }
377       case FontDescription::BITMAP_FONT:
378       {
379         fontDescription.type   = FontDescription::BITMAP_FONT;
380         fontDescription.family = mCacheHandler->mBitmapFontCache[fontIdCacheItem.index].font.name;
381         break;
382       }
383       default:
384       {
385         DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  Invalid type of font\n");
386         fontDescription.type = FontDescription::INVALID;
387         fontDescription.family.clear();
388       }
389     }
390   }
391
392   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  No description found for the font id %d\n", fontId);
393 }
394
395 PointSize26Dot6 FontClient::Plugin::GetPointSize(FontId fontId) const
396 {
397   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
398   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", fontId);
399
400   PointSize26Dot6               pointSize     = TextAbstraction::FontClient::DEFAULT_POINT_SIZE;
401   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
402   if(fontCacheItem != nullptr)
403   {
404     pointSize = fontCacheItem->GetPointSize();
405   }
406   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  point size : %d\n", pointSize);
407
408   return pointSize;
409 }
410
411 bool FontClient::Plugin::IsCharacterSupportedByFont(FontId fontId, Character character) const
412 {
413   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
414   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "    font id : %d\n", fontId);
415   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  character : %p\n", character);
416
417   bool isSupported   = false;
418   auto fontCacheItem = const_cast<FontCacheItemInterface*>(GetCachedFontItem(fontId));
419   if(fontCacheItem != nullptr)
420   {
421     isSupported = fontCacheItem->IsCharacterSupported(character); // May cache
422   }
423
424   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  is supported : %s\n", (isSupported ? "true" : "false"));
425   return isSupported;
426 }
427
428 const FontCacheItemInterface* FontClient::Plugin::GetCachedFontItem(FontId fontId) const
429 {
430   if((fontId > 0u) && (fontId - 1u < mCacheHandler->mFontIdCache.size()))
431   {
432     const auto& fontIdCacheItem = mCacheHandler->mFontIdCache[fontId - 1u];
433     switch(fontIdCacheItem.type)
434     {
435       case FontDescription::FACE_FONT:
436       {
437         return &mCacheHandler->mFontFaceCache[fontIdCacheItem.index];
438       }
439       case FontDescription::BITMAP_FONT:
440       {
441         return &mCacheHandler->mBitmapFontCache[fontIdCacheItem.index];
442       }
443       default:
444       {
445         DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  Invalid type of font\n");
446       }
447     }
448   }
449   return nullptr;
450 }
451
452 FontId FontClient::Plugin::FindFontForCharacter(const FontList&         fontList,
453                                                 const CharacterSetList& characterSetList,
454                                                 Character               character,
455                                                 PointSize26Dot6         requestedPointSize,
456                                                 bool                    preferColor) const
457 {
458   DALI_ASSERT_DEBUG((fontList.size() == characterSetList.Count()) && "FontClient::Plugin::FindFontForCharacter. Different number of fonts and character sets.");
459   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
460   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "           character : %p\n", character);
461   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  requestedPointSize : %d\n", requestedPointSize);
462   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "         preferColor : %s\n", (preferColor ? "true" : "false"));
463
464   FontId fontId     = 0u;
465   bool   foundColor = false;
466
467   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  number of fonts : %d\n", fontList.size());
468
469   // Traverse the list of fonts.
470   // Check for each font if supports the character.
471   for(unsigned int index = 0u, numberOfFonts = fontList.size(); index < numberOfFonts; ++index)
472   {
473     const FontDescription& description  = fontList[index];
474     const FcCharSet* const characterSet = characterSetList[index];
475
476     FONT_LOG_DESCRIPTION(description, "");
477
478     bool foundInRanges = false;
479     if(nullptr != characterSet)
480     {
481       foundInRanges = FcCharSetHasChar(characterSet, character);
482     }
483
484     if(foundInRanges)
485     {
486       fontId = GetFontId(description, requestedPointSize, 0u);
487
488       DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "     font id : %d\n", fontId);
489
490       if(preferColor)
491       {
492         if((fontId > 0) && (fontId - 1u < mCacheHandler->mFontIdCache.size()))
493         {
494           const FontFaceCacheItem& item = mCacheHandler->mFontFaceCache[mCacheHandler->mFontIdCache[fontId - 1u].index];
495
496           foundColor = item.mHasColorTables;
497         }
498
499         DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "  foundColor : %s\n", (foundColor ? "true" : "false"));
500       }
501
502       // Keep going unless we prefer a different (color) font.
503       if(!preferColor || foundColor)
504       {
505         break;
506       }
507     }
508   }
509
510   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", fontId);
511   return fontId;
512 }
513
514 FontId FontClient::Plugin::FindDefaultFont(Character       charcode,
515                                            PointSize26Dot6 requestedPointSize,
516                                            bool            preferColor) const
517 {
518   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
519   FONT_LOG_REQUEST(charcode, requestedPointSize, preferColor);
520
521   FontId fontId(0);
522
523   // Create the list of default fonts if it has not been created.
524   mCacheHandler->InitDefaultFonts();
525   DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "  number of default fonts : %d\n", mCacheHandler->mDefaultFonts.size());
526
527   // Traverse the list of default fonts.
528   // Check for each default font if supports the character.
529   fontId = FindFontForCharacter(mCacheHandler->mDefaultFonts, mCacheHandler->mDefaultFontCharacterSets, charcode, requestedPointSize, preferColor);
530
531   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", fontId);
532   return fontId;
533 }
534
535 FontId FontClient::Plugin::FindFallbackFont(Character              charcode,
536                                             const FontDescription& preferredFontDescription,
537                                             PointSize26Dot6        requestedPointSize,
538                                             bool                   preferColor) const
539 {
540   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
541   FONT_LOG_REQUEST(charcode, requestedPointSize, preferColor);
542
543   DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIND_FALLBACKFONT");
544
545   // The font id to be returned.
546   FontId fontId = 0u;
547
548   FontDescription fontDescription;
549
550   // Fill the font description with the preferred font description and complete with the defaults.
551   fontDescription.family = preferredFontDescription.family.empty() ? DefaultFontFamily() : preferredFontDescription.family;
552   fontDescription.weight = ((FontWeight::NONE == preferredFontDescription.weight) ? DefaultFontWeight() : preferredFontDescription.weight);
553   fontDescription.width  = ((FontWidth::NONE == preferredFontDescription.width) ? DefaultFontWidth() : preferredFontDescription.width);
554   fontDescription.slant  = ((FontSlant::NONE == preferredFontDescription.slant) ? DefaultFontSlant() : preferredFontDescription.slant);
555
556   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  preferredFontDescription --> fontDescription\n");
557   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  [%s] --> [%s]\n", preferredFontDescription.family.c_str(), fontDescription.family.c_str());
558   DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "  [%s] --> [%s]\n", FontWeight::Name[preferredFontDescription.weight], FontWeight::Name[fontDescription.weight]);
559   DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "  [%s] --> [%s]\n", FontWidth::Name[preferredFontDescription.width], FontWidth::Name[fontDescription.width]);
560   DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "  [%s] --> [%s]\n", FontSlant::Name[preferredFontDescription.slant], FontSlant::Name[fontDescription.slant]);
561
562   #if defined(TRACE_ENABLED)
563   if(gTraceFilter && gTraceFilter->IsTraceEnabled())
564   {
565     DALI_LOG_DEBUG_INFO("DALI_TEXT_FIND_FALLBACKFONT : %s -> %s\n", preferredFontDescription.family.c_str(), fontDescription.family.c_str());
566   }
567   #endif
568
569   // Check first if the font's description has been queried before.
570   FontList*         fontList         = nullptr;
571   CharacterSetList* characterSetList = nullptr;
572
573   if(!mCacheHandler->FindFallbackFontList(fontDescription, fontList, characterSetList))
574   {
575     mCacheHandler->CacheFallbackFontList(std::move(fontDescription), fontList, characterSetList);
576   }
577
578   if(fontList && characterSetList)
579   {
580     fontId = FindFontForCharacter(*fontList, *characterSetList, charcode, requestedPointSize, preferColor);
581   }
582
583   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", fontId);
584   return fontId;
585 }
586
587 FontId FontClient::Plugin::GetFontIdByPath(const FontPath& path,
588                                            PointSize26Dot6 requestedPointSize,
589                                            FaceIndex       faceIndex,
590                                            bool            cacheDescription) const
591 {
592   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
593   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "                path : [%s]\n", path.c_str());
594   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  requestedPointSize : %d\n", requestedPointSize);
595
596   FontId id = 0u;
597
598   if(nullptr != mFreeTypeLibrary)
599   {
600     FontId foundId = 0u;
601     if(mCacheHandler->FindFontByPath(path, requestedPointSize, faceIndex, foundId))
602     {
603       id = foundId;
604     }
605     else
606     {
607       id = CreateFont(path, requestedPointSize, faceIndex, cacheDescription);
608     }
609   }
610
611   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", id);
612   return id;
613 }
614
615 FontId FontClient::Plugin::GetFontId(const FontDescription& fontDescription,
616                                      PointSize26Dot6        requestedPointSize,
617                                      FaceIndex              faceIndex) const
618 {
619   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
620   FONT_LOG_DESCRIPTION(fontDescription, "");
621
622   // Special case when font Description don't have family information.
623   // In this case, we just use default description family and path.
624   const FontDescription& realFontDescription = fontDescription.family.empty() ? FontDescription(mCacheHandler->mDefaultFontDescription.path,
625                                                                                                 mCacheHandler->mDefaultFontDescription.family,
626                                                                                                 fontDescription.width,
627                                                                                                 fontDescription.weight,
628                                                                                                 fontDescription.slant,
629                                                                                                 fontDescription.type)
630                                                                               : fontDescription;
631
632   FONT_LOG_DESCRIPTION(realFontDescription, "");
633   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "   requestedPointSize : %d\n", requestedPointSize);
634
635   // This method uses three vectors which caches:
636   // * The bitmap font cache
637   // * Pairs of non validated font descriptions and an index to a vector with paths to font file names.
638   // * The path to font file names.
639   // * The font ids of pairs 'font point size, index to the vector with paths to font file names'.
640
641   // 1) Checks if the font description matches with a previously loaded bitmap font.
642   //    Returns if a font is found.
643   // 2) Checks in the cache if the font's description has been validated before.
644   //    If it was it gets an index to the vector with paths to font file names. Otherwise,
645   //    retrieves using font config a path to a font file name which matches with the
646   //    font's description. The path is stored in the cache.
647   //
648   // 3) Checks in the cache if the pair 'font point size, index to the vector with paths to
649   //    font file names' exists. If exists, it gets the font id. If it doesn't it calls
650   //    the GetFontId() method with the path to the font file name and the point size to
651   //    get the font id.
652
653   // The font id to be returned.
654   FontId fontId = 0u;
655
656   // Check first if the font description matches with a previously loaded bitmap font.
657   if(mCacheHandler->FindBitmapFont(realFontDescription.family, fontId))
658   {
659     return fontId;
660   }
661
662   // Check if the font's description have been validated before.
663   FontDescriptionId fontDescriptionId = 0u;
664
665   if(!mCacheHandler->FindValidatedFont(realFontDescription, fontDescriptionId))
666   {
667     // Use font config to validate the font's description.
668     mCacheHandler->ValidateFont(realFontDescription, fontDescriptionId);
669   }
670
671   using FontCacheIndex          = CacheHandler::FontCacheIndex;
672   FontCacheIndex fontCacheIndex = 0u;
673   // Check if exists a pair 'fontDescriptionId, requestedPointSize' in the cache.
674   if(!mCacheHandler->FindFont(fontDescriptionId, requestedPointSize, fontCacheIndex))
675   {
676     // Retrieve the font file name path.
677     const FontDescription& description = *(mCacheHandler->mFontDescriptionCache.begin() + fontDescriptionId - 1u);
678
679     // Retrieve the font id. Do not cache the description as it has been already cached.
680     // Note : CacheFontPath() API call ValidateFont() + setup CharacterSet + cache the font description.
681     // So set cacheDescription=false, that we don't call CacheFontPath().
682     fontId = GetFontIdByPath(description.path, requestedPointSize, faceIndex, false);
683
684     if((fontId > 0u) && (fontId - 1u < mCacheHandler->mFontIdCache.size()))
685     {
686       fontCacheIndex                                              = mCacheHandler->mFontIdCache[fontId - 1u].index;
687       mCacheHandler->mFontFaceCache[fontCacheIndex].mCharacterSet = FcCharSetCopy(mCacheHandler->mCharacterSetCache[fontDescriptionId - 1u]);
688
689       // Cache the pair 'fontDescriptionId, requestedPointSize' to improve the following queries.
690       mCacheHandler->CacheFontDescriptionSize(fontDescriptionId, requestedPointSize, fontCacheIndex);
691     }
692   }
693   else
694   {
695     fontId = mCacheHandler->mFontFaceCache[fontCacheIndex].mFontId + 1u;
696   }
697
698   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", fontId);
699   return fontId;
700 }
701
702 FontId FontClient::Plugin::GetFontId(const BitmapFont& bitmapFont) const
703 {
704   // The font id to be returned.
705   FontId fontId = 0u;
706   if(!mCacheHandler->FindBitmapFont(bitmapFont.name, fontId))
707   {
708     BitmapFontCacheItem bitmapFontCacheItem(bitmapFont);
709
710     fontId = mCacheHandler->CacheBitmapFontCacheItem(std::move(bitmapFontCacheItem));
711   }
712   return fontId;
713 }
714
715 void FontClient::Plugin::GetFontMetrics(FontId       fontId,
716                                         FontMetrics& metrics) const
717 {
718   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
719   if(fontCacheItem != nullptr)
720   {
721     fontCacheItem->GetFontMetrics(metrics, mDpiVertical);
722   }
723 }
724
725 GlyphIndex FontClient::Plugin::GetGlyphIndex(FontId    fontId,
726                                              Character charcode) const
727 {
728   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
729   if(fontCacheItem != nullptr)
730   {
731     return fontCacheItem->GetGlyphIndex(charcode);
732   }
733
734   return 0u;
735 }
736
737 GlyphIndex FontClient::Plugin::GetGlyphIndex(FontId    fontId,
738                                              Character charcode,
739                                              Character variantSelector) const
740 {
741   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
742   if(fontCacheItem != nullptr)
743   {
744     return fontCacheItem->GetGlyphIndex(charcode, variantSelector);
745   }
746
747   return 0u;
748 }
749
750 bool FontClient::Plugin::GetGlyphMetrics(GlyphInfo* array,
751                                          uint32_t   size,
752                                          GlyphType  type,
753                                          bool       horizontal) const
754 {
755   if(VECTOR_GLYPH == type)
756   {
757     return GetVectorMetrics(array, size, horizontal);
758   }
759
760   return GetBitmapMetrics(array, size, horizontal);
761 }
762
763 bool FontClient::Plugin::GetBitmapMetrics(GlyphInfo* array,
764                                           uint32_t   size,
765                                           bool       horizontal) const
766 {
767   bool success(size > 0u);
768
769   for(unsigned int i = 0; i < size; ++i)
770   {
771     GlyphInfo& glyph = array[i];
772
773     const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(glyph.fontId);
774     if(fontCacheItem != nullptr)
775     {
776       success &= fontCacheItem->GetGlyphMetrics(glyph, mDpiVertical, horizontal);
777     }
778     // Check if it's an embedded image.
779     else if((0u == glyph.fontId) && (0u != glyph.index) && (glyph.index <= mCacheHandler->mEmbeddedItemCache.size()))
780     {
781       mCacheHandler->mEmbeddedItemCache[glyph.index - 1u].GetGlyphMetrics(glyph);
782     }
783     else
784     {
785       success = false;
786     }
787   }
788
789   return success;
790 }
791
792 bool FontClient::Plugin::GetVectorMetrics(GlyphInfo* array,
793                                           uint32_t   size,
794                                           bool       horizontal) const
795 {
796 #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
797   bool success(true);
798
799   for(unsigned int i = 0u; i < size; ++i)
800   {
801     FontId fontId = array[i].fontId;
802
803     if((fontId > 0u) &&
804        (fontId - 1u) < mCacheHandler->mFontIdCache.size())
805     {
806       FontFaceCacheItem& font = mCacheHandler->mFontFaceCache[mCacheHandler->mFontIdCache[fontId - 1u].index];
807
808       if(!font.mVectorFontId)
809       {
810         font.mVectorFontId = mVectorFontCache->GetFontId(font.mPath);
811       }
812
813       mVectorFontCache->GetGlyphMetrics(font.mVectorFontId, array[i]);
814
815       // Vector metrics are in EMs, convert to pixels
816       const float scale = (static_cast<float>(font.mRequestedPointSize) * FROM_266) * static_cast<float>(mDpiVertical) / POINTS_PER_INCH;
817       array[i].width *= scale;
818       array[i].height *= scale;
819       array[i].xBearing *= scale;
820       array[i].yBearing *= scale;
821       array[i].advance *= scale;
822     }
823     else
824     {
825       success = false;
826     }
827   }
828
829   return success;
830 #else
831   return false;
832 #endif
833 }
834
835 void FontClient::Plugin::CreateBitmap(FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth) const
836 {
837   data.isColorBitmap                          = false;
838   data.isColorEmoji                           = false;
839   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
840   if(fontCacheItem != nullptr)
841   {
842     fontCacheItem->CreateBitmap(glyphIndex, data, outlineWidth, isItalicRequired, isBoldRequired);
843   }
844   else if((0u != glyphIndex) && (glyphIndex <= mCacheHandler->mEmbeddedItemCache.size()))
845   {
846     // It's an embedded item.
847     mCacheHandler->mEmbeddedItemCache[glyphIndex - 1u].CreateBitmap(mCacheHandler->mPixelBufferCache, data);
848   }
849 }
850
851 PixelData FontClient::Plugin::CreateBitmap(FontId fontId, GlyphIndex glyphIndex, int outlineWidth) const
852 {
853   TextAbstraction::FontClient::GlyphBufferData data;
854
855   CreateBitmap(fontId, glyphIndex, false, false, data, outlineWidth);
856
857   // If data is compressed or not owned buffer, copy this.
858   if(!data.isBufferOwned || data.compressionType != TextAbstraction::FontClient::GlyphBufferData::CompressionType::NO_COMPRESSION)
859   {
860     uint8_t* newBuffer = (uint8_t*)malloc(data.width * data.height * Pixel::GetBytesPerPixel(data.format));
861     TextAbstraction::FontClient::GlyphBufferData::Decompress(data, newBuffer);
862     if(data.isBufferOwned)
863     {
864       free(data.buffer);
865     }
866
867     data.buffer          = newBuffer;
868     data.isBufferOwned   = true;
869     data.compressionType = TextAbstraction::FontClient::GlyphBufferData::CompressionType::NO_COMPRESSION;
870   }
871
872   return PixelData::New(data.buffer,
873                         data.width * data.height * Pixel::GetBytesPerPixel(data.format),
874                         data.width,
875                         data.height,
876                         data.format,
877                         PixelData::FREE);
878 }
879
880 void FontClient::Plugin::CreateVectorBlob(FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight) const
881 {
882   blob       = nullptr;
883   blobLength = 0;
884
885 #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
886   if((fontId > 0u) &&
887      (fontId - 1u < mCacheHandler->mFontIdCache.size()))
888   {
889     using FontCacheIndex                = CacheHandler::FontCacheIndex;
890     const FontCacheIndex fontCacheIndex = mCacheHandler->mFontIdCache[fontId - 1u].index;
891     FontFaceCacheItem&   font           = mCacheHandler->mFontFaceCache[fontCacheIndex];
892
893     if(!font.mVectorFontId)
894     {
895       font.mVectorFontId = mVectorFontCache->GetFontId(font.mPath);
896     }
897
898     mVectorFontCache->GetVectorBlob(font.mVectorFontId, fontCacheIndex, glyphIndex, blob, blobLength, nominalWidth, nominalHeight);
899   }
900 #endif
901 }
902
903 const GlyphInfo& FontClient::Plugin::GetEllipsisGlyph(PointSize26Dot6 requestedPointSize) const
904 {
905   using EllipsisCacheIndex              = CacheHandler::EllipsisCacheIndex;
906   using EllipsisItem                    = CacheHandler::EllipsisItem;
907   EllipsisCacheIndex ellipsisCacheIndex = 0u;
908
909   if(!mCacheHandler->FindEllipsis(requestedPointSize, ellipsisCacheIndex))
910   {
911     // No glyph has been found. Create one.
912     EllipsisItem item;
913
914     item.requestedPointSize = requestedPointSize;
915     item.index              = ellipsisCacheIndex;
916
917     // Find a font for the ellipsis glyph.
918     item.glyph.fontId = FindDefaultFont(ELLIPSIS_CHARACTER,
919                                         requestedPointSize,
920                                         false);
921
922     // Set the character index to access the glyph inside the font.
923     item.glyph.index = GetGlyphIndex(item.glyph.fontId, ELLIPSIS_CHARACTER);
924
925     // Get glyph informations.
926     GetBitmapMetrics(&item.glyph, 1u, true);
927
928     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  glyph id %d found in the cache.\n", item.glyph.index);
929     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "      font %d.\n", item.glyph.fontId);
930
931     ellipsisCacheIndex = mCacheHandler->CacheEllipsis(std::move(item));
932   }
933   return mCacheHandler->mEllipsisCache[ellipsisCacheIndex].glyph;
934 }
935
936 bool FontClient::Plugin::IsColorGlyph(FontId fontId, GlyphIndex glyphIndex) const
937 {
938   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
939   return fontCacheItem && fontCacheItem->IsColorGlyph(glyphIndex);
940 }
941
942 FT_FaceRec_* FontClient::Plugin::GetFreetypeFace(FontId fontId) const
943 {
944   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
945   if(fontCacheItem != nullptr)
946   {
947     return fontCacheItem->GetTypeface();
948   }
949   return nullptr;
950 }
951
952 FontDescription::Type FontClient::Plugin::GetFontType(FontId fontId) const
953 {
954   const FontId index = fontId - 1u;
955   if((fontId > 0u) && (index < mCacheHandler->mFontIdCache.size()))
956   {
957     return mCacheHandler->mFontIdCache[index].type;
958   }
959   return FontDescription::INVALID;
960 }
961
962 bool FontClient::Plugin::AddCustomFontDirectory(const FontPath& path)
963 {
964   // nullptr as first parameter means the current configuration is used.
965   return FcConfigAppFontAddDir(nullptr, reinterpret_cast<const FcChar8*>(path.c_str()));
966 }
967
968 HarfBuzzFontHandle FontClient::Plugin::GetHarfBuzzFont(FontId fontId) const
969 {
970   FontCacheItemInterface* fontCacheItem = const_cast<FontCacheItemInterface*>(GetCachedFontItem(fontId));
971   if(fontCacheItem != nullptr)
972   {
973     return fontCacheItem->GetHarfBuzzFont(mDpiHorizontal, mDpiVertical); // May cache
974   }
975   return nullptr;
976 }
977
978 GlyphIndex FontClient::Plugin::CreateEmbeddedItem(const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat) const
979 {
980   EmbeddedItem embeddedItem;
981
982   embeddedItem.pixelBufferId = 0u;
983   embeddedItem.width         = description.width;
984   embeddedItem.height        = description.height;
985
986   pixelFormat = Pixel::A8;
987
988   if(!description.url.empty())
989   {
990     // Check if the url is in the cache.
991     Devel::PixelBuffer pixelBuffer;
992     if(!mCacheHandler->FindEmbeddedPixelBufferId(description.url, embeddedItem.pixelBufferId))
993     {
994       // The pixel buffer is not in the cache. Create one and cache it.
995       embeddedItem.pixelBufferId = mCacheHandler->CacheEmbeddedPixelBuffer(description.url);
996     }
997
998     if((embeddedItem.pixelBufferId > 0u) && (embeddedItem.pixelBufferId - 1u) < mCacheHandler->mPixelBufferCache.size())
999     {
1000       // Retrieve the pixel buffer from the cache to set the pixel format.
1001       pixelBuffer = mCacheHandler->mPixelBufferCache[embeddedItem.pixelBufferId - 1u].pixelBuffer;
1002     }
1003
1004     if(pixelBuffer)
1005     {
1006       // Set the size of the embedded item if it has not been set.
1007       if(0u == embeddedItem.width)
1008       {
1009         embeddedItem.width = static_cast<unsigned int>(pixelBuffer.GetWidth());
1010       }
1011
1012       if(0u == embeddedItem.height)
1013       {
1014         embeddedItem.height = static_cast<unsigned int>(pixelBuffer.GetHeight());
1015       }
1016
1017       // Set the pixel format.
1018       pixelFormat = pixelBuffer.GetPixelFormat();
1019     }
1020   }
1021
1022   // Find if the same embeddedItem has already been created.
1023   GlyphIndex index = 0u;
1024   if(!mCacheHandler->FindEmbeddedItem(embeddedItem.pixelBufferId, embeddedItem.width, embeddedItem.height, index))
1025   {
1026     index = mCacheHandler->CacheEmbeddedItem(std::move(embeddedItem));
1027   }
1028   return index;
1029 }
1030
1031 void FontClient::Plugin::EnableAtlasLimitation(bool enabled)
1032 {
1033   mIsAtlasLimitationEnabled = enabled;
1034 }
1035
1036 bool FontClient::Plugin::IsAtlasLimitationEnabled() const
1037 {
1038   return mIsAtlasLimitationEnabled;
1039 }
1040
1041 Size FontClient::Plugin::GetMaximumTextAtlasSize() const
1042 {
1043   return TextAbstraction::FontClient::MAX_TEXT_ATLAS_SIZE;
1044 }
1045
1046 Size FontClient::Plugin::GetDefaultTextAtlasSize() const
1047 {
1048   return TextAbstraction::FontClient::DEFAULT_TEXT_ATLAS_SIZE;
1049 }
1050
1051 Size FontClient::Plugin::GetCurrentMaximumBlockSizeFitInAtlas() const
1052 {
1053   return mCurrentMaximumBlockSizeFitInAtlas;
1054 }
1055
1056 bool FontClient::Plugin::SetCurrentMaximumBlockSizeFitInAtlas(const Size& currentMaximumBlockSizeFitInAtlas)
1057 {
1058   bool            isChanged        = false;
1059   const Size&     maxTextAtlasSize = TextAbstraction::FontClient::MAX_TEXT_ATLAS_SIZE;
1060   const uint16_t& padding          = TextAbstraction::FontClient::PADDING_TEXT_ATLAS_BLOCK;
1061
1062   if(currentMaximumBlockSizeFitInAtlas.width <= maxTextAtlasSize.width - padding && currentMaximumBlockSizeFitInAtlas.height <= maxTextAtlasSize.height - padding)
1063   {
1064     mCurrentMaximumBlockSizeFitInAtlas = currentMaximumBlockSizeFitInAtlas;
1065     isChanged                          = true;
1066   }
1067
1068   return isChanged;
1069 }
1070
1071 uint32_t FontClient::Plugin::GetNumberOfPointsPerOneUnitOfPointSize() const
1072 {
1073   return TextAbstraction::FontClient::NUMBER_OF_POINTS_PER_ONE_UNIT_OF_POINT_SIZE;
1074   ;
1075 }
1076
1077 FontId FontClient::Plugin::CreateFont(const FontPath& path,
1078                                       PointSize26Dot6 requestedPointSize,
1079                                       FaceIndex       faceIndex,
1080                                       bool            cacheDescription) const
1081 {
1082   DALI_LOG_TRACE_METHOD(gFontClientLogFilter);
1083   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "                path : [%s]\n", path.c_str());
1084   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  requestedPointSize : %d\n", requestedPointSize);
1085
1086   DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_CREATE_FONT");
1087   FontId fontId = 0u;
1088
1089   #if defined(TRACE_ENABLED)
1090   if(gTraceFilter && gTraceFilter->IsTraceEnabled())
1091   {
1092     DALI_LOG_DEBUG_INFO("DALI_TEXT_CREATE_FONT : FT_New_Face : %s\n", path.c_str());
1093   }
1094   #endif
1095
1096   // Create & cache new font face
1097   FT_Face ftFace;
1098   int     error = FT_New_Face(mFreeTypeLibrary,
1099                           path.c_str(),
1100                           0,
1101                           &ftFace);
1102
1103   if(FT_Err_Ok == error)
1104   {
1105     // Check if a font is scalable.
1106     const bool isScalable           = (0 != (ftFace->face_flags & FT_FACE_FLAG_SCALABLE));
1107     const bool hasFixedSizedBitmaps = (0 != (ftFace->face_flags & FT_FACE_FLAG_FIXED_SIZES)) && (0 != ftFace->num_fixed_sizes);
1108     const bool hasColorTables       = (0 != (ftFace->face_flags & FT_FACE_FLAG_COLOR));
1109
1110     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "            isScalable : [%s]\n", (isScalable ? "true" : "false"));
1111     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  hasFixedSizedBitmaps : [%s]\n", (hasFixedSizedBitmaps ? "true" : "false"));
1112     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "        hasColorTables : [%s]\n", (hasColorTables ? "true" : "false"));
1113
1114     // Check to see if the font contains fixed sizes?
1115     if(!isScalable && hasFixedSizedBitmaps)
1116     {
1117       PointSize26Dot6 actualPointSize = 0u;
1118       int             fixedSizeIndex  = 0;
1119       for(; fixedSizeIndex < ftFace->num_fixed_sizes; ++fixedSizeIndex)
1120       {
1121         const PointSize26Dot6 fixedSize = static_cast<PointSize26Dot6>(ftFace->available_sizes[fixedSizeIndex].size);
1122         DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "  size index : %d, size : %d\n", fixedSizeIndex, fixedSize);
1123
1124         if(fixedSize >= requestedPointSize)
1125         {
1126           actualPointSize = fixedSize;
1127           break;
1128         }
1129       }
1130
1131       if(0u == actualPointSize)
1132       {
1133         // The requested point size is bigger than the bigest fixed size.
1134         fixedSizeIndex  = ftFace->num_fixed_sizes - 1;
1135         actualPointSize = static_cast<PointSize26Dot6>(ftFace->available_sizes[fixedSizeIndex].size);
1136       }
1137
1138       DALI_LOG_INFO(gFontClientLogFilter, Debug::Verbose, "  size index : %d, actual size : %d\n", fixedSizeIndex, actualPointSize);
1139
1140       // Tell Freetype to use this size
1141       error = FT_Select_Size(ftFace, fixedSizeIndex);
1142       if(FT_Err_Ok != error)
1143       {
1144         DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FreeType Select_Size error: %d\n", error);
1145       }
1146       else
1147       {
1148         FT_Size_Metrics& ftMetrics = ftFace->size->metrics;
1149
1150         FontMetrics metrics(static_cast<float>(ftMetrics.ascender) * FROM_266,
1151                             static_cast<float>(ftMetrics.descender) * FROM_266,
1152                             static_cast<float>(ftMetrics.height) * FROM_266,
1153                             static_cast<float>(ftFace->underline_position) * FROM_266,
1154                             static_cast<float>(ftFace->underline_thickness) * FROM_266);
1155
1156         const float fixedWidth  = static_cast<float>(ftFace->available_sizes[fixedSizeIndex].width);
1157         const float fixedHeight = static_cast<float>(ftFace->available_sizes[fixedSizeIndex].height);
1158
1159         // Create the FreeType font face item to cache.
1160         FontFaceCacheItem fontFaceCacheItem(mFreeTypeLibrary, ftFace, mCacheHandler->GetGlyphCacheManager(), path, requestedPointSize, faceIndex, metrics, fixedSizeIndex, fixedWidth, fixedHeight, hasColorTables);
1161
1162         fontId = mCacheHandler->CacheFontFaceCacheItem(std::move(fontFaceCacheItem));
1163       }
1164     }
1165     else
1166     {
1167       if(mIsAtlasLimitationEnabled)
1168       {
1169         //There is limitation on block size to fit in predefined atlas size.
1170         //If the block size cannot fit into atlas size, then the system cannot draw block.
1171         //This is workaround to avoid issue in advance
1172         //Decrementing point-size until arriving to maximum allowed block size.
1173         auto        requestedPointSizeBackup = requestedPointSize;
1174         const Size& maxSizeFitInAtlas        = GetCurrentMaximumBlockSizeFitInAtlas();
1175         error                                = SearchOnProperPointSize(ftFace, mDpiHorizontal, mDpiVertical, maxSizeFitInAtlas, requestedPointSize);
1176
1177         if(requestedPointSize != requestedPointSizeBackup)
1178         {
1179           DALI_LOG_WARNING(" The requested-point-size : %d, is reduced to point-size : %d\n", requestedPointSizeBackup, requestedPointSize);
1180         }
1181       }
1182       else
1183       {
1184         error = FT_Set_Char_Size(ftFace,
1185                                  0,
1186                                  requestedPointSize,
1187                                  mDpiHorizontal,
1188                                  mDpiVertical);
1189       }
1190
1191       if(FT_Err_Ok == error)
1192       {
1193         FT_Size_Metrics& ftMetrics = ftFace->size->metrics;
1194
1195         FontMetrics metrics(static_cast<float>(ftMetrics.ascender) * FROM_266,
1196                             static_cast<float>(ftMetrics.descender) * FROM_266,
1197                             static_cast<float>(ftMetrics.height) * FROM_266,
1198                             static_cast<float>(ftFace->underline_position) * FROM_266,
1199                             static_cast<float>(ftFace->underline_thickness) * FROM_266);
1200
1201         // Create the FreeType font face item to cache.
1202         FontFaceCacheItem fontFaceCacheItem(mFreeTypeLibrary, ftFace, mCacheHandler->GetGlyphCacheManager(), path, requestedPointSize, faceIndex, metrics);
1203
1204         fontId = mCacheHandler->CacheFontFaceCacheItem(std::move(fontFaceCacheItem));
1205       }
1206       else
1207       {
1208         DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  FreeType Set_Char_Size error: %d for pointSize %d\n", error, requestedPointSize);
1209       }
1210     }
1211
1212     if(0u != fontId)
1213     {
1214       if(cacheDescription)
1215       {
1216         DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  Cache Font Path at font id : %d [%s]\n", fontId, path.c_str());
1217         mCacheHandler->CacheFontPath(ftFace, fontId, requestedPointSize, path);
1218       }
1219     }
1220   }
1221   else
1222   {
1223     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  FreeType New_Face error: %d for [%s]\n", error, path.c_str());
1224   }
1225
1226   DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "  font id : %d\n", fontId);
1227   return fontId;
1228 }
1229
1230 bool FontClient::Plugin::IsScalable(const FontPath& path) const
1231 {
1232   bool isScalable = false;
1233
1234   FT_Face ftFace = nullptr;
1235   int     error  = FT_New_Face(mFreeTypeLibrary,
1236                           path.c_str(),
1237                           0,
1238                           &ftFace);
1239   if(FT_Err_Ok != error)
1240   {
1241     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: %s\n", path.c_str());
1242   }
1243   else
1244   {
1245     isScalable = ftFace->face_flags & FT_FACE_FLAG_SCALABLE;
1246   }
1247
1248   if(ftFace)
1249   {
1250     FT_Done_Face(ftFace);
1251   }
1252
1253   return isScalable;
1254 }
1255
1256 bool FontClient::Plugin::IsScalable(const FontDescription& fontDescription) const
1257 {
1258   // Create a font pattern.
1259   FcPattern* fontFamilyPattern = CreateFontFamilyPattern(fontDescription); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy.
1260
1261   FcResult result = FcResultMatch;
1262
1263   // match the pattern
1264   FcPattern* match      = FcFontMatch(nullptr /* use default configure */, fontFamilyPattern, &result); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy.
1265   bool       isScalable = false;
1266
1267   if(match)
1268   {
1269     // Get the path to the font file name.
1270     FontPath path;
1271     GetFcString(match, FC_FILE, path);
1272     isScalable = IsScalable(path);
1273   }
1274   else
1275   {
1276     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str());
1277   }
1278
1279   // Destroys the created patterns.
1280   FcPatternDestroy(match);
1281   FcPatternDestroy(fontFamilyPattern);
1282
1283   return isScalable;
1284 }
1285
1286 void FontClient::Plugin::GetFixedSizes(const FontPath& path, Vector<PointSize26Dot6>& sizes) const
1287 {
1288   // Empty the caller container
1289   sizes.Clear();
1290
1291   FT_Face ftFace = nullptr;
1292   int     error  = FT_New_Face(mFreeTypeLibrary,
1293                           path.c_str(),
1294                           0,
1295                           &ftFace);
1296   if(FT_Err_Ok != error)
1297   {
1298     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font path : [%s]\n", path.c_str());
1299   }
1300
1301   if(ftFace)
1302   {
1303     // Fetch the number of fixed sizes available
1304     if(ftFace->num_fixed_sizes && ftFace->available_sizes)
1305     {
1306       for(int i = 0; i < ftFace->num_fixed_sizes; ++i)
1307       {
1308         sizes.PushBack(ftFace->available_sizes[i].size);
1309       }
1310     }
1311
1312     FT_Done_Face(ftFace);
1313   }
1314 }
1315
1316 void FontClient::Plugin::GetFixedSizes(const FontDescription&   fontDescription,
1317                                        Vector<PointSize26Dot6>& sizes) const
1318 {
1319   // Create a font pattern.
1320   FcPattern* fontFamilyPattern = CreateFontFamilyPattern(fontDescription); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy.
1321
1322   FcResult result = FcResultMatch;
1323
1324   // match the pattern
1325   FcPattern* match = FcFontMatch(nullptr /* use default configure */, fontFamilyPattern, &result); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy.
1326
1327   if(match)
1328   {
1329     // Get the path to the font file name.
1330     FontPath path;
1331     GetFcString(match, FC_FILE, path);
1332     GetFixedSizes(path, sizes);
1333   }
1334   else
1335   {
1336     DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str());
1337   }
1338
1339   // Destroys the created patterns.
1340   FcPatternDestroy(match);
1341   FcPatternDestroy(fontFamilyPattern);
1342 }
1343
1344 bool FontClient::Plugin::HasItalicStyle(FontId fontId) const
1345 {
1346   const FontCacheItemInterface* fontCacheItem = GetCachedFontItem(fontId);
1347   if(fontCacheItem != nullptr)
1348   {
1349     return fontCacheItem->HasItalicStyle();
1350   }
1351   return false;
1352 }
1353
1354 } // namespace Dali::TextAbstraction::Internal