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