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