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