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