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