Text improvement
[platform/core/uifw/dali-adaptor.git] / dali / internal / text / text-abstraction / cairo-renderer.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/internal/text/text-abstraction/cairo-renderer.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/common/constants.h>
23 #include <cairo.h>
24 #include <cairo-ft.h>
25 #include <cstring>
26 #include <memory>
27
28 #include <ft2build.h>
29 #include FT_FREETYPE_H
30 #include FT_GLYPH_H
31 #include FT_OUTLINE_H
32 #include FT_STROKER_H
33
34 // INTERNAL INCLUDES
35 #include <dali/devel-api/text-abstraction/font-client.h>
36 #include <dali/devel-api/text-abstraction/text-renderer-layout-helper.h>
37 #include <dali/integration-api/debug.h>
38 #include <dali/internal/imaging/common/image-operations.h>
39 #include <dali/internal/text/text-abstraction/font-client-impl.h>
40
41 namespace
42 {
43
44 const float TO_FLOAT = 1.f / 255.f;
45 const float TO_UCHAR = 255.f;
46 const float TWO_PI = 2.f * Dali::Math::PI; ///< 360 degrees in radians
47
48 /**
49  * @brief Run of glyphs that have the same style.
50  */
51 struct GlyphRun
52 {
53   GlyphRun()
54   : fontFace{ nullptr },
55     fontSize{ 0.0 },
56     glyphIndex{ 0u },
57     numberOfGlyphs{ 0u },
58     fontId{ 0u },
59     colorIndex{ 0u },
60     isItalicRequired{ false },
61     isBoldRequired{ false }
62   {}
63
64   FT_Face      fontFace;           ///< The font face used by the glyphs in the run.
65   double       fontSize;           ///< The font size used by the glyphs in the run. According the Cairo's documentation this is in user space units. It works if I set the size in pixels.
66   unsigned int glyphIndex;         ///< Index to the first glyph of the run.
67   unsigned int numberOfGlyphs;     ///< Number of glyphs in the run.
68   unsigned int fontId;             ///< The id of the font.
69   unsigned int colorIndex;         ///< The index to the color of the glyphs.
70   bool         isItalicRequired:1; ///< Whether the italic style is required.
71   bool         isBoldRequired:1;   ///< Whether the bold style is required.
72 };
73
74 /**
75  * @brief Helper struct used to destroy a bitmap buffer.
76  *
77  * The font client allocates a bitmap's buffer with the new operator.
78  * However, the PixelBuffer class allocates the buffer with the
79  * malloc() function and the Rotate() function which is intended
80  * for the PixelBuffer as well allocates memory with malloc().
81  *
82  * This struct keeps the type of allocation and uses the delete[]
83  * operator or the free() function to deallocate resources.
84  */
85 struct GlyphBuffer
86 {
87   enum DestructorType
88   {
89     FREE,
90     DELETE
91   };
92
93   GlyphBuffer( Dali::TextAbstraction::FontClient::GlyphBufferData& data, DestructorType type )
94   : data( data ),
95     type( type )
96   {
97   }
98
99   ~GlyphBuffer()
100   {
101     switch( type )
102     {
103       case FREE:
104       {
105         free( data.buffer );
106         break;
107       }
108       case DELETE:
109       {
110         delete[] data.buffer;
111       }
112     }
113   }
114
115   Dali::TextAbstraction::FontClient::GlyphBufferData& data;
116   DestructorType type;
117 };
118
119 /**
120  * @brief Creates a pixel buffer with all pixels set to transparent.
121  *
122  * @param[in] parameters Contains the width and height of the pixel buffer.
123  *
124  * @return The pixel buffer.
125  */
126 Dali::Devel::PixelBuffer CreateVoidPixelBuffer( const Dali::TextAbstraction::TextRenderer::Parameters& parameters )
127 {
128   Dali::Pixel::Format pixelFormat = parameters.pixelFormat == Dali::TextAbstraction::TextRenderer::Parameters::A8 ? Dali::Pixel::A8 : Dali::Pixel::RGBA8888;
129   Dali::Devel::PixelBuffer pixelBuffer = Dali::Devel::PixelBuffer::New( parameters.width,
130                                                                         parameters.height,
131                                                                         pixelFormat );
132
133   const unsigned int bufferSize = parameters.width * parameters.height * Dali::Pixel::GetBytesPerPixel( pixelFormat );
134   unsigned char* buffer = pixelBuffer.GetBuffer();
135   memset( buffer, 0, bufferSize );
136
137   return pixelBuffer;
138 }
139
140 /**
141  * @brief Wraps the vertices of glyphs laid out on a horizontal strainght line on a circular path.
142  *
143  * It copies the vertices from the extra cairo context created to lay out the text
144  * on a horizontal straight line to the cairo context used to render it.
145  *
146  * @param[in,out] cr The cairo context used to render the text.
147  * @param[in] circularCr The extra cairo context created to layout horizontal text.
148  * @param[in] parameters The parameters of the circular path.
149  */
150 void WrapToCircularPath( cairo_t* cr, cairo_t* circularCr, const Dali::TextAbstraction::CircularTextParameters& parameters )
151 {
152   bool first = true;
153
154   // Copy the path to get a cairo_path_t pointer used to iterate through all its items.
155   std::unique_ptr<cairo_path_t, void(*)(cairo_path_t*)> path( cairo_copy_path( circularCr ), cairo_path_destroy );
156
157   void ( *transformToArc )( const Dali::TextAbstraction::CircularTextParameters&, double&, double& );
158   transformToArc = parameters.isClockwise ? &Dali::TextAbstraction::TransformToArcClockwise : &Dali::TextAbstraction::TransformToArcAntiClockwise;
159
160   // Iterates through all the path items and transform each vertex to follow the circle.
161   // Transformed vertices are added to a new path in the 'cr' context (the one used to render the circular text)
162   for( int i = 0; i < path->num_data; i += path->data[i].header.length )
163   {
164     cairo_path_data_t* data = &path->data[i];
165
166     switch( data->header.type )
167     {
168       case CAIRO_PATH_MOVE_TO:
169       {
170         if( first )
171         {
172           cairo_new_path( cr );
173         }
174
175         first = false;
176         double x = data[1].point.x;
177         double y = data[1].point.y;
178         transformToArc( parameters, x, y );
179         cairo_move_to( cr, x, y );
180         break;
181       }
182       case CAIRO_PATH_LINE_TO:
183       {
184         double x = data[1].point.x;
185         double y = data[1].point.y;
186         transformToArc( parameters, x, y );
187         cairo_line_to( cr, x, y );
188         break;
189       }
190       case CAIRO_PATH_CURVE_TO:
191       {
192         double x1 = data[1].point.x;
193         double y1 = data[1].point.y;
194         double x2 = data[2].point.x;
195         double y2 = data[2].point.y;
196         double x3 = data[3].point.x;
197         double y3 = data[3].point.y;
198         transformToArc( parameters, x1, y1 );
199         transformToArc( parameters, x2, y2 );
200         transformToArc( parameters, x3, y3 );
201         cairo_curve_to( cr, x1, y1, x2, y2, x3, y3 );
202         break;
203       }
204       case CAIRO_PATH_CLOSE_PATH:
205       {
206         cairo_close_path( cr );
207         break;
208       }
209       default:
210       {
211         DALI_LOG_WARNING( "Type of path not handled.\n" );
212         // Nothing else to do.
213         break;
214       }
215     }
216   }
217 }
218
219 } // namespace
220
221 namespace Dali
222 {
223
224 namespace TextAbstraction
225 {
226
227 namespace Internal
228 {
229
230 Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Parameters& parameters )
231 {
232   const unsigned int numberOfGlyphs = parameters.glyphs.Count();
233
234   if( 0u == numberOfGlyphs )
235   {
236     // return a pixel buffer with all pixels set to transparent.
237     return CreateVoidPixelBuffer( parameters );
238   }
239
240   // Convert from DALi glyphs to Cairo glyphs.
241   std::vector<cairo_glyph_t> cairoGlyphs;
242   cairoGlyphs.resize( numberOfGlyphs );
243   cairo_glyph_t* cairoGlyphsBuffer = &cairoGlyphs[0u];
244
245   const GlyphInfo* const daliGlyphsBuffer = parameters.glyphs.Begin();
246   const Vector2* const positionsBuffer = parameters.positions.Begin();
247   const ColorIndex* const colorIndicesBuffer = ( 0u == parameters.colorIndices.Count() ) ? nullptr : parameters.colorIndices.Begin();
248
249   for( unsigned index = 0u; index < numberOfGlyphs; ++index )
250   {
251     const GlyphInfo& daliGlyph = *( daliGlyphsBuffer + index );
252     const Vector2& position = *( positionsBuffer + index );
253     cairo_glyph_t& cairoGlyph = *( cairoGlyphsBuffer + index );
254
255     cairoGlyph.index = daliGlyph.index;
256     cairoGlyph.x = std::round( position.x );
257     cairoGlyph.y = std::round( position.y );
258   }
259
260   // Retrieve the FreeType fonts needed by Cairo from the font-client.
261   Dali::TextAbstraction::FontClient fontClient = Dali::TextAbstraction::FontClient::Get();
262
263   FT_Library ftLibrary;
264   FT_Init_FreeType(&ftLibrary);
265
266   // Vector used to store the FreeType font faces, its size and the run of glyphs that use the font.
267   std::vector<GlyphRun> glyphRuns;
268   glyphRuns.reserve( 8u );
269
270   // The size set in Cairo and FreeType has different units.
271   // Before the size is set in Cairo it needs to be converted according the formula
272   // 'pixel_size = point_size * resolution / 72' got from the FreeType doc.
273   // https://www.freetype.org/freetype2/docs/glyphs/glyphs-2.html
274
275   unsigned int horizontalDpi = 0u;
276   unsigned int verticalDpi = 0u;
277   fontClient.GetDpi( horizontalDpi, verticalDpi );
278   const double dVerticalDpi = static_cast<double>( verticalDpi );
279
280   const double FROM_26_DOT_6_TO_PIXELS = dVerticalDpi / ( 64.0 * 72.0 );
281
282   GlyphRun currentGlyphRun;
283   currentGlyphRun.fontId = 0u;
284   currentGlyphRun.colorIndex = 0u;
285   currentGlyphRun.isItalicRequired = false;
286   currentGlyphRun.isBoldRequired = false;
287   for( unsigned index = 0u; index < numberOfGlyphs; ++index )
288   {
289     const GlyphInfo& daliGlyph = *( daliGlyphsBuffer + index );
290     const FontId fontId = daliGlyph.fontId;
291     const ColorIndex colorIndex = ( nullptr == colorIndicesBuffer ) ? 0u : *( colorIndicesBuffer + index );
292     const bool isItalicRequired = daliGlyph.isItalicRequired;
293     const bool isBoldRequired = daliGlyph.isBoldRequired;
294
295     if( ( fontId != currentGlyphRun.fontId ) ||
296         ( ( 0u == fontId ) && ( 0u != daliGlyph.index ) ) ||
297         ( colorIndex != currentGlyphRun.colorIndex ) ||
298         ( isItalicRequired != currentGlyphRun.isItalicRequired ) ||
299         ( isBoldRequired != currentGlyphRun.isBoldRequired ) )
300     {
301       // There is a new run. First set the number of glyphs of the previous run and store it.
302       currentGlyphRun.numberOfGlyphs = index - currentGlyphRun.glyphIndex;
303       if( 0u != currentGlyphRun.numberOfGlyphs )
304       {
305         glyphRuns.push_back( currentGlyphRun );
306       }
307
308       currentGlyphRun.fontFace = nullptr;
309       currentGlyphRun.fontSize = 0.0;
310       currentGlyphRun.glyphIndex = index;
311       currentGlyphRun.numberOfGlyphs = 0u;
312       currentGlyphRun.fontId = 0u;
313       currentGlyphRun.colorIndex = 0u;
314       currentGlyphRun.isItalicRequired = false;
315       currentGlyphRun.isBoldRequired = false;
316
317       if( 0u != fontId )
318       {
319         // Get the font's path file name from the font Id.
320         FontDescription fontDescription;
321         fontClient.GetDescription( fontId, fontDescription );
322
323         switch( fontDescription.type )
324         {
325           case FontDescription::FACE_FONT:
326           {
327             // Create a FreeType font's face.
328             FT_New_Face(ftLibrary, fontDescription.path.c_str(), 0u, &currentGlyphRun.fontFace);
329
330             // Set the font's size. It needs to be set in the Freetype font and in the Cairo's context.
331             unsigned int fontSize = fontClient.GetPointSize( fontId );
332
333             // Font's size to be set in the Cairo's context.
334             currentGlyphRun.fontSize = FROM_26_DOT_6_TO_PIXELS * static_cast<double>( fontSize );
335             break;
336           }
337           case FontDescription::BITMAP_FONT:
338           {
339             //Nothing to do.
340             break;
341           }
342           default:
343           {
344             //Nothing to do.
345             break;
346           }
347         }
348       }
349       currentGlyphRun.fontId = fontId;
350       currentGlyphRun.colorIndex = colorIndex;
351       currentGlyphRun.isItalicRequired = isItalicRequired;
352       currentGlyphRun.isBoldRequired = isBoldRequired;
353     }
354   }
355
356   // Calculate the number of glyphs of the last run and store it.
357   currentGlyphRun.numberOfGlyphs = numberOfGlyphs - currentGlyphRun.glyphIndex;
358   if( 0u != currentGlyphRun.numberOfGlyphs )
359   {
360     glyphRuns.push_back( currentGlyphRun );
361   }
362
363   // Choose the pixel format to be used.
364   //
365   // @note Behdad wrote "Upper 8 bits maps to the fourth byte in a little-endian machine like the intels."
366   //       https://lists.cairographics.org/archives/cairo/2006-March/006563.html
367   //
368   //       Here in practice Cairo's ARGB32 is like DALi's RGBA8888.
369   //
370   const bool isDstRgba = TextAbstraction::TextRenderer::Parameters::RGBA8888 == parameters.pixelFormat;
371   const Pixel::Format pixelFormat = isDstRgba ? Pixel::Format::RGBA8888 : Pixel::Format::A8;
372   const cairo_format_t cairoFormat = isDstRgba ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_A8;
373
374   // This function provides a stride value that will respect all alignment requirements of the
375   // accelerated image-rendering code within cairo.
376   const int stride = cairo_format_stride_for_width( cairoFormat,
377                                                     static_cast<int>( parameters.width ) );
378   const int strideWidth = stride / Pixel::GetBytesPerPixel( pixelFormat );
379
380   // Creates the pixel buffer and retrieves the buffer pointer used to create the Cairo's surface.
381   Devel::PixelBuffer pixelBuffer = Devel::PixelBuffer::New( strideWidth, parameters.height, pixelFormat );
382
383   unsigned char* buffer = pixelBuffer.GetBuffer();
384   const unsigned int bufferSize = stride * parameters.height;
385   memset( buffer, 0, bufferSize );
386
387   std::unique_ptr<cairo_surface_t, void(*)(cairo_surface_t*)> surfacePtr( cairo_image_surface_create_for_data( buffer,
388                                                                                                                cairoFormat,
389                                                                                                                parameters.width,
390                                                                                                                parameters.height,
391                                                                                                                stride ),
392                                                                           cairo_surface_destroy );
393   cairo_surface_t* surface = surfacePtr.get();
394
395   if( ( nullptr == surface ) || ( CAIRO_STATUS_SUCCESS != cairo_surface_status( surface ) ) )
396   {
397     DALI_LOG_ERROR( "Failed to create a cairo's surface\n" );
398
399     return CreateVoidPixelBuffer( parameters );
400   }
401
402   // Whether the text is circular.
403   const bool isCircularText = 0u != parameters.radius;
404
405   // Creates a surface for circular text.
406   //
407   // The reason to create a surface for circular text is that the strategy
408   // followed is to layout the text in a straight horizontal line and apply a
409   // transform to each vertex that forms the geometry of the glyphs to place
410   // and bend the glyphs accordingly to the circular path.
411   //
412   // As the glyphs are laid out first in a straight line they may exceed the
413   // boundaries of the surface in that case cairo ignores them.
414   std::unique_ptr<cairo_surface_t, void(*)(cairo_surface_t*)> circularSurfacePtr( nullptr, cairo_surface_destroy );
415   cairo_surface_t* circularSurface = nullptr;
416   if( isCircularText )
417   {
418     circularSurfacePtr.reset( cairo_surface_create_similar( surface,
419                                                             CAIRO_CONTENT_ALPHA,
420                                                             parameters.circularWidth,
421                                                             parameters.circularHeight ) );
422     circularSurface = circularSurfacePtr.get();
423
424     if( ( nullptr == circularSurface ) || ( CAIRO_STATUS_SUCCESS != cairo_surface_status( circularSurface ) ) )
425     {
426       DALI_LOG_ERROR( "Failed to create a cairo's circular surface\n" );
427
428       return CreateVoidPixelBuffer( parameters );
429     }
430   }
431
432   std::unique_ptr<cairo_t, void(*)(cairo_t*)> crPtr( cairo_create( surface ), cairo_destroy );
433   cairo_t* cr = crPtr.get();
434
435   if( CAIRO_STATUS_SUCCESS != cairo_status( cr ) )
436   {
437     DALI_LOG_ERROR( "Failed to create a cairo context\n" );
438
439     return CreateVoidPixelBuffer( parameters );
440   }
441
442   std::unique_ptr<cairo_t, void(*)(cairo_t*)> circularCrPtr( nullptr, cairo_destroy );
443   cairo_t* circularCr = nullptr;
444
445   if( isCircularText )
446   {
447     circularCrPtr.reset( cairo_create( circularSurface ) );
448     circularCr = circularCrPtr.get();
449
450     if( CAIRO_STATUS_SUCCESS != cairo_status( circularCr ) )
451     {
452       DALI_LOG_ERROR( "Failed to create a cairo context\n" );
453
454       return CreateVoidPixelBuffer( parameters );
455     }
456   }
457
458   CircularTextParameters circularTextParameters;
459
460   // Render the glyphs.
461   if( isCircularText )
462   {
463     // Set the parameters.
464     circularTextParameters.isClockwise = ( TextAbstraction::TextRenderer::Parameters::CLOCKWISE == parameters.circularLayout );
465
466     circularTextParameters.centerX = static_cast<double>( parameters.centerX );
467     circularTextParameters.centerY = static_cast<double>( parameters.centerY );
468     circularTextParameters.radius = static_cast<double>( parameters.radius );
469     circularTextParameters.invRadius = 1.0 / circularTextParameters.radius;
470     circularTextParameters.beginAngle = -parameters.beginAngle + Dali::Math::PI_2;
471   }
472
473   cairo_move_to( cr, 0.0, 0.0 );
474
475   for( const auto& run: glyphRuns )
476   {
477     const bool isEmoji = parameters.isEmoji[run.glyphIndex];
478     if( isEmoji || ( nullptr == run.fontFace ) )
479     {
480       // Retrieve the color for the glyph.
481       const Vector4& color = parameters.colors[run.colorIndex];
482
483       const unsigned int lastGlyphIndex = run.glyphIndex + run.numberOfGlyphs;
484       for( unsigned int index = run.glyphIndex; index < lastGlyphIndex; ++index )
485       {
486         // Whether it's a bitmap font.
487         const bool doBlendWithTextColor = !isEmoji && ( ColorBlendingMode::MULTIPLY == parameters.blendingMode[index] );
488
489         // Check if there is an embedded image or a bitmap font image.
490         const GlyphIndex glyphFontIndex = daliGlyphsBuffer[index].index;
491         if( 0u != glyphFontIndex )
492         {
493           // The embedded image could be A8, RGBA8888 or BGRA8888.
494           //
495           // If the embedded image is RGBA8888 or BGRA8888 then the cairo's buffer is ARGB32. It's needed to convert from RGBA or BGRA to ARGB.
496           // If the embedded image is A8 it's needed to check if the cairo's buffer is A8 or ARGB32 and do the conversion if needed.
497
498           const cairo_glyph_t& glyph = *( cairoGlyphsBuffer + index );
499
500           // Retrieve the image
501           TextAbstraction::FontClient::GlyphBufferData data;
502           std::unique_ptr<GlyphBuffer> glyphBufferPtr( new GlyphBuffer( data, GlyphBuffer::DELETE ) );
503           if( isEmoji )
504           {
505             data.width = parameters.glyphs[run.glyphIndex].width;
506             data.height = parameters.glyphs[run.glyphIndex].height;
507           }
508
509           fontClient.CreateBitmap( run.fontId, glyphFontIndex, false, false, data, 0u );
510
511           if( nullptr == data.buffer )
512           {
513             // nothing else to do if there is no image.
514             continue;
515           }
516
517           // Calculate the position for the circular text.
518           double glyphX = glyph.x;
519           double glyphY = glyph.y;
520
521           if( isCircularText )
522           {
523             // Center of the bitmap.
524             const double halfWidth = 0.5 * static_cast<double>( data.width );
525             const double halfHeight = 0.5 * static_cast<double>( data.height );
526
527             double centerX = glyph.x + halfWidth;
528             double centerY = glyph.y - halfHeight;
529
530             float radians = circularTextParameters.beginAngle + ( circularTextParameters.isClockwise ? -1.f : 1.f ) * ( Dali::Math::PI_2 + circularTextParameters.invRadius * centerX );
531             radians = fmod( radians, TWO_PI );
532             radians += ( radians < 0.f ) ? TWO_PI : 0.f;
533
534             void ( *transformToArc )( const CircularTextParameters&, double&, double& );
535             transformToArc = circularTextParameters.isClockwise ? &TransformToArcClockwise : &TransformToArcAntiClockwise;
536
537             transformToArc( circularTextParameters, centerX, centerY );
538
539             uint8_t* pixelsOut = nullptr;
540             unsigned int widthOut = data.width;
541             unsigned int heightOut = data.height;
542             const unsigned int pixelSize = Pixel::GetBytesPerPixel( data.format );
543
544             Dali::Internal::Platform::RotateByShear( data.buffer,
545                                                      data.width,
546                                                      data.height,
547                                                      pixelSize,
548                                                      radians,
549                                                      pixelsOut,
550                                                      widthOut,
551                                                      heightOut );
552             if( nullptr != pixelsOut )
553             {
554               delete[] data.buffer;
555               data.buffer = pixelsOut;
556               glyphBufferPtr.get()->type = GlyphBuffer::FREE;
557               data.width = widthOut;
558               data.height = heightOut;
559             }
560
561             glyphX = centerX - 0.5 * static_cast<double>( data.width );
562             glyphY = centerY + 0.5 * static_cast<double>( data.height );
563           }
564
565
566           if( ( Pixel::A8 != data.format ) &&
567               ( Pixel::L8 != data.format ) &&
568               ( Pixel::RGBA8888 != data.format ) &&
569               ( Pixel::BGRA8888 != data.format ) )
570           {
571             DALI_LOG_ERROR( " Cairo Renderer: The valid pixel format for embedded items are A8 or RGBA8888\n" );
572             continue;
573           }
574
575           // Check if the item is out of the buffer.
576           if( ( glyphX + static_cast<float>( data.width ) < 0.f ) ||
577               ( glyphX > static_cast<float>( strideWidth ) ) ||
578               ( glyphY < 0.f ) ||
579               ( glyphY - static_cast<float>( data.height ) > static_cast<float>( parameters.height ) ) )
580           {
581             // The embedded item is completely out of the buffer.
582             continue;
583           }
584
585           const bool isSrcA = ( Pixel::A8 == data.format ) || ( Pixel::L8 == data.format );
586           const bool isSrcRgba = Pixel::RGBA8888 == data.format;
587           const bool isSrcBgra = Pixel::BGRA8888 == data.format;
588
589           // 0 -> image and cairo buffer are A8
590           // 1 -> image is A8, cairo buffer is ARGB
591           // 2 -> image is RGBA and cairo buffer is ARGB
592           // 3 -> image is BGRA and cairo buffer is ARGB
593           int rgbaCase = 0;
594           if( isSrcA && isDstRgba )
595           {
596             rgbaCase = 1;
597           }
598           else if( isSrcRgba && isDstRgba )
599           {
600             rgbaCase = 2;
601           }
602           else if( isSrcBgra && isDstRgba )
603           {
604             rgbaCase = 3;
605           }
606           else if( ( isSrcRgba || isSrcBgra ) && !isDstRgba )
607           {
608             DALI_LOG_ERROR( "Cairo Renderer: The embedded image is RGBA or BGRA and the Cairo's buffer has been creates with A8 format!\n" );
609             continue;
610           }
611
612           // Select the cropped source image area to copy into the surface buffer
613           unsigned int glyphUintX = 0u;
614           unsigned int glyphUintY = 0u;
615           unsigned int srcWidth = data.width;
616           unsigned int srcHeight = data.height;
617           unsigned int xSrcIndex = 0u;
618           unsigned int ySrcIndex = 0u;
619           if( glyphX < 0.f )
620           {
621             xSrcIndex = static_cast<unsigned int>( std::abs( glyphX ) );
622             srcWidth -= xSrcIndex;
623           }
624           else
625           {
626             glyphUintX = static_cast<unsigned int>( glyphX );
627           }
628
629           if( glyphUintX + srcWidth > static_cast<unsigned int>( strideWidth ) )
630           {
631             srcWidth -= ( ( glyphUintX + srcWidth ) - strideWidth );
632           }
633
634           if( glyphY - static_cast<float>( srcHeight ) < 0.f )
635           {
636             ySrcIndex = static_cast<unsigned int>( std::abs( glyphY - static_cast<float>( srcHeight ) ) );
637             srcHeight -= ySrcIndex;
638           }
639           else
640           {
641             glyphUintY = static_cast<unsigned int>( glyphY - static_cast<float>( srcHeight ) );
642           }
643
644           if( glyphUintY + srcHeight > parameters.height )
645           {
646             srcHeight -= ( ( glyphUintY + srcHeight ) - parameters.height );
647           }
648
649           // Calculate the source and destination indices.
650           const unsigned int srcPixelSize = Pixel::GetBytesPerPixel( data.format );
651           const unsigned int dstPixelSize = Pixel::GetBytesPerPixel( pixelFormat );
652
653           unsigned int srcIndex = srcPixelSize * ( ySrcIndex * srcWidth + xSrcIndex );
654           unsigned int dstIndex = dstPixelSize * ( glyphUintY * strideWidth + glyphUintX );
655
656           const unsigned int srcWidthOffset = srcPixelSize * ( data.width - srcWidth );
657           const unsigned int dstWidthOffset = dstPixelSize * ( strideWidth - srcWidth );
658
659           // Copy the image to the surface
660           for( unsigned int j = 0; j < srcHeight; ++j )
661           {
662             for( unsigned int i = 0; i < srcWidth; ++i )
663             {
664               switch( rgbaCase )
665               {
666                 case 0: // Both the image's buffer and cairo's buffer are A8
667                 {
668                   const unsigned char alpha = *( data.buffer + srcIndex );
669                   if( alpha != 0u )
670                   {
671                     // @todo needs a proper blending!
672                     *( buffer + dstIndex ) = alpha;
673                   }
674                   break;
675                 }
676                 case 1: // The image's buffer is A8 and the cairo's buffer is ARGB
677                 {
678                   const unsigned char alpha = *( data.buffer + srcIndex );
679                   if( alpha != 0u )
680                   {
681                     // @todo needs a proper blending!
682                     const float srcAlpha = TO_FLOAT * static_cast<float>( alpha );
683
684                     // Write the RGBA modulated with the given default color.
685                     const float* const colorPtr = color.AsFloat();
686                     *( buffer + dstIndex + 0u ) = static_cast<unsigned char>( TO_UCHAR * colorPtr[0u] * srcAlpha );
687                     *( buffer + dstIndex + 1u ) = static_cast<unsigned char>( TO_UCHAR * colorPtr[1u] * srcAlpha );
688                     *( buffer + dstIndex + 2u ) = static_cast<unsigned char>( TO_UCHAR * colorPtr[2u] * srcAlpha );
689                     *( buffer + dstIndex + 3u ) = static_cast<unsigned char>( TO_UCHAR * colorPtr[3u] * srcAlpha );
690                   }
691                   break;
692                 }
693                 case 2: // The image's buffer is RGBA and the cairo's buffer is ARGB
694                 {
695                   const unsigned char alpha = *(data.buffer + srcIndex + 3u);
696                   if( alpha != 0u )
697                   {
698                     if( doBlendWithTextColor )
699                     {
700                       const float* const colorPtr = color.AsFloat();
701
702                       const float srcAlpha = TO_FLOAT * static_cast<float>(alpha) * colorPtr[3u];
703
704                       *(buffer + dstIndex + 0u) = static_cast<unsigned char>( static_cast<float>( *(data.buffer + srcIndex + 0u) ) * colorPtr[0u] );
705                       *(buffer + dstIndex + 1u) = static_cast<unsigned char>( static_cast<float>( *(data.buffer + srcIndex + 1u) ) * colorPtr[1u] );
706                       *(buffer + dstIndex + 2u) = static_cast<unsigned char>( static_cast<float>( *(data.buffer + srcIndex + 2u) ) * colorPtr[2u] );
707
708                       // Write the alpha.
709                       *(buffer + dstIndex + 3u) = static_cast<unsigned char>( TO_UCHAR * srcAlpha );
710                     }
711                     else
712                     {
713                       // @todo needs a proper blending!
714                       // Write the RGB
715                       *(buffer + dstIndex + 0u) = *(data.buffer + srcIndex + 0u);
716                       *(buffer + dstIndex + 1u) = *(data.buffer + srcIndex + 1u);
717                       *(buffer + dstIndex + 2u) = *(data.buffer + srcIndex + 2u);
718
719                       // Write the alpha.
720                       *(buffer + dstIndex + 3u) = *(data.buffer + srcIndex + 3u);
721                     }
722                   }
723                   break;
724                 }
725                 case 3: // The image's buffer is BGRA and the cairo's buffer is ARGB
726                 {
727                   const unsigned char alpha = *(data.buffer + srcIndex + 3u);
728                   if( alpha != 0u )
729                   {
730                     if( doBlendWithTextColor )
731                     {
732                       const float* const colorPtr = color.AsFloat();
733
734                       const float srcAlpha = TO_FLOAT * static_cast<float>(alpha) * colorPtr[3u];
735
736                       *(buffer + dstIndex + 0u) = static_cast<unsigned char>( static_cast<float>( *(data.buffer + srcIndex + 2u) ) * colorPtr[0u] );
737                       *(buffer + dstIndex + 1u) = static_cast<unsigned char>( static_cast<float>( *(data.buffer + srcIndex + 1u) ) * colorPtr[1u] );
738                       *(buffer + dstIndex + 2u) = static_cast<unsigned char>( static_cast<float>( *(data.buffer + srcIndex + 0u) ) * colorPtr[2u] );
739
740                       // Write the alpha.
741                       *(buffer + dstIndex + 3u) = static_cast<unsigned char>( TO_UCHAR * srcAlpha );
742                     }
743                     else
744                     {
745                       // @todo needs a proper blending!
746                       // Write the RGBA
747                       *(buffer + dstIndex + 0u) = *(data.buffer + srcIndex + 2u);
748                       *(buffer + dstIndex + 1u) = *(data.buffer + srcIndex + 1u);
749                       *(buffer + dstIndex + 2u) = *(data.buffer + srcIndex + 0u);
750                       *(buffer + dstIndex + 3u) = *(data.buffer + srcIndex + 3u);
751                     }
752                   }
753                   break;
754                 }
755                 default:
756                 {
757                   DALI_ASSERT_ALWAYS( !"Cairo Renderer: The accepted values for this switch case are: 0, 1, 2!" );
758                 }
759               } // switch
760               srcIndex += srcPixelSize;
761               dstIndex += dstPixelSize;
762             } // for width
763             srcIndex += srcWidthOffset;
764             dstIndex += dstWidthOffset;
765           } // for height
766         }
767       }
768     }
769     else
770     {
771       // Sets the color. The color is actually BGRA
772       const Vector4& color = parameters.colors[run.colorIndex];
773
774       cairo_set_source_rgba( cr,
775                              static_cast<double>( color.b ),
776                              static_cast<double>( color.g ),
777                              static_cast<double>( color.r ),
778                              static_cast<double>( color.a ) );
779
780       // Create the Cairo's font from the FreeType font.
781       std::unique_ptr<cairo_font_face_t, void(*)(cairo_font_face_t*)> fontFacePtr( cairo_ft_font_face_create_for_ft_face( run.fontFace, 0 ), cairo_font_face_destroy );
782       cairo_font_face_t* fontFace = fontFacePtr.get();
783
784       static const cairo_user_data_key_t key = { 0 };
785       cairo_status_t status = cairo_font_face_set_user_data( fontFace, &key, run.fontFace, reinterpret_cast<cairo_destroy_func_t>( FT_Done_Face ) );
786       if( status )
787       {
788         cairo_font_face_destroy(fontFace);
789       }
790
791       unsigned int ftSynthesizeFlag = 0u;
792       if( run.isBoldRequired && !( run.fontFace->style_flags & FT_STYLE_FLAG_BOLD ) )
793       {
794         ftSynthesizeFlag |= CAIRO_FT_SYNTHESIZE_BOLD;
795       }
796
797       cairo_ft_font_face_set_synthesize( fontFace, ftSynthesizeFlag );
798
799       cairo_font_face_reference( fontFace );
800
801       const bool synthesizeItalic = ( run.isItalicRequired && !( run.fontFace->style_flags & FT_STYLE_FLAG_ITALIC ) );
802
803       if( CAIRO_STATUS_SUCCESS != cairo_font_face_status( fontFace ) )
804       {
805         DALI_LOG_ERROR( "Failed to load the Freetype Font\n" );
806       }
807
808       // Sets the font.
809       cairo_set_font_face( isCircularText ? circularCr : cr, fontFace );
810
811       // Sets the size
812       cairo_set_font_size( isCircularText ? circularCr : cr, run.fontSize );
813
814       // Render the glyphs.
815       if( isCircularText )
816       {
817         // Create a new path where the text is laid out on a horizontal straight line.
818         cairo_new_path( circularCr );
819         cairo_move_to( circularCr, 0.0, 0.0 );
820
821         cairo_glyph_path( circularCr, ( cairoGlyphsBuffer + run.glyphIndex ), run.numberOfGlyphs );
822         WrapToCircularPath( cr, circularCr, circularTextParameters );
823       }
824       else
825       {
826         if( synthesizeItalic )
827         {
828           // Apply a shear transform to synthesize the italics.
829           // For a reason Cairo may trim some glyphs if the CAIRO_FT_SYNTHESIZE_OBLIQUE flag is used.
830
831           // This is to calculate an offset used to compensate the 'translation' done by the shear transform
832           // as it's done for the whole render buffer.
833           double maxY = 0.0;
834           for( unsigned int index = run.glyphIndex, endIndex = run.glyphIndex + run.numberOfGlyphs; index < endIndex; ++index )
835           {
836             maxY = std::max( maxY, (*( cairoGlyphsBuffer + index )).y );
837           }
838
839           cairo_matrix_t matrix;
840           cairo_matrix_init( &matrix,
841                                                                                   1.0, 0.0,
842                                    -TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, 1.0,
843                              maxY * TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, 0.0 );
844
845           cairo_transform( cr, &matrix );
846         }
847
848         cairo_show_glyphs( cr, ( cairoGlyphsBuffer + run.glyphIndex ), run.numberOfGlyphs );
849
850         if( synthesizeItalic )
851         {
852           // Restore the transform matrix to the identity.
853           cairo_matrix_t matrix;
854           cairo_matrix_init_identity( &matrix );
855           cairo_set_matrix( cr, &matrix );
856         }
857       }
858       cairo_fill( cr );
859     }
860   }
861
862   return pixelBuffer;
863 }
864
865 } // namespace Internal
866
867 } // namespace TextAbstraction
868
869 } // namespace Dali