[4.0] 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, 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   // Set the offset for the vertical alignment.
289   int penY = 0;
290
291   switch( mModel->GetVerticalAlignment() )
292   {
293     case VerticalAlignment::TOP:
294     {
295       // No offset to add.
296       break;
297     }
298     case VerticalAlignment::CENTER:
299     {
300       penY = static_cast<int>( 0.5f * ( size.height - layoutSize.height ) );
301       break;
302     }
303     case VerticalAlignment::BOTTOM:
304     {
305       penY = static_cast<int>( size.height - layoutSize.height );
306       break;
307     }
308   }
309
310   // Calculate vertical line alignment
311   switch( mModel->GetVerticalLineAlignment() )
312   {
313     case DevelText::VerticalLineAlignment::TOP:
314     {
315       break;
316     }
317     case DevelText::VerticalLineAlignment::MIDDLE:
318     {
319       const auto& line = *mModel->GetLines();
320       penY -= line.descender;
321       penY += static_cast<int>(line.lineSpacing*0.5f + line.descender);
322       break;
323     }
324     case DevelText::VerticalLineAlignment::BOTTOM:
325     {
326       const auto& line = *mModel->GetLines();
327       const auto lineHeight = line.ascender + (-line.descender) + line.lineSpacing;
328       penY += static_cast<int>(lineHeight - (line.ascender - line.descender));
329       break;
330     }
331   }
332
333   // Generate the image buffers of the text for each different style first,
334   // then combine all of them together as one final image buffer. We try to
335   // do all of these in CPU only, so that once the final texture is generated,
336   // no calculation is needed in GPU during each frame.
337
338   const unsigned int bufferWidth = static_cast<unsigned int>( size.width );
339   const unsigned int bufferHeight = static_cast<unsigned int>( size.height );
340
341   const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
342   const unsigned int bufferSizeChar = 4u * bufferSizeInt;
343
344   Length numberOfGlyphs = mModel->GetNumberOfGlyphs();
345
346   Devel::PixelBuffer imageBuffer;
347
348   if( RENDER_MASK == behaviour )
349   {
350     // Generate the image buffer as an alpha mask for color glyphs.
351     imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penY, 0u, numberOfGlyphs - 1 );
352   }
353   else if( RENDER_NO_TEXT == behaviour )
354   {
355     // Generate an empty image buffer so that it can been combined with the image buffers for styles
356     imageBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
357     memset( imageBuffer.GetBuffer(), 0u, bufferSizeChar );
358   }
359   else
360   {
361     // Generate the image buffer for the text with no style.
362     imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penY, 0u, numberOfGlyphs -1 );
363   }
364
365   if ( ( RENDER_NO_STYLES != behaviour ) && ( RENDER_MASK != behaviour ) )
366   {
367
368     // Generate the outline if enabled
369     const float outlineWidth = mModel->GetOutlineWidth();
370     if ( outlineWidth > Math::MACHINE_EPSILON_1 )
371     {
372       // Create the image buffer for outline
373       Devel::PixelBuffer outlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penY, 0u, numberOfGlyphs -1 );
374
375       // Combine the two buffers
376       imageBuffer = CombineImageBuffer( imageBuffer, outlineImageBuffer, bufferWidth, bufferHeight );
377     }
378
379     // @todo. Support shadow and underline for partial text later on.
380
381     // Generate the shadow if enabled
382     const Vector2& shadowOffset = mModel->GetShadowOffset();
383     if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
384     {
385       // Create the image buffer for shadow
386       Devel::PixelBuffer shadowImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penY, 0u, numberOfGlyphs - 1 );
387
388       // Check whether it will be a soft shadow
389       const float& blurRadius = mModel->GetShadowBlurRadius();
390
391       if ( blurRadius > Math::MACHINE_EPSILON_1 )
392       {
393         shadowImageBuffer.ApplyGaussianBlur( blurRadius );
394       }
395
396       // Combine the two buffers
397       imageBuffer = CombineImageBuffer( imageBuffer, shadowImageBuffer, bufferWidth, bufferHeight );
398     }
399
400     // Generate the underline if enabled
401     const bool underlineEnabled = mModel->IsUnderlineEnabled();
402     if ( underlineEnabled )
403     {
404       // Create the image buffer for underline
405       Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penY, 0u, numberOfGlyphs - 1 );
406
407       // Combine the two buffers
408       imageBuffer = CombineImageBuffer( imageBuffer, underlineImageBuffer, bufferWidth, bufferHeight );
409     }
410   }
411
412   // Create the final PixelData for the combined image buffer
413   PixelData pixelData = Devel::PixelBuffer::Convert( imageBuffer );
414
415   return pixelData;
416 }
417
418 Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth, const unsigned int bufferHeight, Typesetter::Style style, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat, int verticalOffset, GlyphIndex fromGlyphIndex, GlyphIndex toGlyphIndex )
419 {
420   // Retrieve lines, glyphs, positions and colors from the view model.
421   const Length modelNumberOfLines = mModel->GetNumberOfLines();
422   const LineRun* const modelLinesBuffer = mModel->GetLines();
423   const Length numberOfGlyphs = mModel->GetNumberOfGlyphs();
424   const GlyphInfo* const glyphsBuffer = mModel->GetGlyphs();
425   const Vector2* const positionBuffer = mModel->GetLayout();
426   const Vector4* const colorsBuffer = mModel->GetColors();
427   const ColorIndex* const colorIndexBuffer = mModel->GetColorIndices();
428
429   // Whether to use the default color.
430   const bool useDefaultColor = ( NULL == colorsBuffer );
431   const Vector4& defaultColor = mModel->GetDefaultColor();
432
433   // Create and initialize the pixel buffer.
434   GlyphData glyphData;
435   glyphData.verticalOffset = verticalOffset;
436   glyphData.width = bufferWidth;
437   glyphData.height = bufferHeight;
438   glyphData.bitmapBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, pixelFormat );
439   glyphData.horizontalOffset = 0;
440
441   if ( Pixel::RGBA8888 == pixelFormat )
442   {
443     const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
444     const unsigned int bufferSizeChar = 4u * bufferSizeInt;
445     memset( glyphData.bitmapBuffer.GetBuffer(), 0u, bufferSizeChar );
446   }
447   else
448   {
449     memset( glyphData.bitmapBuffer.GetBuffer(), 0, bufferWidth * bufferHeight );
450   }
451
452   // Get a handle of the font client. Used to retrieve the bitmaps of the glyphs.
453   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
454
455   // Traverses the lines of the text.
456   for( LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex )
457   {
458     const LineRun& line = *( modelLinesBuffer + lineIndex );
459
460     // Sets the horizontal offset of the line.
461     glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast<int>( line.alignmentOffset );
462
463     // Increases the vertical offset with the line's ascender.
464     glyphData.verticalOffset += static_cast<int>( line.ascender );
465
466     // Include line spacing after first line
467     if( lineIndex > 0u )
468     {
469       glyphData.verticalOffset += static_cast<int>( line.lineSpacing );
470     }
471
472     // Retrieves the glyph's outline width
473     float outlineWidth = mModel->GetOutlineWidth();
474
475     if( style == Typesetter::STYLE_OUTLINE )
476     {
477       glyphData.horizontalOffset -= outlineWidth;
478       if( lineIndex == 0u )
479       {
480         // Only need to add the vertical outline offset for the first line
481         glyphData.verticalOffset -= outlineWidth;
482       }
483     }
484     else if ( style == Typesetter::STYLE_SHADOW )
485     {
486       const Vector2& shadowOffset = mModel->GetShadowOffset();
487       glyphData.horizontalOffset += shadowOffset.x - outlineWidth; // if outline enabled then shadow should offset from outline
488
489       if ( lineIndex == 0u )
490       {
491         // Only need to add the vertical shadow offset for first line
492         glyphData.verticalOffset += shadowOffset.y - outlineWidth;
493       }
494     }
495
496     const bool underlineEnabled = mModel->IsUnderlineEnabled();
497     const Vector4& underlineColor = mModel->GetUnderlineColor();
498     const float underlineHeight = mModel->GetUnderlineHeight();
499
500     // Get the underline runs.
501     const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns();
502     Vector<GlyphRun> underlineRuns;
503     underlineRuns.Resize( numberOfUnderlineRuns );
504     mModel->GetUnderlineRuns( underlineRuns.Begin(), 0u, numberOfUnderlineRuns );
505
506     bool thereAreUnderlinedGlyphs = false;
507
508     float currentUnderlinePosition = 0.0f;
509     float currentUnderlineThickness = underlineHeight;
510     float maxUnderlineThickness = currentUnderlineThickness;
511
512     FontId lastUnderlinedFontId = 0;
513
514     float lineExtentLeft = bufferWidth;
515     float lineExtentRight = 0.0f;
516     float baseline = 0.0f;
517
518     // Traverses the glyphs of the line.
519     const GlyphIndex endGlyphIndex = std::min( numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs );
520     for( GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex )
521     {
522       if ( glyphIndex < fromGlyphIndex || glyphIndex > toGlyphIndex )
523       {
524         // Ignore any glyph that out of the specified range
525         continue;
526       }
527
528       // Retrieve the glyph's info.
529       const GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
530
531       if( ( glyphInfo->width < Math::MACHINE_EPSILON_1000 ) ||
532           ( glyphInfo->height < Math::MACHINE_EPSILON_1000 ) )
533       {
534         // Nothing to do if the glyph's width or height is zero.
535         continue;
536       }
537
538       const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( glyphIndex, underlineRuns );
539       thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
540
541       // Are we still using the same fontId as previous
542       if( underlineGlyph && ( glyphInfo->fontId != lastUnderlinedFontId ) )
543       {
544         // We need to fetch fresh font underline metrics
545         FontMetrics fontMetrics;
546         fontClient.GetFontMetrics( glyphInfo->fontId, fontMetrics );
547         currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
548         const float descender = ceil( fabsf( fontMetrics.descender ) );
549
550         if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
551         {
552           currentUnderlineThickness = fontMetrics.underlineThickness;
553
554           // Ensure underline will be at least a pixel high
555           if ( currentUnderlineThickness < 1.0f )
556           {
557             currentUnderlineThickness = 1.0f;
558           }
559           else
560           {
561             currentUnderlineThickness = ceil( currentUnderlineThickness );
562           }
563         }
564
565         // The underline thickness should be the max underline thickness of all glyphs of the line.
566         if ( currentUnderlineThickness > maxUnderlineThickness )
567         {
568           maxUnderlineThickness = currentUnderlineThickness;
569         }
570
571         // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
572         if( currentUnderlinePosition > descender )
573         {
574           currentUnderlinePosition = descender;
575         }
576
577         if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
578         {
579           // Move offset down by one ( EFL behavior )
580           currentUnderlinePosition = 1.0f;
581         }
582
583         lastUnderlinedFontId = glyphInfo->fontId;
584       } // underline
585
586       // Retrieves the glyph's position.
587       const Vector2* const position = positionBuffer + glyphIndex;
588       if ( baseline < position->y + glyphInfo->yBearing )
589       {
590         baseline = position->y + glyphInfo->yBearing;
591       }
592
593       // Calculate the positions of leftmost and rightmost glyphs in the current line
594       if ( position->x < lineExtentLeft)
595       {
596         lineExtentLeft = position->x;
597       }
598
599       if ( position->x + glyphInfo->width > lineExtentRight)
600       {
601         lineExtentRight = position->x + glyphInfo->width;
602       }
603
604       // Retrieves the glyph's color.
605       const ColorIndex colorIndex = *( colorIndexBuffer + glyphIndex );
606
607       Vector4 color;
608       if ( style == Typesetter::STYLE_SHADOW )
609       {
610         color = mModel->GetShadowColor();
611       }
612       else if ( style == Typesetter::STYLE_OUTLINE )
613       {
614         color = mModel->GetOutlineColor();
615       }
616       else
617       {
618         color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + ( colorIndex - 1u ) );
619       }
620
621       // Premultiply alpha
622       color.r *= color.a;
623       color.g *= color.a;
624       color.b *= color.a;
625
626       // Retrieves the glyph's bitmap.
627       glyphData.glyphBitmap.buffer = NULL;
628       glyphData.glyphBitmap.width = glyphInfo->width;   // Desired width and height.
629       glyphData.glyphBitmap.height = glyphInfo->height;
630
631       if( style != Typesetter::STYLE_OUTLINE && style != Typesetter::STYLE_SHADOW )
632       {
633         // Don't render outline for other styles
634         outlineWidth = 0.0f;
635       }
636       if( style != Typesetter::STYLE_UNDERLINE )
637       {
638         fontClient.CreateBitmap( glyphInfo->fontId,
639                                  glyphInfo->index,
640                                  glyphData.glyphBitmap,
641                                  outlineWidth );
642       }
643
644
645       // Sets the glyph's bitmap into the bitmap of the whole text.
646       if( NULL != glyphData.glyphBitmap.buffer )
647       {
648         TypesetGlyph( glyphData,
649                       position,
650                       &color,
651                       style,
652                       pixelFormat);
653         // delete the glyphBitmap.buffer as it is now copied into glyphData.bitmapBuffer
654         delete []glyphData.glyphBitmap.buffer;
655         glyphData.glyphBitmap.buffer = NULL;
656       }
657     }
658
659     // Draw the underline from the leftmost glyph to the rightmost glyph
660     if ( thereAreUnderlinedGlyphs && style == Typesetter::STYLE_UNDERLINE )
661     {
662       int underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition;
663
664       for( unsigned int y = underlineYOffset; y < underlineYOffset + maxUnderlineThickness; y++ )
665       {
666         if( y > bufferHeight - 1 )
667         {
668           // Do not write out of bounds.
669           break;
670         }
671
672         for( unsigned int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++ )
673         {
674           if( x > bufferWidth - 1 )
675           {
676             // Do not write out of bounds.
677             break;
678           }
679
680           // Always RGBA image for text with styles
681           uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( glyphData.bitmapBuffer.GetBuffer() );
682           uint32_t underlinePixel = *( bitmapBuffer + y * glyphData.width + x );
683           uint8_t* underlinePixelBuffer = reinterpret_cast<uint8_t*>( &underlinePixel );
684
685           // Write the underline color to the pixel buffer
686           uint8_t colorAlpha = static_cast< uint8_t >( underlineColor.a * 255.f );
687           *( underlinePixelBuffer + 3u ) = colorAlpha;
688           *( underlinePixelBuffer + 2u ) = static_cast< uint8_t >( underlineColor.b * colorAlpha );
689           *( underlinePixelBuffer + 1u ) = static_cast< uint8_t >( underlineColor.g * colorAlpha );
690           *( underlinePixelBuffer      ) = static_cast< uint8_t >( underlineColor.r * colorAlpha );
691
692           *( bitmapBuffer + y * glyphData.width + x ) = underlinePixel;
693         }
694       }
695     }
696
697     // Increases the vertical offset with the line's descender.
698     glyphData.verticalOffset += static_cast<int>( -line.descender );
699   }
700
701   return glyphData.bitmapBuffer;
702 }
703
704 Devel::PixelBuffer Typesetter::CombineImageBuffer( Devel::PixelBuffer topPixelBuffer, Devel::PixelBuffer bottomPixelBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight )
705 {
706   unsigned char* topBuffer = topPixelBuffer.GetBuffer();
707   unsigned char* bottomBuffer = bottomPixelBuffer.GetBuffer();
708
709   Devel::PixelBuffer combinedPixelBuffer;
710
711   if ( topBuffer == NULL && bottomBuffer == NULL )
712   {
713     // Nothing to do if both buffers are empty.
714     return combinedPixelBuffer;
715   }
716
717   if ( topBuffer == NULL )
718   {
719     // Nothing to do if topBuffer is empty.
720     return bottomPixelBuffer;
721   }
722
723   if ( bottomBuffer == NULL )
724   {
725     // Nothing to do if bottomBuffer is empty.
726     return topPixelBuffer;
727   }
728
729   // Always combine two RGBA images
730   const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
731   const unsigned int bufferSizeChar = 4u * bufferSizeInt;
732
733   combinedPixelBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
734   uint8_t* combinedBuffer = reinterpret_cast< uint8_t* >( combinedPixelBuffer.GetBuffer() );
735   memset( combinedBuffer, 0u, bufferSizeChar );
736
737   for (unsigned int pixelIndex = 0; pixelIndex < bufferSizeInt; pixelIndex++)
738   {
739     // If the alpha of the pixel in either buffer is not fully opaque, blend the two pixels.
740     // Otherwise, copy pixel from topBuffer to combinedBuffer.
741
742     unsigned int alphaBuffer1 = topBuffer[pixelIndex*4+3];
743
744     if ( alphaBuffer1 != 255 )
745     {
746       // At least one pixel is not fully opaque
747       // "Over" blend the the pixel from topBuffer with the pixel in bottomBuffer
748       combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4] + ( bottomBuffer[pixelIndex*4] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
749       combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1] + ( bottomBuffer[pixelIndex*4+1] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
750       combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2] + ( bottomBuffer[pixelIndex*4+2] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
751       combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3] + ( bottomBuffer[pixelIndex*4+3] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
752     }
753     else
754     {
755       // Copy the pixel from topBuffer to combinedBuffer
756       combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4];
757       combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1];
758       combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2];
759       combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3];
760     }
761   }
762
763   return combinedPixelBuffer;
764 }
765
766 Typesetter::Typesetter( const ModelInterface* const model )
767 : mModel( new ViewModel( model ) )
768 {
769 }
770
771 Typesetter::~Typesetter()
772 {
773   delete mModel;
774 }
775
776 } // namespace Text
777
778 } // namespace Toolkit
779
780 } // namespace Dali