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