Make alpha value pre-multiplied in all text cases
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / rendering / text-typesetter.cpp
1 /*
2  * Copyright (c) 2018 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 // CLASS HEADER
19 #include <dali-toolkit/internal/text/rendering/text-typesetter.h>
20
21 // EXTERNAL INCLUDES
22 #include <memory.h>
23 #include <dali/devel-api/text-abstraction/font-client.h>
24 #include <dali/public-api/common/constants.h>
25
26 // INTERNAL INCLUDES
27 #include <dali-toolkit/internal/text/rendering/view-model.h>
28 #include <dali-toolkit/devel-api/controls/text-controls/text-label-devel.h>
29
30 namespace Dali
31 {
32
33 namespace Toolkit
34 {
35
36 namespace Text
37 {
38
39 namespace
40 {
41
42 /**
43  * @brief Data struct used to set the buffer of the glyph's bitmap into the final bitmap's buffer.
44  */
45 struct GlyphData
46 {
47   Devel::PixelBuffer                           bitmapBuffer;     ///< The buffer of the whole bitmap. The format is RGBA8888.
48   Vector2*                                     position;         ///< The position of the glyph.
49   TextAbstraction::FontClient::GlyphBufferData glyphBitmap;      ///< The glyph's bitmap.
50   unsigned int                                 width;            ///< The bitmap's width.
51   unsigned int                                 height;           ///< The bitmap's height.
52   int                                          horizontalOffset; ///< The horizontal offset to be added to the 'x' glyph's position.
53   int                                          verticalOffset;   ///< The vertical offset to be added to the 'y' glyph's position.
54 };
55
56 /**
57  * @brief Sets the glyph's buffer into the bitmap's buffer.
58  *
59  * @param[in] data Struct which contains the glyph's data and the bitmap's data.
60  * @param[in] position The position of the glyph.
61  * @param[in] color The color of the glyph.
62  * @param[in] style The style of the text.
63  * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
64  */
65 void TypesetGlyph( GlyphData& data,
66                    const Vector2* const position,
67                    const Vector4* const color,
68                    Typesetter::Style style,
69                    Pixel::Format pixelFormat )
70 {
71   if( ( 0u == data.glyphBitmap.width ) || ( 0u == data.glyphBitmap.height ) )
72   {
73     // Nothing to do if the width or height of the buffer is zero.
74     return;
75   }
76
77   const int widthMinusOne = static_cast<int>( data.width - 1u );
78   const int heightMinusOne = static_cast<int>( data.height - 1u );
79
80   if ( Pixel::RGBA8888 == pixelFormat )
81   {
82     // Whether the given glyph is a color one.
83     const bool isColorGlyph = Pixel::BGRA8888 == data.glyphBitmap.format;
84
85     // Pointer to the color glyph if there is one.
86     const uint32_t* const colorGlyphBuffer = isColorGlyph ? reinterpret_cast<uint32_t*>( data.glyphBitmap.buffer ) : NULL;
87
88     // Initial vertical offset.
89     const int yOffset = data.verticalOffset + position->y;
90
91     // Traverse the pixels of the glyph line per line.
92     for( int lineIndex = 0, glyphHeight = static_cast<int>( data.glyphBitmap.height ); lineIndex < glyphHeight; ++lineIndex )
93     {
94       const int yOffsetIndex = yOffset + lineIndex;
95       if( ( 0 > yOffsetIndex ) || ( yOffsetIndex > heightMinusOne ) )
96       {
97         // Do not write out of bounds.
98         continue;
99       }
100
101       const int verticalOffset = yOffsetIndex * data.width;
102       const int xOffset = data.horizontalOffset + position->x;
103       const int glyphBufferOffset = lineIndex * static_cast<int>( data.glyphBitmap.width );
104       for( int index = 0, glyphWidth = static_cast<int>( data.glyphBitmap.width ); index < glyphWidth; ++index )
105       {
106         const int xOffsetIndex = xOffset + index;
107         if( ( 0 > xOffsetIndex ) || ( xOffsetIndex > widthMinusOne ) )
108         {
109           // Don't write out of bounds.
110           continue;
111         }
112
113         uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( data.bitmapBuffer.GetBuffer() );
114
115         if( isColorGlyph )
116         {
117           // Retrieves the color from the color glyph. The format is BGRA8888.
118           uint32_t packedColorGlyph = *( colorGlyphBuffer + glyphBufferOffset + index );
119           uint8_t* packedColorGlyphBuffer = reinterpret_cast<uint8_t*>( &packedColorGlyph );
120
121           // Update the alpha channel.
122           if( Typesetter::STYLE_MASK == style || Typesetter::STYLE_OUTLINE == style ) // Outline not shown for color glyph
123           {
124             // Create an alpha mask for color glyph.
125             *( packedColorGlyphBuffer + 3u ) = 0u;
126             *( packedColorGlyphBuffer + 2u ) = 0u;
127             *( packedColorGlyphBuffer + 1u ) = 0u;
128               *packedColorGlyphBuffer        = 0u;
129           }
130           else
131           {
132             uint8_t colorAlpha = static_cast<uint8_t>( color->a * static_cast<float>( *( packedColorGlyphBuffer + 3u ) ) );
133             *( packedColorGlyphBuffer + 3u ) = colorAlpha;
134
135             if( Typesetter::STYLE_SHADOW == style )
136             {
137               // The shadow of color glyph needs to have the shadow color.
138               *( packedColorGlyphBuffer + 2u ) = static_cast<uint8_t>( color->b * colorAlpha );
139               *( packedColorGlyphBuffer + 1u ) = static_cast<uint8_t>( color->g * colorAlpha );
140                 *packedColorGlyphBuffer        = static_cast<uint8_t>( color->r * colorAlpha );
141             }
142             else
143             {
144               std::swap( *packedColorGlyphBuffer, *( packedColorGlyphBuffer + 2u ) ); // Swap B and R.
145
146               *( packedColorGlyphBuffer + 2u ) = ( *( packedColorGlyphBuffer + 2u ) * colorAlpha / 255 );
147               *( packedColorGlyphBuffer + 1u ) = ( *( packedColorGlyphBuffer + 1u ) * colorAlpha / 255 );
148                 *packedColorGlyphBuffer        = ( *( packedColorGlyphBuffer      ) * colorAlpha / 255 );
149             }
150           }
151
152           // Set the color into the final pixel buffer.
153           *( bitmapBuffer + verticalOffset + xOffsetIndex ) = packedColorGlyph;
154         }
155         else
156         {
157           // Pack the given color into a 32bit buffer. The alpha channel will be updated later for each pixel.
158           // The format is RGBA8888.
159           uint32_t packedColor = 0u;
160           uint8_t* packedColorBuffer = reinterpret_cast<uint8_t*>( &packedColor );
161
162           // Update the alpha channel.
163           const uint8_t alpha = *( data.glyphBitmap.buffer + glyphBufferOffset + index );
164
165           // Copy non-transparent pixels only
166           if ( alpha > 0u )
167           {
168             // Check alpha of overlapped pixels
169             uint32_t& currentColor = *( bitmapBuffer + verticalOffset + xOffsetIndex );
170             uint8_t* packedCurrentColorBuffer = reinterpret_cast<uint8_t*>( &currentColor );
171
172             // For any pixel overlapped with the pixel in previous glyphs, make sure we don't
173             // overwrite a previous bigger alpha with a smaller alpha (in order to avoid
174             // semi-transparent gaps between joint glyphs with overlapped pixels, which could
175             // happen, for example, in the RTL text when we copy glyphs from right to left).
176             uint8_t currentAlpha = *( packedCurrentColorBuffer + 3u );
177             currentAlpha = std::max( currentAlpha, alpha );
178
179             // Color is pre-muliplied with its alpha.
180             *( packedColorBuffer + 3u ) = static_cast<uint8_t>( color->a * currentAlpha );
181             *( packedColorBuffer + 2u ) = static_cast<uint8_t>( color->b * currentAlpha );
182             *( packedColorBuffer + 1u ) = static_cast<uint8_t>( color->g * currentAlpha );
183             *( packedColorBuffer      ) = static_cast<uint8_t>( color->r * currentAlpha );
184
185             // Set the color into the final pixel buffer.
186             currentColor = packedColor;
187           }
188         }
189       }
190     }
191   }
192   else
193   {
194     // Whether the given glyph is a color one.
195     const bool isColorGlyph = Pixel::BGRA8888 == data.glyphBitmap.format;
196
197     // Initial vertical offset.
198     const int yOffset = data.verticalOffset + position->y;
199
200     // Traverse the pixels of the glyph line per line.
201     for( int lineIndex = 0, glyphHeight = static_cast<int>( data.glyphBitmap.height ); lineIndex < glyphHeight; ++lineIndex )
202     {
203       const int yOffsetIndex = yOffset + lineIndex;
204       if( ( 0 > yOffsetIndex ) || ( yOffsetIndex > heightMinusOne ) )
205       {
206         // Do not write out of bounds.
207         continue;
208       }
209
210       const int verticalOffset = yOffsetIndex * data.width;
211       const int xOffset = data.horizontalOffset + position->x;
212       const int glyphBufferOffset = lineIndex * static_cast<int>( data.glyphBitmap.width );
213       for( int index = 0, glyphWidth = static_cast<int>( data.glyphBitmap.width ); index < glyphWidth; ++index )
214       {
215         const int xOffsetIndex = xOffset + index;
216         if( ( 0 > xOffsetIndex ) || ( xOffsetIndex > widthMinusOne ) )
217         {
218           // Don't write out of bounds.
219           continue;
220         }
221
222         uint8_t* bitmapBuffer = reinterpret_cast< uint8_t* >( data.bitmapBuffer.GetBuffer() );
223
224         if ( !isColorGlyph )
225         {
226           // Update the alpha channel.
227           const uint8_t alpha = *( data.glyphBitmap.buffer + glyphBufferOffset + index );
228
229           // Copy non-transparent pixels only
230           if ( alpha > 0u )
231           {
232             // Check alpha of overlapped pixels
233             uint8_t& currentAlpha = *( bitmapBuffer + verticalOffset + xOffsetIndex );
234
235             // For any pixel overlapped with the pixel in previous glyphs, make sure we don't
236             // overwrite a previous bigger alpha with a smaller alpha (in order to avoid
237             // semi-transparent gaps between joint glyphs with overlapped pixels, which could
238             // happen, for example, in the RTL text when we copy glyphs from right to left).
239             *( bitmapBuffer + verticalOffset + xOffsetIndex ) = std::max( currentAlpha, alpha );
240           }
241         }
242       }
243     }
244   }
245 }
246
247 bool IsGlyphUnderlined( GlyphIndex index,
248                          const Vector<GlyphRun>& underlineRuns )
249 {
250   for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
251          endIt = underlineRuns.End();
252          it != endIt;
253        ++it )
254   {
255     const GlyphRun& run = *it;
256
257     if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
258     {
259       return true;
260     }
261   }
262
263   return false;
264 }
265
266 } // namespace
267
268 TypesetterPtr Typesetter::New( const ModelInterface* const model )
269 {
270   return TypesetterPtr( new Typesetter( model ) );
271 }
272
273 ViewModel* Typesetter::GetViewModel()
274 {
275   return mModel;
276 }
277
278 PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirection::Type textDirection, RenderBehaviour behaviour, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat )
279 {
280   // @todo. This initial implementation for a TextLabel has only one visible page.
281
282   // Elides the text if needed.
283   mModel->ElideGlyphs();
284
285   // Retrieves the layout size.
286   const Size& layoutSize = mModel->GetLayoutSize();
287
288   const float outlineWidth = mModel->GetOutlineWidth();
289
290   // Set the offset for the horizontal alignment according to the text direction and outline width.
291   int penX = 0;
292
293   switch( mModel->GetHorizontalAlignment() )
294   {
295     case HorizontalAlignment::BEGIN:
296     {
297       // No offset to add.
298       break;
299     }
300     case HorizontalAlignment::CENTER:
301     {
302       penX += ( textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT ) ? -outlineWidth : outlineWidth;
303       break;
304     }
305     case HorizontalAlignment::END:
306     {
307       penX += ( textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT ) ? -outlineWidth * 2.0f : outlineWidth * 2.0f;
308       break;
309     }
310   }
311
312   // Set the offset for the vertical alignment.
313   int penY = 0;
314
315   switch( mModel->GetVerticalAlignment() )
316   {
317     case VerticalAlignment::TOP:
318     {
319       // No offset to add.
320       break;
321     }
322     case VerticalAlignment::CENTER:
323     {
324       penY = static_cast<int>( 0.5f * ( size.height - layoutSize.height ) );
325       break;
326     }
327     case VerticalAlignment::BOTTOM:
328     {
329       penY = static_cast<int>( size.height - layoutSize.height );
330       break;
331     }
332   }
333
334   // Calculate vertical line alignment
335   switch( mModel->GetVerticalLineAlignment() )
336   {
337     case DevelText::VerticalLineAlignment::TOP:
338     {
339       break;
340     }
341     case DevelText::VerticalLineAlignment::MIDDLE:
342     {
343       const auto& line = *mModel->GetLines();
344       penY -= line.descender;
345       penY += static_cast<int>(line.lineSpacing*0.5f + line.descender);
346       break;
347     }
348     case DevelText::VerticalLineAlignment::BOTTOM:
349     {
350       const auto& line = *mModel->GetLines();
351       const auto lineHeight = line.ascender + (-line.descender) + line.lineSpacing;
352       penY += static_cast<int>(lineHeight - (line.ascender - line.descender));
353       break;
354     }
355   }
356
357   // Generate the image buffers of the text for each different style first,
358   // then combine all of them together as one final image buffer. We try to
359   // do all of these in CPU only, so that once the final texture is generated,
360   // no calculation is needed in GPU during each frame.
361
362   const unsigned int bufferWidth = static_cast<unsigned int>( size.width );
363   const unsigned int bufferHeight = static_cast<unsigned int>( size.height );
364
365   const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
366   const unsigned int bufferSizeChar = 4u * bufferSizeInt;
367
368   Length numberOfGlyphs = mModel->GetNumberOfGlyphs();
369
370   Devel::PixelBuffer imageBuffer;
371
372   if( RENDER_MASK == behaviour )
373   {
374     // Generate the image buffer as an alpha mask for color glyphs.
375     imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 );
376   }
377   else if( RENDER_NO_TEXT == behaviour )
378   {
379     // Generate an empty image buffer so that it can been combined with the image buffers for styles
380     imageBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
381     memset( imageBuffer.GetBuffer(), 0u, bufferSizeChar );
382   }
383   else
384   {
385     // Generate the image buffer for the text with no style.
386     imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 );
387   }
388
389   if ( ( RENDER_NO_STYLES != behaviour ) && ( RENDER_MASK != behaviour ) )
390   {
391
392     // Generate the outline if enabled
393     const float outlineWidth = mModel->GetOutlineWidth();
394     if ( outlineWidth > Math::MACHINE_EPSILON_1 )
395     {
396       // Create the image buffer for outline
397       Devel::PixelBuffer outlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 );
398
399       // Combine the two buffers
400       imageBuffer = CombineImageBuffer( imageBuffer, outlineImageBuffer, bufferWidth, bufferHeight );
401     }
402
403     // @todo. Support shadow and underline for partial text later on.
404
405     // Generate the shadow if enabled
406     const Vector2& shadowOffset = mModel->GetShadowOffset();
407     if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
408     {
409       // Create the image buffer for shadow
410       Devel::PixelBuffer shadowImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 );
411
412       // Check whether it will be a soft shadow
413       const float& blurRadius = mModel->GetShadowBlurRadius();
414
415       if ( blurRadius > Math::MACHINE_EPSILON_1 )
416       {
417         shadowImageBuffer.ApplyGaussianBlur( blurRadius );
418       }
419
420       // Combine the two buffers
421       imageBuffer = CombineImageBuffer( imageBuffer, shadowImageBuffer, bufferWidth, bufferHeight );
422     }
423
424     // Generate the underline if enabled
425     const bool underlineEnabled = mModel->IsUnderlineEnabled();
426     if ( underlineEnabled )
427     {
428       // Create the image buffer for underline
429       Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 );
430
431       // Combine the two buffers
432       imageBuffer = CombineImageBuffer( imageBuffer, underlineImageBuffer, bufferWidth, bufferHeight );
433     }
434
435     // Generate the background if enabled
436     const bool backgroundEnabled = mModel->IsBackgroundEnabled();
437     if ( backgroundEnabled )
438     {
439       Devel::PixelBuffer backgroundImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_BACKGROUND, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 );
440
441       // Combine the two buffers
442       imageBuffer = CombineImageBuffer( imageBuffer, backgroundImageBuffer, bufferWidth, bufferHeight );
443     }
444   }
445
446   // Create the final PixelData for the combined image buffer
447   PixelData pixelData = Devel::PixelBuffer::Convert( imageBuffer );
448
449   return pixelData;
450 }
451
452 Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth, const unsigned int bufferHeight, Typesetter::Style style, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat, int horizontalOffset, int verticalOffset, GlyphIndex fromGlyphIndex, GlyphIndex toGlyphIndex )
453 {
454   // Retrieve lines, glyphs, positions and colors from the view model.
455   const Length modelNumberOfLines = mModel->GetNumberOfLines();
456   const LineRun* const modelLinesBuffer = mModel->GetLines();
457   const Length numberOfGlyphs = mModel->GetNumberOfGlyphs();
458   const GlyphInfo* const glyphsBuffer = mModel->GetGlyphs();
459   const Vector2* const positionBuffer = mModel->GetLayout();
460   const Vector4* const colorsBuffer = mModel->GetColors();
461   const ColorIndex* const colorIndexBuffer = mModel->GetColorIndices();
462
463   // Whether to use the default color.
464   const bool useDefaultColor = ( NULL == colorsBuffer );
465   const Vector4& defaultColor = mModel->GetDefaultColor();
466
467   // Create and initialize the pixel buffer.
468   GlyphData glyphData;
469   glyphData.verticalOffset = verticalOffset;
470   glyphData.width = bufferWidth;
471   glyphData.height = bufferHeight;
472   glyphData.bitmapBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, pixelFormat );
473   glyphData.horizontalOffset = 0;
474
475   if ( Pixel::RGBA8888 == pixelFormat )
476   {
477     const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
478     const unsigned int bufferSizeChar = 4u * bufferSizeInt;
479     memset( glyphData.bitmapBuffer.GetBuffer(), 0u, bufferSizeChar );
480   }
481   else
482   {
483     memset( glyphData.bitmapBuffer.GetBuffer(), 0, bufferWidth * bufferHeight );
484   }
485
486   // Get a handle of the font client. Used to retrieve the bitmaps of the glyphs.
487   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
488
489   // Traverses the lines of the text.
490   for( LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex )
491   {
492     const LineRun& line = *( modelLinesBuffer + lineIndex );
493
494     // Sets the horizontal offset of the line.
495     glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast<int>( line.alignmentOffset );
496     glyphData.horizontalOffset += horizontalOffset;
497
498     // Increases the vertical offset with the line's ascender.
499     glyphData.verticalOffset += static_cast<int>( line.ascender );
500
501     // Include line spacing after first line
502     if( lineIndex > 0u )
503     {
504       glyphData.verticalOffset += static_cast<int>( line.lineSpacing );
505     }
506
507     // Retrieves the glyph's outline width
508     float outlineWidth = mModel->GetOutlineWidth();
509
510     if( style == Typesetter::STYLE_OUTLINE )
511     {
512       glyphData.horizontalOffset -= outlineWidth;
513       if( lineIndex == 0u )
514       {
515         // Only need to add the vertical outline offset for the first line
516         glyphData.verticalOffset -= outlineWidth;
517       }
518     }
519     else if ( style == Typesetter::STYLE_SHADOW )
520     {
521       const Vector2& shadowOffset = mModel->GetShadowOffset();
522       glyphData.horizontalOffset += shadowOffset.x - outlineWidth; // if outline enabled then shadow should offset from outline
523
524       if ( lineIndex == 0u )
525       {
526         // Only need to add the vertical shadow offset for first line
527         glyphData.verticalOffset += shadowOffset.y - outlineWidth;
528       }
529     }
530
531     const bool underlineEnabled = mModel->IsUnderlineEnabled();
532     const Vector4& underlineColor = mModel->GetUnderlineColor();
533     const float underlineHeight = mModel->GetUnderlineHeight();
534
535     // Get the underline runs.
536     const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns();
537     Vector<GlyphRun> underlineRuns;
538     underlineRuns.Resize( numberOfUnderlineRuns );
539     mModel->GetUnderlineRuns( underlineRuns.Begin(), 0u, numberOfUnderlineRuns );
540
541     bool thereAreUnderlinedGlyphs = false;
542
543     float currentUnderlinePosition = 0.0f;
544     float currentUnderlineThickness = underlineHeight;
545     float maxUnderlineThickness = currentUnderlineThickness;
546
547     FontId lastUnderlinedFontId = 0;
548
549     float lineExtentLeft = bufferWidth;
550     float lineExtentRight = 0.0f;
551     float baseline = 0.0f;
552
553     // Traverses the glyphs of the line.
554     const GlyphIndex endGlyphIndex = std::min( numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs );
555     for( GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex )
556     {
557       if ( glyphIndex < fromGlyphIndex || glyphIndex > toGlyphIndex )
558       {
559         // Ignore any glyph that out of the specified range
560         continue;
561       }
562
563       // Retrieve the glyph's info.
564       const GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
565
566       if( ( glyphInfo->width < Math::MACHINE_EPSILON_1000 ) ||
567           ( glyphInfo->height < Math::MACHINE_EPSILON_1000 ) )
568       {
569         // Nothing to do if the glyph's width or height is zero.
570         continue;
571       }
572
573       const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( glyphIndex, underlineRuns );
574       thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
575
576       // Are we still using the same fontId as previous
577       if( underlineGlyph && ( glyphInfo->fontId != lastUnderlinedFontId ) )
578       {
579         // We need to fetch fresh font underline metrics
580         FontMetrics fontMetrics;
581         fontClient.GetFontMetrics( glyphInfo->fontId, fontMetrics );
582         currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
583         const float descender = ceil( fabsf( fontMetrics.descender ) );
584
585         if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
586         {
587           currentUnderlineThickness = fontMetrics.underlineThickness;
588
589           // Ensure underline will be at least a pixel high
590           if ( currentUnderlineThickness < 1.0f )
591           {
592             currentUnderlineThickness = 1.0f;
593           }
594           else
595           {
596             currentUnderlineThickness = ceil( currentUnderlineThickness );
597           }
598         }
599
600         // The underline thickness should be the max underline thickness of all glyphs of the line.
601         if ( currentUnderlineThickness > maxUnderlineThickness )
602         {
603           maxUnderlineThickness = currentUnderlineThickness;
604         }
605
606         // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
607         if( currentUnderlinePosition > descender )
608         {
609           currentUnderlinePosition = descender;
610         }
611
612         if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
613         {
614           // Move offset down by one ( EFL behavior )
615           currentUnderlinePosition = 1.0f;
616         }
617
618         lastUnderlinedFontId = glyphInfo->fontId;
619       } // underline
620
621       // Retrieves the glyph's position.
622       const Vector2* const position = positionBuffer + glyphIndex;
623       if ( baseline < position->y + glyphInfo->yBearing )
624       {
625         baseline = position->y + glyphInfo->yBearing;
626       }
627
628       // Calculate the positions of leftmost and rightmost glyphs in the current line
629       if ( position->x < lineExtentLeft)
630       {
631         lineExtentLeft = position->x;
632       }
633
634       if ( position->x + glyphInfo->width > lineExtentRight)
635       {
636         lineExtentRight = position->x + glyphInfo->width;
637       }
638
639       // Retrieves the glyph's color.
640       const ColorIndex colorIndex = *( colorIndexBuffer + glyphIndex );
641
642       Vector4 color;
643       if ( style == Typesetter::STYLE_SHADOW )
644       {
645         color = mModel->GetShadowColor();
646       }
647       else if ( style == Typesetter::STYLE_OUTLINE )
648       {
649         color = mModel->GetOutlineColor();
650       }
651       else
652       {
653         color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + ( colorIndex - 1u ) );
654       }
655
656       // Premultiply alpha
657       color.r *= color.a;
658       color.g *= color.a;
659       color.b *= color.a;
660
661       // Retrieves the glyph's bitmap.
662       glyphData.glyphBitmap.buffer = NULL;
663       glyphData.glyphBitmap.width = glyphInfo->width;   // Desired width and height.
664       glyphData.glyphBitmap.height = glyphInfo->height;
665
666       if( style != Typesetter::STYLE_OUTLINE && style != Typesetter::STYLE_SHADOW )
667       {
668         // Don't render outline for other styles
669         outlineWidth = 0.0f;
670       }
671       if( style != Typesetter::STYLE_UNDERLINE )
672       {
673         fontClient.CreateBitmap( glyphInfo->fontId,
674                                  glyphInfo->index,
675                                  glyphData.glyphBitmap,
676                                  outlineWidth );
677       }
678
679
680       // Sets the glyph's bitmap into the bitmap of the whole text.
681       if( NULL != glyphData.glyphBitmap.buffer )
682       {
683         TypesetGlyph( glyphData,
684                       position,
685                       &color,
686                       style,
687                       pixelFormat);
688         // delete the glyphBitmap.buffer as it is now copied into glyphData.bitmapBuffer
689         delete []glyphData.glyphBitmap.buffer;
690         glyphData.glyphBitmap.buffer = NULL;
691       }
692     }
693
694     // Draw the underline from the leftmost glyph to the rightmost glyph
695     if ( thereAreUnderlinedGlyphs && style == Typesetter::STYLE_UNDERLINE )
696     {
697       int underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition;
698
699       for( unsigned int y = underlineYOffset; y < underlineYOffset + maxUnderlineThickness; y++ )
700       {
701         if( y > bufferHeight - 1 )
702         {
703           // Do not write out of bounds.
704           break;
705         }
706
707         for( unsigned int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++ )
708         {
709           if( x > bufferWidth - 1 )
710           {
711             // Do not write out of bounds.
712             break;
713           }
714
715           // Always RGBA image for text with styles
716           uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( glyphData.bitmapBuffer.GetBuffer() );
717           uint32_t underlinePixel = *( bitmapBuffer + y * glyphData.width + x );
718           uint8_t* underlinePixelBuffer = reinterpret_cast<uint8_t*>( &underlinePixel );
719
720           // Write the underline color to the pixel buffer
721           uint8_t colorAlpha = static_cast< uint8_t >( underlineColor.a * 255.f );
722           *( underlinePixelBuffer + 3u ) = colorAlpha;
723           *( underlinePixelBuffer + 2u ) = static_cast< uint8_t >( underlineColor.b * colorAlpha );
724           *( underlinePixelBuffer + 1u ) = static_cast< uint8_t >( underlineColor.g * colorAlpha );
725           *( underlinePixelBuffer      ) = static_cast< uint8_t >( underlineColor.r * colorAlpha );
726
727           *( bitmapBuffer + y * glyphData.width + x ) = underlinePixel;
728         }
729       }
730     }
731
732     // Draw the background color from the leftmost glyph to the rightmost glyph
733     if ( style == Typesetter::STYLE_BACKGROUND )
734     {
735       Vector4 backgroundColor = mModel->GetBackgroundColor();
736
737       for( int y = glyphData.verticalOffset + baseline - line.ascender; y < glyphData.verticalOffset + baseline - line.descender; y++ )
738       {
739         if( ( y < 0 ) || ( y > static_cast<int>(bufferHeight - 1) ) )
740         {
741           // Do not write out of bounds.
742           continue;
743         }
744
745         for( int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++ )
746         {
747           if( ( x < 0 ) || ( x > static_cast<int>(bufferWidth - 1) ) )
748           {
749             // Do not write out of bounds.
750             continue;
751           }
752
753           // Always RGBA image for text with styles
754           uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( glyphData.bitmapBuffer.GetBuffer() );
755           uint32_t backgroundPixel = *( bitmapBuffer + y * glyphData.width + x );
756           uint8_t* backgroundPixelBuffer = reinterpret_cast<uint8_t*>( &backgroundPixel );
757
758           // Write the background color to the pixel buffer
759           uint8_t colorAlpha = static_cast< uint8_t >( backgroundColor.a * 255.f );
760           *( backgroundPixelBuffer + 3u ) = colorAlpha;
761           *( backgroundPixelBuffer + 2u ) = static_cast< uint8_t >( backgroundColor.b * colorAlpha );
762           *( backgroundPixelBuffer + 1u ) = static_cast< uint8_t >( backgroundColor.g * colorAlpha );
763           *( backgroundPixelBuffer      ) = static_cast< uint8_t >( backgroundColor.r * colorAlpha );
764
765           *( bitmapBuffer + y * glyphData.width + x ) = backgroundPixel;
766         }
767       }
768     }
769
770     // Increases the vertical offset with the line's descender.
771     glyphData.verticalOffset += static_cast<int>( -line.descender );
772   }
773
774   return glyphData.bitmapBuffer;
775 }
776
777 Devel::PixelBuffer Typesetter::CombineImageBuffer( Devel::PixelBuffer topPixelBuffer, Devel::PixelBuffer bottomPixelBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight )
778 {
779   unsigned char* topBuffer = topPixelBuffer.GetBuffer();
780   unsigned char* bottomBuffer = bottomPixelBuffer.GetBuffer();
781
782   Devel::PixelBuffer combinedPixelBuffer;
783
784   if ( topBuffer == NULL && bottomBuffer == NULL )
785   {
786     // Nothing to do if both buffers are empty.
787     return combinedPixelBuffer;
788   }
789
790   if ( topBuffer == NULL )
791   {
792     // Nothing to do if topBuffer is empty.
793     return bottomPixelBuffer;
794   }
795
796   if ( bottomBuffer == NULL )
797   {
798     // Nothing to do if bottomBuffer is empty.
799     return topPixelBuffer;
800   }
801
802   // Always combine two RGBA images
803   const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
804   const unsigned int bufferSizeChar = 4u * bufferSizeInt;
805
806   combinedPixelBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
807   uint8_t* combinedBuffer = reinterpret_cast< uint8_t* >( combinedPixelBuffer.GetBuffer() );
808   memset( combinedBuffer, 0u, bufferSizeChar );
809
810   for (unsigned int pixelIndex = 0; pixelIndex < bufferSizeInt; pixelIndex++)
811   {
812     // If the alpha of the pixel in either buffer is not fully opaque, blend the two pixels.
813     // Otherwise, copy pixel from topBuffer to combinedBuffer.
814
815     unsigned int alphaBuffer1 = topBuffer[pixelIndex*4+3];
816
817     if ( alphaBuffer1 != 255 )
818     {
819       // At least one pixel is not fully opaque
820       // "Over" blend the the pixel from topBuffer with the pixel in bottomBuffer
821       combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4] + ( bottomBuffer[pixelIndex*4] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
822       combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1] + ( bottomBuffer[pixelIndex*4+1] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
823       combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2] + ( bottomBuffer[pixelIndex*4+2] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
824       combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3] + ( bottomBuffer[pixelIndex*4+3] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
825     }
826     else
827     {
828       // Copy the pixel from topBuffer to combinedBuffer
829       combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4];
830       combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1];
831       combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2];
832       combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3];
833     }
834   }
835
836   return combinedPixelBuffer;
837 }
838
839 Typesetter::Typesetter( const ModelInterface* const model )
840 : mModel( new ViewModel( model ) )
841 {
842 }
843
844 Typesetter::~Typesetter()
845 {
846   delete mModel;
847 }
848
849 } // namespace Text
850
851 } // namespace Toolkit
852
853 } // namespace Dali