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