fix linespacing calculation in TextLabel
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / logical-model-impl.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 // CLASS HEADER
19 #include <dali-toolkit/internal/text/logical-model-impl.h>
20
21 // INTERNAL INCLUDES
22 #include <dali-toolkit/internal/text/bounded-paragraph-helper-functions.h>
23 #include <dali-toolkit/internal/text/input-style.h>
24 #include <dali-toolkit/internal/text/text-run-container.h>
25
26 namespace Dali
27 {
28 namespace Toolkit
29 {
30 namespace Text
31 {
32 void FreeFontFamilyNames(Vector<FontDescriptionRun>& fontDescriptionRuns)
33 {
34   for(Vector<FontDescriptionRun>::Iterator it    = fontDescriptionRuns.Begin(),
35                                            endIt = fontDescriptionRuns.End();
36       it != endIt;
37       ++it)
38   {
39     delete[](*it).familyName;
40   }
41
42   fontDescriptionRuns.Clear();
43 }
44
45 void FreeEmbeddedItems(Vector<EmbeddedItem>& embeddedItem)
46 {
47   for(Vector<EmbeddedItem>::Iterator it    = embeddedItem.Begin(),
48                                      endIt = embeddedItem.End();
49       it != endIt;
50       ++it)
51   {
52     EmbeddedItem& item = *it;
53     delete[] item.url;
54   }
55
56   embeddedItem.Clear();
57 }
58
59 void FreeAnchors(Vector<Anchor>& anchors)
60 {
61   for(auto&& anchor : anchors)
62   {
63     delete[] anchor.href;
64   }
65
66   anchors.Clear();
67 }
68
69 LogicalModelPtr LogicalModel::New()
70 {
71   return LogicalModelPtr(new LogicalModel());
72 }
73
74 Script LogicalModel::GetScript(CharacterIndex characterIndex) const
75 {
76   // If this operation is too slow, consider a binary search.
77
78   const ScriptRun* const scriptRunBuffer = mScriptRuns.Begin();
79   for(Length index = 0u, length = mScriptRuns.Count(); index < length; ++index)
80   {
81     const ScriptRun* const scriptRun = scriptRunBuffer + index;
82
83     if((scriptRun->characterRun.characterIndex <= characterIndex) &&
84        (characterIndex < scriptRun->characterRun.characterIndex + scriptRun->characterRun.numberOfCharacters))
85     {
86       return scriptRun->script;
87     }
88   }
89
90   return TextAbstraction::UNKNOWN;
91 }
92
93 CharacterDirection LogicalModel::GetCharacterDirection(CharacterIndex characterIndex) const
94 {
95   if(characterIndex >= mCharacterDirections.Count())
96   {
97     // The model has no right to left characters, so the vector of directions is void.
98     return false;
99   }
100
101   return *(mCharacterDirections.Begin() + characterIndex);
102 }
103
104 CharacterIndex LogicalModel::GetLogicalCursorIndex(CharacterIndex visualCursorIndex)
105 {
106   // The character's directions buffer.
107   const CharacterDirection* const modelCharacterDirections = mCharacterDirections.Begin();
108
109   // The bidirectional line info.
110   const BidirectionalLineInfoRun* const bidirectionalLineInfo = mBidirectionalLineInfo.Begin() + mBidirectionalLineIndex;
111
112   // Whether the paragraph starts with a right to left character.
113   const bool isRightToLeftParagraph = bidirectionalLineInfo->direction;
114
115   // The total number of characters of the line.
116   const Length lastCharacterIndex = bidirectionalLineInfo->characterRun.characterIndex + bidirectionalLineInfo->characterRun.numberOfCharacters;
117
118   CharacterIndex logicalCursorIndex = 0u;
119
120   if(bidirectionalLineInfo->characterRun.characterIndex == visualCursorIndex)
121   {
122     if(isRightToLeftParagraph)
123     {
124       logicalCursorIndex = lastCharacterIndex;
125     }
126     else // else logical position is the first of the line.
127     {
128       logicalCursorIndex = bidirectionalLineInfo->characterRun.characterIndex;
129     }
130   }
131   else if(lastCharacterIndex == visualCursorIndex)
132   {
133     if(isRightToLeftParagraph)
134     {
135       logicalCursorIndex = bidirectionalLineInfo->characterRun.characterIndex;
136     }
137     else // else logical position is the number of characters.
138     {
139       logicalCursorIndex = lastCharacterIndex;
140     }
141   }
142   else
143   {
144     // Get the character indexed by  index - 1 and index
145     // and calculate the logical position according the directions of
146     // both characters and the direction of the paragraph.
147
148     const CharacterIndex previousVisualCursorIndex  = visualCursorIndex - 1u;
149     const CharacterIndex previousLogicalCursorIndex = *(bidirectionalLineInfo->visualToLogicalMap + previousVisualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex;
150     const CharacterIndex currentLogicalCursorIndex  = *(bidirectionalLineInfo->visualToLogicalMap + visualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex;
151
152     const CharacterDirection previousCharacterDirection = *(modelCharacterDirections + previousLogicalCursorIndex);
153     const CharacterDirection currentCharacterDirection  = *(modelCharacterDirections + currentLogicalCursorIndex);
154
155     if(previousCharacterDirection == currentCharacterDirection)
156     {
157       // Both glyphs have the same direction.
158       if(previousCharacterDirection)
159       {
160         logicalCursorIndex = previousLogicalCursorIndex;
161       }
162       else
163       {
164         logicalCursorIndex = currentLogicalCursorIndex;
165       }
166     }
167     else
168     {
169       if(isRightToLeftParagraph)
170       {
171         if(currentCharacterDirection)
172         {
173           logicalCursorIndex = currentLogicalCursorIndex + 1u;
174         }
175         else
176         {
177           logicalCursorIndex = previousLogicalCursorIndex;
178         }
179       }
180       else
181       {
182         if(previousCharacterDirection)
183         {
184           logicalCursorIndex = currentLogicalCursorIndex;
185         }
186         else
187         {
188           logicalCursorIndex = previousLogicalCursorIndex + 1u;
189         }
190       }
191     }
192   }
193
194   return logicalCursorIndex;
195 }
196
197 CharacterIndex LogicalModel::GetLogicalCharacterIndex(CharacterIndex visualCharacterIndex)
198 {
199   // The bidirectional line info.
200   const BidirectionalLineInfoRun* const bidirectionalLineInfo = mBidirectionalLineInfo.Begin() + mBidirectionalLineIndex;
201
202   return *(bidirectionalLineInfo->visualToLogicalMap + visualCharacterIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex;
203 }
204
205 bool LogicalModel::FetchBidirectionalLineInfo(CharacterIndex characterIndex)
206 {
207   // The number of bidirectional lines.
208   const Length numberOfBidirectionalLines = mBidirectionalLineInfo.Count();
209
210   if(0u == numberOfBidirectionalLines)
211   {
212     // If there is no bidirectional info.
213     return false;
214   }
215
216   // Find the bidi line where the character is laid-out.
217
218   const BidirectionalLineInfoRun* const bidirectionalLineInfoBuffer = mBidirectionalLineInfo.Begin();
219
220   // Check first if the character is in the previously fetched line.
221
222   BidirectionalLineRunIndex bidiLineIndex                 = 0u;
223   CharacterIndex            lastCharacterOfRightToLeftRun = 0u;
224   if(mBidirectionalLineIndex < numberOfBidirectionalLines)
225   {
226     const BidirectionalLineInfoRun& bidiLineRun = *(bidirectionalLineInfoBuffer + mBidirectionalLineIndex);
227
228     const CharacterIndex lastCharacterOfRunPlusOne = bidiLineRun.characterRun.characterIndex + bidiLineRun.characterRun.numberOfCharacters;
229     if((bidiLineRun.characterRun.characterIndex <= characterIndex) &&
230        (characterIndex < lastCharacterOfRunPlusOne))
231     {
232       // The character is in the previously fetched bidi line.
233       return true;
234     }
235     else
236     {
237       // The character is not in the previously fetched line.
238       // Set the bidi line index from where to start the fetch.
239
240       if(characterIndex < bidiLineRun.characterRun.characterIndex)
241       {
242         // Start the fetch from the beginning.
243         bidiLineIndex = 0u;
244       }
245       else
246       {
247         // Start the fetch from the next line.
248         bidiLineIndex                 = mBidirectionalLineIndex + 1u;
249         lastCharacterOfRightToLeftRun = lastCharacterOfRunPlusOne - 1u;
250       }
251     }
252   }
253
254   // The character has not been found in the previously fetched bidi line.
255   for(Vector<BidirectionalLineInfoRun>::ConstIterator it    = bidirectionalLineInfoBuffer + bidiLineIndex,
256                                                       endIt = mBidirectionalLineInfo.End();
257       it != endIt;
258       ++it, ++bidiLineIndex)
259   {
260     const BidirectionalLineInfoRun& bidiLineRun = *it;
261
262     if((lastCharacterOfRightToLeftRun < characterIndex) &&
263        (characterIndex < bidiLineRun.characterRun.characterIndex))
264     {
265       // The character is not inside a bidi line.
266       return false;
267     }
268
269     const CharacterIndex lastCharacterOfRunPlusOne = bidiLineRun.characterRun.characterIndex + bidiLineRun.characterRun.numberOfCharacters;
270     lastCharacterOfRightToLeftRun                  = lastCharacterOfRunPlusOne - 1u;
271     if((bidiLineRun.characterRun.characterIndex <= characterIndex) &&
272        (characterIndex < lastCharacterOfRunPlusOne))
273     {
274       // Bidi line found. Fetch the line.
275       mBidirectionalLineIndex = bidiLineIndex;
276       return true;
277     }
278   }
279
280   return false;
281 }
282
283 BidirectionalLineRunIndex LogicalModel::GetBidirectionalLineInfo() const
284 {
285   return mBidirectionalLineIndex;
286 }
287
288 void LogicalModel::UpdateTextStyleRuns(CharacterIndex index, int numberOfCharacters)
289 {
290   const Length totalNumberOfCharacters = mText.Count();
291
292   // Process the color runs.
293   Vector<ColorRun> removedColorRuns;
294   UpdateCharacterRuns<ColorRun>(index,
295                                 numberOfCharacters,
296                                 totalNumberOfCharacters,
297                                 mColorRuns,
298                                 removedColorRuns);
299
300   // This is needed until now for underline tag in mark-up processor
301   // Process the underlined runs.
302   Vector<UnderlinedCharacterRun> removedUnderlinedCharacterRuns;
303   UpdateCharacterRuns<UnderlinedCharacterRun>(index,
304                                               numberOfCharacters,
305                                               totalNumberOfCharacters,
306                                               mUnderlinedCharacterRuns,
307                                               removedUnderlinedCharacterRuns);
308
309   // Process the strikethrough runs.
310   Vector<StrikethroughCharacterRun> removedStrikethroughCharacterRuns;
311   UpdateCharacterRuns<StrikethroughCharacterRun>(index,
312                                                  numberOfCharacters,
313                                                  totalNumberOfCharacters,
314                                                  mStrikethroughCharacterRuns,
315                                                  removedStrikethroughCharacterRuns);
316
317   // Process the background color runs.
318   Vector<ColorRun> removedBackgroundColorRuns;
319   UpdateCharacterRuns<ColorRun>(index,
320                                 numberOfCharacters,
321                                 totalNumberOfCharacters,
322                                 mBackgroundColorRuns,
323                                 removedBackgroundColorRuns);
324
325   // Process the font description runs.
326   Vector<FontDescriptionRun> removedFontDescriptionRuns;
327   UpdateCharacterRuns<FontDescriptionRun>(index,
328                                           numberOfCharacters,
329                                           totalNumberOfCharacters,
330                                           mFontDescriptionRuns,
331                                           removedFontDescriptionRuns);
332
333   // Free memory allocated for the font family name.
334   FreeFontFamilyNames(removedFontDescriptionRuns);
335
336   // Process the bounded paragraph runs
337   MergeBoundedParagraphRunsWhenRemoveCharacters(mText,
338                                                 index,
339                                                 numberOfCharacters,
340                                                 mBoundedParagraphRuns);
341
342   Vector<BoundedParagraphRun> removedBoundedParagraphRuns;
343   UpdateCharacterRuns<BoundedParagraphRun>(index,
344                                            numberOfCharacters,
345                                            totalNumberOfCharacters,
346                                            mBoundedParagraphRuns,
347                                            removedBoundedParagraphRuns);
348 }
349
350 void LogicalModel::RetrieveStyle(CharacterIndex index, InputStyle& style)
351 {
352   unsigned int runIndex = 0u;
353
354   // Set the text color.
355   bool                  colorOverriden  = false;
356   unsigned int          colorIndex      = 0u;
357   const ColorRun* const colorRunsBuffer = mColorRuns.Begin();
358   for(Vector<ColorRun>::ConstIterator it    = colorRunsBuffer,
359                                       endIt = mColorRuns.End();
360       it != endIt;
361       ++it, ++runIndex)
362   {
363     const ColorRun& colorRun = *it;
364
365     if((colorRun.characterRun.characterIndex <= index) &&
366        (index < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters))
367     {
368       colorIndex     = runIndex;
369       colorOverriden = true;
370     }
371   }
372
373   // Set the text's color if it's overriden.
374   if(colorOverriden)
375   {
376     style.textColor      = (*(colorRunsBuffer + colorIndex)).color;
377     style.isDefaultColor = false;
378   }
379
380   // Reset the run index.
381   runIndex = 0u;
382
383   // Set the font's parameters.
384   bool                            nameOverriden             = false;
385   bool                            weightOverriden           = false;
386   bool                            widthOverriden            = false;
387   bool                            slantOverriden            = false;
388   bool                            sizeOverriden             = false;
389   unsigned int                    nameIndex                 = 0u;
390   unsigned int                    weightIndex               = 0u;
391   unsigned int                    widthIndex                = 0u;
392   unsigned int                    slantIndex                = 0u;
393   unsigned int                    sizeIndex                 = 0u;
394   const FontDescriptionRun* const fontDescriptionRunsBuffer = mFontDescriptionRuns.Begin();
395   for(Vector<FontDescriptionRun>::ConstIterator it    = fontDescriptionRunsBuffer,
396                                                 endIt = mFontDescriptionRuns.End();
397       it != endIt;
398       ++it, ++runIndex)
399   {
400     const FontDescriptionRun& fontDescriptionRun = *it;
401
402     if((fontDescriptionRun.characterRun.characterIndex <= index) &&
403        (index < fontDescriptionRun.characterRun.characterIndex + fontDescriptionRun.characterRun.numberOfCharacters))
404     {
405       if(fontDescriptionRun.familyDefined)
406       {
407         nameIndex     = runIndex;
408         nameOverriden = true;
409       }
410
411       if(fontDescriptionRun.weightDefined)
412       {
413         weightIndex     = runIndex;
414         weightOverriden = true;
415       }
416
417       if(fontDescriptionRun.widthDefined)
418       {
419         widthIndex     = runIndex;
420         widthOverriden = true;
421       }
422
423       if(fontDescriptionRun.slantDefined)
424       {
425         slantIndex     = runIndex;
426         slantOverriden = true;
427       }
428
429       if(fontDescriptionRun.sizeDefined)
430       {
431         sizeIndex     = runIndex;
432         sizeOverriden = true;
433       }
434     }
435   }
436
437   // Set the font's family name if it's overriden.
438   if(nameOverriden)
439   {
440     const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + nameIndex);
441
442     style.familyName      = std::string(fontDescriptionRun.familyName, fontDescriptionRun.familyLength);
443     style.isFamilyDefined = true;
444   }
445
446   // Set the font's weight if it's overriden.
447   if(weightOverriden)
448   {
449     const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + weightIndex);
450
451     style.weight          = fontDescriptionRun.weight;
452     style.isWeightDefined = true;
453   }
454
455   // Set the font's width if it's overriden.
456   if(widthOverriden)
457   {
458     const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + widthIndex);
459
460     style.width          = fontDescriptionRun.width;
461     style.isWidthDefined = true;
462   }
463
464   // Set the font's slant if it's overriden.
465   if(slantOverriden)
466   {
467     const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + slantIndex);
468
469     style.slant          = fontDescriptionRun.slant;
470     style.isSlantDefined = true;
471   }
472
473   // Set the font's size if it's overriden.
474   if(sizeOverriden)
475   {
476     const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + sizeIndex);
477
478     style.size          = static_cast<float>(fontDescriptionRun.size) / 64.f;
479     style.isSizeDefined = true;
480   }
481 }
482
483 void LogicalModel::ClearFontDescriptionRuns()
484 {
485   FreeFontFamilyNames(mFontDescriptionRuns);
486 }
487
488 void LogicalModel::ClearStrikethroughRuns()
489 {
490   mStrikethroughCharacterRuns.Clear();
491 }
492
493 void LogicalModel::CreateParagraphInfo(CharacterIndex startIndex,
494                                        Length         numberOfCharacters)
495 {
496   const Length totalNumberOfCharacters = mLineBreakInfo.Count();
497
498   // Count the number of LINE_MUST_BREAK to reserve some space for the vector of paragraph's info.
499   Vector<CharacterIndex> paragraphs;
500   paragraphs.Reserve(numberOfCharacters);
501   const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer       = mLineBreakInfo.Begin();
502   const CharacterIndex                  lastCharacterIndexPlusOne = startIndex + numberOfCharacters;
503   for(Length index = startIndex; index < lastCharacterIndexPlusOne; ++index)
504   {
505     if(TextAbstraction::LINE_MUST_BREAK == *(lineBreakInfoBuffer + index))
506     {
507       paragraphs.PushBack(index);
508     }
509   }
510
511   // Whether the current paragraphs are updated or set from scratch.
512   const bool updateCurrentParagraphs = numberOfCharacters < totalNumberOfCharacters;
513
514   // Reserve space for current paragraphs plus new ones.
515   const Length numberOfNewParagraphs   = paragraphs.Count();
516   const Length totalNumberOfParagraphs = mParagraphInfo.Count() + numberOfNewParagraphs;
517   mParagraphInfo.Resize(totalNumberOfParagraphs);
518
519   ParagraphRun*        paragraphInfoBuffer = NULL;
520   Vector<ParagraphRun> newParagraphs;
521
522   if(updateCurrentParagraphs)
523   {
524     newParagraphs.Resize(numberOfNewParagraphs);
525     paragraphInfoBuffer = newParagraphs.Begin();
526   }
527   else
528   {
529     paragraphInfoBuffer = mParagraphInfo.Begin();
530   }
531
532   // Find where to insert the new paragraphs.
533   ParagraphRunIndex paragraphIndex = 0u;
534   CharacterIndex    firstIndex     = startIndex;
535
536   if(updateCurrentParagraphs)
537   {
538     for(Vector<ParagraphRun>::ConstIterator it    = mParagraphInfo.Begin(),
539                                             endIt = mParagraphInfo.Begin() + totalNumberOfParagraphs - numberOfNewParagraphs;
540         it != endIt;
541         ++it)
542     {
543       const ParagraphRun& paragraph(*it);
544
545       if(startIndex < paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters)
546       {
547         firstIndex = paragraph.characterRun.characterIndex;
548         break;
549       }
550
551       ++paragraphIndex;
552     }
553   }
554
555   // Create the paragraph info.
556   ParagraphRunIndex newParagraphIndex = 0u;
557   for(Vector<CharacterIndex>::ConstIterator it    = paragraphs.Begin(),
558                                             endIt = paragraphs.End();
559       it != endIt;
560       ++it, ++newParagraphIndex)
561   {
562     const CharacterIndex index = *it;
563
564     ParagraphRun& paragraph                   = *(paragraphInfoBuffer + newParagraphIndex);
565     paragraph.characterRun.characterIndex     = firstIndex;
566     paragraph.characterRun.numberOfCharacters = 1u + index - firstIndex;
567
568     firstIndex += paragraph.characterRun.numberOfCharacters;
569   }
570
571   // Insert the new paragraphs.
572   if(updateCurrentParagraphs)
573   {
574     mParagraphInfo.Insert(mParagraphInfo.Begin() + paragraphIndex,
575                           newParagraphs.Begin(),
576                           newParagraphs.End());
577
578     mParagraphInfo.Resize(totalNumberOfParagraphs);
579
580     // Update the next paragraph indices.
581     for(Vector<ParagraphRun>::Iterator it    = mParagraphInfo.Begin() + paragraphIndex + newParagraphs.Count(),
582                                        endIt = mParagraphInfo.End();
583         it != endIt;
584         ++it)
585     {
586       ParagraphRun& paragraph(*it);
587
588       paragraph.characterRun.characterIndex += numberOfCharacters;
589     }
590   }
591 }
592
593 void LogicalModel::FindParagraphs(CharacterIndex             index,
594                                   Length                     numberOfCharacters,
595                                   Vector<ParagraphRunIndex>& paragraphs)
596 {
597   // Reserve som space for the paragraph indices.
598   paragraphs.Reserve(mParagraphInfo.Count());
599
600   // Traverse the paragraphs to find which ones contain the given characters.
601   ParagraphRunIndex paragraphIndex = 0u;
602   for(Vector<ParagraphRun>::ConstIterator it    = mParagraphInfo.Begin(),
603                                           endIt = mParagraphInfo.End();
604       it != endIt;
605       ++it, ++paragraphIndex)
606   {
607     const ParagraphRun& paragraph(*it);
608
609     if((paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters > index) &&
610        (paragraph.characterRun.characterIndex < index + numberOfCharacters))
611     {
612       paragraphs.PushBack(paragraphIndex);
613     }
614   }
615 }
616
617 Length LogicalModel::GetNumberOfBoundedParagraphRuns() const
618 {
619   return mBoundedParagraphRuns.Count();
620 }
621
622 const Vector<BoundedParagraphRun>& LogicalModel::GetBoundedParagraphRuns() const
623 {
624   return mBoundedParagraphRuns;
625 }
626
627 void LogicalModel::ClearEmbeddedImages()
628 {
629   FreeEmbeddedItems(mEmbeddedItems);
630 }
631
632 void LogicalModel::ClearAnchors()
633 {
634   FreeAnchors(mAnchors);
635 }
636
637 LogicalModel::~LogicalModel()
638 {
639   ClearFontDescriptionRuns();
640   ClearEmbeddedImages();
641 }
642
643 LogicalModel::LogicalModel()
644 : mBidirectionalLineIndex(0u)
645 {
646 }
647
648 } // namespace Text
649
650 } // namespace Toolkit
651
652 } // namespace Dali