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