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