9137a2f6a3d6a9dd263e50867109fba884854c40
[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/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     totalHeight += GetLineHeight(lineRun);
159
160     if(visualY < totalHeight)
161     {
162       matchedLine = true;
163       return lineIndex;
164     }
165   }
166
167   if(lineIndex == 0)
168   {
169     return 0;
170   }
171
172   return lineIndex - 1u;
173 }
174
175 float CalculateLineOffset(const Vector<LineRun>& lines,
176                           LineIndex              lineIndex)
177 {
178   float offset = 0.f;
179
180   for(Vector<LineRun>::ConstIterator it    = lines.Begin(),
181                                      endIt = lines.Begin() + lineIndex;
182       it != endIt;
183       ++it)
184   {
185     const LineRun& lineRun = *it;
186
187     offset += GetLineHeight(lineRun);
188   }
189
190   return offset;
191 }
192
193 CharacterIndex GetClosestCursorIndex(VisualModelPtr         visualModel,
194                                      LogicalModelPtr        logicalModel,
195                                      MetricsPtr             metrics,
196                                      float                  visualX,
197                                      float                  visualY,
198                                      CharacterHitTest::Mode mode,
199                                      bool&                  matchedCharacter)
200 {
201   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY);
202
203   // Whether there is a hit on a glyph.
204   matchedCharacter = false;
205
206   CharacterIndex logicalIndex = 0;
207
208   const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
209   const Length totalNumberOfLines  = visualModel->mLines.Count();
210   if((0 == totalNumberOfGlyphs) ||
211      (0 == totalNumberOfLines))
212   {
213     return logicalIndex;
214   }
215   const float characterSpacing = visualModel->GetCharacterSpacing();
216
217   // Whether there is a hit on a line.
218   bool matchedLine = false;
219
220   // Find which line is closest.
221   const LineIndex lineIndex = Text::GetClosestLine(visualModel,
222                                                    visualY,
223                                                    matchedLine);
224
225   if(!matchedLine && (CharacterHitTest::TAP == mode))
226   {
227     // Return the first or the last character if the touch point doesn't hit a line.
228     return (visualY < 0.f) ? 0 : logicalModel->mText.Count();
229   }
230
231   // Convert from text's coords to line's coords.
232   const LineRun& line = *(visualModel->mLines.Begin() + lineIndex);
233
234   // Transform the tap point from text's coords to line's coords.
235   visualX -= line.alignmentOffset;
236
237   // Get the positions of the glyphs.
238   const Vector2* const positionsBuffer = visualModel->mGlyphPositions.Begin();
239
240   // Get the character to glyph conversion table.
241   const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin();
242
243   // Get the glyphs per character table.
244   const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin();
245
246   // Get the characters per glyph table.
247   const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin();
248
249   // Get the glyph's info buffer.
250   const GlyphInfo* const glyphInfoBuffer = visualModel->mGlyphs.Begin();
251
252   const CharacterIndex startCharacter = line.characterRun.characterIndex;
253   const CharacterIndex endCharacter   = line.characterRun.characterIndex + line.characterRun.numberOfCharacters;
254   DALI_ASSERT_DEBUG(endCharacter <= logicalModel->mText.Count() && "Invalid line info");
255
256   // Whether this line is a bidirectional line.
257   const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo(startCharacter);
258
259   // The character's direction buffer.
260   const CharacterDirection* const directionsBuffer = bidiLineFetched ? logicalModel->mCharacterDirections.Begin() : NULL;
261
262   // Whether the touch point if before the first glyph.
263   bool isBeforeFirstGlyph = false;
264
265   // Traverses glyphs in visual order. To do that use the visual to logical conversion table.
266   CharacterIndex          visualIndex               = startCharacter;
267   Length                  numberOfVisualCharacters  = 0;
268   float                   calculatedAdvance         = 0.f;
269   Vector<CharacterIndex>& glyphToCharacterMap       = visualModel->mGlyphsToCharacters;
270   const CharacterIndex*   glyphToCharacterMapBuffer = glyphToCharacterMap.Begin();
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       calculatedAdvance = GetCalculatedAdvance(*(logicalModel->mText.Begin() + (*(glyphToCharacterMapBuffer + firstLogicalGlyphIndex))), characterSpacing, (*(visualModel->mGlyphs.Begin() + firstLogicalGlyphIndex)).advance);
291       GetGlyphsMetrics(firstLogicalGlyphIndex,
292                        numberOfGlyphs,
293                        glyphMetrics,
294                        glyphInfoBuffer,
295                        metrics,
296                        calculatedAdvance);
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 void GetCursorPosition(GetCursorPositionParameters& parameters,
467                        float                        defaultFontLineHeight,
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   CharacterIndex index;
490   GlyphMetrics   glyphMetrics;
491   MetricsPtr&    metrics        = parameters.metrics;
492   GlyphIndex     glyphIndex     = 0u;
493   Length         numberOfGlyphs = 0u;
494
495   if(isLastNewParagraph)
496   {
497     // The cursor is in a new line with no characters. Place the cursor in that line.
498     const LineIndex newLineIndex = lineIndex + 1u;
499     const LineRun&  newLine      = *(modelLines + newLineIndex);
500
501     cursorInfo.isSecondaryCursor = false;
502
503     // Set the line offset and height.
504     cursorInfo.lineOffset = CalculateLineOffset(parameters.visualModel->mLines,
505                                                 newLineIndex);
506
507     // The line height is the addition of the line ascender and the line descender.
508     // However, the line descender has a negative value, hence the subtraction also line spacing should not be included in cursor height.
509     cursorInfo.lineHeight = newLine.ascender - newLine.descender;
510
511     index                                = 0u;
512     const Length totalNumberOfCharacters = parameters.logicalModel->mText.Count();
513     if(totalNumberOfCharacters > 0u)
514     {
515       index = totalNumberOfCharacters - 1u;
516     }
517
518     GetGlyphMetricsFromCharacterIndex(index, parameters.visualModel, parameters.logicalModel, metrics, glyphMetrics, glyphIndex, numberOfGlyphs);
519
520     // Set the primary cursor's height.
521     // 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.
522     cursorInfo.primaryCursorHeight = (totalNumberOfCharacters > 0) ? (cursorInfo.isSecondaryCursor ? 0.5f * glyphMetrics.fontHeight : glyphMetrics.fontHeight) : defaultFontLineHeight;
523
524     // Set the primary cursor's position.
525     cursorInfo.primaryPosition.x = (LTR == line.direction) ? newLine.alignmentOffset : parameters.visualModel->mControlSize.width - newLine.alignmentOffset;
526     cursorInfo.primaryPosition.y = cursorInfo.lineOffset;
527   }
528   else
529   {
530     // Whether this line is a bidirectional line.
531     const bool bidiLineFetched = parameters.logicalModel->FetchBidirectionalLineInfo(characterOfLine);
532
533     // Check if the logical position is the first or the last one of the line.
534     const bool isFirstPositionOfLine = line.characterRun.characterIndex == parameters.logical;
535     const bool isLastPositionOfLine  = line.characterRun.characterIndex + line.characterRun.numberOfCharacters == parameters.logical;
536
537     // 'logical' is the logical 'cursor' index.
538     // Get the next and current logical 'character' index.
539     const CharacterIndex characterIndex     = isFirstPositionOfLine ? parameters.logical : parameters.logical - 1u;
540     const CharacterIndex nextCharacterIndex = isLastPositionOfLine ? characterIndex : parameters.logical;
541
542     // The character's direction buffer.
543     const CharacterDirection* const directionsBuffer = bidiLineFetched ? parameters.logicalModel->mCharacterDirections.Begin() : NULL;
544
545     CharacterDirection isCurrentRightToLeft = false;
546     CharacterDirection isNextRightToLeft    = false;
547     if(bidiLineFetched) // If bidiLineFetched is false, it means the whole text is left to right.
548     {
549       isCurrentRightToLeft = *(directionsBuffer + characterIndex);
550       isNextRightToLeft    = *(directionsBuffer + nextCharacterIndex);
551     }
552
553     // Get the paragraph's direction.
554     const CharacterDirection isRightToLeftParagraph = line.direction;
555
556     // Check whether there is an alternative position:
557     cursorInfo.isSecondaryCursor = ((!isLastPositionOfLine && (isCurrentRightToLeft != isNextRightToLeft)) ||
558                                     (isLastPositionOfLine && (isRightToLeftParagraph != isCurrentRightToLeft)) ||
559                                     (isFirstPositionOfLine && (isRightToLeftParagraph != isCurrentRightToLeft)));
560
561     // Set the line offset and height.
562     cursorInfo.lineOffset = CalculateLineOffset(parameters.visualModel->mLines,
563                                                 lineIndex);
564
565     // The line height is the addition of the line ascender and the line descender.
566     // However, the line descender has a negative value, hence the subtraction also line spacing should not be included in cursor height.
567     cursorInfo.lineHeight = line.ascender - line.descender;
568
569     // Calculate the primary cursor.
570
571     index = characterIndex;
572     if(cursorInfo.isSecondaryCursor)
573     {
574       // If there is a secondary position, the primary cursor may be in a different place than the logical index.
575
576       if(isLastPositionOfLine)
577       {
578         // The position of the cursor after the last character needs special
579         // care depending on its direction and the direction of the paragraph.
580
581         // Need to find the first character after the last character with the paragraph's direction.
582         // i.e l0 l1 l2 r0 r1 should find r0.
583
584         index = isRightToLeftParagraph ? line.characterRun.characterIndex : line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u;
585         if(bidiLineFetched)
586         {
587           index = parameters.logicalModel->GetLogicalCharacterIndex(index);
588         }
589       }
590       else if(isFirstPositionOfLine)
591       {
592         index = isRightToLeftParagraph ? line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u : line.characterRun.characterIndex;
593         if(bidiLineFetched)
594         {
595           index = parameters.logicalModel->GetLogicalCharacterIndex(index);
596         }
597       }
598       else
599       {
600         index = (isRightToLeftParagraph == isCurrentRightToLeft) ? characterIndex : nextCharacterIndex;
601       }
602     }
603
604     const Length* const         charactersPerGlyphBuffer = parameters.visualModel->mCharactersPerGlyph.Begin();
605     const CharacterIndex* const glyphsToCharactersBuffer = parameters.visualModel->mGlyphsToCharacters.Begin();
606     const Vector2* const        glyphPositionsBuffer     = parameters.visualModel->mGlyphPositions.Begin();
607     const float                 characterSpacing         = parameters.visualModel->GetCharacterSpacing();
608
609     // Get the metrics for the group of glyphs.
610     GetGlyphMetricsFromCharacterIndex(index, parameters.visualModel, parameters.logicalModel, metrics, glyphMetrics, glyphIndex, numberOfGlyphs);
611
612     // Convert the cursor position into the glyph position.
613     const GlyphIndex primaryGlyphIndex         = glyphIndex;
614     const Length     primaryNumberOfCharacters = *(charactersPerGlyphBuffer + primaryGlyphIndex);
615
616     // Whether to add the glyph's advance to the cursor position.
617     // 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,
618     //     if the logical cursor is one, the position is the position of the first glyph and the advance is added.
619     // A 'truth table' was build and an online Karnaugh map tool was used to simplify the logic.
620     //
621     // FLCP A
622     // ------
623     // 0000 1
624     // 0001 1
625     // 0010 0
626     // 0011 0
627     // 0100 1
628     // 0101 0
629     // 0110 1
630     // 0111 0
631     // 1000 0
632     // 1001 1
633     // 1010 0
634     // 1011 1
635     // 1100 x
636     // 1101 x
637     // 1110 x
638     // 1111 x
639     //
640     // Where F -> isFirstPosition
641     //       L -> isLastPosition
642     //       C -> isCurrentRightToLeft
643     //       P -> isRightToLeftParagraph
644     //       A -> Whether to add the glyph's advance.
645
646     const bool addGlyphAdvance = ((isLastPositionOfLine && !isRightToLeftParagraph) ||
647                                   (isFirstPositionOfLine && isRightToLeftParagraph) ||
648                                   (!isFirstPositionOfLine && !isLastPosition && !isCurrentRightToLeft));
649
650     float glyphAdvance = addGlyphAdvance ? (glyphMetrics.advance) : 0.f;
651
652     if(!isLastPositionOfLine &&
653        (primaryNumberOfCharacters > 1u))
654     {
655       const CharacterIndex firstIndex = *(glyphsToCharactersBuffer + primaryGlyphIndex);
656
657       bool isCurrentRightToLeft = false;
658       if(bidiLineFetched) // If bidiLineFetched is false, it means the whole text is left to right.
659       {
660         isCurrentRightToLeft = *(directionsBuffer + index);
661       }
662
663       Length numberOfGlyphAdvance = (isFirstPositionOfLine ? 0 : 1u) + characterIndex - firstIndex;
664       if(isCurrentRightToLeft)
665       {
666         numberOfGlyphAdvance = primaryNumberOfCharacters - numberOfGlyphAdvance;
667       }
668
669       glyphAdvance = static_cast<float>(numberOfGlyphAdvance) * (glyphMetrics.advance) / static_cast<float>(primaryNumberOfCharacters);
670     }
671
672     // Get the glyph position and x bearing (in the line's coords).
673     const Vector2& primaryPosition = *(glyphPositionsBuffer + primaryGlyphIndex);
674
675     // Set the primary cursor's height.
676     cursorInfo.primaryCursorHeight = cursorInfo.isSecondaryCursor ? 0.5f * glyphMetrics.fontHeight : glyphMetrics.fontHeight;
677
678     cursorInfo.glyphOffset = line.ascender - glyphMetrics.ascender;
679     // Set the primary cursor's position.
680     cursorInfo.primaryPosition.x = -glyphMetrics.xBearing + primaryPosition.x + glyphAdvance;
681     cursorInfo.primaryPosition.y = cursorInfo.lineOffset + cursorInfo.glyphOffset;
682
683     // Transform the cursor info from line's coords to text's coords.
684     cursorInfo.primaryPosition.x += line.alignmentOffset;
685
686     // Calculate the secondary cursor.
687     if(cursorInfo.isSecondaryCursor)
688     {
689       // Set the secondary cursor's height.
690       cursorInfo.secondaryCursorHeight = 0.5f * glyphMetrics.fontHeight;
691
692       CharacterIndex index = characterIndex;
693       if(!isLastPositionOfLine)
694       {
695         index = (isRightToLeftParagraph == isCurrentRightToLeft) ? nextCharacterIndex : characterIndex;
696       }
697
698       GetGlyphMetricsFromCharacterIndex(index, parameters.visualModel, parameters.logicalModel, metrics, glyphMetrics, glyphIndex, numberOfGlyphs);
699
700       const GlyphIndex secondaryGlyphIndex = glyphIndex;
701       const Vector2&   secondaryPosition   = *(glyphPositionsBuffer + secondaryGlyphIndex);
702
703       // Set the secondary cursor's position.
704
705       // FCP A
706       // ------
707       // 000 1
708       // 001 x
709       // 010 0
710       // 011 0
711       // 100 x
712       // 101 0
713       // 110 1
714       // 111 x
715       //
716       // Where F -> isFirstPosition
717       //       C -> isCurrentRightToLeft
718       //       P -> isRightToLeftParagraph
719       //       A -> Whether to add the glyph's advance.
720
721       const bool addGlyphAdvance = ((!isFirstPositionOfLine && !isCurrentRightToLeft) ||
722                                     (isFirstPositionOfLine && !isRightToLeftParagraph));
723
724       cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + (addGlyphAdvance ? (glyphMetrics.advance + characterSpacing) : 0.f);
725       cursorInfo.secondaryPosition.y = cursorInfo.lineOffset + cursorInfo.lineHeight - cursorInfo.secondaryCursorHeight;
726
727       // Transform the cursor info from line's coords to text's coords.
728       cursorInfo.secondaryPosition.x += line.alignmentOffset;
729     }
730   }
731 }
732
733 bool FindSelectionIndices(VisualModelPtr  visualModel,
734                           LogicalModelPtr logicalModel,
735                           MetricsPtr      metrics,
736                           float           visualX,
737                           float           visualY,
738                           CharacterIndex& startIndex,
739                           CharacterIndex& endIndex,
740                           CharacterIndex& noTextHitIndex)
741 {
742   /*
743   Hit character                                           Select
744 |-------------------------------------------------------|------------------------------------------|
745 | On a word                                             | The word                                 |
746 | On a single white space between words                 | The word before or after the white space |
747 | On one of the multiple contiguous white spaces        | The white spaces                         |
748 | On a single white space which is in the position zero | The white space and the next word        |
749 | On a new paragraph character                          | The word or group of white spaces before |
750 |-------------------------------------------------------|------------------------------------------|
751 */
752   const Length totalNumberOfCharacters = logicalModel->mText.Count();
753   startIndex                           = 0;
754   endIndex                             = 0;
755   noTextHitIndex                       = 0;
756
757   if(0 == totalNumberOfCharacters)
758   {
759     // Nothing to do if the model is empty.
760     return false;
761   }
762
763   bool           matchedCharacter = false;
764   CharacterIndex hitCharacter     = Text::GetClosestCursorIndex(visualModel,
765                                                             logicalModel,
766                                                             metrics,
767                                                             visualX,
768                                                             visualY,
769                                                             CharacterHitTest::TAP,
770                                                             matchedCharacter);
771
772   if(!matchedCharacter)
773   {
774     noTextHitIndex = hitCharacter;
775   }
776
777   DALI_ASSERT_DEBUG((hitCharacter <= totalNumberOfCharacters) && "GetClosestCursorIndex returned out of bounds index");
778
779   if(hitCharacter >= totalNumberOfCharacters)
780   {
781     // Closest hit character is the last character.
782     if(hitCharacter == totalNumberOfCharacters)
783     {
784       hitCharacter--; //Hit character index set to last character in logical model
785     }
786     else
787     {
788       // hitCharacter is out of bounds
789       return false;
790     }
791   }
792
793   const Character* const textBuffer = logicalModel->mText.Begin();
794
795   startIndex = hitCharacter;
796   endIndex   = hitCharacter;
797
798   // Whether the hit character is a new paragraph character.
799   const bool isHitCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + hitCharacter));
800
801   // Whether the hit character is a white space. Note a new paragraph character is a white space as well but here is not wanted.
802   const bool isHitCharacterWhiteSpace = TextAbstraction::IsWhiteSpace(*(textBuffer + hitCharacter)) && !isHitCharacterNewParagraph;
803
804   FindWordData data(textBuffer,
805                     totalNumberOfCharacters,
806                     hitCharacter,
807                     isHitCharacterWhiteSpace,
808                     isHitCharacterNewParagraph);
809
810   if(isHitCharacterNewParagraph)
811   {
812     // Find the first character before the hit one which is not a new paragraph character.
813
814     if(hitCharacter > 0)
815     {
816       endIndex = hitCharacter - 1u;
817       for(; endIndex > 0; --endIndex)
818       {
819         const Dali::Toolkit::Text::Character character = *(data.textBuffer + endIndex);
820
821         if(!Dali::TextAbstraction::IsNewParagraph(character))
822         {
823           break;
824         }
825       }
826     }
827
828     data.hitCharacter   = endIndex;
829     data.isNewParagraph = false;
830     data.isWhiteSpace   = TextAbstraction::IsWhiteSpace(*(textBuffer + data.hitCharacter));
831   }
832
833   // Find the start of the word.
834   FindStartOfWord(data);
835   startIndex = data.foundIndex;
836
837   // Find the end of the word.
838   FindEndOfWord(data);
839   endIndex = data.foundIndex;
840
841   if(1u == (endIndex - startIndex))
842   {
843     if(isHitCharacterWhiteSpace)
844     {
845       // Select the word before or after the white space
846
847       if(0 == hitCharacter)
848       {
849         data.isWhiteSpace = false;
850         FindEndOfWord(data);
851         endIndex = data.foundIndex;
852       }
853       else if(hitCharacter > 0)
854       {
855         // Find the start of the word.
856         data.hitCharacter = hitCharacter - 1u;
857         data.isWhiteSpace = false;
858         FindStartOfWord(data);
859         startIndex = data.foundIndex;
860
861         --endIndex;
862       }
863     }
864   }
865
866   return matchedCharacter;
867 }
868
869 } // namespace Text
870
871 } // namespace Toolkit
872
873 } // namespace Dali