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