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