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