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