TextModel - Create the bidirectional info for a given range of characters inside...
[platform/core/uifw/dali-toolkit.git] / automated-tests / src / dali-toolkit / dali-toolkit-test-utils / toolkit-text-model.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 #include "toolkit-text-model.h"
19
20 // EXTERNAL INCLUDES
21 #include <dali/devel-api/text-abstraction/font-client.h>
22
23 // INTERNAL INCLUDES
24 #include <dali-toolkit/internal/text/bidirectional-support.h>
25 #include <dali-toolkit/internal/text/character-set-conversion.h>
26 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
27 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
28 #include <dali-toolkit/internal/text/metrics.h>
29 #include <dali-toolkit/internal/text/multi-language-support.h>
30 #include <dali-toolkit/internal/text/segmentation.h>
31 #include <dali-toolkit/internal/text/shaper.h>
32 #include <dali-toolkit/internal/text/text-controller-impl.h>
33
34 namespace Dali
35 {
36
37 namespace Toolkit
38 {
39
40 namespace Text
41 {
42
43 /**
44  * @brief Frees previously allocated bidirectional resources.
45  *
46  * @param[in] bidirectionalLineInfo Bidirectional info per line.
47  * @param[in] index Index to the first line with bidirectional info to be freed.
48  */
49 void FreeBidirectionalLineInfoResources( Vector<BidirectionalLineInfoRun> bidirectionalLineInfo,
50                                          uint32_t index )
51 {
52   // Free the allocated memory used to store the conversion table in the bidirectional line info run.
53   for( Vector<BidirectionalLineInfoRun>::Iterator it = bidirectionalLineInfo.Begin() + index,
54          endIt = bidirectionalLineInfo.End();
55        it != endIt;
56        ++it )
57   {
58     BidirectionalLineInfoRun& bidiLineInfo = *it;
59
60     free( bidiLineInfo.visualToLogicalMap );
61   }
62 }
63
64 /**
65  * @brief Clear all the model data except for LogicalModel::mText.
66  *
67  * @param[in] characterIndex Clear data starting from the index.
68  */
69 void ClearModelData( CharacterIndex characterIndex,
70                      LogicalModelPtr logicalModel,
71                      VisualModelPtr visualModel )
72 {
73   // n.b. This does not Clear the mText from mLogicalModel
74
75   // Frees previously allocated resources.
76   FreeBidirectionalLineInfoResources( logicalModel->mBidirectionalLineInfo, 0u );
77
78   logicalModel->mScriptRuns.Clear();
79   logicalModel->mFontRuns.Clear();
80   logicalModel->mWordBreakInfo.Clear();
81   logicalModel->mBidirectionalParagraphInfo.Clear();
82   logicalModel->mCharacterDirections.Clear();
83   logicalModel->mBidirectionalLineInfo.Clear();
84   logicalModel->mLogicalToVisualMap.Clear();
85   logicalModel->mVisualToLogicalMap.Clear();
86   visualModel->mGlyphs.Clear();
87   visualModel->mGlyphsToCharacters.Clear();
88   visualModel->mCharactersToGlyph.Clear();
89   visualModel->mCharactersPerGlyph.Clear();
90   visualModel->mGlyphsPerCharacter.Clear();
91   visualModel->mGlyphPositions.Clear();
92   visualModel->mLines.Clear();
93   visualModel->mColorRuns.Clear();
94
95   visualModel->ClearCaches();
96 }
97
98 void CreateTextModel( const std::string& text,
99                       const Size& textArea,
100                       Size& layoutSize,
101                       LogicalModelPtr logicalModel,
102                       VisualModelPtr visualModel )
103 {
104   // 1) Convert to utf32
105   Vector<Character>& utf32Characters = logicalModel->mText;
106   utf32Characters.Resize( text.size() );
107
108   const uint32_t numberOfCharacters = Utf8ToUtf32( reinterpret_cast<const uint8_t* const>( text.c_str() ),
109                                                    text.size(),
110                                                    &utf32Characters[0u] );
111   utf32Characters.Resize( numberOfCharacters );
112
113   // 2) Set the break and paragraph info.
114   Vector<LineBreakInfo>& lineBreakInfo = logicalModel->mLineBreakInfo;
115   lineBreakInfo.Resize( numberOfCharacters );
116
117   SetLineBreakInfo( utf32Characters, lineBreakInfo );
118
119   if( 0u == numberOfCharacters )
120   {
121     // Nothing else to do if the number of characters is zero.
122     return;
123   }
124
125   // Retrieves the word break info. The word break info is used to layout the text (where to wrap the text in lines).
126   Vector<WordBreakInfo>& wordBreakInfo = logicalModel->mWordBreakInfo;
127   wordBreakInfo.Resize( numberOfCharacters );
128
129   SetWordBreakInfo( utf32Characters,
130                     0u,
131                     numberOfCharacters,
132                     wordBreakInfo );
133
134   // 3) Set the script info.
135   MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
136
137   Vector<ScriptRun>& scripts = logicalModel->mScriptRuns;
138   multilanguageSupport.SetScripts( utf32Characters,
139                                    0u,
140                                    numberOfCharacters,
141                                    scripts );
142
143   // 4) Set the font info
144   Vector<FontDescriptionRun>& fontDescriptionRuns = logicalModel->mFontDescriptionRuns;
145   Vector<FontRun>& validFonts = logicalModel->mFontRuns;
146
147   // The default font id.
148   FontDefaults fontDefaults;
149   fontDefaults.mFontDescription.family = "";
150   fontDefaults.familyDefined = true;
151   fontDefaults.mDefaultPointSize = 12.f;
152   fontDefaults.sizeDefined = true;
153
154   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
155   fontClient.SetDpi( 96u, 96u );
156
157   const FontId defaultFontId = fontDefaults.GetFontId( fontClient );
158
159   // Validates the fonts. If there is a character with no assigned font it sets a default one.
160   // After this call, fonts are validated.
161   multilanguageSupport.ValidateFonts( utf32Characters,
162                                       scripts,
163                                       fontDescriptionRuns,
164                                       defaultFontId,
165                                       0u,
166                                       numberOfCharacters,
167                                       validFonts );
168
169   // 5) Set the bidirectional info per paragraph.
170   Vector<Character> mirroredUtf32Characters;
171   bool textMirrored = false;
172
173   // Reserve some space for the vector of paragraph's bidirectional info.
174   Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = logicalModel->mBidirectionalParagraphInfo;
175
176   // Calculates the bidirectional info for the whole paragraph if it contains right to left scripts.
177   SetBidirectionalInfo( utf32Characters,
178                         scripts,
179                         lineBreakInfo,
180                         0u,
181                         numberOfCharacters,
182                         bidirectionalInfo );
183
184   // 6) Set character directions.
185   Vector<CharacterDirection>& characterDirections = logicalModel->mCharacterDirections;
186   if( 0u != bidirectionalInfo.Count() )
187   {
188     // Only set the character directions if there is right to left characters.
189     GetCharactersDirection( bidirectionalInfo,
190                             numberOfCharacters,
191                             0u,
192                             numberOfCharacters,
193                             characterDirections );
194
195
196     // This paragraph has right to left text. Some characters may need to be mirrored.
197     textMirrored = GetMirroredText( utf32Characters,
198                                     characterDirections,
199                                     bidirectionalInfo,
200                                     0u,
201                                     numberOfCharacters,
202                                     mirroredUtf32Characters );
203   }
204   else
205   {
206     // There is no right to left characters. Clear the directions vector.
207     characterDirections.Clear();
208   }
209
210   // 7) Shape the text.
211
212   Vector<GlyphInfo>& glyphs = visualModel->mGlyphs;
213   Vector<CharacterIndex>& glyphsToCharactersMap = visualModel->mGlyphsToCharacters;
214   Vector<Length>& charactersPerGlyph = visualModel->mCharactersPerGlyph;
215   Vector<GlyphIndex> newParagraphGlyphs;
216
217   const Length currentNumberOfGlyphs = glyphs.Count();
218   const Vector<Character>& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters;
219
220   ShapeText( textToShape,
221              lineBreakInfo,
222              scripts,
223              validFonts,
224              glyphs,
225              glyphsToCharactersMap,
226              charactersPerGlyph,
227              newParagraphGlyphs );
228
229   // Create the 'number of glyphs' per character and the glyph to character conversion tables.
230   visualModel->CreateGlyphsPerCharacterTable( numberOfCharacters );
231   visualModel->CreateCharacterToGlyphTable( numberOfCharacters );
232
233   const Length numberOfGlyphs = glyphs.Count() - currentNumberOfGlyphs;
234
235   // 8) Get the glyph metrics
236   MetricsPtr metrics = Metrics::New( fontClient );
237
238   const GlyphIndex glyphIndex = currentNumberOfGlyphs;
239
240   GlyphInfo* glyphsBuffer = glyphs.Begin() + glyphIndex;
241   metrics->GetGlyphMetrics( glyphsBuffer, numberOfGlyphs );
242
243   // Update the width and advance of all new paragraph characters.
244   for( Vector<GlyphIndex>::ConstIterator it = newParagraphGlyphs.Begin(),
245          endIt = newParagraphGlyphs.End();
246        it != endIt;
247        ++it )
248   {
249     const GlyphIndex index = *it;
250     GlyphInfo& glyph = *( glyphsBuffer + ( index - glyphIndex ) );
251
252     glyph.xBearing = 0.f;
253     glyph.width = 0.f;
254     glyph.advance = 0.f;
255   }
256
257   // 9) Layout the text
258   LayoutEngine layoutEngine;
259   layoutEngine.SetMetrics( metrics );
260   layoutEngine.SetLayout( LayoutEngine::MULTI_LINE_BOX );
261
262   // Set the layout parameters.
263   const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
264   const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
265   LayoutParameters layoutParameters( textArea,
266                                      utf32Characters.Begin(),
267                                      lineBreakInfo.Begin(),
268                                      wordBreakInfo.Begin(),
269                                      ( 0u != characterDirections.Count() ) ? characterDirections.Begin() : NULL,
270                                      glyphs.Count(),
271                                      glyphs.Begin(),
272                                      glyphsToCharactersMap.Begin(),
273                                      charactersPerGlyph.Begin() );
274
275   // Get the character to glyph conversion table and set into the layout.
276   layoutParameters.charactersToGlyphsBuffer = charactersToGlyph.Begin();
277   // Get the glyphs per character table and set into the layout.
278   layoutParameters.glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
279
280   Vector<LineRun>& lines = visualModel->mLines;
281
282   Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
283   glyphPositions.Resize( numberOfGlyphs );
284
285   layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( utf32Characters.Begin() + ( logicalModel->mText.Count() - 1u ) ) );
286
287   layoutEngine.LayoutText( layoutParameters,
288                            glyphPositions,
289                            lines,
290                            layoutSize );
291
292   // 10) Reorder the lines
293   if( 0u != bidirectionalInfo.Count() )
294   {
295     Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = logicalModel->mBidirectionalLineInfo;
296
297     // Get the lines
298     const Length numberOfLines = lines.Count();
299
300     // Reorder the lines.
301     bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
302     ReorderLines( bidirectionalInfo,
303                   0u,
304                   numberOfCharacters,
305                   lines,
306                   bidirectionalLineInfo );
307
308     // Set the bidirectional info per line into the layout parameters.
309     layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
310     layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
311
312     // Set the bidirectional info into the model.
313     logicalModel->SetVisualToLogicalMap( layoutParameters.lineBidirectionalInfoRunsBuffer,
314                                          layoutParameters.numberOfBidirectionalInfoRuns,
315                                          0u,
316                                          numberOfCharacters );
317
318     // Re-layout the text. Reorder those lines with right to left characters.
319     layoutEngine.ReLayoutRightToLeftLines( layoutParameters,
320                                            glyphPositions );
321   }
322 }
323
324 } // namespace Text
325
326 } // namespace Toolkit
327
328 } // namespace Dali