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