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