1bce75a5d47fb53dd7e46d7114ac7c6348a1eb75
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / cursor-helper-functions.cpp
1 /*
2  * Copyright (c) 2016 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
30 #if defined(DEBUG_ENABLED)
31   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
32 #endif
33
34 } // namespace
35
36 namespace Dali
37 {
38
39 namespace Toolkit
40 {
41
42 namespace Text
43 {
44
45 LineIndex GetClosestLine( VisualModelPtr visualModel,
46                           float visualY )
47 {
48   float totalHeight = 0.f;
49   LineIndex lineIndex = 0u;
50
51   const Vector<LineRun>& lines = visualModel->mLines;
52   for( LineIndex endLine = lines.Count();
53        lineIndex < endLine;
54        ++lineIndex )
55   {
56     const LineRun& lineRun = lines[lineIndex];
57     totalHeight += lineRun.ascender + -lineRun.descender;
58     if( visualY < totalHeight )
59     {
60       return lineIndex;
61     }
62   }
63
64   if( lineIndex == 0 )
65   {
66     return 0;
67   }
68
69   return lineIndex-1;
70 }
71
72 CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel,
73                                       LogicalModelPtr logicalModel,
74                                       MetricsPtr metrics,
75                                       float visualX,
76                                       float visualY )
77 {
78   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY );
79
80   CharacterIndex logicalIndex = 0u;
81
82   const Length numberOfGlyphs = visualModel->mGlyphs.Count();
83   const Length numberOfLines  = visualModel->mLines.Count();
84   if( ( 0 == numberOfGlyphs ) ||
85       ( 0 == numberOfLines ) )
86   {
87     return logicalIndex;
88   }
89
90   // Find which line is closest.
91   const LineIndex lineIndex = Text::GetClosestLine( visualModel,
92                                                     visualY );
93   const LineRun& line = visualModel->mLines[lineIndex];
94
95   // Get the positions of the glyphs.
96   const Vector<Vector2>& positions = visualModel->mGlyphPositions;
97   const Vector2* const positionsBuffer = positions.Begin();
98
99   // Get the character to glyph conversion table.
100   const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin();
101
102   // Get the glyphs per character table.
103   const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin();
104
105   // Get the glyph's info buffer.
106   const GlyphInfo* const glyphInfoBuffer = visualModel->mGlyphs.Begin();
107
108   const CharacterIndex startCharacter = line.characterRun.characterIndex;
109   const CharacterIndex endCharacter   = line.characterRun.characterIndex + line.characterRun.numberOfCharacters;
110   DALI_ASSERT_DEBUG( endCharacter <= logicalModel->mText.Count() && "Invalid line info" );
111
112   // Whether this line is a bidirectional line.
113   const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo( startCharacter );
114
115   // Whether there is a hit on a glyph.
116   bool matched = false;
117
118   // Traverses glyphs in visual order. To do that use the visual to logical conversion table.
119   CharacterIndex visualIndex = startCharacter;
120   Length numberOfCharacters = 0u;
121   for( ; !matched && ( visualIndex < endCharacter ); ++visualIndex )
122   {
123     // The character in logical order.
124     const CharacterIndex characterLogicalOrderIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( visualIndex ) : visualIndex );
125
126     // Get the script of the character.
127     const Script script = logicalModel->GetScript( characterLogicalOrderIndex );
128
129     // The number of glyphs for that character
130     const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterLogicalOrderIndex );
131     ++numberOfCharacters;
132
133
134     if( 0u != numberOfGlyphs )
135     {
136       // Get the first character/glyph of the group of glyphs.
137       const CharacterIndex firstVisualCharacterIndex = 1u + visualIndex - numberOfCharacters;
138       const CharacterIndex firstLogicalCharacterIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( firstVisualCharacterIndex ) : firstVisualCharacterIndex );
139       const GlyphIndex firstLogicalGlyphIndex = *( charactersToGlyphBuffer + firstLogicalCharacterIndex );
140
141       // Get the metrics for the group of glyphs.
142       GlyphMetrics glyphMetrics;
143       GetGlyphsMetrics( firstLogicalGlyphIndex,
144                         numberOfGlyphs,
145                         glyphMetrics,
146                         glyphInfoBuffer,
147                         metrics );
148
149       // Get the position of the first glyph.
150       const Vector2& position = *( positionsBuffer + firstLogicalGlyphIndex );
151
152       // Whether the glyph can be split, like Latin ligatures fi, ff or Arabic ﻻ.
153       const bool isInterglyphIndex = ( numberOfCharacters > numberOfGlyphs ) && HasLigatureMustBreak( script );
154       const Length numberOfBlocks = isInterglyphIndex ? numberOfCharacters : 1u;
155       const float glyphAdvance = glyphMetrics.advance / static_cast<float>( numberOfBlocks );
156
157       GlyphIndex index = 0u;
158       for( ; !matched && ( index < numberOfBlocks ); ++index )
159       {
160         // Find the mid-point of the area containing the glyph
161         const float glyphCenter = -glyphMetrics.xBearing + position.x + ( static_cast<float>( index ) + 0.5f ) * glyphAdvance;
162
163         if( visualX < glyphCenter )
164         {
165           matched = true;
166           break;
167         }
168       }
169
170       if( matched )
171       {
172         visualIndex = firstVisualCharacterIndex + index;
173         break;
174       }
175
176       numberOfCharacters = 0u;
177     }
178
179   }
180
181   // Return the logical position of the cursor in characters.
182
183   if( !matched )
184   {
185     visualIndex = endCharacter;
186   }
187
188   logicalIndex = ( bidiLineFetched ? logicalModel->GetLogicalCursorIndex( visualIndex ) : visualIndex );
189   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "closest visualIndex %d logicalIndex %d\n", visualIndex, logicalIndex );
190
191   DALI_ASSERT_DEBUG( ( logicalIndex <= logicalModel->mText.Count() && logicalIndex >= 0 ) && "GetClosestCursorIndex - Out of bounds index" );
192
193   return logicalIndex;
194 }
195
196
197 void GetCursorPosition( VisualModelPtr visualModel,
198                         LogicalModelPtr logicalModel,
199                         MetricsPtr metrics,
200                         CharacterIndex logical,
201                         CursorInfo& cursorInfo )
202 {
203   // TODO: Check for multiline with \n, etc...
204
205   const Length numberOfCharacters = logicalModel->mText.Count();
206
207   // Check if the logical position is the first or the last one of the text.
208   const bool isFirstPosition = 0u == logical;
209   const bool isLastPosition = numberOfCharacters == logical;
210
211   // 'logical' is the logical 'cursor' index.
212   // Get the next and current logical 'character' index.
213   const CharacterIndex nextCharacterIndex = logical;
214   const CharacterIndex characterIndex = isFirstPosition ? logical : logical - 1u;
215
216   // Get the direction of the character and the next one.
217   const CharacterDirection* const modelCharacterDirectionsBuffer = ( 0u != logicalModel->mCharacterDirections.Count() ) ? logicalModel->mCharacterDirections.Begin() : NULL;
218
219   CharacterDirection isCurrentRightToLeft = false;
220   CharacterDirection isNextRightToLeft = false;
221   if( NULL != modelCharacterDirectionsBuffer ) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right.
222   {
223     isCurrentRightToLeft = *( modelCharacterDirectionsBuffer + characterIndex );
224     isNextRightToLeft = *( modelCharacterDirectionsBuffer + nextCharacterIndex );
225   }
226
227   // Get the line where the character is laid-out.
228   const LineRun* const modelLines = visualModel->mLines.Begin();
229
230   const LineIndex lineIndex = visualModel->GetLineOfCharacter( characterIndex );
231   const LineRun& line = *( modelLines + lineIndex );
232
233   // Get the paragraph's direction.
234   const CharacterDirection isRightToLeftParagraph = line.direction;
235
236   // Check whether there is an alternative position:
237
238   cursorInfo.isSecondaryCursor = ( !isLastPosition && ( isCurrentRightToLeft != isNextRightToLeft ) ) ||
239                                  ( isLastPosition && ( isRightToLeftParagraph != isCurrentRightToLeft ) );
240
241   // Set the line offset and height.
242   cursorInfo.lineOffset = 0.f;
243   cursorInfo.lineHeight = line.ascender + -line.descender;
244
245   // Calculate the primary cursor.
246
247   CharacterIndex index = characterIndex;
248   if( cursorInfo.isSecondaryCursor )
249   {
250     // If there is a secondary position, the primary cursor may be in a different place than the logical index.
251
252     if( isLastPosition )
253     {
254       // The position of the cursor after the last character needs special
255       // care depending on its direction and the direction of the paragraph.
256
257       // Need to find the first character after the last character with the paragraph's direction.
258       // i.e l0 l1 l2 r0 r1 should find r0.
259
260       // TODO: check for more than one line!
261       index = isRightToLeftParagraph ? line.characterRun.characterIndex : line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u;
262       index = logicalModel->GetLogicalCharacterIndex( index );
263     }
264     else
265     {
266       index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? characterIndex : nextCharacterIndex;
267     }
268   }
269
270   const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin();
271   const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin();
272   const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin();
273   const CharacterIndex* const glyphsToCharactersBuffer = visualModel->mGlyphsToCharacters.Begin();
274   const Vector2* const glyphPositionsBuffer = visualModel->mGlyphPositions.Begin();
275   const GlyphInfo* const glyphInfoBuffer = visualModel->mGlyphs.Begin();
276
277   // Convert the cursor position into the glyph position.
278   const GlyphIndex primaryGlyphIndex = *( charactersToGlyphBuffer + index );
279   const Length primaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index );
280   const Length primaryNumberOfCharacters = *( charactersPerGlyphBuffer + primaryGlyphIndex );
281
282   // Get the metrics for the group of glyphs.
283   GlyphMetrics glyphMetrics;
284   GetGlyphsMetrics( primaryGlyphIndex,
285                     primaryNumberOfGlyphs,
286                     glyphMetrics,
287                     glyphInfoBuffer,
288                     metrics );
289
290   // Whether to add the glyph's advance to the cursor position.
291   // 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,
292   //     if the logical cursor is one, the position is the position of the first glyph and the advance is added.
293   // A 'truth table' was build and an online Karnaugh map tool was used to simplify the logic.
294   //
295   // FLCP A
296   // ------
297   // 0000 1
298   // 0001 1
299   // 0010 0
300   // 0011 0
301   // 0100 1
302   // 0101 0
303   // 0110 1
304   // 0111 0
305   // 1000 0
306   // 1001 x
307   // 1010 x
308   // 1011 1
309   // 1100 x
310   // 1101 x
311   // 1110 x
312   // 1111 x
313   //
314   // Where F -> isFirstPosition
315   //       L -> isLastPosition
316   //       C -> isCurrentRightToLeft
317   //       P -> isRightToLeftParagraph
318   //       A -> Whether to add the glyph's advance.
319
320   const bool addGlyphAdvance = ( ( isLastPosition && !isRightToLeftParagraph ) ||
321                                  ( isFirstPosition && isRightToLeftParagraph ) ||
322                                  ( !isFirstPosition && !isLastPosition && !isCurrentRightToLeft ) );
323
324   float glyphAdvance = addGlyphAdvance ? glyphMetrics.advance : 0.f;
325
326   if( !isLastPosition &&
327       ( primaryNumberOfCharacters > 1u ) )
328   {
329     const CharacterIndex firstIndex = *( glyphsToCharactersBuffer + primaryGlyphIndex );
330
331     bool isCurrentRightToLeft = false;
332     if( NULL != modelCharacterDirectionsBuffer ) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right.
333     {
334       isCurrentRightToLeft = *( modelCharacterDirectionsBuffer + index );
335     }
336
337     Length numberOfGlyphAdvance = ( isFirstPosition ? 0u : 1u ) + characterIndex - firstIndex;
338     if( isCurrentRightToLeft )
339     {
340       numberOfGlyphAdvance = primaryNumberOfCharacters - numberOfGlyphAdvance;
341     }
342
343     glyphAdvance = static_cast<float>( numberOfGlyphAdvance ) * glyphMetrics.advance / static_cast<float>( primaryNumberOfCharacters );
344   }
345
346   // Get the glyph position and x bearing.
347   const Vector2& primaryPosition = *( glyphPositionsBuffer + primaryGlyphIndex );
348
349   // Set the primary cursor's height.
350   cursorInfo.primaryCursorHeight = cursorInfo.isSecondaryCursor ? 0.5f * glyphMetrics.fontHeight : glyphMetrics.fontHeight;
351
352   // Set the primary cursor's position.
353   cursorInfo.primaryPosition.x = -glyphMetrics.xBearing + primaryPosition.x + glyphAdvance;
354   cursorInfo.primaryPosition.y = line.ascender - glyphMetrics.ascender;
355
356   // Calculate the secondary cursor.
357
358   if( cursorInfo.isSecondaryCursor )
359   {
360     // Set the secondary cursor's height.
361     cursorInfo.secondaryCursorHeight = 0.5f * glyphMetrics.fontHeight;
362
363     CharacterIndex index = characterIndex;
364     if( !isLastPosition )
365     {
366       index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? nextCharacterIndex : characterIndex;
367     }
368
369     const GlyphIndex secondaryGlyphIndex = *( charactersToGlyphBuffer + index );
370     const Length secondaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index );
371
372     const Vector2& secondaryPosition = *( glyphPositionsBuffer + secondaryGlyphIndex );
373
374     GetGlyphsMetrics( secondaryGlyphIndex,
375                       secondaryNumberOfGlyphs,
376                       glyphMetrics,
377                       glyphInfoBuffer,
378                       metrics );
379
380     // Set the secondary cursor's position.
381     cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + ( isCurrentRightToLeft ? 0.f : glyphMetrics.advance );
382     cursorInfo.secondaryPosition.y = cursorInfo.lineHeight - cursorInfo.secondaryCursorHeight - line.descender - ( glyphMetrics.fontHeight - glyphMetrics.ascender );
383   }
384 }
385
386 void FindSelectionIndices( VisualModelPtr visualModel,
387                            LogicalModelPtr logicalModel,
388                            MetricsPtr metrics,
389                            float visualX,
390                            float visualY,
391                            CharacterIndex& startIndex,
392                            CharacterIndex& endIndex )
393 {
394   CharacterIndex hitCharacter = Text::GetClosestCursorIndex( visualModel,
395                                                              logicalModel,
396                                                              metrics,
397                                                              visualX,
398                                                              visualY );
399   DALI_ASSERT_DEBUG( hitCharacter <= logicalModel->mText.Count() && "GetClosestCursorIndex returned out of bounds index" );
400
401   if( logicalModel->mText.Count() == 0 )
402   {
403     return;  // if model empty
404   }
405
406   if( hitCharacter >= logicalModel->mText.Count() )
407   {
408     // Closest hit character is the last character.
409     if( hitCharacter ==  logicalModel->mText.Count() )
410     {
411       hitCharacter--; //Hit character index set to last character in logical model
412     }
413     else
414     {
415       // hitCharacter is out of bounds
416       return;
417     }
418   }
419
420   startIndex = hitCharacter;
421   endIndex = hitCharacter;
422   bool isHitCharacterWhitespace = TextAbstraction::IsWhiteSpace( logicalModel->mText[hitCharacter] );
423
424   // Find the start and end of the text
425   for( startIndex = hitCharacter; startIndex > 0; --startIndex )
426   {
427     if( isHitCharacterWhitespace != TextAbstraction::IsWhiteSpace( logicalModel->mText[ startIndex-1 ] ) )
428     {
429       break;
430     }
431   }
432   const CharacterIndex pastTheEnd = logicalModel->mText.Count();
433   for( endIndex = hitCharacter + 1u; endIndex < pastTheEnd; ++endIndex )
434   {
435     if( isHitCharacterWhitespace != TextAbstraction::IsWhiteSpace( logicalModel->mText[ endIndex ] ) )
436     {
437       break;
438     }
439   }
440 }
441
442 } // namespace Text
443
444 } // namespace Toolkit
445
446 } // namespace Dali