Merge "Tizen Directory Migration" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / cursor-helper-functions.cpp
1 /*
2  * Copyright (c) 2016 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 // FILE HEADER
19 #include <dali-toolkit/internal/text/cursor-helper-functions.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23
24 // INTERNAL INCLUDES
25 #include <dali-toolkit/internal/text/glyph-metrics-helper.h>
26
27 namespace
28 {
29
30 #if defined(DEBUG_ENABLED)
31   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
32 #endif
33
34 const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction.
35
36 struct FindWordData
37 {
38   FindWordData( const Dali::Toolkit::Text::Character* const textBuffer,
39                 Dali::Toolkit::Text::Length totalNumberOfCharacters,
40                 Dali::Toolkit::Text::CharacterIndex hitCharacter,
41                 bool isWhiteSpace,
42                 bool isNewParagraph )
43   : textBuffer( textBuffer ),
44     totalNumberOfCharacters( totalNumberOfCharacters ),
45     hitCharacter( hitCharacter ),
46     foundIndex( 0u ),
47     isWhiteSpace( isWhiteSpace ),
48     isNewParagraph( isNewParagraph )
49   {}
50
51   ~FindWordData()
52   {}
53
54   const Dali::Toolkit::Text::Character* const textBuffer;
55   Dali::Toolkit::Text::Length                 totalNumberOfCharacters;
56   Dali::Toolkit::Text::CharacterIndex         hitCharacter;
57   Dali::Toolkit::Text::CharacterIndex         foundIndex;
58   bool                                        isWhiteSpace   : 1u;
59   bool                                        isNewParagraph : 1u;
60 };
61
62 bool IsWhiteSpaceOrNewParagraph( Dali::Toolkit::Text::Character character,
63                                  bool isHitWhiteSpace,
64                                  bool isHitWhiteSpaceOrNewParagraph )
65 {
66   bool isWhiteSpaceOrNewParagraph = false;
67   if( isHitWhiteSpaceOrNewParagraph )
68   {
69     if( isHitWhiteSpace )
70     {
71       // Whether the current character is a white space. Note a new paragraph character is a white space as well but here is not wanted.
72       isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character ) && !Dali::TextAbstraction::IsNewParagraph( character );
73     }
74     else
75     {
76       // Whether the current character is a new paragraph character.
77       isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsNewParagraph( character );
78     }
79   }
80   else
81   {
82     // Whether the current character is a white space or a new paragraph character (note the new paragraph character is a white space as well).
83     isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character );
84   }
85
86   return isWhiteSpaceOrNewParagraph;
87 }
88
89 void FindStartOfWord( FindWordData& data )
90 {
91   const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph;
92
93   for( data.foundIndex = data.hitCharacter; data.foundIndex > 0; --data.foundIndex )
94   {
95     const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex - 1u );
96
97     const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character,
98                                                                         data.isWhiteSpace,
99                                                                         isHitWhiteSpaceOrNewParagraph );
100
101     if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph )
102     {
103       break;
104     }
105   }
106 }
107
108 void FindEndOfWord( FindWordData& data )
109 {
110   const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph;
111
112   for( data.foundIndex = data.hitCharacter + 1u; data.foundIndex < data.totalNumberOfCharacters; ++data.foundIndex )
113   {
114     const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex );
115
116     const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character,
117                                                                         data.isWhiteSpace,
118                                                                         isHitWhiteSpaceOrNewParagraph );
119
120     if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph )
121     {
122       break;
123     }
124   }
125 }
126
127 } //namespace
128
129 namespace Dali
130 {
131
132 namespace Toolkit
133 {
134
135 namespace Text
136 {
137
138 LineIndex GetClosestLine( VisualModelPtr visualModel,
139                           float visualY )
140 {
141   float totalHeight = 0.f;
142   LineIndex lineIndex = 0u;
143
144   const Vector<LineRun>& lines = visualModel->mLines;
145
146   for( Vector<LineRun>::ConstIterator it = lines.Begin(),
147          endIt = lines.End();
148        it != endIt;
149        ++it, ++lineIndex )
150   {
151     const LineRun& lineRun = *it;
152
153     // The line height is the addition of the line ascender and the line descender.
154     // However, the line descender has a negative value, hence the subtraction.
155     totalHeight += lineRun.ascender - lineRun.descender;
156
157     if( visualY < totalHeight )
158     {
159       return lineIndex;
160     }
161   }
162
163   if( lineIndex == 0u )
164   {
165     return 0;
166   }
167
168   return lineIndex-1;
169 }
170
171 float CalculateLineOffset( const Vector<LineRun>& lines,
172                            LineIndex lineIndex )
173 {
174   float offset = 0.f;
175
176   for( Vector<LineRun>::ConstIterator it = lines.Begin(),
177          endIt = lines.Begin() + lineIndex;
178        it != endIt;
179        ++it )
180   {
181     const LineRun& lineRun = *it;
182
183     // The line height is the addition of the line ascender and the line descender.
184     // However, the line descender has a negative value, hence the subtraction.
185     offset += lineRun.ascender - lineRun.descender;
186   }
187
188   return offset;
189 }
190
191 CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel,
192                                       LogicalModelPtr logicalModel,
193                                       MetricsPtr metrics,
194                                       float visualX,
195                                       float visualY )
196 {
197   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY );
198
199   CharacterIndex logicalIndex = 0u;
200
201   const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
202   const Length totalNumberOfLines  = visualModel->mLines.Count();
203   if( ( 0 == totalNumberOfGlyphs ) ||
204       ( 0 == totalNumberOfLines ) )
205   {
206     return logicalIndex;
207   }
208
209   // Find which line is closest.
210   const LineIndex lineIndex = Text::GetClosestLine( visualModel,
211                                                     visualY );
212
213   // Convert from text's coords to line's coords.
214   const LineRun& line = *( visualModel->mLines.Begin() + lineIndex );
215
216   // Transform the tap point from text's coords to line's coords.
217   visualX -= line.alignmentOffset;
218
219   // Get the positions of the glyphs.
220   const Vector2* const positionsBuffer = visualModel->mGlyphPositions.Begin();
221
222   // Get the character to glyph conversion table.
223   const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin();
224
225   // Get the glyphs per character table.
226   const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin();
227
228   // Get the characters per glyph table.
229   const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin();
230
231   // Get the glyph's info buffer.
232   const GlyphInfo* const glyphInfoBuffer = visualModel->mGlyphs.Begin();
233
234   const CharacterIndex startCharacter = line.characterRun.characterIndex;
235   const CharacterIndex endCharacter   = line.characterRun.characterIndex + line.characterRun.numberOfCharacters;
236   DALI_ASSERT_DEBUG( endCharacter <= logicalModel->mText.Count() && "Invalid line info" );
237
238   // Whether this line is a bidirectional line.
239   const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo( startCharacter );
240
241   // The character's direction buffer.
242   const CharacterDirection* const directionsBuffer = bidiLineFetched ? logicalModel->mCharacterDirections.Begin() : NULL;
243
244   // Whether there is a hit on a glyph.
245   bool matched = false;
246
247   // Traverses glyphs in visual order. To do that use the visual to logical conversion table.
248   CharacterIndex visualIndex = startCharacter;
249   Length numberOfVisualCharacters = 0u;
250   for( ; visualIndex < endCharacter; ++visualIndex )
251   {
252     // The character in logical order.
253     const CharacterIndex characterLogicalOrderIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( visualIndex ) : visualIndex );
254     const CharacterDirection direction = ( bidiLineFetched ? *( directionsBuffer + characterLogicalOrderIndex ) : LTR );
255
256     // The number of glyphs for that character
257     const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterLogicalOrderIndex );
258     ++numberOfVisualCharacters;
259
260     if( 0u != numberOfGlyphs )
261     {
262       // Get the first character/glyph of the group of glyphs.
263       const CharacterIndex firstVisualCharacterIndex = 1u + visualIndex - numberOfVisualCharacters;
264       const CharacterIndex firstLogicalCharacterIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( firstVisualCharacterIndex ) : firstVisualCharacterIndex );
265       const GlyphIndex firstLogicalGlyphIndex = *( charactersToGlyphBuffer + firstLogicalCharacterIndex );
266
267       // Get the metrics for the group of glyphs.
268       GlyphMetrics glyphMetrics;
269       GetGlyphsMetrics( firstLogicalGlyphIndex,
270                         numberOfGlyphs,
271                         glyphMetrics,
272                         glyphInfoBuffer,
273                         metrics );
274
275       // Get the position of the first glyph.
276       const Vector2& position = *( positionsBuffer + firstLogicalGlyphIndex );
277
278       // Whether the glyph can be split, like Latin ligatures fi, ff or Arabic (ل + ا).
279       Length numberOfCharacters = *( charactersPerGlyphBuffer + firstLogicalGlyphIndex );
280       if( direction != LTR )
281       {
282         // As characters are being traversed in visual order,
283         // for right to left ligatures, the character which contains the
284         // number of glyphs in the table is found first.
285         // Jump the number of characters to the next glyph is needed.
286
287         if( 0u == numberOfCharacters )
288         {
289           // TODO: This is a workaround to fix an issue with complex characters in the arabic
290           // script like i.e. رّ or الأَبْجَدِيَّة العَرَبِيَّة
291           // There are characters that are not shaped in one glyph but in combination with
292           // the next one generates two of them.
293           // The visual to logical conversion table have characters in different order than
294           // expected even if all of them are arabic.
295
296           // The workaround doesn't fix the issue completely but it prevents the application
297           // to hang in an infinite loop.
298
299           // Find the number of characters.
300           for( GlyphIndex index = firstLogicalGlyphIndex + 1u;
301                ( 0u == numberOfCharacters ) && ( index < totalNumberOfGlyphs ) ;
302                ++index )
303           {
304             numberOfCharacters = *( charactersPerGlyphBuffer + index );
305           }
306
307           if( 2u > numberOfCharacters )
308           {
309             continue;
310           }
311
312           --numberOfCharacters;
313         }
314
315         visualIndex += numberOfCharacters - 1u;
316       }
317
318       // Get the script of the character.
319       const Script script = logicalModel->GetScript( characterLogicalOrderIndex );
320
321       const bool isInterglyphIndex = ( numberOfCharacters > numberOfGlyphs ) && HasLigatureMustBreak( script );
322       const Length numberOfBlocks = isInterglyphIndex ? numberOfCharacters : 1u;
323       const float glyphAdvance = glyphMetrics.advance / static_cast<float>( numberOfBlocks );
324
325       CharacterIndex index = 0u;
326       for( ; index < numberOfBlocks; ++index )
327       {
328         // Find the mid-point of the area containing the glyph
329         const float glyphCenter = -glyphMetrics.xBearing + position.x + ( static_cast<float>( index ) + 0.5f ) * glyphAdvance;
330
331         if( visualX < glyphCenter )
332         {
333           matched = true;
334           break;
335         }
336       }
337
338       if( matched )
339       {
340         // If the glyph is shaped from more than one character, it matches the character of the glyph.
341         visualIndex = firstVisualCharacterIndex + index;
342         break;
343       }
344
345       numberOfVisualCharacters = 0u;
346     }
347   }
348
349   // The number of characters of the whole text.
350   const Length totalNumberOfCharacters = logicalModel->mText.Count();
351
352   // Return the logical position of the cursor in characters.
353
354   if( !matched )
355   {
356     // If no character is matched, then the last character (in visual order) of the line is used.
357     visualIndex = endCharacter;
358   }
359
360   // Get the paragraph direction.
361   const CharacterDirection paragraphDirection = line.direction;
362
363   if( totalNumberOfCharacters != visualIndex )
364   {
365     // The visual index is not at the end of the text.
366
367     if( LTR == paragraphDirection )
368     {
369       // The paragraph direction is left to right.
370
371       if( visualIndex == endCharacter )
372       {
373         // It places the cursor just before the last character in visual order.
374         // i.e. it places the cursor just before the '\n' or before the last character
375         // if there is a long line with no word breaks which is wrapped.
376
377         // It doesn't check if the closest line is the last one like the RTL branch below
378         // because the total number of characters is different than the visual index and
379         // the visual index is the last character of the line.
380         --visualIndex;
381       }
382     }
383     else
384     {
385       // The paragraph direction is right to left.
386
387       if( ( lineIndex != totalNumberOfLines - 1u ) && // is not the last line.
388           ( visualIndex == startCharacter ) )
389       {
390         // It places the cursor just after the first character in visual order.
391         // i.e. it places the cursor just after the '\n' or after the last character
392         // if there is a long line with no word breaks which is wrapped.
393
394         // If the last line doesn't end with '\n' it won't increase the visual index
395         // placing the cursor at the beginning of the line (in visual order).
396         ++visualIndex;
397       }
398     }
399   }
400   else
401   {
402     // The visual index is at the end of text.
403
404     // If the text ends with a new paragraph character i.e. a '\n', an extra line with no characters is added at the end of the text.
405     // This branch checks if the closest line is the one with the last '\n'. If it is, it decrements the visual index to place
406     // the cursor just before the last '\n'.
407
408     if( ( lineIndex != totalNumberOfLines - 1u ) &&
409         TextAbstraction::IsNewParagraph( *( logicalModel->mText.Begin() + visualIndex - 1u ) ) )
410     {
411       --visualIndex;
412     }
413   }
414
415   logicalIndex = ( bidiLineFetched ? logicalModel->GetLogicalCursorIndex( visualIndex ) : visualIndex );
416
417   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "closest visualIndex %d logicalIndex %d\n", visualIndex, logicalIndex );
418
419   DALI_ASSERT_DEBUG( ( logicalIndex <= logicalModel->mText.Count() && logicalIndex >= 0 ) && "GetClosestCursorIndex - Out of bounds index" );
420
421   return logicalIndex;
422 }
423
424
425 void GetCursorPosition( VisualModelPtr visualModel,
426                         LogicalModelPtr logicalModel,
427                         MetricsPtr metrics,
428                         CharacterIndex logical,
429                         CursorInfo& cursorInfo )
430 {
431   // Whether the logical cursor position is at the end of the whole text.
432   const bool isLastPosition = logicalModel->mText.Count() == logical;
433
434   // Get the line where the character is laid-out.
435   const CharacterIndex characterOfLine = isLastPosition ? ( logical - 1u ) : logical;
436
437   // Whether the cursor is in the last position and the last position is a new paragraph character.
438   const bool isLastNewParagraph = isLastPosition && TextAbstraction::IsNewParagraph( *( logicalModel->mText.Begin() + characterOfLine ) );
439
440   const LineRun* const modelLines = visualModel->mLines.Begin();
441
442   const LineIndex lineIndex = visualModel->GetLineOfCharacter( characterOfLine );
443   const LineRun& line = *( modelLines + lineIndex );
444
445   if( isLastNewParagraph )
446   {
447     // The cursor is in a new line with no characters. Place the cursor in that line.
448     const LineIndex newLineIndex = lineIndex + 1u;
449     const LineRun& newLine = *( modelLines + newLineIndex );
450
451     cursorInfo.isSecondaryCursor = false;
452
453     // Set the line offset and height.
454     cursorInfo.lineOffset = CalculateLineOffset( visualModel->mLines,
455                                                  newLineIndex );
456
457     // The line height is the addition of the line ascender and the line descender.
458     // However, the line descender has a negative value, hence the subtraction.
459     cursorInfo.lineHeight = newLine.ascender - newLine.descender;
460
461     // Set the primary cursor's height.
462     cursorInfo.primaryCursorHeight = cursorInfo.lineHeight;
463
464     // Set the primary cursor's position.
465     cursorInfo.primaryPosition.x = 0.f;
466     cursorInfo.primaryPosition.y = cursorInfo.lineOffset;
467
468     // Transform the cursor info from line's coords to text's coords.
469     cursorInfo.primaryPosition.x += ( LTR == line.direction ) ? 0.f : visualModel->mControlSize.width;
470   }
471   else
472   {
473     // Whether this line is a bidirectional line.
474     const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo( characterOfLine );
475
476     // Check if the logical position is the first or the last one of the line.
477     const bool isFirstPositionOfLine = line.characterRun.characterIndex == logical;
478     const bool isLastPositionOfLine = line.characterRun.characterIndex + line.characterRun.numberOfCharacters == logical;
479
480     // 'logical' is the logical 'cursor' index.
481     // Get the next and current logical 'character' index.
482     const CharacterIndex characterIndex = isFirstPositionOfLine ? logical : logical - 1u;
483     const CharacterIndex nextCharacterIndex = isLastPositionOfLine ? characterIndex : logical;
484
485     // The character's direction buffer.
486     const CharacterDirection* const directionsBuffer = bidiLineFetched ? logicalModel->mCharacterDirections.Begin() : NULL;
487
488     CharacterDirection isCurrentRightToLeft = false;
489     CharacterDirection isNextRightToLeft = false;
490     if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right.
491     {
492       isCurrentRightToLeft = *( directionsBuffer + characterIndex );
493       isNextRightToLeft = *( directionsBuffer + nextCharacterIndex );
494     }
495
496     // Get the paragraph's direction.
497     const CharacterDirection isRightToLeftParagraph = line.direction;
498
499     // Check whether there is an alternative position:
500     cursorInfo.isSecondaryCursor = ( ( !isLastPositionOfLine && ( isCurrentRightToLeft != isNextRightToLeft ) )     ||
501                                      ( isLastPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) ||
502                                      ( isFirstPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) );
503
504     // Set the line offset and height.
505     cursorInfo.lineOffset = CalculateLineOffset( visualModel->mLines,
506                                                  lineIndex );
507
508     // The line height is the addition of the line ascender and the line descender.
509     // However, the line descender has a negative value, hence the subtraction.
510     cursorInfo.lineHeight = line.ascender - line.descender;
511
512     // Calculate the primary cursor.
513
514     CharacterIndex index = characterIndex;
515     if( cursorInfo.isSecondaryCursor )
516     {
517       // If there is a secondary position, the primary cursor may be in a different place than the logical index.
518
519       if( isLastPositionOfLine )
520       {
521         // The position of the cursor after the last character needs special
522         // care depending on its direction and the direction of the paragraph.
523
524         // Need to find the first character after the last character with the paragraph's direction.
525         // i.e l0 l1 l2 r0 r1 should find r0.
526
527         index = isRightToLeftParagraph ? line.characterRun.characterIndex : line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u;
528         if( bidiLineFetched )
529         {
530           index = logicalModel->GetLogicalCharacterIndex( index );
531         }
532       }
533       else if( isFirstPositionOfLine )
534       {
535         index = isRightToLeftParagraph ? line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u : line.characterRun.characterIndex;
536         if( bidiLineFetched )
537         {
538           index = logicalModel->GetLogicalCharacterIndex( index );
539         }
540       }
541       else
542       {
543         index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? characterIndex : nextCharacterIndex;
544       }
545     }
546
547     const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin();
548     const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin();
549     const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin();
550     const CharacterIndex* const glyphsToCharactersBuffer = visualModel->mGlyphsToCharacters.Begin();
551     const Vector2* const glyphPositionsBuffer = visualModel->mGlyphPositions.Begin();
552     const GlyphInfo* const glyphInfoBuffer = visualModel->mGlyphs.Begin();
553
554     // Convert the cursor position into the glyph position.
555     const GlyphIndex primaryGlyphIndex = *( charactersToGlyphBuffer + index );
556     const Length primaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index );
557     const Length primaryNumberOfCharacters = *( charactersPerGlyphBuffer + primaryGlyphIndex );
558
559     // Get the metrics for the group of glyphs.
560     GlyphMetrics glyphMetrics;
561     GetGlyphsMetrics( primaryGlyphIndex,
562                       primaryNumberOfGlyphs,
563                       glyphMetrics,
564                       glyphInfoBuffer,
565                       metrics );
566
567     // Whether to add the glyph's advance to the cursor position.
568     // i.e if the paragraph is left to right and the logical cursor is zero, the position is the position of the first glyph and the advance is not added,
569     //     if the logical cursor is one, the position is the position of the first glyph and the advance is added.
570     // A 'truth table' was build and an online Karnaugh map tool was used to simplify the logic.
571     //
572     // FLCP A
573     // ------
574     // 0000 1
575     // 0001 1
576     // 0010 0
577     // 0011 0
578     // 0100 1
579     // 0101 0
580     // 0110 1
581     // 0111 0
582     // 1000 0
583     // 1001 1
584     // 1010 0
585     // 1011 1
586     // 1100 x
587     // 1101 x
588     // 1110 x
589     // 1111 x
590     //
591     // Where F -> isFirstPosition
592     //       L -> isLastPosition
593     //       C -> isCurrentRightToLeft
594     //       P -> isRightToLeftParagraph
595     //       A -> Whether to add the glyph's advance.
596
597     const bool addGlyphAdvance = ( ( isLastPositionOfLine && !isRightToLeftParagraph ) ||
598                                    ( isFirstPositionOfLine && isRightToLeftParagraph ) ||
599                                    ( !isFirstPositionOfLine && !isLastPosition && !isCurrentRightToLeft ) );
600
601     float glyphAdvance = addGlyphAdvance ? glyphMetrics.advance : 0.f;
602
603     if( !isLastPositionOfLine &&
604         ( primaryNumberOfCharacters > 1u ) )
605     {
606       const CharacterIndex firstIndex = *( glyphsToCharactersBuffer + primaryGlyphIndex );
607
608       bool isCurrentRightToLeft = false;
609       if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right.
610       {
611         isCurrentRightToLeft = *( directionsBuffer + index );
612       }
613
614       Length numberOfGlyphAdvance = ( isFirstPositionOfLine ? 0u : 1u ) + characterIndex - firstIndex;
615       if( isCurrentRightToLeft )
616       {
617         numberOfGlyphAdvance = primaryNumberOfCharacters - numberOfGlyphAdvance;
618       }
619
620       glyphAdvance = static_cast<float>( numberOfGlyphAdvance ) * glyphMetrics.advance / static_cast<float>( primaryNumberOfCharacters );
621     }
622
623     // Get the glyph position and x bearing (in the line's coords).
624     const Vector2& primaryPosition = *( glyphPositionsBuffer + primaryGlyphIndex );
625
626     // Set the primary cursor's height.
627     cursorInfo.primaryCursorHeight = cursorInfo.isSecondaryCursor ? 0.5f * glyphMetrics.fontHeight : glyphMetrics.fontHeight;
628
629     // Set the primary cursor's position.
630     cursorInfo.primaryPosition.x = -glyphMetrics.xBearing + primaryPosition.x + glyphAdvance;
631     cursorInfo.primaryPosition.y = cursorInfo.lineOffset + line.ascender - glyphMetrics.ascender;
632
633     // Transform the cursor info from line's coords to text's coords.
634     cursorInfo.primaryPosition.x += line.alignmentOffset;
635
636     // Calculate the secondary cursor.
637     if( cursorInfo.isSecondaryCursor )
638     {
639       // Set the secondary cursor's height.
640       cursorInfo.secondaryCursorHeight = 0.5f * glyphMetrics.fontHeight;
641
642       CharacterIndex index = characterIndex;
643       if( !isLastPositionOfLine )
644       {
645         index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? nextCharacterIndex : characterIndex;
646       }
647
648       const GlyphIndex secondaryGlyphIndex = *( charactersToGlyphBuffer + index );
649       const Length secondaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index );
650
651       const Vector2& secondaryPosition = *( glyphPositionsBuffer + secondaryGlyphIndex );
652
653       GetGlyphsMetrics( secondaryGlyphIndex,
654                         secondaryNumberOfGlyphs,
655                         glyphMetrics,
656                         glyphInfoBuffer,
657                         metrics );
658
659       // Set the secondary cursor's position.
660
661       // FCP A
662       // ------
663       // 000 1
664       // 001 x
665       // 010 0
666       // 011 0
667       // 100 x
668       // 101 0
669       // 110 1
670       // 111 x
671       //
672       // Where F -> isFirstPosition
673       //       C -> isCurrentRightToLeft
674       //       P -> isRightToLeftParagraph
675       //       A -> Whether to add the glyph's advance.
676
677       const bool addGlyphAdvance = ( ( !isFirstPositionOfLine && !isCurrentRightToLeft ) ||
678                                      ( isFirstPositionOfLine && !isRightToLeftParagraph ) );
679
680       cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + ( addGlyphAdvance ? glyphMetrics.advance : 0.f );
681       cursorInfo.secondaryPosition.y = cursorInfo.lineOffset + cursorInfo.lineHeight - cursorInfo.secondaryCursorHeight;
682
683       // Transform the cursor info from line's coords to text's coords.
684       cursorInfo.secondaryPosition.x += line.alignmentOffset;
685     }
686   }
687 }
688
689 bool FindSelectionIndices( VisualModelPtr visualModel,
690                            LogicalModelPtr logicalModel,
691                            MetricsPtr metrics,
692                            float visualX,
693                            float visualY,
694                            CharacterIndex& startIndex,
695                            CharacterIndex& endIndex )
696 {
697
698 /*
699   Hit character                                           Select
700 |-------------------------------------------------------|------------------------------------------|
701 | On a word                                             | The word                                 |
702 | On a single white space between words                 | The word before or after the white space |
703 | On one of the multiple contiguous white spaces        | The white spaces                         |
704 | On a single white space which is in the position zero | The white space and the next word        |
705 | On a new paragraph character                          | The word or group of white spaces before |
706 |-------------------------------------------------------|------------------------------------------|
707 */
708
709   CharacterIndex hitCharacter = Text::GetClosestCursorIndex( visualModel,
710                                                              logicalModel,
711                                                              metrics,
712                                                              visualX,
713                                                              visualY );
714
715   const Length totalNumberOfCharacters = logicalModel->mText.Count();
716
717   DALI_ASSERT_DEBUG( ( hitCharacter <= totalNumberOfCharacters ) && "GetClosestCursorIndex returned out of bounds index" );
718
719   if( 0u == totalNumberOfCharacters )
720   {
721     // Nothing to do if the model is empty.
722     return false;
723   }
724
725   if( hitCharacter >= totalNumberOfCharacters )
726   {
727     // Closest hit character is the last character.
728     if( hitCharacter == totalNumberOfCharacters )
729     {
730       hitCharacter--; //Hit character index set to last character in logical model
731     }
732     else
733     {
734       // hitCharacter is out of bounds
735       return false;
736     }
737   }
738
739   const Character* const textBuffer = logicalModel->mText.Begin();
740
741   startIndex = hitCharacter;
742   endIndex = hitCharacter;
743
744   // Whether the hit character is a new paragraph character.
745   const bool isHitCharacterNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + hitCharacter ) );
746
747   // Whether the hit character is a white space. Note a new paragraph character is a white space as well but here is not wanted.
748   const bool isHitCharacterWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + hitCharacter ) ) && !isHitCharacterNewParagraph;
749
750   FindWordData data( textBuffer,
751                      totalNumberOfCharacters,
752                      hitCharacter,
753                      isHitCharacterWhiteSpace,
754                      isHitCharacterNewParagraph );
755
756   if( isHitCharacterNewParagraph )
757   {
758     // Find the first character before the hit one which is not a new paragraph character.
759
760     if( hitCharacter > 0u )
761     {
762       endIndex = hitCharacter - 1u;
763       for( ; endIndex > 0; --endIndex )
764       {
765         const Dali::Toolkit::Text::Character character = *( data.textBuffer + endIndex );
766
767         if( !Dali::TextAbstraction::IsNewParagraph( character ) )
768         {
769           break;
770         }
771       }
772     }
773
774     data.hitCharacter = endIndex;
775     data.isNewParagraph = false;
776     data.isWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + data.hitCharacter ) );
777   }
778
779   // Find the start of the word.
780   FindStartOfWord( data );
781   startIndex = data.foundIndex;
782
783   // Find the end of the word.
784   FindEndOfWord( data );
785   endIndex = data.foundIndex;
786
787   if( 1u == ( endIndex - startIndex ) )
788   {
789     if( isHitCharacterWhiteSpace )
790     {
791       // Select the word before or after the white space
792
793       if( 0u == hitCharacter )
794       {
795         data.isWhiteSpace = false;
796         FindEndOfWord( data );
797         endIndex = data.foundIndex;
798       }
799       else if( hitCharacter > 0u )
800       {
801         // Find the start of the word.
802         data.hitCharacter = hitCharacter - 1u;
803         data.isWhiteSpace = false;
804         FindStartOfWord( data );
805         startIndex = data.foundIndex;
806
807         --endIndex;
808       }
809     }
810   }
811
812   return true;
813 }
814
815 } // namespace Text
816
817 } // namespace Toolkit
818
819 } // namespace Dali