Add text wrapping hyphen mode support
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / devel-api / text / text-utils-devel.cpp
1 /*
2  * Copyright (c) 2021 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 // FILE HEADER
19 #include <dali-toolkit/devel-api/text/text-utils-devel.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/scripting/enum-helper.h>
23 #include <dali/devel-api/text-abstraction/font-client.h>
24 #include <dali/devel-api/text-abstraction/text-renderer-layout-helper.h>
25 #include <dali/devel-api/text-abstraction/text-renderer.h>
26 #include <dali/integration-api/debug.h>
27 #include <cstring>
28 #include <limits>
29
30 // INTERNAL INCLUDES
31 #include <dali-toolkit/internal/text/bidirectional-support.h>
32 #include <dali-toolkit/internal/text/character-set-conversion.h>
33 #include <dali-toolkit/internal/text/color-segmentation.h>
34 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
35 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
36 #include <dali-toolkit/internal/text/markup-processor.h>
37 #include <dali-toolkit/internal/text/multi-language-support.h>
38 #include <dali-toolkit/internal/text/segmentation.h>
39 #include <dali-toolkit/internal/text/shaper.h>
40 #include <dali-toolkit/internal/text/text-enumerations-impl.h>
41 #include <dali-toolkit/internal/text/text-font-style.h>
42 #include <dali-toolkit/internal/text/text-model.h>
43
44 namespace Dali
45 {
46 using namespace TextAbstraction;
47
48 namespace Toolkit
49 {
50 using namespace Text;
51
52 namespace DevelText
53 {
54 namespace Layout
55 {
56 /**
57  * @brief The text's layout.
58  */
59 enum Type
60 {
61   SINGLELINE, ///< The text is laid out on a single line.
62   MULTILINE,  ///< The text is laid out in multiple lines.
63   CIRCULAR,   ///< The text is laid out on a single line following a circular path.
64 };
65
66 } // namespace Layout
67
68 namespace CircularAlignment
69 {
70 /**
71  * @brief The enumerations for the circular alignment.
72  */
73 enum Type
74 {
75   BEGIN,  ///< The text is aligned to the @p begin angle of the arc (or to the @p begin+increment if it's a RTL text).
76   CENTER, ///< The text is centered within the arc.
77   END,    ///< The text is aligned to the @p begin+increment angle of the arc (or to the @p begin if it's a RTL text).
78 };
79
80 } // namespace CircularAlignment
81
82 const float TO_POINT_26_DOT_6 = 64.f;
83 const float TO_FLOAT          = 1.f / 255.f;
84 const float TO_UCHAR          = 255.f;
85 const bool  RTL               = true;
86 const float TWO_PI            = 2.f * Dali::Math::PI;    ///< 360 degrees in radians
87 const float RAD_135           = Math::PI_2 + Math::PI_4; ///< 135 degrees in radians;
88 const float RAD_225           = RAD_135 + Math::PI_2;    ///< 225 degrees in radians;
89 const float RAD_270           = 3.f * Math::PI_2;        ///< 270 degrees in radians;
90 const float RAD_315           = RAD_225 + Math::PI_2;    ///< 315 degrees in radians;
91 const float MAX_INT           = std::numeric_limits<int>::max();
92
93 DALI_ENUM_TO_STRING_TABLE_BEGIN(LAYOUT_TYPE)
94   DALI_ENUM_TO_STRING_WITH_SCOPE(DevelText::Layout, SINGLELINE)
95   DALI_ENUM_TO_STRING_WITH_SCOPE(DevelText::Layout, MULTILINE)
96   DALI_ENUM_TO_STRING_WITH_SCOPE(DevelText::Layout, CIRCULAR)
97 DALI_ENUM_TO_STRING_TABLE_END(LAYOUT_TYPE)
98
99 DALI_ENUM_TO_STRING_TABLE_BEGIN(CIRCULAR_ALIGNMENT_TYPE)
100   DALI_ENUM_TO_STRING_WITH_SCOPE(DevelText::CircularAlignment, BEGIN)
101   DALI_ENUM_TO_STRING_WITH_SCOPE(DevelText::CircularAlignment, CENTER)
102   DALI_ENUM_TO_STRING_WITH_SCOPE(DevelText::CircularAlignment, END)
103 DALI_ENUM_TO_STRING_TABLE_END(CIRCULAR_ALIGNMENT_TYPE)
104
105 struct InternalDataModel
106 {
107   InternalDataModel(FontClient&    fontClient,
108                     MetricsPtr     metrics,
109                     Text::ModelPtr textModel)
110   : fontClient(fontClient),
111     metrics(metrics),
112     textModel(textModel),
113     numberOfCharacters{0u},
114     isTextMirrored{false},
115     numberOfGlyphs{0u}
116   {
117     layoutEngine.SetMetrics(metrics);
118   }
119
120   FontClient&               fontClient;
121   MetricsPtr                metrics;
122   Text::Layout::Engine      layoutEngine; ///< The layout engine.
123   Text::ModelPtr            textModel;    ///< Pointer to the text's model.
124   Vector<ColorBlendingMode> blendingMode; ///< How embedded items and bitmap font glyphs are blended with color text.
125   Vector<bool>              isEmoji;      ///< Whether the glyph is an emoji.
126
127   Vector<Character> mirroredUtf32Characters; // The utf32Characters Characters but mirrored if there are RTL text.
128
129   Length numberOfCharacters; // The number of characters (not glyphs!).
130   bool   isTextMirrored;     // Whether the text has been mirrored.
131
132   Length numberOfGlyphs;
133   Size   textLayoutArea;
134 };
135
136 bool GetLayoutEnumeration(const Property::Value& propertyValue, DevelText::Layout::Type& layout)
137 {
138   return Scripting::GetEnumerationProperty(propertyValue, LAYOUT_TYPE_TABLE, LAYOUT_TYPE_TABLE_COUNT, layout);
139 }
140
141 bool GetCircularAlignmentEnumeration(const Property::Value& propertyValue, DevelText::CircularAlignment::Type& circularAlignment)
142 {
143   return Scripting::GetEnumerationProperty(propertyValue, CIRCULAR_ALIGNMENT_TYPE_TABLE, CIRCULAR_ALIGNMENT_TYPE_TABLE_COUNT, circularAlignment);
144 }
145
146 void ShapeTextPreprocess(const RendererParameters& textParameters, TextAbstraction::TextRenderer::Parameters& rendererParameters, InternalDataModel& internalDataModel)
147 {
148   MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
149   const uint8_t*       utf8                 = NULL; // pointer to the first character of the text (encoded in utf8)
150   Length               textSize             = 0u;   // The length of the utf8 string.
151
152   Length&            numberOfCharacters      = internalDataModel.numberOfCharacters;
153   Vector<Character>& mirroredUtf32Characters = internalDataModel.mirroredUtf32Characters;
154   Text::ModelPtr&    textModel               = internalDataModel.textModel;
155
156   Vector<Character>&                     utf32Characters     = textModel->mLogicalModel->mText;                       // Characters encoded in utf32.
157   Vector<LineBreakInfo>&                 lineBreakInfo       = textModel->mLogicalModel->mLineBreakInfo;              // The line break info.
158   Vector<ScriptRun>&                     scripts             = textModel->mLogicalModel->mScriptRuns;                 // Charactes's script.
159   Vector<FontDescriptionRun>&            fontDescriptionRuns = textModel->mLogicalModel->mFontDescriptionRuns;        // Desired font descriptions.
160   Vector<FontRun>&                       validFonts          = textModel->mLogicalModel->mFontRuns;                   // Validated fonts.
161   Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo   = textModel->mLogicalModel->mBidirectionalParagraphInfo; // The bidirectional info per paragraph.
162   Vector<CharacterDirection>&            directions          = textModel->mLogicalModel->mCharacterDirections;        // Character's directions.
163   Vector<ColorRun>&                      colorRuns           = textModel->mLogicalModel->mColorRuns;                  // colors of the text.
164
165   // the default font's description.
166   FontDescription defaultFontDescription;
167   PointSize26Dot6 defaultPointSize = FontClient::DEFAULT_POINT_SIZE;
168
169   ////////////////////////////////////////////////////////////////////////////////
170   // Process the markup string if the mark-up processor is enabled.
171   ////////////////////////////////////////////////////////////////////////////////
172
173   MarkupProcessData markupProcessData(colorRuns,
174                                       fontDescriptionRuns,
175                                       textModel->mLogicalModel->mEmbeddedItems,
176                                       textModel->mLogicalModel->mAnchors,
177                                       textModel->mLogicalModel->mUnderlinedCharacterRuns);
178
179   if(textParameters.markupEnabled)
180   {
181     ProcessMarkupString(textParameters.text, markupProcessData);
182     textSize = markupProcessData.markupProcessedText.size();
183
184     // This is a bit horrible but std::string returns a (signed) char*
185     utf8 = reinterpret_cast<const uint8_t*>(markupProcessData.markupProcessedText.c_str());
186   }
187   else
188   {
189     textSize = textParameters.text.size();
190
191     // This is a bit horrible but std::string returns a (signed) char*
192     utf8 = reinterpret_cast<const uint8_t*>(textParameters.text.c_str());
193   }
194
195   ////////////////////////////////////////////////////////////////////////////////
196   // Convert from utf8 to utf32
197   ////////////////////////////////////////////////////////////////////////////////
198
199   utf32Characters.Resize(textSize);
200
201   // Transform a text array encoded in utf8 into an array encoded in utf32.
202   // It returns the actual number of characters.
203   numberOfCharacters = Utf8ToUtf32(utf8, textSize, utf32Characters.Begin());
204   utf32Characters.Resize(numberOfCharacters);
205
206   ////////////////////////////////////////////////////////////////////////////////
207   // Retrieve the Line and Word Break Info.
208   ////////////////////////////////////////////////////////////////////////////////
209
210   lineBreakInfo.Resize(numberOfCharacters, LINE_NO_BREAK);
211
212   SetLineBreakInfo(utf32Characters,
213                    0u,
214                    numberOfCharacters,
215                    lineBreakInfo);
216
217   ////////////////////////////////////////////////////////////////////////////////
218   // Retrieve the script runs.
219   ////////////////////////////////////////////////////////////////////////////////
220
221   multilanguageSupport.SetScripts(utf32Characters,
222                                   0u,
223                                   numberOfCharacters,
224                                   scripts);
225
226   // Check if there are emojis.
227   // If there are an RGBA8888 pixel format is needed.
228   for(const auto& run : scripts)
229   {
230     if(run.script == TextAbstraction::Script::EMOJI)
231     {
232       rendererParameters.pixelFormat = TextAbstraction::TextRenderer::Parameters::RGBA8888;
233       break;
234     }
235   }
236
237   ////////////////////////////////////////////////////////////////////////////////
238   // Retrieve the font runs.
239   ////////////////////////////////////////////////////////////////////////////////
240
241   // Set the description font run with the given text parameters.
242   FontDescriptionRun fontDescriptionRun;
243   fontDescriptionRun.characterRun.characterIndex     = 0u;
244   fontDescriptionRun.characterRun.numberOfCharacters = numberOfCharacters;
245
246   fontDescriptionRun.familyLength  = 0u;
247   fontDescriptionRun.familyName    = nullptr;
248   fontDescriptionRun.familyDefined = !textParameters.fontFamily.empty();
249   if(fontDescriptionRun.familyDefined)
250   {
251     // The allocated memory will be freed when the logical model is destroyed.
252     fontDescriptionRun.familyLength = textParameters.fontFamily.size();
253     fontDescriptionRun.familyName   = new char[fontDescriptionRun.familyLength];
254     memcpy(fontDescriptionRun.familyName, textParameters.fontFamily.c_str(), fontDescriptionRun.familyLength);
255   }
256
257   fontDescriptionRun.weightDefined = !textParameters.fontWeight.empty();
258   if(fontDescriptionRun.weightDefined)
259   {
260     fontDescriptionRun.weight = StringToWeight(textParameters.fontWeight.c_str());
261   }
262
263   fontDescriptionRun.widthDefined = !textParameters.fontWidth.empty();
264   if(fontDescriptionRun.widthDefined)
265   {
266     fontDescriptionRun.width = StringToWidth(textParameters.fontWidth.c_str());
267   }
268
269   fontDescriptionRun.slantDefined = !textParameters.fontSlant.empty();
270   if(fontDescriptionRun.slantDefined)
271   {
272     fontDescriptionRun.slant = StringToSlant(textParameters.fontSlant.c_str());
273   }
274
275   fontDescriptionRun.sizeDefined = !EqualsZero(textParameters.fontSize);
276   if(fontDescriptionRun.sizeDefined)
277   {
278     fontDescriptionRun.size = static_cast<unsigned int>(textParameters.fontSize * TO_POINT_26_DOT_6);
279   }
280
281   fontDescriptionRuns.PushBack(fontDescriptionRun);
282
283   // Validates the fonts. If there is a character with no assigned font it sets a default one.
284   // After this call, fonts are validated.
285   multilanguageSupport.ValidateFonts(utf32Characters,
286                                      scripts,
287                                      fontDescriptionRuns,
288                                      defaultFontDescription,
289                                      defaultPointSize,
290                                      0u,
291                                      numberOfCharacters,
292                                      validFonts);
293
294   ////////////////////////////////////////////////////////////////////////////////
295   // Retrieve the Bidirectional info.
296   ////////////////////////////////////////////////////////////////////////////////
297
298   bidirectionalInfo.Reserve(1u);
299
300   SetBidirectionalInfo(utf32Characters,
301                        scripts,
302                        lineBreakInfo,
303                        0u,
304                        numberOfCharacters,
305                        bidirectionalInfo);
306
307   const bool hasBidirectionalText = 0u != bidirectionalInfo.Count();
308   if(hasBidirectionalText)
309   {
310     // Only set the character directions if there is right to left characters.
311     GetCharactersDirection(bidirectionalInfo,
312                            numberOfCharacters,
313                            0u,
314                            numberOfCharacters,
315                            directions);
316
317     // This paragraph has right to left text. Some characters may need to be mirrored.
318     // TODO: consider if the mirrored string can be stored as well.
319
320     internalDataModel.isTextMirrored = GetMirroredText(utf32Characters,
321                                                        directions,
322                                                        bidirectionalInfo,
323                                                        0u,
324                                                        numberOfCharacters,
325                                                        mirroredUtf32Characters);
326   }
327 }
328
329 void ShapeText(TextAbstraction::TextRenderer::Parameters& rendererParameters, Vector<EmbeddedItemInfo>& embeddedItemLayout, InternalDataModel& internalDataModel)
330 {
331   Vector<GlyphIndex>           newParagraphGlyphs; // Glyphs for the new paragraph characters.
332   const Length                 numberOfCharacters      = internalDataModel.numberOfCharacters;
333   const bool                   isTextMirrored          = internalDataModel.isTextMirrored;
334   Text::ModelPtr&              textModel               = internalDataModel.textModel;
335   const Vector<Character>&     mirroredUtf32Characters = internalDataModel.mirroredUtf32Characters;
336   FontClient&                  fontClient              = internalDataModel.fontClient;
337   const Vector<Character>&     utf32Characters         = textModel->mLogicalModel->mText;          // Characters encoded in utf32.
338   const Vector<LineBreakInfo>& lineBreakInfo           = textModel->mLogicalModel->mLineBreakInfo; // The line break info.
339   const Vector<ScriptRun>&     scripts                 = textModel->mLogicalModel->mScriptRuns;    // Charactes's script.
340   const Vector<FontRun>&       validFonts              = textModel->mLogicalModel->mFontRuns;      // Validated fonts.
341
342   Vector<CharacterIndex>& glyphsToCharacters = textModel->mVisualModel->mGlyphsToCharacters; // Glyphs to character map.
343   Vector<Length>&         charactersPerGlyph = textModel->mVisualModel->mCharactersPerGlyph; // Number of characters per glyph.
344
345   ////////////////////////////////////////////////////////////////////////////////
346   // Retrieve the glyphs. Text shaping
347   ////////////////////////////////////////////////////////////////////////////////
348
349   const Vector<Character>& textToShape = isTextMirrored ? mirroredUtf32Characters : utf32Characters;
350
351   newParagraphGlyphs.Reserve(1u);
352
353   // Shapes the text.
354   ShapeText(textToShape,
355             lineBreakInfo,
356             scripts,
357             validFonts,
358             0u,
359             0u,
360             numberOfCharacters,
361             rendererParameters.glyphs,
362             glyphsToCharacters,
363             charactersPerGlyph,
364             newParagraphGlyphs);
365
366   // Create the 'number of glyphs' per character and the glyph to character conversion tables.
367   textModel->mVisualModel->CreateGlyphsPerCharacterTable(0u, 0u, numberOfCharacters);
368   textModel->mVisualModel->CreateCharacterToGlyphTable(0u, 0u, numberOfCharacters);
369
370   internalDataModel.numberOfGlyphs = rendererParameters.glyphs.Count();
371
372   // Once the text has been shaped and the glyphs created it's possible to replace the font id of those glyphs
373   // that represent an image or an item and create the embedded item layout info.
374   // Note: the position of the embedded item can't be set until the text is laid-out.
375   embeddedItemLayout.Reserve(textModel->mLogicalModel->mEmbeddedItems.Count());
376   for(const auto& item : textModel->mLogicalModel->mEmbeddedItems)
377   {
378     // Get the glyph that matches with the character index.
379     const GlyphIndex glyphIndex = textModel->mVisualModel->mCharactersToGlyph[item.characterIndex];
380     GlyphInfo&       glyph      = rendererParameters.glyphs[glyphIndex];
381
382     glyph.fontId                                                     = 0u;
383     Pixel::Format                                        pixelFormat = Pixel::A8;
384     TextAbstraction::FontClient::EmbeddedItemDescription description = {std::string(item.url, item.urlLength), item.width, item.height, item.colorBlendingMode};
385     glyph.index                                                      = fontClient.CreateEmbeddedItem(description, pixelFormat); // Set here an index to an item.
386
387     if((Pixel::RGBA8888 == pixelFormat) || (Pixel::BGRA8888 == pixelFormat))
388     {
389       rendererParameters.pixelFormat = TextAbstraction::TextRenderer::Parameters::RGBA8888;
390     }
391
392     // If the url is empty the item is going to be added after the text is rendered. It's needed to store the layout here.
393     if(description.url.empty())
394     {
395       EmbeddedItemInfo embeddedInfo =
396         {
397           item.characterIndex,
398           glyphIndex,
399           Vector2::ZERO,
400           Size(static_cast<float>(item.width), static_cast<float>(item.height)),
401           Size(static_cast<float>(item.width), static_cast<float>(item.height)),
402           Degree(0.f),
403           item.colorBlendingMode};
404
405       embeddedItemLayout.PushBack(embeddedInfo);
406     }
407   }
408 }
409
410 void SetColorSegmentation(const RendererParameters& textParameters, InternalDataModel& internalDataModel)
411 {
412   Text::ModelPtr&            textModel    = internalDataModel.textModel;
413   Vector<ColorBlendingMode>& blendingMode = internalDataModel.blendingMode;
414
415   Vector<ColorRun>& colorRuns = textModel->mLogicalModel->mColorRuns; // colors of the text.
416
417   Vector<GlyphIndex>& charactersToGlyph  = textModel->mVisualModel->mCharactersToGlyph;  // Characters to glyphs map.
418   Vector<Length>&     glyphsPerCharacter = textModel->mVisualModel->mGlyphsPerCharacter; // The number of glyphs that are shaped.
419
420   ////////////////////////////////////////////////////////////////////////////////
421   // Set the color runs in glyphs.
422   ////////////////////////////////////////////////////////////////////////////////
423
424   SetColorSegmentationInfo(colorRuns,
425                            charactersToGlyph,
426                            glyphsPerCharacter,
427                            0u,
428                            0u,
429                            internalDataModel.numberOfCharacters,
430                            textModel->mVisualModel->mColors,
431                            textModel->mVisualModel->mColorIndices);
432
433   // Insert the default color at the beginning of the vector.
434   textModel->mVisualModel->mColors.Insert(textModel->mVisualModel->mColors.Begin(), textParameters.textColor);
435
436   // Set how the embedded items are blended with text color.
437   blendingMode.Resize(internalDataModel.numberOfGlyphs, textParameters.isTextColorSet ? ColorBlendingMode::MULTIPLY : ColorBlendingMode::NONE);
438
439   if(!textParameters.isTextColorSet)
440   {
441     // Traverse the color runs.
442     for(const auto& run : colorRuns)
443     {
444       const GlyphIndex     firstGlyph       = textModel->mVisualModel->mCharactersToGlyph[run.characterRun.characterIndex];
445       const CharacterIndex lastCharacter    = run.characterRun.characterIndex + run.characterRun.numberOfCharacters - 1u;
446       const GlyphIndex     lastGlyphPlusOne = textModel->mVisualModel->mCharactersToGlyph[lastCharacter] + textModel->mVisualModel->mGlyphsPerCharacter[lastCharacter];
447
448       for(GlyphIndex index = firstGlyph; index < lastGlyphPlusOne; ++index)
449       {
450         blendingMode[index] = ColorBlendingMode::MULTIPLY;
451       }
452     }
453   }
454
455   // Traverse the embedded items and update the blending mode vector.
456   for(const auto& item : textModel->mLogicalModel->mEmbeddedItems)
457   {
458     const GlyphIndex glyphIndex = textModel->mVisualModel->mCharactersToGlyph[item.characterIndex];
459     blendingMode[glyphIndex]    = item.colorBlendingMode;
460   }
461 }
462
463 void SetEmojiVector(InternalDataModel& internalDataModel)
464 {
465   Vector<bool>&   isEmoji        = internalDataModel.isEmoji;
466   Text::ModelPtr& textModel      = internalDataModel.textModel;
467   const Length    numberOfGlyphs = internalDataModel.numberOfGlyphs;
468
469   const Vector<ScriptRun>& scripts = textModel->mLogicalModel->mScriptRuns; // Charactes's script.
470   ////////////////////////////////////////////////////////////////////////////////
471   // Set the isEmoji Vector
472   ////////////////////////////////////////////////////////////////////////////////
473
474   isEmoji.Resize(numberOfGlyphs, false);
475
476   for(const auto& run : scripts)
477   {
478     if(run.script == TextAbstraction::Script::EMOJI)
479     {
480       const GlyphIndex     firstGlyph       = textModel->mVisualModel->mCharactersToGlyph[run.characterRun.characterIndex];
481       const CharacterIndex lastCharacter    = run.characterRun.characterIndex + run.characterRun.numberOfCharacters - 1u;
482       const GlyphIndex     lastGlyphPlusOne = textModel->mVisualModel->mCharactersToGlyph[lastCharacter] + textModel->mVisualModel->mGlyphsPerCharacter[lastCharacter];
483
484       for(GlyphIndex index = firstGlyph; index < lastGlyphPlusOne; ++index)
485       {
486         isEmoji[index] = true;
487       }
488     }
489   }
490 }
491
492 void Align(const RendererParameters& textParameters, TextAbstraction::TextRenderer::Parameters& rendererParameters, Vector<EmbeddedItemInfo>& embeddedItemLayout, InternalDataModel& internalDataModel, const Size& newLayoutSize)
493 {
494   Text::Layout::Engine& layoutEngine       = internalDataModel.layoutEngine;
495   Text::ModelPtr&       textModel          = internalDataModel.textModel;
496   const Length          numberOfCharacters = internalDataModel.numberOfCharacters;
497   Size&                 textLayoutArea     = internalDataModel.textLayoutArea;
498
499   Vector<LineRun>& lines = textModel->mVisualModel->mLines; // The laid out lines.
500
501   ////////////////////////////////////////////////////////////////////////////////
502   // Align the text.
503   ////////////////////////////////////////////////////////////////////////////////
504
505   HorizontalAlignment::Type horizontalAlignment         = Toolkit::HorizontalAlignment::CENTER;
506   HorizontalAlignment::Type horizontalCircularAlignment = Toolkit::HorizontalAlignment::CENTER;
507   VerticalAlignment::Type   verticalAlignment           = VerticalAlignment::CENTER;
508   CircularAlignment::Type   circularAlignment           = CircularAlignment::BEGIN;
509
510   Layout::Type layout = Layout::SINGLELINE;
511
512   // Sets the alignment
513   Property::Value horizontalAlignmentStr(textParameters.horizontalAlignment);
514   GetHorizontalAlignmentEnumeration(horizontalAlignmentStr, horizontalAlignment);
515   horizontalCircularAlignment = horizontalAlignment;
516
517   Property::Value verticalAlignmentStr(textParameters.verticalAlignment);
518   GetVerticalAlignmentEnumeration(verticalAlignmentStr, verticalAlignment);
519
520   Property::Value circularAlignmentStr(textParameters.circularAlignment);
521   GetCircularAlignmentEnumeration(circularAlignmentStr, circularAlignment);
522
523   Property::Value layoutStr(textParameters.layout);
524   GetLayoutEnumeration(layoutStr, layout);
525
526   // Whether the layout is circular.
527   const bool isCircularTextLayout = (Layout::CIRCULAR == layout);
528   const bool isClockwise          = isCircularTextLayout && (0.f < textParameters.incrementAngle);
529
530   // Convert CircularAlignment to HorizontalAlignment.
531   if(isCircularTextLayout)
532   {
533     switch(circularAlignment)
534     {
535       case CircularAlignment::BEGIN:
536       {
537         horizontalCircularAlignment = Toolkit::HorizontalAlignment::BEGIN;
538         break;
539       }
540       case CircularAlignment::CENTER:
541       {
542         horizontalCircularAlignment = Toolkit::HorizontalAlignment::CENTER;
543         break;
544       }
545       case CircularAlignment::END:
546       {
547         horizontalCircularAlignment = Toolkit::HorizontalAlignment::END;
548         break;
549       }
550     }
551   }
552   textModel->mHorizontalAlignment = isCircularTextLayout ? horizontalCircularAlignment : horizontalAlignment;
553
554   // Retrieve the line of text to know the direction and the width. @todo multi-line
555   const LineRun& line = lines[0u];
556
557   if(isCircularTextLayout)
558   {
559     // Set the circular alignment.
560     rendererParameters.circularLayout = isClockwise ? TextRenderer::Parameters::CLOCKWISE : TextRenderer::Parameters::COUNTER_CLOCKWISE;
561
562     // Update the text's height to be used by the ellipsis code.
563     textLayoutArea.height = newLayoutSize.height;
564
565     // Set the size of the text laid out on a straight horizontal line.
566     rendererParameters.circularWidth  = static_cast<unsigned int>(newLayoutSize.width);
567     rendererParameters.circularHeight = static_cast<unsigned int>(newLayoutSize.height);
568
569     // Calculate the center of the circular text according the horizontal and vertical alingments and the radius.
570     switch(horizontalAlignment)
571     {
572       case HorizontalAlignment::BEGIN:
573       {
574         rendererParameters.centerX = static_cast<int>(textParameters.radius);
575         break;
576       }
577       case HorizontalAlignment::CENTER:
578       {
579         rendererParameters.centerX = static_cast<int>(textParameters.textWidth / 2u);
580         break;
581       }
582       case HorizontalAlignment::END:
583       {
584         rendererParameters.centerX = static_cast<int>(textParameters.textWidth) - static_cast<int>(textParameters.radius);
585         break;
586       }
587     }
588
589     switch(verticalAlignment)
590     {
591       case VerticalAlignment::TOP:
592       {
593         rendererParameters.centerY = static_cast<int>(textParameters.radius);
594         break;
595       }
596       case VerticalAlignment::CENTER:
597       {
598         rendererParameters.centerY = static_cast<int>(textParameters.textHeight / 2u);
599         break;
600       }
601       case VerticalAlignment::BOTTOM:
602       {
603         rendererParameters.centerY = static_cast<int>(textParameters.textHeight) - static_cast<int>(textParameters.radius);
604         break;
605       }
606     }
607
608     // Calculate the beginning angle according with the given horizontal alignment.
609     const bool isRTL = RTL == line.direction;
610
611     CircularAlignment::Type alignment = circularAlignment;
612     if(isRTL)
613     {
614       // Swap the alignment type if the line is right to left.
615       switch(alignment)
616       {
617         case CircularAlignment::BEGIN:
618         {
619           alignment = CircularAlignment::END;
620           break;
621         }
622         case CircularAlignment::CENTER:
623         {
624           // Nothing to do.
625           break;
626         }
627         case CircularAlignment::END:
628         {
629           alignment = CircularAlignment::BEGIN;
630           break;
631         }
632       }
633     }
634
635     float angleOffset = 0.f;
636
637     switch(alignment)
638     {
639       case CircularAlignment::BEGIN:
640       {
641         angleOffset = 0.f;
642         break;
643       }
644       case CircularAlignment::CENTER:
645       {
646         const bool  isNeg     = textParameters.incrementAngle < 0.f;
647         const float textWidth = static_cast<float>(rendererParameters.circularWidth);
648         angleOffset           = (isNeg ? -0.5f : 0.5f) * (textLayoutArea.width - textWidth) / static_cast<float>(rendererParameters.radius);
649         break;
650       }
651       case CircularAlignment::END:
652       {
653         const bool  isNeg     = textParameters.incrementAngle < 0.f;
654         const float textWidth = static_cast<float>(rendererParameters.circularWidth);
655         angleOffset           = (isNeg ? -1.f : 1.f) * (textLayoutArea.width - textWidth) / static_cast<float>(rendererParameters.radius);
656         break;
657       }
658     }
659
660     // Update the beginning angle with the calculated offset.
661     rendererParameters.beginAngle = Radian(Degree(textParameters.beginAngle)) + angleOffset;
662
663     // Set the vertical position of the glyphs.
664     for(auto& position : rendererParameters.positions)
665     {
666       position.y = 0.f;
667     }
668   }
669   else
670   {
671     // Calculate the vertical offset according with the given alignment.
672     float penY = 0.f;
673
674     switch(verticalAlignment)
675     {
676       case VerticalAlignment::TOP:
677       {
678         penY = line.ascender;
679         break;
680       }
681       case VerticalAlignment::CENTER:
682       {
683         penY = line.ascender + 0.5f * (textLayoutArea.height - (line.ascender - line.descender));
684         break;
685       }
686       case VerticalAlignment::BOTTOM:
687       {
688         penY = textLayoutArea.height;
689         break;
690       }
691     }
692
693     // Calculate the horizontal offset according with the given alignment.
694     float alignmentOffset = 0.f;
695     layoutEngine.Align(textLayoutArea,
696                        0u,
697                        numberOfCharacters,
698                        horizontalAlignment,
699                        lines,
700                        alignmentOffset,
701                        Dali::LayoutDirection::LEFT_TO_RIGHT,
702                        false);
703
704     // Update the position of the glyphs with the calculated offsets.
705     for(auto& position : rendererParameters.positions)
706     {
707       position.x += line.alignmentOffset;
708       position.y = penY;
709     }
710   }
711
712   // Cairo adds the bearing to the position of the glyph
713   // that has already been added by the DALi's layout engine,
714   // so it's needed to be removed here.
715   for(unsigned int index = 0u; index < rendererParameters.glyphs.Count(); ++index)
716   {
717     const GlyphInfo& glyph    = rendererParameters.glyphs[index];
718     Vector2&         position = rendererParameters.positions[index];
719
720     position.x -= glyph.xBearing;
721   }
722
723   // Set the position of the embedded items (if there is any).
724   EmbeddedItemInfo* embeddedItemLayoutBuffer = embeddedItemLayout.Begin();
725
726   for(Length index = 0u, endIndex = embeddedItemLayout.Count(); index < endIndex; ++index)
727   {
728     EmbeddedItemInfo& embeddedItem = *(embeddedItemLayoutBuffer + index);
729
730     embeddedItem.position = rendererParameters.positions[embeddedItem.glyphIndex];
731
732     if(isCircularTextLayout)
733     {
734       // Calculate the new position of the embedded item in the circular path.
735
736       // Center of the bitmap.
737       const float halfWidth  = 0.5f * embeddedItem.size.width;
738       const float halfHeight = 0.5f * embeddedItem.size.height;
739       double      centerX    = static_cast<double>(embeddedItem.position.x + halfWidth);
740       double      centerY    = static_cast<double>(embeddedItem.position.y - halfHeight);
741
742       Dali::TextAbstraction::CircularTextParameters circularTextParameters;
743
744       circularTextParameters.radius     = static_cast<double>(rendererParameters.radius);
745       circularTextParameters.invRadius  = 1.0 / circularTextParameters.radius;
746       circularTextParameters.beginAngle = static_cast<double>(-rendererParameters.beginAngle + Dali::Math::PI_2);
747       circularTextParameters.centerX    = 0.5f * static_cast<double>(textParameters.textWidth);
748       circularTextParameters.centerY    = 0.5f * static_cast<double>(textParameters.textHeight);
749
750       // Calculate the rotation angle.
751       float radians = rendererParameters.beginAngle;
752       if(isClockwise)
753       {
754         radians += static_cast<float>(circularTextParameters.invRadius * centerX);
755         radians = -radians;
756       }
757       else
758       {
759         radians -= static_cast<float>(circularTextParameters.invRadius * centerX);
760         radians = -radians + Dali::Math::PI;
761       }
762       embeddedItem.angle = Degree(Radian(radians));
763
764       Dali::TextAbstraction::TransformToArc(circularTextParameters, centerX, centerY);
765
766       // Recalculate the size of the embedded item after the rotation to position it correctly.
767       float width  = embeddedItem.size.width;
768       float height = embeddedItem.size.height;
769
770       // Transform the input angle into the range [0..2PI]
771       radians = fmod(radians, TWO_PI);
772       radians += (radians < 0.f) ? TWO_PI : 0.f;
773
774       // Does the same operations than rotate by shear.
775       if((radians > Math::PI_4) && (radians <= RAD_135))
776       {
777         std::swap(width, height);
778         radians -= Math::PI_2;
779       }
780       else if((radians > RAD_135) && (radians <= RAD_225))
781       {
782         radians -= Math::PI;
783       }
784       else if((radians > RAD_225) && (radians <= RAD_315))
785       {
786         std::swap(width, height);
787         radians -= RAD_270;
788       }
789
790       if(fabs(radians) > Dali::Math::MACHINE_EPSILON_10)
791       {
792         const float angleSinus   = fabs(sin(radians));
793         const float angleCosinus = cos(radians);
794
795         // Calculate the rotated image dimensions.
796         embeddedItem.rotatedSize.height = width * angleSinus + height * angleCosinus;
797         embeddedItem.rotatedSize.width  = height * angleSinus + width * angleCosinus + 1.f;
798       }
799
800       embeddedItem.position.x = floor(static_cast<float>(centerX) - 0.5f * embeddedItem.rotatedSize.width);
801       embeddedItem.position.y = floor(static_cast<float>(centerY) - 0.5f * embeddedItem.rotatedSize.height);
802     }
803     else
804     {
805       embeddedItem.position.y -= embeddedItem.size.height;
806     }
807   }
808 }
809
810 void Ellipsis(const RendererParameters& textParameters, TextAbstraction::TextRenderer::Parameters& rendererParameters, Vector<EmbeddedItemInfo>& embeddedItemLayout, InternalDataModel& internalDataModel)
811 {
812   Text::ModelPtr& textModel  = internalDataModel.textModel;
813   FontClient&     fontClient = internalDataModel.fontClient;
814
815   Vector<LineRun>& lines          = textModel->mVisualModel->mLines; // The laid out lines.
816   Vector<bool>&    isEmoji        = internalDataModel.isEmoji;
817   const Size       textLayoutArea = internalDataModel.textLayoutArea;
818   ////////////////////////////////////////////////////////////////////////////////
819   // Ellipsis the text.
820   ////////////////////////////////////////////////////////////////////////////////
821
822   if(textParameters.ellipsisEnabled)
823   {
824     const LineRun& line = lines[0u]; // TODO: multi-line
825
826     if(line.ellipsis)
827     {
828       Length finalNumberOfGlyphs = 0u;
829
830       if((line.ascender - line.descender) > textLayoutArea.height)
831       {
832         // The height of the line is bigger than the height of the text area.
833         // Show the ellipsis glyph even if it doesn't fit in the text area.
834         // If no text is rendered then issues are rised and it may be a while
835         // until is find out that the text area is too small.
836
837         // Get the first glyph which is going to be replaced and the ellipsis glyph.
838         GlyphInfo&       glyphInfo     = rendererParameters.glyphs[0u];
839         const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph(fontClient.GetPointSize(glyphInfo.fontId));
840
841         // Change the 'x' and 'y' position of the ellipsis glyph.
842         Vector2& position = rendererParameters.positions[0u];
843         position.x        = ellipsisGlyph.xBearing;
844         position.y        = textLayoutArea.height - ellipsisGlyph.yBearing;
845
846         // Replace the glyph by the ellipsis glyph.
847         glyphInfo = ellipsisGlyph;
848
849         // Set the final number of glyphs
850         finalNumberOfGlyphs = 1u;
851       }
852       else
853       {
854         // firstPenX, penY and firstPenSet are used to position the ellipsis glyph if needed.
855         float firstPenX   = 0.f; // Used if rtl text is elided.
856         bool  firstPenSet = false;
857
858         // Add the ellipsis glyph.
859         bool   inserted              = false;
860         float  removedGlypsWidth     = 0.f;
861         Length numberOfRemovedGlyphs = 0u;
862         if(line.glyphRun.numberOfGlyphs > 0u)
863         {
864           GlyphIndex index = line.glyphRun.numberOfGlyphs - 1u;
865
866           GlyphInfo* glyphs         = rendererParameters.glyphs.Begin();
867           Vector2*   glyphPositions = rendererParameters.positions.Begin();
868
869           float penY = 0.f;
870
871           // The ellipsis glyph has to fit in the place where the last glyph(s) is(are) removed.
872           while(!inserted)
873           {
874             const GlyphInfo& glyphToRemove = *(glyphs + index);
875
876             if(0u != glyphToRemove.fontId)
877             {
878               // i.e. The font id of the glyph shaped from the '\n' character is zero.
879
880               // Need to reshape the glyph as the font may be different in size.
881               const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph(fontClient.GetPointSize(glyphToRemove.fontId));
882
883               if(!firstPenSet)
884               {
885                 const Vector2& position = *(glyphPositions + index);
886
887                 // Calculates the penY of the current line. It will be used to position the ellipsis glyph.
888                 penY = position.y;
889
890                 // Calculates the first penX which will be used if rtl text is elided.
891                 firstPenX = position.x - glyphToRemove.xBearing;
892                 if(firstPenX < -ellipsisGlyph.xBearing)
893                 {
894                   // Avoids to exceed the bounding box when rtl text is elided.
895                   firstPenX = -ellipsisGlyph.xBearing;
896                 }
897
898                 removedGlypsWidth = -ellipsisGlyph.xBearing;
899
900                 firstPenSet = true;
901               }
902
903               removedGlypsWidth += std::min(glyphToRemove.advance, (glyphToRemove.xBearing + glyphToRemove.width));
904
905               // Calculate the width of the ellipsis glyph and check if it fits.
906               const float ellipsisGlyphWidth = ellipsisGlyph.width + ellipsisGlyph.xBearing;
907               if(ellipsisGlyphWidth < removedGlypsWidth)
908               {
909                 GlyphInfo& glyphInfo = *(glyphs + index);
910                 Vector2&   position  = *(glyphPositions + index);
911                 position.x -= (0.f > glyphInfo.xBearing) ? glyphInfo.xBearing : 0.f;
912
913                 // Replace the glyph by the ellipsis glyph.
914                 glyphInfo = ellipsisGlyph;
915
916                 // Update the isEmoji vector
917                 isEmoji[index] = false;
918
919                 // Change the 'x' and 'y' position of the ellipsis glyph.
920
921                 if(position.x > firstPenX)
922                 {
923                   position.x = firstPenX + removedGlypsWidth - ellipsisGlyphWidth;
924                 }
925
926                 position.x += ellipsisGlyph.xBearing;
927                 position.y = penY;
928
929                 inserted = true;
930               }
931             }
932
933             if(!inserted)
934             {
935               if(index > 0u)
936               {
937                 --index;
938               }
939               else
940               {
941                 // No space for the ellipsis.
942                 inserted = true;
943               }
944               ++numberOfRemovedGlyphs;
945             }
946
947             // Set the final number of glyphs
948             finalNumberOfGlyphs = line.glyphRun.numberOfGlyphs - numberOfRemovedGlyphs;
949           }
950         }
951
952         // Resize the number of glyphs/positions
953         rendererParameters.glyphs.Resize(finalNumberOfGlyphs);
954         rendererParameters.positions.Resize(finalNumberOfGlyphs);
955
956         // Remove from the embedded items those exceding the last laid out glyph.
957         embeddedItemLayout.Erase(std::remove_if(embeddedItemLayout.Begin(),
958                                                 embeddedItemLayout.End(),
959                                                 [finalNumberOfGlyphs](const EmbeddedItemInfo& item) {
960                                                   return item.glyphIndex >= finalNumberOfGlyphs;
961                                                 }),
962                                  embeddedItemLayout.End());
963       }
964     }
965   }
966 }
967
968 Size LayoutText(const RendererParameters& textParameters, TextAbstraction::TextRenderer::Parameters& rendererParameters, Vector<EmbeddedItemInfo>& embeddedItemLayout, InternalDataModel& internalDataModel)
969 {
970   ////////////////////////////////////////////////////////////////////////////////
971   // Layout the text.
972   ////////////////////////////////////////////////////////////////////////////////
973   Text::ModelPtr&          textModel               = internalDataModel.textModel;
974   Text::Layout::Engine&    layoutEngine            = internalDataModel.layoutEngine;
975   FontClient&              fontClient              = internalDataModel.fontClient;
976   const Length             numberOfGlyphs          = internalDataModel.numberOfGlyphs;
977   const bool               isTextMirrored          = internalDataModel.isTextMirrored;
978   const Vector<Character>& mirroredUtf32Characters = internalDataModel.mirroredUtf32Characters;
979   const Length             numberOfCharacters      = internalDataModel.numberOfCharacters;
980
981   Layout::Type layout = Layout::SINGLELINE;
982
983   Property::Value layoutStr(textParameters.layout);
984   GetLayoutEnumeration(layoutStr, layout);
985
986   // Whether the layout is multi-line.
987   const Text::Layout::Engine::Type horizontalLayout = (Layout::MULTILINE == layout) ? Text::Layout::Engine::MULTI_LINE_BOX : Text::Layout::Engine::SINGLE_LINE_BOX;
988   layoutEngine.SetLayout(horizontalLayout); // TODO: multi-line.
989
990   // Set minimun line size
991   layoutEngine.SetDefaultLineSize(textParameters.minLineSize);
992
993   // Whether the layout is circular.
994   const bool isCircularTextLayout = (Layout::CIRCULAR == layout);
995   const bool isClockwise          = isCircularTextLayout && (0.f < textParameters.incrementAngle);
996
997   // Calculates the max ascender or the max descender.
998   // Is used to calculate the radius of the base line of the text.
999   float maxAscenderDescender = 0.f;
1000   if(isCircularTextLayout)
1001   {
1002     FontId currentFontId = 0u;
1003     for(const auto& glyph : rendererParameters.glyphs)
1004     {
1005       if(currentFontId != glyph.fontId)
1006       {
1007         currentFontId = glyph.fontId;
1008         FontMetrics metrics;
1009         fontClient.GetFontMetrics(currentFontId, metrics);
1010         maxAscenderDescender = std::max(maxAscenderDescender, isClockwise ? metrics.ascender : metrics.descender);
1011       }
1012     }
1013   }
1014   const unsigned int radius = textParameters.radius - static_cast<unsigned int>(maxAscenderDescender);
1015
1016   // Set the layout parameters.
1017   Size textLayoutArea = Size(static_cast<float>(textParameters.textWidth),
1018                              static_cast<float>(textParameters.textHeight));
1019
1020   // padding
1021   Extents padding                  = textParameters.padding;
1022   internalDataModel.textLayoutArea = Size(textLayoutArea.x - (padding.start + padding.end), textLayoutArea.y - (padding.top + padding.bottom));
1023
1024   if(isCircularTextLayout)
1025   {
1026     // In a circular layout, the length of the text area depends on the radius.
1027     rendererParameters.radius              = radius;
1028     internalDataModel.textLayoutArea.width = fabs(Radian(Degree(textParameters.incrementAngle)) * static_cast<float>(rendererParameters.radius));
1029   }
1030   // Resize the vector of positions to have the same size than the vector of glyphs.
1031   rendererParameters.positions.Resize(numberOfGlyphs);
1032
1033   textModel->mLineWrapMode                 = Text::LineWrap::WORD;
1034   textModel->mIgnoreSpacesAfterText        = false;
1035   textModel->mMatchSystemLanguageDirection = false;
1036   Text::Layout::Parameters layoutParameters(internalDataModel.textLayoutArea,
1037                                             textModel);
1038
1039   // Whether the last character is a new paragraph character.
1040   const Vector<Character>& textToShape = isTextMirrored ? mirroredUtf32Characters : textModel->mLogicalModel->mText;
1041   layoutParameters.isLastNewParagraph  = TextAbstraction::IsNewParagraph(textToShape[numberOfCharacters - 1u]);
1042
1043   // The initial glyph and the number of glyphs to layout.
1044   layoutParameters.startGlyphIndex        = 0u;
1045   layoutParameters.numberOfGlyphs         = numberOfGlyphs;
1046   layoutParameters.startLineIndex         = 0u;
1047   layoutParameters.estimatedNumberOfLines = 1u;
1048   layoutParameters.interGlyphExtraAdvance = 0.f;
1049
1050   // Update the visual model.
1051   Size newLayoutSize;
1052   bool isAutoScrollEnabled = false;
1053   layoutEngine.LayoutText(layoutParameters,
1054                           newLayoutSize,
1055                           textParameters.ellipsisEnabled,
1056                           isAutoScrollEnabled);
1057
1058   return newLayoutSize;
1059 }
1060
1061 Devel::PixelBuffer RenderText(const RendererParameters& textParameters, TextAbstraction::TextRenderer::Parameters& rendererParameters)
1062 {
1063   ////////////////////////////////////////////////////////////////////////////////
1064   // Render the text.
1065   ////////////////////////////////////////////////////////////////////////////////
1066
1067   rendererParameters.width  = textParameters.textWidth;
1068   rendererParameters.height = textParameters.textHeight;
1069
1070   TextAbstraction::TextRenderer renderer = TextAbstraction::TextRenderer::Get();
1071   return renderer.Render(rendererParameters);
1072 }
1073
1074 Devel::PixelBuffer Render(const RendererParameters& textParameters, Vector<EmbeddedItemInfo>& embeddedItemLayout)
1075 {
1076   if(textParameters.text.empty())
1077   {
1078     Dali::Devel::PixelBuffer pixelBuffer = Dali::Devel::PixelBuffer::New(textParameters.textWidth,
1079                                                                          textParameters.textHeight,
1080                                                                          Dali::Pixel::RGBA8888);
1081
1082     const unsigned int bufferSize = textParameters.textWidth * textParameters.textHeight * Dali::Pixel::GetBytesPerPixel(Dali::Pixel::RGBA8888);
1083     unsigned char*     buffer     = pixelBuffer.GetBuffer();
1084     memset(buffer, 0, bufferSize);
1085
1086     return pixelBuffer;
1087   }
1088
1089   FontClient fontClient = FontClient::Get();
1090   MetricsPtr metrics;
1091   // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
1092   metrics = Metrics::New(fontClient);
1093
1094   Text::ModelPtr    textModel = Text::Model::New();
1095   InternalDataModel internalData(fontClient, metrics, textModel);
1096
1097   TextAbstraction::TextRenderer::Parameters rendererParameters(internalData.textModel->mVisualModel->mGlyphs,
1098                                                                internalData.textModel->mVisualModel->mGlyphPositions,
1099                                                                internalData.textModel->mVisualModel->mColors,
1100                                                                internalData.textModel->mVisualModel->mColorIndices,
1101                                                                internalData.blendingMode,
1102                                                                internalData.isEmoji);
1103
1104   rendererParameters.width       = textParameters.textWidth;
1105   rendererParameters.height      = textParameters.textHeight;
1106   rendererParameters.pixelFormat = TextAbstraction::TextRenderer::Parameters::RGBA8888; // @note: At the moment all textures are generated RGBA8888
1107
1108   ////////////////////////////////////////////////////////////////////////////////
1109   // Process the markup string if the mark-up processor is enabled.
1110   ////////////////////////////////////////////////////////////////////////////////
1111   ShapeTextPreprocess(textParameters, rendererParameters, internalData);
1112
1113   ////////////////////////////////////////////////////////////////////////////////
1114   // Retrieve the glyphs. Text shaping
1115   ////////////////////////////////////////////////////////////////////////////////
1116   ShapeText(rendererParameters, embeddedItemLayout, internalData);
1117
1118   ////////////////////////////////////////////////////////////////////////////////
1119   // Retrieve the glyph's metrics.
1120   ////////////////////////////////////////////////////////////////////////////////
1121
1122   metrics->GetGlyphMetrics(rendererParameters.glyphs.Begin(), internalData.numberOfGlyphs);
1123
1124   ////////////////////////////////////////////////////////////////////////////////
1125   // Set the color runs in glyphs.
1126   ////////////////////////////////////////////////////////////////////////////////
1127   SetColorSegmentation(textParameters, internalData);
1128
1129   ////////////////////////////////////////////////////////////////////////////////
1130   // Set the isEmoji Vector
1131   ////////////////////////////////////////////////////////////////////////////////
1132   SetEmojiVector(internalData);
1133
1134   ////////////////////////////////////////////////////////////////////////////////
1135   // Layout the text
1136   ////////////////////////////////////////////////////////////////////////////////
1137   Size newLayoutSize = LayoutText(textParameters, rendererParameters, embeddedItemLayout, internalData);
1138
1139   ////////////////////////////////////////////////////////////////////////////////
1140   // Align the text.
1141   ////////////////////////////////////////////////////////////////////////////////
1142   Align(textParameters, rendererParameters, embeddedItemLayout, internalData, newLayoutSize);
1143
1144   ////////////////////////////////////////////////////////////////////////////////
1145   // Ellipsis the text.
1146   ////////////////////////////////////////////////////////////////////////////////
1147   Ellipsis(textParameters, rendererParameters, embeddedItemLayout, internalData);
1148
1149   ////////////////////////////////////////////////////////////////////////////////
1150   // Render the text.
1151   ////////////////////////////////////////////////////////////////////////////////
1152   return RenderText(textParameters, rendererParameters);
1153 }
1154
1155 Devel::PixelBuffer CreateShadow(const ShadowParameters& shadowParameters)
1156 {
1157   // The size of the pixel data.
1158   const int width  = static_cast<int>(shadowParameters.input.GetWidth());
1159   const int height = static_cast<int>(shadowParameters.input.GetHeight());
1160
1161   // The shadow's offset.
1162   const int xOffset = static_cast<int>(shadowParameters.offset.x);
1163   const int yOffset = static_cast<int>(shadowParameters.offset.y);
1164
1165   // The size in bytes of the pixel of the input's buffer.
1166   const Pixel::Format inputFormat    = shadowParameters.input.GetPixelFormat();
1167   const unsigned int  inputPixelSize = Pixel::GetBytesPerPixel(inputFormat);
1168   const bool          isA8           = Pixel::A8 == inputFormat;
1169
1170   // Creates the output pixel buffer.
1171   Devel::PixelBuffer outputPixelBuffer = Devel::PixelBuffer::New(width, height, Pixel::RGBA8888);
1172
1173   // Clear the output buffer
1174   unsigned char* outputPixelBufferPtr = outputPixelBuffer.GetBuffer();
1175   memset(outputPixelBufferPtr, 0, width * height * Pixel::GetBytesPerPixel(Pixel::RGBA8888));
1176
1177   // Gets the buffer of the input pixel buffer.
1178   const unsigned char* const inputPixelBuffer = shadowParameters.input.GetBuffer();
1179
1180   float textColor[4u];
1181   if(isA8)
1182   {
1183     memcpy(textColor, shadowParameters.textColor.AsFloat(), 4u * sizeof(float));
1184   }
1185   const float* const shadowColor = shadowParameters.color.AsFloat();
1186
1187   // Traverse the input pixel buffer and write the text on the foreground and the shadow on the background.
1188   for(int rowIndex = 0; rowIndex < height; ++rowIndex)
1189   {
1190     // Calculates the rowIndex to the input pixel buffer for the shadow and whether it's within the boundaries.
1191     const int  yOffsetIndex    = rowIndex - yOffset;
1192     const bool isValidRowIndex = ((yOffsetIndex >= 0) && (yOffsetIndex < height));
1193
1194     const int rows       = rowIndex * width;
1195     const int offsetRows = yOffsetIndex * width;
1196     for(int columnIndex = 0; columnIndex < width; ++columnIndex)
1197     {
1198       // Index to the input buffer to retrieve the alpha value of the foreground text.
1199       const unsigned int index = inputPixelSize * static_cast<unsigned int>(rows + columnIndex);
1200
1201       // Build the index to the input buffer to retrieve the alpha value of the background shadow.
1202       unsigned int shadowIndex        = 0u;
1203       bool         isValidShadowIndex = false;
1204       if(isValidRowIndex)
1205       {
1206         const int xOffsetIndex = columnIndex - xOffset;
1207         isValidShadowIndex     = ((xOffsetIndex >= 0) && (xOffsetIndex < width));
1208
1209         if(isValidShadowIndex)
1210         {
1211           shadowIndex = inputPixelSize * static_cast<unsigned int>(offsetRows + xOffsetIndex);
1212         }
1213       }
1214
1215       // If the input buffer is an alpha mask, retrieve the values for the foreground text and the background shadow.
1216       // If not retrieve the color.
1217       float inputShadowOffsetAlphaValue = 1.f;
1218       float inputAlphaValue             = 1.f;
1219       if(isA8)
1220       {
1221         // Retrieve the alpha value for the shadow.
1222         inputShadowOffsetAlphaValue = isValidShadowIndex ? (static_cast<float>(*(inputPixelBuffer + shadowIndex)) / 255.f) : 0.f;
1223
1224         // Retrieve the alpha value for the text.
1225         inputAlphaValue = static_cast<float>(*(inputPixelBuffer + index)) / 255.f;
1226       }
1227       else
1228       {
1229         // The input buffer is not an alpha mask. Retrieve the color.
1230         textColor[0u]               = TO_FLOAT * static_cast<float>(*(inputPixelBuffer + index + 0u));
1231         textColor[1u]               = TO_FLOAT * static_cast<float>(*(inputPixelBuffer + index + 1u));
1232         textColor[2u]               = TO_FLOAT * static_cast<float>(*(inputPixelBuffer + index + 2u));
1233         textColor[3u]               = TO_FLOAT * static_cast<float>(*(inputPixelBuffer + index + 3u));
1234         inputAlphaValue             = textColor[3u];
1235         inputShadowOffsetAlphaValue = isValidShadowIndex ? TO_FLOAT * static_cast<float>(*(inputPixelBuffer + shadowIndex + 3u)) : 0.f;
1236       }
1237
1238       // Build the output color.
1239       float outputColor[4u];
1240
1241       if(shadowParameters.blendShadow)
1242       {
1243         // Blend the shadow's color with the text's color on top
1244         const float textAlpha   = textColor[3u] * inputAlphaValue;
1245         const float shadowAlpha = shadowColor[3u] * inputShadowOffsetAlphaValue;
1246
1247         // Blends the alpha.
1248         outputColor[3u]              = 1.f - ((1.f - textAlpha) * (1.f - shadowAlpha));
1249         const bool isOutputAlphaZero = outputColor[3u] < Dali::Math::MACHINE_EPSILON_1000;
1250         if(isOutputAlphaZero)
1251         {
1252           std::fill(outputColor, outputColor + 4u, 0.f);
1253         }
1254         else
1255         {
1256           // Blends the RGB components.
1257           float shadowComponent = 0.f;
1258           float textComponent   = 0.f;
1259
1260           shadowComponent = shadowColor[0u] * inputShadowOffsetAlphaValue;
1261           textComponent   = textColor[0u] * inputAlphaValue;
1262           outputColor[0u] = (textComponent * textAlpha / outputColor[3u]) + (shadowComponent * shadowAlpha * (1.f - textAlpha) / outputColor[3u]);
1263
1264           shadowComponent = shadowColor[1u] * inputShadowOffsetAlphaValue;
1265           textComponent   = textColor[1u] * inputAlphaValue;
1266           outputColor[1u] = (textComponent * textAlpha / outputColor[3u]) + (shadowComponent * shadowAlpha * (1.f - textAlpha) / outputColor[3u]);
1267
1268           shadowComponent = shadowColor[2u] * inputShadowOffsetAlphaValue;
1269           textComponent   = textColor[2u] * inputAlphaValue;
1270           outputColor[2u] = (textComponent * textAlpha / outputColor[3u]) + (shadowComponent * shadowAlpha * (1.f - textAlpha) / outputColor[3u]);
1271         }
1272       }
1273       else
1274       {
1275         // No blending!!!
1276         std::fill(outputColor, outputColor + 4u, 0.f);
1277
1278         const float textAlpha   = textColor[3u];
1279         const float shadowAlpha = shadowColor[3u] * inputShadowOffsetAlphaValue;
1280
1281         // Write shadow first.
1282         if(shadowAlpha > Dali::Math::MACHINE_EPSILON_1000)
1283         {
1284           outputColor[0u] = shadowColor[0u] * inputShadowOffsetAlphaValue;
1285           outputColor[1u] = shadowColor[1u] * inputShadowOffsetAlphaValue;
1286           outputColor[2u] = shadowColor[2u] * inputShadowOffsetAlphaValue;
1287           outputColor[3u] = shadowAlpha;
1288         }
1289
1290         // Write character on top.
1291         if(textAlpha > Dali::Math::MACHINE_EPSILON_1000)
1292         {
1293           outputColor[0u] = textColor[0u];
1294           outputColor[1u] = textColor[1u];
1295           outputColor[2u] = textColor[2u];
1296           outputColor[3u] = textAlpha;
1297         }
1298       }
1299
1300       // Write the color into the output pixel buffer.
1301       const unsigned int outputIndex             = 4u * (rows + columnIndex);
1302       *(outputPixelBufferPtr + outputIndex + 0u) = static_cast<unsigned char>(TO_UCHAR * outputColor[0u]);
1303       *(outputPixelBufferPtr + outputIndex + 1u) = static_cast<unsigned char>(TO_UCHAR * outputColor[1u]);
1304       *(outputPixelBufferPtr + outputIndex + 2u) = static_cast<unsigned char>(TO_UCHAR * outputColor[2u]);
1305       *(outputPixelBufferPtr + outputIndex + 3u) = static_cast<unsigned char>(TO_UCHAR * outputColor[3u]);
1306     }
1307   }
1308
1309   // Returns the pixel buffer.
1310   return outputPixelBuffer;
1311 }
1312
1313 Devel::PixelBuffer ConvertToRgba8888(Devel::PixelBuffer pixelBuffer, const Vector4& color, bool multiplyByAlpha)
1314 {
1315   if(Dali::Pixel::A8 != pixelBuffer.GetPixelFormat())
1316   {
1317     // Does nothing.
1318     return pixelBuffer;
1319   }
1320
1321   const unsigned int width          = pixelBuffer.GetWidth();
1322   const unsigned int height         = pixelBuffer.GetHeight();
1323   Devel::PixelBuffer newPixelBuffer = Devel::PixelBuffer::New(width, height, Dali::Pixel::RGBA8888);
1324
1325   unsigned char*             dstBuffer = newPixelBuffer.GetBuffer();
1326   const unsigned char* const srcBuffer = pixelBuffer.GetBuffer();
1327
1328   const unsigned char r = static_cast<unsigned char>(TO_UCHAR * color.r);
1329   const unsigned char g = static_cast<unsigned char>(TO_UCHAR * color.g);
1330   const unsigned char b = static_cast<unsigned char>(TO_UCHAR * color.b);
1331
1332   unsigned char dstColor[4];
1333   for(unsigned int j = 0u; j < height; ++j)
1334   {
1335     const unsigned int lineIndex = j * width;
1336     for(unsigned int i = 0u; i < width; ++i)
1337     {
1338       const unsigned int srcIndex = lineIndex + i;
1339
1340       const float srcAlpha = static_cast<float>(*(srcBuffer + srcIndex));
1341
1342       if(multiplyByAlpha)
1343       {
1344         dstColor[0u] = static_cast<unsigned char>(srcAlpha * color.r);
1345         dstColor[1u] = static_cast<unsigned char>(srcAlpha * color.g);
1346         dstColor[2u] = static_cast<unsigned char>(srcAlpha * color.b);
1347         dstColor[3u] = static_cast<unsigned char>(srcAlpha * color.a);
1348       }
1349       else
1350       {
1351         dstColor[0u] = r;
1352         dstColor[1u] = g;
1353         dstColor[2u] = b;
1354         dstColor[3u] = static_cast<unsigned char>(srcAlpha);
1355       }
1356
1357       const unsigned int dstIndex = srcIndex * 4u;
1358       memcpy(dstBuffer + dstIndex, dstColor, 4u);
1359     }
1360   }
1361
1362   return newPixelBuffer;
1363 }
1364
1365 void UpdateBuffer(Devel::PixelBuffer src, Devel::PixelBuffer dst, unsigned int x, unsigned int y, bool blend)
1366 {
1367   const Dali::Pixel::Format pixelFormat = dst.GetPixelFormat();
1368   if(src.GetPixelFormat() != pixelFormat)
1369   {
1370     DALI_LOG_ERROR("PixelBuffer::SetBuffer. The pixel format of the new data must be the same of the current pixel buffer.");
1371     return;
1372   }
1373
1374   const unsigned int srcWidth  = src.GetWidth();
1375   const unsigned int srcHeight = src.GetHeight();
1376   const unsigned int dstWidth  = dst.GetWidth();
1377   const unsigned int dstHeight = dst.GetHeight();
1378
1379   if((x > dstWidth) ||
1380      (y > dstHeight) ||
1381      (x + srcWidth > dstWidth) ||
1382      (y + srcHeight > dstHeight))
1383   {
1384     DALI_LOG_ERROR("PixelBuffer::SetBuffer. The source pixel buffer is out of the boundaries of the destination pixel buffer.");
1385     return;
1386   }
1387
1388   const unsigned int bytesPerPixel = Dali::Pixel::GetBytesPerPixel(pixelFormat);
1389   if(bytesPerPixel == 0u || bytesPerPixel == 12u || bytesPerPixel == 24u)
1390   {
1391     return;
1392   }
1393   const unsigned int alphaIndex = bytesPerPixel - 1u;
1394
1395   const unsigned char* const srcBuffer = src.GetBuffer();
1396   unsigned char*             dstBuffer = dst.GetBuffer();
1397
1398   if(!blend)
1399   {
1400     const unsigned int currentLineSize = dstWidth * bytesPerPixel;
1401     const unsigned int newLineSize     = srcWidth * bytesPerPixel;
1402     unsigned char*     currentBuffer   = dstBuffer + (y * dstWidth + x) * bytesPerPixel;
1403     for(unsigned int j = 0u; j < srcHeight; ++j)
1404     {
1405       memcpy(currentBuffer + j * currentLineSize, srcBuffer + j * newLineSize, newLineSize);
1406     }
1407   }
1408   else
1409   {
1410     float outputColor[4u];
1411
1412     // Blend the src pixel buffer with the dst pixel buffer as background.
1413     //
1414     //  fgColor, fgAlpha, bgColor, bgAlpha
1415     //
1416     //  alpha = 1 - ( 1 - fgAlpha ) * ( 1 - bgAlpha )
1417     //  color = ( fgColor * fgAlpha / alpha ) + ( bgColor * bgAlpha * ( 1 - fgAlpha ) / alpha )
1418
1419     // Jump till the 'x,y' position
1420     const unsigned int dstWidthBytes = dstWidth * bytesPerPixel;
1421     dstBuffer += (y * dstWidthBytes + x * bytesPerPixel);
1422
1423     for(unsigned int j = 0u; j < srcHeight; ++j)
1424     {
1425       const unsigned int srcLineIndex = j * srcWidth;
1426       for(unsigned int i = 0u; i < srcWidth; ++i)
1427       {
1428         const float srcAlpha = TO_FLOAT * static_cast<float>(*(srcBuffer + bytesPerPixel * (srcLineIndex + i) + alphaIndex));
1429         const float dstAlpha = TO_FLOAT * static_cast<float>(*(dstBuffer + i * bytesPerPixel + alphaIndex));
1430
1431         // Blends the alpha channel.
1432         const float oneMinusSrcAlpha = 1.f - srcAlpha;
1433         outputColor[alphaIndex]      = 1.f - (oneMinusSrcAlpha * (1.f - dstAlpha));
1434
1435         // Blends the RGB channels.
1436         const bool isOutputAlphaZero = outputColor[alphaIndex] < Dali::Math::MACHINE_EPSILON_1000;
1437         if(isOutputAlphaZero)
1438         {
1439           std::fill(outputColor, outputColor + bytesPerPixel, 0.f);
1440         }
1441         else
1442         {
1443           const float srcAlphaOverOutputAlpha                 = srcAlpha / outputColor[alphaIndex];                    // fgAlpha / alpha
1444           const float dstAlphaOneMinusSrcAlphaOverOutputAlpha = dstAlpha * oneMinusSrcAlpha / outputColor[alphaIndex]; // bgAlpha * ( 1 - fgAlpha ) / alpha
1445           for(unsigned int index = 0u; index < alphaIndex; ++index)
1446           {
1447             const float dstComponent = TO_FLOAT * static_cast<float>(*(dstBuffer + i * bytesPerPixel + index)) * dstAlpha;
1448             const float srcComponent = TO_FLOAT * static_cast<float>(*(srcBuffer + bytesPerPixel * (srcLineIndex + i) + index)) * srcAlpha;
1449             outputColor[index]       = (srcComponent * srcAlphaOverOutputAlpha) + (dstComponent * dstAlphaOneMinusSrcAlphaOverOutputAlpha);
1450           }
1451         }
1452
1453         for(unsigned int index = 0u; index < bytesPerPixel; ++index)
1454         {
1455           *(dstBuffer + i * bytesPerPixel + index) = static_cast<unsigned char>(TO_UCHAR * outputColor[index]);
1456         }
1457       }
1458
1459       dstBuffer += dstWidthBytes;
1460     }
1461   }
1462 }
1463
1464 Dali::Property::Array RenderForLastIndex(RendererParameters& textParameters)
1465 {
1466   Property::Array offsetValues;
1467   if(textParameters.text.empty())
1468   {
1469     return offsetValues;
1470   }
1471   FontClient fontClient = FontClient::Get();
1472   MetricsPtr metrics;
1473   metrics = Metrics::New(fontClient);
1474
1475   Text::ModelPtr    textModel = Text::Model::New();
1476   InternalDataModel internalData(fontClient, metrics, textModel);
1477
1478   TextAbstraction::TextRenderer::Parameters rendererParameters(textModel->mVisualModel->mGlyphs,
1479                                                                textModel->mVisualModel->mGlyphPositions,
1480                                                                textModel->mVisualModel->mColors,
1481                                                                textModel->mVisualModel->mColorIndices,
1482                                                                internalData.blendingMode,
1483                                                                internalData.isEmoji);
1484
1485   rendererParameters.width  = textParameters.textWidth;
1486   rendererParameters.height = textParameters.textHeight;
1487
1488   ////////////////////////////////////////////////////////////////////////////////
1489   // Process the markup string if the mark-up processor is enabled.
1490   ////////////////////////////////////////////////////////////////////////////////
1491   ShapeTextPreprocess(textParameters, rendererParameters, internalData);
1492
1493   ////////////////////////////////////////////////////////////////////////////////
1494   // Retrieve the glyphs. Text shaping
1495   ////////////////////////////////////////////////////////////////////////////////
1496   Dali::Vector<Dali::Toolkit::DevelText::EmbeddedItemInfo> embeddedItemLayout;
1497   ShapeText(rendererParameters, embeddedItemLayout, internalData);
1498
1499   ////////////////////////////////////////////////////////////////////////////////
1500   // Retrieve the glyph's metrics.
1501   ////////////////////////////////////////////////////////////////////////////////
1502   metrics->GetGlyphMetrics(rendererParameters.glyphs.Begin(), internalData.numberOfGlyphs);
1503
1504   ////////////////////////////////////////////////////////////////////////////////
1505   // Layout the text
1506   ////////////////////////////////////////////////////////////////////////////////
1507   int boundingBox           = textParameters.textHeight - (textParameters.padding.top + textParameters.padding.bottom);
1508   textParameters.textHeight = MAX_INT; // layout for the entire area.
1509   LayoutText(textParameters, rendererParameters, embeddedItemLayout, internalData);
1510
1511   ////////////////////////////////////////////////////////////////////////////////
1512   // Calculation last character index
1513   ////////////////////////////////////////////////////////////////////////////////
1514   Vector<LineRun>& lines              = internalData.textModel->mVisualModel->mLines;
1515   unsigned int     numberOfLines      = lines.Count();
1516   int              numberOfCharacters = 0;
1517   float            penY               = 0.f;
1518   float            lineSize           = internalData.layoutEngine.GetDefaultLineSize();
1519   float            lineOffset         = 0.f;
1520   for(unsigned int index = 0u; index < numberOfLines; ++index)
1521   {
1522     const LineRun& line = *(lines.Begin() + index);
1523     numberOfCharacters += line.characterRun.numberOfCharacters;
1524
1525     lineOffset = lineSize > 0.f ? lineSize : (line.ascender + -line.descender);
1526     penY += lineOffset;
1527     if((penY + lineOffset) > boundingBox)
1528     {
1529       offsetValues.PushBack(numberOfCharacters);
1530       penY = 0.f;
1531     }
1532   }
1533   if(penY > 0.f)
1534   {
1535     // add remain character index
1536     offsetValues.PushBack(numberOfCharacters);
1537   }
1538
1539   return offsetValues;
1540 }
1541
1542 Dali::Property::Array GetLastCharacterIndex(RendererParameters& textParameters)
1543 {
1544   Dali::Property::Array offsetValues = Toolkit::DevelText::RenderForLastIndex(textParameters);
1545   return offsetValues;
1546 }
1547
1548 } // namespace DevelText
1549
1550 } // namespace Toolkit
1551
1552 } // namespace Dali