5a5c0d855921ea12b495f3bd024588eede90fb22
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / multi-language-support-impl.cpp
1 /*
2  * Copyright (c) 2023 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-toolkit/internal/text/multi-language-support-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/common/singleton-service.h>
23 #include <dali/devel-api/text-abstraction/font-client.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/integration-api/trace.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-toolkit/internal/text/emoji-helper.h>
29 #include <dali-toolkit/internal/text/multi-language-helper-functions.h>
30
31 namespace Dali
32 {
33 namespace Toolkit
34 {
35 namespace
36 {
37 #if defined(DEBUG_ENABLED)
38 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_MULTI_LANGUAGE_SUPPORT");
39 #endif
40
41 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_FONT_PERFORMANCE_MARKER, false);
42
43 const Dali::Toolkit::Text::Character UTF32_A = 0x0041;
44
45 // TODO : Customization required for these values.
46 constexpr std::size_t MAX_VALIDATE_FONTS_PER_SCRIPT_CACHE_SIZE = 63;
47 constexpr std::size_t MAX_DEFAULT_FONTS_CACHE_SIZE             = 15;
48
49 constexpr int VALIDATE_FONTS_PER_SCRIPT_REMAIN_COUNT = 8;
50 constexpr int DEFAULT_FONTS_REMAIN_COUNT             = 2;
51 } // namespace
52
53 namespace Text
54 {
55 namespace Internal
56 {
57
58 namespace
59 {
60 void CheckFontSupportsCharacter(
61   bool& isValidFont,
62   bool& isCommonScript,
63   const Character& character,
64   ValidateFontsPerScript**& validFontsPerScriptCacheBuffer,
65   const Script& script,
66   FontId& fontId,
67   TextAbstraction::FontClient& fontClient,
68   const bool isValidCachedDefaultFont,
69   const FontId& cachedDefaultFontId,
70   const TextAbstraction::FontDescription& currentFontDescription,
71   const TextAbstraction::PointSize26Dot6& currentFontPointSize,
72   DefaultFonts**& defaultFontPerScriptCacheBuffer)
73 {
74   // Need to check if the given font supports the current character.
75   if(!isValidFont) // (1)
76   {
77     // Whether the current character is common for all scripts (i.e. white spaces, ...)
78
79     // Is not desirable to cache fonts for the common script.
80     //
81     // i.e. Consider the text " हिंदी", the 'white space' has assigned the DEVANAGARI script.
82     //      The user may have set a font or the platform's default is used.
83     //
84     //      As the 'white space' is the first character, no font is cached so the font validation
85     //      retrieves a glyph from the given font.
86     //
87     //      Many fonts support 'white spaces' so probably the font set by the user or the platform's default
88     //      supports the 'white space'. However, that font may not support the DEVANAGARI script.
89     isCommonScript = TextAbstraction::IsCommonScript(character) || TextAbstraction::IsEmojiPresentationSelector(character);
90
91     // Check in the valid fonts cache.
92     ValidateFontsPerScript* validateFontsPerScript = *(validFontsPerScriptCacheBuffer + script);
93
94     if(NULL != validateFontsPerScript)
95     {
96       // This cache stores valid fonts set by the user.
97       isValidFont = validateFontsPerScript->IsValidFont(fontId);
98
99       // It may happen that a validated font for a script doesn't have all the glyphs for that script.
100       // i.e a font validated for the CJK script may contain glyphs for the chinese language but not for the Japanese.
101       if(isValidFont)
102       {
103         // Checks if the current character is supported by the font is needed.
104         isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character);
105       }
106     }
107
108     if(!isValidFont) // (2)
109     {
110       // The selected font is not stored in any cache.
111
112       // Checks if the current character is supported by the selected font.
113       isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character);
114
115       // If there is a valid font, cache it.
116       if(isValidFont && !isCommonScript)
117       {
118         if(NULL == validateFontsPerScript)
119         {
120           validateFontsPerScript = new ValidateFontsPerScript();
121
122           *(validFontsPerScriptCacheBuffer + script) = validateFontsPerScript;
123         }
124
125         validateFontsPerScript->Cache(fontId);
126       }
127
128       if(!isValidFont && (fontId != cachedDefaultFontId) && (!TextAbstraction::IsNewParagraph(character))) // (3)
129       {
130         // The selected font by the user or the platform's default font has failed to validate the character.
131
132         // Checks if the previously discarted cached default font supports the character.
133         bool isValidCachedFont = false;
134         if(isValidCachedDefaultFont)
135         {
136           isValidCachedFont = fontClient.IsCharacterSupportedByFont(cachedDefaultFontId, character);
137         }
138
139         if(isValidCachedFont)
140         {
141           // Use the cached default font for the script if there is one.
142           fontId      = cachedDefaultFontId;
143           isValidFont = true;
144         }
145         else
146         {
147           // There is no valid cached default font for the script.
148
149           DefaultFonts* defaultFontsPerScript = NULL;
150
151           // Find a fallback-font.
152           fontId = fontClient.FindFallbackFont(character,
153                                                currentFontDescription,
154                                                currentFontPointSize,
155                                                false);
156
157           if(0u == fontId)
158           {
159             fontId = fontClient.FindDefaultFont(UTF32_A, currentFontPointSize);
160           }
161
162           if(!isCommonScript && (script != TextAbstraction::UNKNOWN))
163           {
164             // Cache the font if it is not an unknown script
165             if(NULL == defaultFontsPerScript)
166             {
167               defaultFontsPerScript = *(defaultFontPerScriptCacheBuffer + script);
168
169               if(NULL == defaultFontsPerScript)
170               {
171                 defaultFontsPerScript                       = new DefaultFonts();
172                 *(defaultFontPerScriptCacheBuffer + script) = defaultFontsPerScript;
173               }
174             }
175             defaultFontsPerScript->Cache(currentFontDescription, fontId);
176             isValidFont = true;
177           }
178         }
179       } // !isValidFont (3)
180     }   // !isValidFont (2)
181   }     // !isValidFont (1)
182 }
183 } // unnamed namespace
184
185 bool ValidateFontsPerScript::IsValidFont(FontId fontId) const
186 {
187   for(Vector<FontId>::ConstIterator it    = mValidFonts.Begin(),
188                                     endIt = mValidFonts.End();
189       it != endIt;
190       ++it)
191   {
192     if(fontId == *it)
193     {
194       return true;
195     }
196   }
197
198   return false;
199 }
200 void ValidateFontsPerScript::Cache(FontId fontId)
201 {
202   mValidFonts.PushBack(fontId);
203   if(MAX_VALIDATE_FONTS_PER_SCRIPT_CACHE_SIZE < mValidFonts.Count())
204   {
205     // Clear cache but remaind some last items.
206     const auto offset = mValidFonts.Count() - VALIDATE_FONTS_PER_SCRIPT_REMAIN_COUNT;
207     for(int i = 0; i < VALIDATE_FONTS_PER_SCRIPT_REMAIN_COUNT; ++i)
208     {
209       mValidFonts[i] = std::move(mValidFonts[offset + i]);
210     }
211     mValidFonts.Resize(VALIDATE_FONTS_PER_SCRIPT_REMAIN_COUNT);
212   }
213 }
214
215 FontId DefaultFonts::FindFont(TextAbstraction::FontClient&            fontClient,
216                               const TextAbstraction::FontDescription& description,
217                               PointSize26Dot6                         size) const
218 {
219   for(std::vector<CacheItem>::const_iterator it    = mFonts.begin(),
220                                              endIt = mFonts.end();
221       it != endIt;
222       ++it)
223   {
224     const CacheItem& item = *it;
225
226     if(((TextAbstraction::FontWeight::NONE == description.weight) || (description.weight == item.description.weight)) &&
227        ((TextAbstraction::FontWidth::NONE == description.width) || (description.width == item.description.width)) &&
228        ((TextAbstraction::FontSlant::NONE == description.slant) || (description.slant == item.description.slant)) &&
229        (size == fontClient.GetPointSize(item.fontId)) &&
230        (description.family.empty() || (description.family == item.description.family)))
231     {
232       return item.fontId;
233     }
234   }
235
236   return 0u;
237 }
238
239 void DefaultFonts::Cache(const TextAbstraction::FontDescription& description, FontId fontId)
240 {
241   CacheItem item;
242   item.description = description;
243   item.fontId      = fontId;
244   mFonts.push_back(item);
245   if(MAX_DEFAULT_FONTS_CACHE_SIZE < mFonts.size())
246   {
247     // Clear cache but remaind some last items.
248     const auto offset = mFonts.size() - DEFAULT_FONTS_REMAIN_COUNT;
249     for(int i = 0; i < DEFAULT_FONTS_REMAIN_COUNT; ++i)
250     {
251       mFonts[i] = std::move(mFonts[offset + i]);
252     }
253     mFonts.resize(DEFAULT_FONTS_REMAIN_COUNT);
254   }
255 }
256
257 MultilanguageSupport::MultilanguageSupport()
258 : mDefaultFontPerScriptCache(),
259   mValidFontsPerScriptCache()
260 {
261   // Initializes the default font cache to zero (invalid font).
262   // Reserves space to cache the default fonts and access them with the script as an index.
263   mDefaultFontPerScriptCache.Resize(TextAbstraction::GetNumberOfScripts(), NULL);
264
265   // Initializes the valid fonts cache to NULL (no valid fonts).
266   // Reserves space to cache the valid fonts and access them with the script as an index.
267   mValidFontsPerScriptCache.Resize(TextAbstraction::GetNumberOfScripts(), NULL);
268 }
269
270 MultilanguageSupport::~MultilanguageSupport()
271 {
272   // Destroy the default font per script cache.
273   for(Vector<DefaultFonts*>::Iterator it    = mDefaultFontPerScriptCache.Begin(),
274                                       endIt = mDefaultFontPerScriptCache.End();
275       it != endIt;
276       ++it)
277   {
278     delete *it;
279   }
280
281   // Destroy the valid fonts per script cache.
282   for(Vector<ValidateFontsPerScript*>::Iterator it    = mValidFontsPerScriptCache.Begin(),
283                                                 endIt = mValidFontsPerScriptCache.End();
284       it != endIt;
285       ++it)
286   {
287     delete *it;
288   }
289 }
290
291 Text::MultilanguageSupport MultilanguageSupport::Get()
292 {
293   Text::MultilanguageSupport multilanguageSupportHandle;
294
295   SingletonService service(SingletonService::Get());
296   if(service)
297   {
298     // Check whether the singleton is already created
299     Dali::BaseHandle handle = service.GetSingleton(typeid(Text::MultilanguageSupport));
300     if(handle)
301     {
302       // If so, downcast the handle
303       MultilanguageSupport* impl = dynamic_cast<Internal::MultilanguageSupport*>(handle.GetObjectPtr());
304       multilanguageSupportHandle = Text::MultilanguageSupport(impl);
305     }
306     else // create and register the object
307     {
308       multilanguageSupportHandle = Text::MultilanguageSupport(new MultilanguageSupport);
309       service.Register(typeid(multilanguageSupportHandle), multilanguageSupportHandle);
310     }
311   }
312
313   return multilanguageSupportHandle;
314 }
315
316 void MultilanguageSupport::SetScripts(const Vector<Character>& text,
317                                       CharacterIndex           startIndex,
318                                       Length                   numberOfCharacters,
319                                       Vector<ScriptRun>&       scripts)
320 {
321   if(0u == numberOfCharacters)
322   {
323     // Nothing to do if there are no characters.
324     return;
325   }
326
327   // Find the first index where to insert the script.
328   ScriptRunIndex scriptIndex = 0u;
329   if(0u != startIndex)
330   {
331     for(Vector<ScriptRun>::ConstIterator it    = scripts.Begin(),
332                                          endIt = scripts.End();
333         it != endIt;
334         ++it, ++scriptIndex)
335     {
336       const ScriptRun& run = *it;
337       if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters)
338       {
339         // Run found.
340         break;
341       }
342     }
343   }
344
345   // Stores the current script run.
346   ScriptRun currentScriptRun;
347   currentScriptRun.characterRun.characterIndex     = startIndex;
348   currentScriptRun.characterRun.numberOfCharacters = 0u;
349   currentScriptRun.script                          = TextAbstraction::UNKNOWN;
350
351   // Reserve some space to reduce the number of reallocations.
352   scripts.Reserve(text.Count() << 2u);
353
354   // Whether the first valid script needs to be set.
355   bool isFirstScriptToBeSet = true;
356
357   // Whether the first valid script is a right to left script.
358   bool isParagraphRTL = false;
359
360   // Count the number of characters which are valid for all scripts. i.e. white spaces or '\n'.
361   Length numberOfAllScriptCharacters = 0u;
362
363   // Pointers to the text buffer.
364   const Character* const textBuffer = text.Begin();
365
366   // Initialize whether is right to left direction
367   currentScriptRun.isRightToLeft = false;
368
369   // Traverse all characters and set the scripts.
370   const Length lastCharacter = startIndex + numberOfCharacters - 1u;
371
372   for(Length index = startIndex; index <= lastCharacter; ++index)
373   {
374     Character character = *(textBuffer + index);
375
376     // Get the script of the character.
377     Script script = TextAbstraction::GetCharacterScript(character);
378
379     // Some characters (like white spaces) are valid for many scripts. The rules to set a script
380     // for them are:
381     // - If they are at the begining of a paragraph they get the script of the first character with
382     //   a defined script. If they are at the end, they get the script of the last one.
383     // - If they are between two scripts with the same direction, they get the script of the previous
384     //   character with a defined script. If the two scripts have different directions, they get the
385     //   script of the first character of the paragraph with a defined script.
386
387     // Skip those characters valid for many scripts like white spaces or '\n'.
388     bool endOfText = index > lastCharacter;
389
390     //Handle all Emoji Sequence cases
391     if(IsNewSequence(textBuffer, currentScriptRun.script, index, lastCharacter, script))
392     {
393       AddCurrentScriptAndCreatNewScript(script,
394                                         false,
395                                         false,
396                                         currentScriptRun,
397                                         numberOfAllScriptCharacters,
398                                         scripts,
399                                         scriptIndex);
400     }
401     else if(IsScriptChangedToFollowSequence(currentScriptRun.script, character, script))
402     {
403       currentScriptRun.script = script;
404     }
405     else if(IsOneOfEmojiScripts(currentScriptRun.script) && (TextAbstraction::COMMON == script))
406     {
407       // Emojis doesn't mix well with characters common to all scripts. Insert the emoji run.
408       AddCurrentScriptAndCreatNewScript(TextAbstraction::UNKNOWN,
409                                         false,
410                                         false,
411                                         currentScriptRun,
412                                         numberOfAllScriptCharacters,
413                                         scripts,
414                                         scriptIndex);
415     }
416
417     while(!endOfText &&
418           (TextAbstraction::COMMON == script))
419     {
420       // Check if whether is right to left markup and Keeps true if the previous value was true.
421       currentScriptRun.isRightToLeft = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftMark(character);
422
423       // Count all these characters to be added into a script.
424       ++numberOfAllScriptCharacters;
425
426       if(TextAbstraction::IsNewParagraph(character))
427       {
428         // The character is a new paragraph.
429         // To know when there is a new paragraph is needed because if there is a white space
430         // between two scripts with different directions, it is added to the script with
431         // the same direction than the first script of the paragraph.
432         isFirstScriptToBeSet = true;
433
434         AddCurrentScriptAndCreatNewScript(TextAbstraction::UNKNOWN,
435                                           false,
436                                           false,
437                                           currentScriptRun,
438                                           numberOfAllScriptCharacters,
439                                           scripts,
440                                           scriptIndex);
441       }
442
443       // Get the next character.
444       ++index;
445       endOfText = index > lastCharacter;
446       if(!endOfText)
447       {
448         character = *(textBuffer + index);
449         script    = TextAbstraction::GetCharacterScript(character);
450
451         //Handle all Emoji Sequence cases
452         if(IsNewSequence(textBuffer, currentScriptRun.script, index, lastCharacter, script))
453         {
454           AddCurrentScriptAndCreatNewScript(script,
455                                             false,
456                                             false,
457                                             currentScriptRun,
458                                             numberOfAllScriptCharacters,
459                                             scripts,
460                                             scriptIndex);
461         }
462         else if(IsScriptChangedToFollowSequence(currentScriptRun.script, character, script))
463         {
464           currentScriptRun.script = script;
465         }
466       }
467     } // end while( !endOfText && ( TextAbstraction::COMMON == script ) )
468
469     if(endOfText)
470     {
471       // Last characters of the text are 'white spaces'.
472       // There is nothing else to do. Just add the remaining characters to the last script after this bucle.
473       break;
474     }
475
476     // Check if it is the first character of a paragraph.
477     if(isFirstScriptToBeSet &&
478        (TextAbstraction::UNKNOWN != script) &&
479        (TextAbstraction::COMMON != script) &&
480        (TextAbstraction::EMOJI != script) &&
481        (TextAbstraction::EMOJI_TEXT != script) &&
482        (TextAbstraction::EMOJI_COLOR != script) &&
483        (!TextAbstraction::IsSymbolScript(script)))
484     {
485       // Sets the direction of the first valid script.
486       isParagraphRTL       = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftScript(script);
487       isFirstScriptToBeSet = false;
488     }
489
490     if((script != currentScriptRun.script) &&
491        (TextAbstraction::COMMON != script))
492     {
493       // Current run needs to be stored and a new one initialized.
494
495       if((isParagraphRTL == TextAbstraction::IsRightToLeftScript(currentScriptRun.script)) &&
496          (TextAbstraction::UNKNOWN != currentScriptRun.script))
497       {
498         // Previous script has the same direction than the first script of the paragraph.
499         // All the previously skipped characters need to be added to the previous script before it's stored.
500         currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
501         numberOfAllScriptCharacters = 0u;
502       }
503       else if((TextAbstraction::IsRightToLeftScript(currentScriptRun.script) == TextAbstraction::IsRightToLeftScript(script)) &&
504               (TextAbstraction::UNKNOWN != currentScriptRun.script))
505       {
506         // Current script and previous one have the same direction.
507         // All the previously skipped characters need to be added to the previous script before it's stored.
508         currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
509         numberOfAllScriptCharacters = 0u;
510       }
511       else if((TextAbstraction::UNKNOWN == currentScriptRun.script) &&
512               (TextAbstraction::IsSymbolOrEmojiOrTextScript(script)))
513       {
514         currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
515         numberOfAllScriptCharacters = 0u;
516       }
517
518       // Adds the white spaces which are at the begining of the script.
519       numberOfAllScriptCharacters++;
520       AddCurrentScriptAndCreatNewScript(script,
521                                         TextAbstraction::IsRightToLeftScript(script),
522                                         true,
523                                         currentScriptRun,
524                                         numberOfAllScriptCharacters,
525                                         scripts,
526                                         scriptIndex);
527     }
528     else
529     {
530       if(TextAbstraction::UNKNOWN != currentScriptRun.script)
531       {
532         // Adds white spaces between characters.
533         currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
534         numberOfAllScriptCharacters = 0u;
535       }
536
537       // Add one more character to the run.
538       ++currentScriptRun.characterRun.numberOfCharacters;
539     }
540   }
541
542   // Add remaining characters into the last script.
543   currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
544
545   if(0u != currentScriptRun.characterRun.numberOfCharacters)
546   {
547     // Store the last run.
548     scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun);
549     ++scriptIndex;
550   }
551
552   if(scriptIndex < scripts.Count())
553   {
554     // Update the indices of the next script runs.
555     const ScriptRun& run                = *(scripts.Begin() + scriptIndex - 1u);
556     CharacterIndex   nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters;
557
558     for(Vector<ScriptRun>::Iterator it    = scripts.Begin() + scriptIndex,
559                                     endIt = scripts.End();
560         it != endIt;
561         ++it)
562     {
563       ScriptRun& run                  = *it;
564       run.characterRun.characterIndex = nextCharacterIndex;
565       nextCharacterIndex += run.characterRun.numberOfCharacters;
566     }
567   }
568 }
569
570 void MultilanguageSupport::ValidateFonts(const Vector<Character>&                text,
571                                          const Vector<ScriptRun>&                scripts,
572                                          const Vector<FontDescriptionRun>&       fontDescriptions,
573                                          const TextAbstraction::FontDescription& defaultFontDescription,
574                                          TextAbstraction::PointSize26Dot6        defaultFontPointSize,
575                                          float                                   fontSizeScale,
576                                          CharacterIndex                          startIndex,
577                                          Length                                  numberOfCharacters,
578                                          Vector<FontRun>&                        fonts)
579 {
580   DALI_LOG_INFO(gLogFilter, Debug::General, "-->MultilanguageSupport::ValidateFonts\n");
581
582   if(0u == numberOfCharacters)
583   {
584     DALI_LOG_INFO(gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n");
585     // Nothing to do if there are no characters.
586     return;
587   }
588
589   DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FONTS_VALIDATE");
590
591   // Find the first index where to insert the font run.
592   FontRunIndex fontIndex = 0u;
593   if(0u != startIndex)
594   {
595     for(Vector<FontRun>::ConstIterator it    = fonts.Begin(),
596                                        endIt = fonts.End();
597         it != endIt;
598         ++it, ++fontIndex)
599     {
600       const FontRun& run = *it;
601       if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters)
602       {
603         // Run found.
604         break;
605       }
606     }
607   }
608
609   // Traverse the characters and validate/set the fonts.
610
611   // Get the caches.
612   DefaultFonts**           defaultFontPerScriptCacheBuffer = mDefaultFontPerScriptCache.Begin();
613   ValidateFontsPerScript** validFontsPerScriptCacheBuffer  = mValidFontsPerScriptCache.Begin();
614
615   // Stores the validated font runs.
616   fonts.Reserve(fontDescriptions.Count());
617
618   // Initializes a validated font run.
619   FontRun currentFontRun;
620   currentFontRun.characterRun.characterIndex     = startIndex;
621   currentFontRun.characterRun.numberOfCharacters = 0u;
622   currentFontRun.fontId                          = 0u;
623   currentFontRun.isBoldRequired                  = false;
624   currentFontRun.isItalicRequired                = false;
625
626   // Get the font client.
627   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
628
629   const Character* const textBuffer = text.Begin();
630
631   // Iterators of the script runs.
632   Vector<ScriptRun>::ConstIterator scriptRunIt             = scripts.Begin();
633   Vector<ScriptRun>::ConstIterator scriptRunEndIt          = scripts.End();
634   bool                             isNewParagraphCharacter = false;
635
636   FontId                  previousEmojiFontId = 0u;
637   FontId                  currentFontId       = 0u;
638   FontId                  previousFontId      = 0u;
639   TextAbstraction::Script previousScript      = TextAbstraction::UNKNOWN;
640
641   CharacterIndex lastCharacter = startIndex + numberOfCharacters - 1u;
642   for(Length index = startIndex; index <= lastCharacter; ++index)
643   {
644     // Get the current character.
645     const Character character        = *(textBuffer + index);
646     bool            isItalicRequired = false;
647     bool            isBoldRequired   = false;
648
649     // new description for current character
650     TextAbstraction::FontDescription currentFontDescription;
651     TextAbstraction::PointSize26Dot6 currentFontPointSize = defaultFontPointSize;
652     bool                             isDefaultFont        = true;
653     MergeFontDescriptions(fontDescriptions,
654                           defaultFontDescription,
655                           defaultFontPointSize,
656                           fontSizeScale,
657                           index,
658                           currentFontDescription,
659                           currentFontPointSize,
660                           isDefaultFont);
661
662     // Get the font for the current character.
663     FontId fontId = fontClient.GetFontId(currentFontDescription, currentFontPointSize);
664     currentFontId = fontId;
665
666     // Get the script for the current character.
667     Script script = GetScript(index,
668                               scriptRunIt,
669                               scriptRunEndIt);
670
671 #ifdef DEBUG_ENABLED
672     if(gLogFilter->IsEnabledFor(Debug::Verbose))
673     {
674       Dali::TextAbstraction::FontDescription description;
675       fontClient.GetDescription(fontId, description);
676
677       DALI_LOG_INFO(gLogFilter,
678                     Debug::Verbose,
679                     "  Initial font set\n  Character : %x, Script : %s, Font : %s \n",
680                     character,
681                     Dali::TextAbstraction::ScriptName[script],
682                     description.path.c_str());
683     }
684 #endif
685
686     // Validate whether the current character is supported by the given font.
687     bool isValidFont = false;
688
689     // Check first in the cache of default fonts per script and size.
690
691     FontId        cachedDefaultFontId = 0u;
692     DefaultFonts* defaultFonts        = *(defaultFontPerScriptCacheBuffer + script);
693     if(NULL != defaultFonts)
694     {
695       // This cache stores fall-back fonts.
696       cachedDefaultFontId = defaultFonts->FindFont(fontClient,
697                                                    currentFontDescription,
698                                                    currentFontPointSize);
699     }
700
701     // Whether the cached default font is valid.
702     const bool isValidCachedDefaultFont = 0u != cachedDefaultFontId;
703
704     // The font is valid if it matches with the default one for the current script and size and it's different than zero.
705     isValidFont = isValidCachedDefaultFont && (fontId == cachedDefaultFontId);
706
707     if(isValidFont)
708     {
709       // Check if the font supports the character.
710       isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character);
711     }
712
713     bool isCommonScript = false;
714     bool isEmojiScript  = TextAbstraction::IsOneOfEmojiScripts(script);
715
716     if(isEmojiScript && (previousScript == script))
717     {
718       // Emoji sequence should use the previous emoji font.
719       if(0u != previousEmojiFontId)
720       {
721         fontId      = previousEmojiFontId;
722         isValidFont = true;
723       }
724     }
725
726     if(TextAbstraction::IsSpace(character) &&
727        TextAbstraction::HasLigatureMustBreak(script) &&
728        isValidCachedDefaultFont &&
729        (isDefaultFont || (currentFontId == previousFontId)))
730     {
731       fontId      = cachedDefaultFontId;
732       isValidFont = true;
733     }
734
735     // If the given font is not valid, it means either:
736     // - there is no cached font for the current script yet or,
737     // - the user has set a different font than the default one for the current script or,
738     // - the platform default font is different than the default font for the current script.
739
740     // Need to check if the given font supports the current character.
741     CheckFontSupportsCharacter(isValidFont, isCommonScript, character, validFontsPerScriptCacheBuffer, script, fontId, fontClient,
742                                isValidCachedDefaultFont, cachedDefaultFontId, currentFontDescription, currentFontPointSize, defaultFontPerScriptCacheBuffer);
743
744     if(isEmojiScript && (previousScript != script))
745     {
746       //New Emoji sequence should select font according to the variation selector (VS15 or VS16).
747       if(0u != currentFontRun.characterRun.numberOfCharacters)
748       {
749         // Store the font run.
750         fonts.Insert(fonts.Begin() + fontIndex, currentFontRun);
751         ++fontIndex;
752       }
753
754       // Initialize the new one.
755       currentFontRun.characterRun.characterIndex     = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters;
756       currentFontRun.characterRun.numberOfCharacters = 0u;
757       currentFontRun.fontId                          = fontId;
758       currentFontRun.isItalicRequired                = false;
759       currentFontRun.isBoldRequired                  = false;
760
761       if(TextAbstraction::IsEmojiColorScript(script) || TextAbstraction::IsEmojiTextScript(script))
762       {
763         bool       isModifiedByVariationSelector = false;
764         GlyphIndex glyphIndexChar                = fontClient.GetGlyphIndex(fontId, character);
765         GlyphIndex glyphIndexCharByVS            = fontClient.GetGlyphIndex(fontId, character, Text::GetVariationSelectorByScript(script));
766
767         isModifiedByVariationSelector = glyphIndexChar != glyphIndexCharByVS;
768
769         if(isModifiedByVariationSelector)
770         {
771           FontId requestedFontId = fontClient.FindDefaultFont(character, currentFontPointSize, IsEmojiColorScript(script));
772           if(0u != requestedFontId)
773           {
774             currentFontRun.fontId = fontId = requestedFontId;
775             isValidFont                    = true;
776           }
777         }
778       }
779     }
780
781     // Store the font id when the first character is an emoji.
782     if(isEmojiScript)
783     {
784       if(0u != fontId && previousScript != script)
785       {
786         previousEmojiFontId = fontId;
787       }
788     }
789     else
790     {
791       previousEmojiFontId = 0u;
792     }
793
794 #ifdef DEBUG_ENABLED
795     if(gLogFilter->IsEnabledFor(Debug::Verbose))
796     {
797       Dali::TextAbstraction::FontDescription description;
798       fontClient.GetDescription(fontId, description);
799       DALI_LOG_INFO(gLogFilter,
800                     Debug::Verbose,
801                     "  Validated font set\n  Character : %x, Script : %s, Font : %s \n",
802                     character,
803                     Dali::TextAbstraction::ScriptName[script],
804                     description.path.c_str());
805     }
806 #endif
807     if(!isValidFont && !isCommonScript)
808     {
809       Dali::TextAbstraction::FontDescription descriptionForLog;
810       fontClient.GetDescription(fontId, descriptionForLog);
811       DALI_LOG_RELEASE_INFO("Validated font set fail : Character : %x, Script : %s, Font : %s \n",
812                             character,
813                             Dali::TextAbstraction::ScriptName[script],
814                             descriptionForLog.path.c_str());
815     }
816
817     // Whether bols style is required.
818     isBoldRequired = (currentFontDescription.weight >= TextAbstraction::FontWeight::BOLD);
819
820     // Whether italic style is required.
821     isItalicRequired = (currentFontDescription.slant >= TextAbstraction::FontSlant::ITALIC);
822
823     // The font is now validated.
824     if((fontId != currentFontRun.fontId) ||
825        isNewParagraphCharacter ||
826        // If font id is same as previous but style is diffrent, initialize new one
827        ((fontId == currentFontRun.fontId) && ((isBoldRequired != currentFontRun.isBoldRequired) || (isItalicRequired != currentFontRun.isItalicRequired))))
828     {
829       // Current run needs to be stored and a new one initialized.
830
831       if(0u != currentFontRun.characterRun.numberOfCharacters)
832       {
833         // Store the font run.
834         fonts.Insert(fonts.Begin() + fontIndex, currentFontRun);
835         ++fontIndex;
836       }
837
838       // Initialize the new one.
839       currentFontRun.characterRun.characterIndex     = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters;
840       currentFontRun.characterRun.numberOfCharacters = 0u;
841       currentFontRun.fontId                          = fontId;
842       currentFontRun.isBoldRequired                  = isBoldRequired;
843       currentFontRun.isItalicRequired                = isItalicRequired;
844     }
845
846     // Add one more character to the run.
847     ++currentFontRun.characterRun.numberOfCharacters;
848
849     // Whether the current character is a new paragraph character.
850     isNewParagraphCharacter = TextAbstraction::IsNewParagraph(character);
851     previousScript          = script;
852     previousFontId          = currentFontId;
853   } // end traverse characters.
854
855   if(0u != currentFontRun.characterRun.numberOfCharacters)
856   {
857     // Store the last run.
858     fonts.Insert(fonts.Begin() + fontIndex, currentFontRun);
859     ++fontIndex;
860   }
861
862   if(fontIndex < fonts.Count())
863   {
864     // Update the indices of the next font runs.
865     const FontRun& run                = *(fonts.Begin() + fontIndex - 1u);
866     CharacterIndex nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters;
867
868     for(Vector<FontRun>::Iterator it    = fonts.Begin() + fontIndex,
869                                   endIt = fonts.End();
870         it != endIt;
871         ++it)
872     {
873       FontRun& run = *it;
874
875       run.characterRun.characterIndex = nextCharacterIndex;
876       nextCharacterIndex += run.characterRun.numberOfCharacters;
877     }
878   }
879
880   DALI_LOG_INFO(gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n");
881 }
882
883 void MultilanguageSupport::AddCurrentScriptAndCreatNewScript(const Script       requestedScript,
884                                                              const bool         isRightToLeft,
885                                                              const bool         addScriptCharactersToNewScript,
886                                                              ScriptRun&         currentScriptRun,
887                                                              Length&            numberOfAllScriptCharacters,
888                                                              Vector<ScriptRun>& scripts,
889                                                              ScriptRunIndex&    scriptIndex)
890 {
891   // Add the pending characters to the current script
892   currentScriptRun.characterRun.numberOfCharacters += (addScriptCharactersToNewScript ? 0u : numberOfAllScriptCharacters);
893
894   // In-case the current script is empty then no need to add it for scripts
895   if(0u != currentScriptRun.characterRun.numberOfCharacters)
896   {
897     // Store the script run.
898     scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun);
899     ++scriptIndex;
900   }
901
902   // Initialize the new one by the requested script
903   currentScriptRun.characterRun.characterIndex     = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters;
904   currentScriptRun.characterRun.numberOfCharacters = (addScriptCharactersToNewScript ? numberOfAllScriptCharacters : 0u);
905   currentScriptRun.script                          = requestedScript;
906   numberOfAllScriptCharacters                      = 0u;
907   // Initialize whether is right to left direction
908   currentScriptRun.isRightToLeft = isRightToLeft;
909 }
910
911 } // namespace Internal
912
913 } // namespace Text
914
915 } // namespace Toolkit
916
917 } // namespace Dali