Merge "replaced toolkit pushbutton images with shorter images." into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / layouts / layout-engine.cpp
1 /*
2  * Copyright (c) 2015 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/layouts/layout-engine.h>
20
21 // EXTERNAL INCLUDES
22 #include <limits>
23 #include <dali/public-api/math/vector2.h>
24 #include <dali/devel-api/text-abstraction/font-client.h>
25 #include <dali/integration-api/debug.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
29 #include <dali-toolkit/internal/text/bidirectional-line-info-run.h>
30
31 namespace Dali
32 {
33
34 namespace Toolkit
35 {
36
37 namespace Text
38 {
39
40 namespace
41 {
42
43 #if defined(DEBUG_ENABLED)
44   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_LAYOUT");
45 #endif
46
47 const float MAX_FLOAT = std::numeric_limits<float>::max();
48 const bool RTL = true;
49
50 } //namespace
51
52 /**
53  * @brief Stores temporary layout info of the line.
54  */
55 struct LineLayout
56 {
57   LineLayout()
58   : glyphIndex( 0u ),
59     characterIndex( 0u ),
60     numberOfGlyphs( 0u ),
61     numberOfCharacters( 0u ),
62     length( 0.f ),
63     extraBearing( 0.f ),
64     extraWidth( 0.f ),
65     wsLengthEndOfLine( 0.f ),
66     ascender( 0.f ),
67     descender( MAX_FLOAT )
68   {}
69
70   ~LineLayout()
71   {}
72
73   void Clear()
74   {
75     glyphIndex = 0u;
76     characterIndex = 0u;
77     numberOfGlyphs = 0u;
78     numberOfCharacters = 0u;
79     length = 0.f;
80     extraBearing = 0.f;
81     extraWidth = 0.f;
82     wsLengthEndOfLine = 0.f;
83     ascender = 0.f;
84     descender = MAX_FLOAT;
85   }
86
87   GlyphIndex     glyphIndex;         ///< Index of the first glyph to be laid-out.
88   CharacterIndex characterIndex;     ///< Index of the first character to be laid-out.
89   Length         numberOfGlyphs;     ///< The number of glyph which fit in one line.
90   Length         numberOfCharacters; ///< The number of characters which fit in one line.
91   float          length;             ///< The addition of the advance metric of all the glyphs which fit in one line.
92   float          extraBearing;       ///< The extra width to be added to the line's length when the bearing of the first glyph is negative.
93   float          extraWidth;         ///< The extra width to be added to the line's length when the bearing + width of the last glyph is greater than the advance.
94   float          wsLengthEndOfLine;  ///< The length of the white spaces at the end of the line.
95   float          ascender;           ///< The maximum ascender of all fonts in the line.
96   float          descender;          ///< The minimum descender of all fonts in the line.
97 };
98
99 struct LayoutEngine::Impl
100 {
101   Impl()
102   : mLayout( LayoutEngine::SINGLE_LINE_BOX ),
103     mHorizontalAlignment( LayoutEngine::HORIZONTAL_ALIGN_BEGIN ),
104     mVerticalAlignment( LayoutEngine::VERTICAL_ALIGN_TOP ),
105     mEllipsisEnabled( false )
106   {
107     mFontClient = TextAbstraction::FontClient::Get();
108   }
109
110   /**
111    * @brief Updates the line ascender and descender with the metrics of a new font.
112    *
113    * @param[in] fontId The id of the new font.
114    * @param[in,out] lineLayout The line layout.
115    */
116   void UpdateLineHeight( FontId fontId, LineLayout& lineLayout )
117   {
118     Text::FontMetrics fontMetrics;
119     mFontClient.GetFontMetrics( fontId, fontMetrics );
120
121     // Sets the maximum ascender.
122     if( fontMetrics.ascender > lineLayout.ascender )
123     {
124       lineLayout.ascender = fontMetrics.ascender;
125     }
126
127     // Sets the minimum descender.
128     if( fontMetrics.descender < lineLayout.descender )
129     {
130       lineLayout.descender = fontMetrics.descender;
131     }
132   }
133
134   /**
135    * @brief Merges a temporary line layout into the line layout.
136    *
137    * @param[in,out] lineLayout The line layout.
138    * @param[in] tmpLineLayout A temporary line layout.
139    */
140   void MergeLineLayout( LineLayout& lineLayout,
141                         const LineLayout& tmpLineLayout )
142   {
143     lineLayout.numberOfCharacters += tmpLineLayout.numberOfCharacters;
144     lineLayout.numberOfGlyphs += tmpLineLayout.numberOfGlyphs;
145     lineLayout.length += tmpLineLayout.length;
146
147     if( 0.f < tmpLineLayout.length )
148     {
149       lineLayout.length += lineLayout.wsLengthEndOfLine;
150
151       lineLayout.wsLengthEndOfLine = tmpLineLayout.wsLengthEndOfLine;
152     }
153     else
154     {
155       lineLayout.wsLengthEndOfLine += tmpLineLayout.wsLengthEndOfLine;
156     }
157
158     if( tmpLineLayout.ascender > lineLayout.ascender )
159     {
160       lineLayout.ascender = tmpLineLayout.ascender;
161     }
162
163     if( tmpLineLayout.descender < lineLayout.descender )
164     {
165       lineLayout.descender = tmpLineLayout.descender;
166     }
167   }
168
169   /**
170    * Retrieves the line layout for a given box width.
171    *
172    * @note This method lais out text as it were left to right. At this point is not possible to reorder the line
173    *       because the number of characters of the line is not known (one of the responsabilities of this method
174    *       is calculate that). Due to glyph's 'x' bearing, width and advance, when right to left or mixed right to left
175    *       and left to right text is laid out, it can be small differences in the line length. One solution is to
176    *       reorder and re-lay out the text after this method and add or remove one extra glyph if needed. However,
177    *       this method calculates which are the first and last glyphs of the line (the ones that causes the
178    *       differences). This is a good point to check if there is problems with the text exceeding the boundaries
179    *       of the control when there is right to left text.
180    *
181    * @param[in] parameters The layout parameters.
182    * @param[out] lineLayout The line layout.
183    * @param[in,out] paragraphDirection in: the current paragraph's direction, out: the next paragraph's direction. Is set after a must break.
184    * @param[in] completelyFill Whether to completely fill the line ( even if the last word exceeds the boundaries ).
185    */
186   void GetLineLayoutForBox( const LayoutParameters& parameters,
187                             LineLayout& lineLayout,
188                             CharacterDirection& paragraphDirection,
189                             bool completelyFill )
190   {
191     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->GetLineLayoutForBox\n" );
192     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  initial glyph index : %d\n", lineLayout.glyphIndex );
193     // Stores temporary line layout which has not been added to the final line layout.
194     LineLayout tmpLineLayout;
195
196     const bool isMultiline = mLayout == MULTI_LINE_BOX;
197     const GlyphIndex lastGlyphIndex = parameters.totalNumberOfGlyphs - 1u;
198
199     // If the first glyph has a negative bearing its absolute value needs to be added to the line length.
200     // In the case the line starts with a right to left character, if the width is longer than the advance,
201     // the difference needs to be added to the line length.
202     const GlyphInfo& glyphInfo = *( parameters.glyphsBuffer + lineLayout.glyphIndex );
203
204     // Set the direction of the first character of the line.
205     lineLayout.characterIndex = *( parameters.glyphsToCharactersBuffer + lineLayout.glyphIndex );
206     const CharacterDirection firstCharacterDirection = ( NULL == parameters.characterDirectionBuffer ) ? false : *( parameters.characterDirectionBuffer + lineLayout.characterIndex );
207     CharacterDirection previousCharacterDirection = firstCharacterDirection;
208
209     const float extraWidth = glyphInfo.xBearing + glyphInfo.width - glyphInfo.advance;
210     float tmpExtraWidth = ( 0.f < extraWidth ) ? extraWidth : 0.f;
211
212     float tmpExtraBearing = ( 0.f > glyphInfo.xBearing ) ? -glyphInfo.xBearing : 0.f;
213
214     tmpLineLayout.length += 1.f; // Added one unit to give some space to the cursor.
215
216     // Calculate the line height if there is no characters.
217     FontId lastFontId = glyphInfo.fontId;
218     UpdateLineHeight( lastFontId, tmpLineLayout );
219
220     bool oneWordLaidOut = false;
221
222     for( GlyphIndex glyphIndex = lineLayout.glyphIndex;
223          glyphIndex < parameters.totalNumberOfGlyphs;
224          ++glyphIndex )
225     {
226       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  glyph index : %d\n", glyphIndex );
227       const bool isLastGlyph = glyphIndex == lastGlyphIndex;
228
229       // Get the glyph info.
230       const GlyphInfo& glyphInfo = *( parameters.glyphsBuffer + glyphIndex );
231
232       // Check if the font of the current glyph is the same of the previous one.
233       // If it's different the ascender and descender need to be updated.
234       if( lastFontId != glyphInfo.fontId )
235       {
236         UpdateLineHeight( glyphInfo.fontId, tmpLineLayout );
237         lastFontId = glyphInfo.fontId;
238       }
239
240       // Get the character indices for the current glyph. The last character index is needed
241       // because there are glyphs formed by more than one character but their break info is
242       // given only for the last character.
243       const Length charactersPerGlyph = *( parameters.charactersPerGlyphBuffer + glyphIndex );
244       const CharacterIndex characterFirstIndex = *( parameters.glyphsToCharactersBuffer + glyphIndex );
245       const CharacterIndex characterLastIndex = characterFirstIndex + ( ( 1u > charactersPerGlyph ) ? 0u : charactersPerGlyph - 1u );
246
247       // Get the line break info for the current character.
248       const LineBreakInfo lineBreakInfo = *( parameters.lineBreakInfoBuffer + characterLastIndex );
249
250       // Get the word break info for the current character.
251       const WordBreakInfo wordBreakInfo = *( parameters.wordBreakInfoBuffer + characterLastIndex );
252
253       // Increase the number of characters.
254       tmpLineLayout.numberOfCharacters += charactersPerGlyph;
255
256       // Increase the number of glyphs.
257       tmpLineLayout.numberOfGlyphs++;
258
259       // Check whether is a white space.
260       const Character character = *( parameters.textBuffer + characterFirstIndex );
261       const bool isWhiteSpace = TextAbstraction::IsWhiteSpace( character );
262
263       // Used to restore the temporal line layout when a single word does not fit in the control's width and is split by character.
264       const float previousTmpLineLength = tmpLineLayout.length;
265       const float previousTmpExtraBearing = tmpExtraBearing;
266       const float previousTmpExtraWidth = tmpExtraWidth;
267
268       // Get the character's direction.
269       const CharacterDirection characterDirection = ( NULL == parameters.characterDirectionBuffer ) ? false : *( parameters.characterDirectionBuffer + characterFirstIndex );
270
271       // Increase the accumulated length.
272       if( isWhiteSpace )
273       {
274         // Add the length to the length of white spaces at the end of the line.
275         tmpLineLayout.wsLengthEndOfLine += glyphInfo.advance; // The advance is used as the width is always zero for the white spaces.
276       }
277       else
278       {
279         // Add as well any previous white space length.
280         tmpLineLayout.length += tmpLineLayout.wsLengthEndOfLine + glyphInfo.advance;
281
282         // An extra space may be added to the line for the first and last glyph of the line.
283         // If the bearing of the first glyph is negative, its positive value needs to be added.
284         // If the bearing plus the width of the last glyph is greater than the advance, the difference
285         // needs to be added.
286
287         if( characterDirection == paragraphDirection )
288         {
289           if( RTL == characterDirection )
290           {
291             //       <--
292             // |   Rrrrr|
293             // or
294             // |  Rllrrr|
295             // or
296             // |lllrrrrr|
297             // |     Rll|
298             //
299
300             tmpExtraBearing = ( 0.f > glyphInfo.xBearing ) ? -glyphInfo.xBearing : 0.f;
301           }
302           else // LTR
303           {
304             //  -->
305             // |lllL    |
306             // or
307             // |llrrL   |
308             // or
309             // |lllllrrr|
310             // |rrL     |
311             //
312
313             const float extraWidth = glyphInfo.xBearing + glyphInfo.width - glyphInfo.advance;
314             tmpExtraWidth = ( 0.f < extraWidth ) ? extraWidth : 0.f;
315           }
316         }
317         else
318         {
319           if( characterDirection != previousCharacterDirection )
320           {
321             if( RTL == characterDirection )
322             {
323               //  -->
324               // |lllR    |
325
326               const float extraWidth = glyphInfo.xBearing + glyphInfo.width - glyphInfo.advance;
327               tmpExtraWidth = ( 0.f < extraWidth ) ? extraWidth : 0.f;
328             }
329             else // LTR
330             {
331               //       <--
332               // |   Lrrrr|
333
334               tmpExtraBearing = ( 0.f > glyphInfo.xBearing ) ? -glyphInfo.xBearing : 0.f;
335             }
336           }
337           else if( characterDirection == firstCharacterDirection )
338           {
339             if( RTL == characterDirection )
340             {
341               //  -->
342               // |llllllrr|
343               // |Rr      |
344
345               tmpExtraBearing = ( 0.f > glyphInfo.xBearing ) ? -glyphInfo.xBearing : 0.f;
346             }
347             else // LTR
348             {
349               //       <--
350               // |llllrrrr|
351               // |     llL|
352
353               const float extraWidth = glyphInfo.xBearing + glyphInfo.width - glyphInfo.advance;
354               tmpExtraWidth = ( 0.f < extraWidth ) ? extraWidth : 0.f;
355             }
356           }
357         }
358
359         // Clear the white space length at the end of the line.
360         tmpLineLayout.wsLengthEndOfLine = 0.f;
361       }
362
363       // Check if the accumulated length fits in the width of the box.
364       if( ( completelyFill || isMultiline ) && !isWhiteSpace &&
365           ( tmpExtraBearing + lineLayout.length + lineLayout.wsLengthEndOfLine + tmpLineLayout.length + tmpExtraWidth > parameters.boundingBox.width ) )
366       {
367         // Current word does not fit in the box's width.
368         if( !oneWordLaidOut || completelyFill )
369         {
370           DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  Break the word by character\n" );
371
372           // The word's with doesn't fit in the control's with. It needs to be split by character.
373           if( tmpLineLayout.numberOfGlyphs > 0u )
374           {
375             tmpLineLayout.numberOfCharacters -= charactersPerGlyph;
376             --tmpLineLayout.numberOfGlyphs;
377             tmpLineLayout.length = previousTmpLineLength;
378             tmpExtraBearing = previousTmpExtraBearing;
379             tmpExtraWidth = previousTmpExtraWidth;
380           }
381
382           // Add part of the word to the line layout.
383           MergeLineLayout( lineLayout, tmpLineLayout );
384         }
385         else
386         {
387           DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  Current word does not fit.\n" );
388         }
389
390         lineLayout.extraBearing = tmpExtraBearing;
391         lineLayout.extraWidth = tmpExtraWidth;
392
393         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox.\n" );
394
395         return;
396       }
397
398       if( ( isMultiline || isLastGlyph ) &&
399           ( TextAbstraction::LINE_MUST_BREAK == lineBreakInfo ) )
400       {
401         // Must break the line. Update the line layout and return.
402         MergeLineLayout( lineLayout, tmpLineLayout );
403
404         // Set the next paragraph's direction.
405         if( !isLastGlyph &&
406             ( NULL != parameters.characterDirectionBuffer ) )
407         {
408           paragraphDirection = *( parameters.characterDirectionBuffer + 1u + characterLastIndex );
409         }
410
411         lineLayout.extraBearing = tmpExtraBearing;
412         lineLayout.extraWidth = tmpExtraWidth;
413
414         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  Must break\n" );
415         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n" );
416         return;
417       }
418
419       if( isMultiline &&
420           ( TextAbstraction::WORD_BREAK == wordBreakInfo ) )
421       {
422         oneWordLaidOut = true;
423         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  One word laid out\n" );
424
425         // Current glyph is the last one of the current word.
426         // Add the temporal layout to the current one.
427         MergeLineLayout( lineLayout, tmpLineLayout );
428
429         tmpLineLayout.Clear();
430       }
431
432       previousCharacterDirection = characterDirection;
433     }
434
435     lineLayout.extraBearing = tmpExtraBearing;
436     lineLayout.extraWidth = tmpExtraWidth;
437
438     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n" );
439   }
440
441   void SetGlyphPositions( const GlyphInfo* const glyphsBuffer,
442                           Length numberOfGlyphs,
443                           float penY,
444                           Vector2* glyphPositionsBuffer )
445   {
446     // Traverse the glyphs and set the positions.
447
448     // Check if the x bearing of the first character is negative.
449     // If it has a negative x bearing, it will exceed the boundaries of the actor,
450     // so the penX position needs to be moved to the right.
451
452     const GlyphInfo& glyph = *glyphsBuffer;
453     float penX = ( 0.f > glyph.xBearing ) ? -glyph.xBearing : 0.f;
454     penX += 1.f; // Added one unit to give some space to the cursor.
455
456     for( GlyphIndex i = 0u; i < numberOfGlyphs; ++i )
457     {
458       const GlyphInfo& glyph = *( glyphsBuffer + i );
459       Vector2& position = *( glyphPositionsBuffer + i );
460
461       position.x = penX + glyph.xBearing;
462       position.y = penY - glyph.yBearing;
463
464       penX += glyph.advance;
465     }
466   }
467
468   bool LayoutText( const LayoutParameters& layoutParameters,
469                    Vector<Vector2>& glyphPositions,
470                    Vector<LineRun>& lines,
471                    Size& actualSize )
472   {
473     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->LayoutText\n" );
474     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  box size %f, %f\n", layoutParameters.boundingBox.width, layoutParameters.boundingBox.height );
475
476     // Set the first paragraph's direction.
477     CharacterDirection paragraphDirection = ( NULL != layoutParameters.characterDirectionBuffer ) ? *layoutParameters.characterDirectionBuffer : !RTL;
478
479     float penY = 0.f;
480     for( GlyphIndex index = 0u; index < layoutParameters.totalNumberOfGlyphs; )
481     {
482       CharacterDirection currentParagraphDirection = paragraphDirection;
483
484       // Get the layout for the line.
485       LineLayout layout;
486       layout.glyphIndex = index;
487       GetLineLayoutForBox( layoutParameters,
488                            layout,
489                            paragraphDirection,
490                            false );
491
492       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "           glyph index %d\n", layout.glyphIndex );
493       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "       character index %d\n", layout.characterIndex );
494       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "      number of glyphs %d\n", layout.numberOfGlyphs );
495       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  number of characters %d\n", layout.numberOfCharacters );
496       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "                length %f\n", layout.length );
497
498       if( 0u == layout.numberOfGlyphs )
499       {
500         // The width is too small and no characters are laid-out.
501         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--LayoutText width too small!\n\n" );
502         return false;
503       }
504
505       // Set the line position. Discard if ellipsis is enabled and the position exceeds the boundaries
506       // of the box.
507       penY += layout.ascender;
508
509       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "  pen y %f\n", penY );
510       if( mEllipsisEnabled &&
511           ( ( penY - layout.descender > layoutParameters.boundingBox.height ) ||
512             ( ( mLayout == SINGLE_LINE_BOX ) &&
513               ( layout.extraBearing + layout.length + layout.extraWidth > layoutParameters.boundingBox.width ) ) ) )
514       {
515         // Do not layout more lines if ellipsis is enabled.
516
517         // The last line needs to be completely filled with characters.
518         // Part of a word may be used.
519
520         const Length numberOfLines = lines.Count();
521
522         LineRun lineRun;
523         LineLayout ellipsisLayout;
524         if( 0u != numberOfLines )
525         {
526           // Get the last line and layout it again with the 'completelyFill' flag to true.
527           lineRun = *( lines.Begin() + ( numberOfLines - 1u ) );
528
529           penY -= layout.ascender - lineRun.descender;
530
531           ellipsisLayout.glyphIndex = lineRun.glyphIndex;
532         }
533         else
534         {
535           lineRun.glyphIndex = 0u;
536           ellipsisLayout.glyphIndex = 0u;
537         }
538
539         GetLineLayoutForBox( layoutParameters,
540                              ellipsisLayout,
541                              currentParagraphDirection,
542                              true );
543
544         lineRun.numberOfGlyphs = ellipsisLayout.numberOfGlyphs;
545         lineRun.characterRun.characterIndex = ellipsisLayout.characterIndex;
546         lineRun.characterRun.numberOfCharacters = ellipsisLayout.numberOfCharacters;
547         lineRun.width = ellipsisLayout.length;
548         lineRun.extraLength =  ( ellipsisLayout.wsLengthEndOfLine > 0.f ) ? ellipsisLayout.wsLengthEndOfLine - ellipsisLayout.extraWidth : 0.f;
549         lineRun.ascender = ellipsisLayout.ascender;
550         lineRun.descender = ellipsisLayout.descender;
551         lineRun.ellipsis = true;
552
553         actualSize.width = layoutParameters.boundingBox.width;
554         actualSize.height += ( lineRun.ascender + -lineRun.descender );
555
556         SetGlyphPositions( layoutParameters.glyphsBuffer + lineRun.glyphIndex,
557                            ellipsisLayout.numberOfGlyphs,
558                            penY,
559                            glyphPositions.Begin() + lineRun.glyphIndex );
560
561         if( 0u != numberOfLines )
562         {
563           // Set the last line with the ellipsis layout.
564           *( lines.Begin() + ( numberOfLines - 1u ) ) = lineRun;
565         }
566         else
567         {
568           // Push the line.
569           lines.PushBack( lineRun );
570         }
571
572         break;
573       }
574       else
575       {
576         const bool isLastLine = index + layout.numberOfGlyphs == layoutParameters.totalNumberOfGlyphs;
577
578         LineRun lineRun;
579         lineRun.glyphIndex = index;
580         lineRun.numberOfGlyphs = layout.numberOfGlyphs;
581         lineRun.characterRun.characterIndex = layout.characterIndex;
582         lineRun.characterRun.numberOfCharacters = layout.numberOfCharacters;
583         if( isLastLine )
584         {
585           const float width = layout.extraBearing + layout.length + layout.extraWidth + layout.wsLengthEndOfLine;
586           if( MULTI_LINE_BOX == mLayout )
587           {
588             lineRun.width = ( width > layoutParameters.boundingBox.width ) ? layoutParameters.boundingBox.width : width;
589           }
590           else
591           {
592             lineRun.width = width;
593           }
594
595           lineRun.extraLength = 0.f;
596         }
597         else
598         {
599           lineRun.width = layout.extraBearing + layout.length + layout.extraWidth;
600           lineRun.extraLength = ( layout.wsLengthEndOfLine > 0.f ) ? layout.wsLengthEndOfLine - layout.extraWidth : 0.f;
601         }
602         lineRun.ascender = layout.ascender;
603         lineRun.descender = layout.descender;
604         lineRun.direction = false;
605         lineRun.ellipsis = false;
606
607         lines.PushBack( lineRun );
608
609         // Update the actual size.
610         if( lineRun.width > actualSize.width )
611         {
612           actualSize.width = lineRun.width;
613         }
614
615         actualSize.height += ( lineRun.ascender + -lineRun.descender );
616
617         SetGlyphPositions( layoutParameters.glyphsBuffer + index,
618                            layout.numberOfGlyphs,
619                            penY,
620                            glyphPositions.Begin() + index );
621
622         penY += -layout.descender;
623
624         // Increase the glyph index.
625         index += layout.numberOfGlyphs;
626       }
627     }
628
629     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--LayoutText\n\n" );
630
631     return true;
632   }
633
634   void ReLayoutRightToLeftLines( const LayoutParameters& layoutParameters,
635                                  Vector<Vector2>& glyphPositions )
636   {
637     // Traverses the paragraphs with right to left characters.
638     for( LineIndex lineIndex = 0u; lineIndex < layoutParameters.numberOfBidirectionalInfoRuns; ++lineIndex )
639     {
640       const BidirectionalLineInfoRun& bidiLine = *( layoutParameters.lineBidirectionalInfoRunsBuffer + lineIndex );
641
642       const CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *bidiLine.visualToLogicalMap;
643       const GlyphInfo& glyph = *( layoutParameters.glyphsBuffer + *( layoutParameters.charactersToGlyphsBuffer + characterVisualIndex ) );
644
645       float penX = ( 0.f > glyph.xBearing ) ? -glyph.xBearing : 0.f;
646       penX += 1.f; // Added one unit to give some space to the cursor.
647
648       Vector2* glyphPositionsBuffer = glyphPositions.Begin();
649
650       // Traverses the characters of the right to left paragraph.
651       for( CharacterIndex characterLogicalIndex = 0u;
652            characterLogicalIndex < bidiLine.characterRun.numberOfCharacters;
653            ++characterLogicalIndex )
654       {
655         // Convert the character in the logical order into the character in the visual order.
656         const CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *( bidiLine.visualToLogicalMap + characterLogicalIndex );
657
658         // Get the number of glyphs of the character.
659         const Length numberOfGlyphs = *( layoutParameters.glyphsPerCharacterBuffer + characterVisualIndex );
660
661         for( GlyphIndex index = 0u; index < numberOfGlyphs; ++index )
662         {
663           // Convert the character in the visual order into the glyph in the visual order.
664           const GlyphIndex glyphIndex = *( layoutParameters.charactersToGlyphsBuffer + characterVisualIndex ) + index;
665
666           DALI_ASSERT_DEBUG( 0u <= glyphIndex && glyphIndex < layoutParameters.totalNumberOfGlyphs );
667
668           const GlyphInfo& glyph = *( layoutParameters.glyphsBuffer + glyphIndex );
669           Vector2& position = *( glyphPositionsBuffer + glyphIndex );
670
671           position.x = penX + glyph.xBearing;
672           penX += glyph.advance;
673         }
674       }
675     }
676   }
677
678   void Align( const Size& layoutSize,
679               Vector<LineRun>& lines )
680   {
681     // Traverse all lines and align the glyphs.
682
683     for( Vector<LineRun>::Iterator it = lines.Begin(), endIt = lines.End();
684          it != endIt;
685          ++it )
686     {
687       LineRun& line = *it;
688       const bool isLastLine = lines.End() == it + 1u;
689
690       // Calculate the alignment offset accordingly with the align option,
691       // the box width, line length, and the paragraphs direction.
692       CalculateHorizontalAlignment( layoutSize.width,
693                                     line,
694                                     isLastLine );
695     }
696   }
697
698   void CalculateHorizontalAlignment( float boxWidth,
699                                      LineRun& line,
700                                      bool isLastLine )
701   {
702     line.alignmentOffset = 0.f;
703     const bool isRTL = RTL == line.direction;
704     float lineLength = line.width;
705
706     HorizontalAlignment alignment = mHorizontalAlignment;
707     if( isRTL &&
708         ( HORIZONTAL_ALIGN_CENTER != alignment ) )
709     {
710       if( HORIZONTAL_ALIGN_BEGIN == alignment )
711       {
712         alignment = HORIZONTAL_ALIGN_END;
713       }
714       else
715       {
716         alignment = HORIZONTAL_ALIGN_BEGIN;
717       }
718     }
719
720     switch( alignment )
721     {
722       case HORIZONTAL_ALIGN_BEGIN:
723       {
724         line.alignmentOffset = 0.f;
725
726         if( isRTL )
727         {
728           // 'Remove' the white spaces at the end of the line (which are at the beginning in visual order)
729           line.alignmentOffset -= line.extraLength;
730
731           if( isLastLine )
732           {
733             line.alignmentOffset += std::min( line.extraLength, boxWidth - lineLength );
734           }
735         }
736         break;
737       }
738       case HORIZONTAL_ALIGN_CENTER:
739       {
740         if( isLastLine && !isRTL )
741         {
742           lineLength += line.extraLength;
743           if( lineLength > boxWidth )
744           {
745             lineLength = boxWidth;
746             line.alignmentOffset = 0.f;
747             break;
748           }
749         }
750
751         line.alignmentOffset = 0.5f * ( boxWidth - lineLength );
752
753         if( isRTL )
754         {
755           line.alignmentOffset -= line.extraLength;
756
757           if( isLastLine )
758           {
759             line.alignmentOffset += 0.5f * std::min( line.extraLength, boxWidth - lineLength );
760           }
761         }
762
763         line.alignmentOffset = floorf( line.alignmentOffset ); // try to avoid pixel alignment.
764         break;
765       }
766       case HORIZONTAL_ALIGN_END:
767       {
768         if( isLastLine && !isRTL )
769         {
770           lineLength += line.extraLength;
771           if( lineLength > boxWidth )
772           {
773             line.alignmentOffset = 0.f;
774             break;
775           }
776         }
777
778         if( isRTL )
779         {
780           lineLength += line.extraLength;
781         }
782
783         line.alignmentOffset = boxWidth - lineLength;
784         break;
785       }
786     }
787   }
788
789   LayoutEngine::Layout mLayout;
790   LayoutEngine::HorizontalAlignment mHorizontalAlignment;
791   LayoutEngine::VerticalAlignment mVerticalAlignment;
792
793   TextAbstraction::FontClient mFontClient;
794
795   bool mEllipsisEnabled:1;
796 };
797
798 LayoutEngine::LayoutEngine()
799 : mImpl( NULL )
800 {
801   mImpl = new LayoutEngine::Impl();
802 }
803
804 LayoutEngine::~LayoutEngine()
805 {
806   delete mImpl;
807 }
808
809 void LayoutEngine::SetLayout( Layout layout )
810 {
811   mImpl->mLayout = layout;
812 }
813
814 unsigned int LayoutEngine::GetLayout() const
815 {
816   return mImpl->mLayout;
817 }
818
819 void LayoutEngine::SetTextEllipsisEnabled( bool enabled )
820 {
821   mImpl->mEllipsisEnabled = enabled;
822 }
823
824 bool LayoutEngine::GetTextEllipsisEnabled() const
825 {
826   return mImpl->mEllipsisEnabled;
827 }
828
829 void LayoutEngine::SetHorizontalAlignment( HorizontalAlignment alignment )
830 {
831   mImpl->mHorizontalAlignment = alignment;
832 }
833
834 LayoutEngine::HorizontalAlignment LayoutEngine::GetHorizontalAlignment() const
835 {
836   return mImpl->mHorizontalAlignment;
837 }
838
839 void LayoutEngine::SetVerticalAlignment( VerticalAlignment alignment )
840 {
841   mImpl->mVerticalAlignment = alignment;
842 }
843
844 LayoutEngine::VerticalAlignment LayoutEngine::GetVerticalAlignment() const
845 {
846   return mImpl->mVerticalAlignment;
847 }
848
849 bool LayoutEngine::LayoutText( const LayoutParameters& layoutParameters,
850                                Vector<Vector2>& glyphPositions,
851                                Vector<LineRun>& lines,
852                                Size& actualSize )
853 {
854   return mImpl->LayoutText( layoutParameters,
855                             glyphPositions,
856                             lines,
857                             actualSize );
858 }
859
860 void LayoutEngine::ReLayoutRightToLeftLines( const LayoutParameters& layoutParameters,
861                                              Vector<Vector2>& glyphPositions )
862 {
863   mImpl->ReLayoutRightToLeftLines( layoutParameters,
864                                    glyphPositions );
865 }
866
867 void LayoutEngine::Align( const Size& layoutSize,
868                           Vector<LineRun>& lines )
869 {
870   mImpl->Align( layoutSize,
871                 lines );
872 }
873
874 } // namespace Text
875
876 } // namespace Toolkit
877
878 } // namespace Dali