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