924815156e8d081d99a340e432eeb5444faac761
[platform/core/uifw/dali-toolkit.git] / automated-tests / src / dali-toolkit-internal / dali-toolkit-test-utils / toolkit-text-utils.cpp
1 /*
2  * Copyright (c) 2017 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 "toolkit-text-utils.h"
20
21 // EXTERNAL INCLUDES
22 #include <limits>
23 #include <dali/devel-api/text-abstraction/font-client.h>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/internal/text/bidirectional-support.h>
27 #include <dali-toolkit/internal/text/character-set-conversion.h>
28 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
29 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
30 #include <dali-toolkit/internal/text/multi-language-support.h>
31 #include <dali-toolkit/internal/text/segmentation.h>
32 #include <dali-toolkit/internal/text/shaper.h>
33 #include <dali-toolkit/internal/text/text-controller-impl.h>
34
35 namespace Dali
36 {
37
38 namespace Toolkit
39 {
40
41 namespace Text
42 {
43
44 /**
45  * @brief Frees previously allocated bidirectional resources.
46  *
47  * @param[in] bidirectionalLineInfo Bidirectional info per line.
48  * @param[in] index Index to the first line with bidirectional info to be freed.
49  */
50 void FreeBidirectionalLineInfoResources( Vector<BidirectionalLineInfoRun> bidirectionalLineInfo,
51                                          uint32_t index )
52 {
53   // Free the allocated memory used to store the conversion table in the bidirectional line info run.
54   for( Vector<BidirectionalLineInfoRun>::Iterator it = bidirectionalLineInfo.Begin() + index,
55          endIt = bidirectionalLineInfo.End();
56        it != endIt;
57        ++it )
58   {
59     BidirectionalLineInfoRun& bidiLineInfo = *it;
60
61     free( bidiLineInfo.visualToLogicalMap );
62   }
63 }
64
65 /**
66  * @brief Clear all the model data except for LogicalModel::mText.
67  *
68  * @param[in] characterIndex Clear data starting from the index.
69  */
70 void ClearModelData( CharacterIndex characterIndex,
71                      LogicalModelPtr logicalModel,
72                      VisualModelPtr visualModel )
73 {
74   // n.b. This does not Clear the mText from mLogicalModel
75
76   // Frees previously allocated resources.
77   FreeBidirectionalLineInfoResources( logicalModel->mBidirectionalLineInfo, 0u );
78
79   logicalModel->mScriptRuns.Clear();
80   logicalModel->mFontRuns.Clear();
81   logicalModel->mWordBreakInfo.Clear();
82   logicalModel->mBidirectionalParagraphInfo.Clear();
83   logicalModel->mCharacterDirections.Clear();
84   logicalModel->mBidirectionalLineInfo.Clear();
85   visualModel->mGlyphs.Clear();
86   visualModel->mGlyphsToCharacters.Clear();
87   visualModel->mCharactersToGlyph.Clear();
88   visualModel->mCharactersPerGlyph.Clear();
89   visualModel->mGlyphsPerCharacter.Clear();
90   visualModel->mGlyphPositions.Clear();
91   visualModel->mLines.Clear();
92
93   visualModel->ClearCaches();
94 }
95
96 void CreateTextModel( const std::string& text,
97                       const Size& textArea,
98                       const Vector<FontDescriptionRun>& fontDescriptions,
99                       const LayoutOptions& options,
100                       Size& layoutSize,
101                       LogicalModelPtr& logicalModel,
102                       VisualModelPtr& visualModel,
103                       MetricsPtr& metrics )
104 {
105   logicalModel = LogicalModel::New();
106   visualModel = VisualModel::New();
107
108   // 1) Convert to utf32
109   Vector<Character>& utf32Characters = logicalModel->mText;
110   utf32Characters.Resize( text.size() );
111
112   const uint32_t numberOfCharacters = Utf8ToUtf32( reinterpret_cast<const uint8_t* const>( text.c_str() ),
113                                                    text.size(),
114                                                    &utf32Characters[0u] );
115   utf32Characters.Resize( numberOfCharacters );
116
117   // 2) Set the break and paragraph info.
118   Vector<LineBreakInfo>& lineBreakInfo = logicalModel->mLineBreakInfo;
119   lineBreakInfo.Resize( numberOfCharacters );
120
121   SetLineBreakInfo( utf32Characters,
122                     0u,
123                     numberOfCharacters,
124                     lineBreakInfo );
125
126   if( 0u == numberOfCharacters )
127   {
128     // Nothing else to do if the number of characters is zero.
129     return;
130   }
131
132   // Retrieves the word break info. The word break info is used to layout the text (where to wrap the text in lines).
133   Vector<WordBreakInfo>& wordBreakInfo = logicalModel->mWordBreakInfo;
134   wordBreakInfo.Resize( numberOfCharacters );
135
136   SetWordBreakInfo( utf32Characters,
137                     0u,
138                     numberOfCharacters,
139                     wordBreakInfo );
140
141   // 3) Set the script info.
142   MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
143
144   Vector<ScriptRun>& scripts = logicalModel->mScriptRuns;
145   multilanguageSupport.SetScripts( utf32Characters,
146                                    0u,
147                                    numberOfCharacters,
148                                    scripts );
149
150   // 4) Set the font info
151   Vector<FontDescriptionRun>& fontDescriptionRuns = logicalModel->mFontDescriptionRuns;
152   fontDescriptionRuns = fontDescriptions;
153   Vector<FontRun>& validFonts = logicalModel->mFontRuns;
154
155   // The default font description.
156   TextAbstraction::FontDescription fontDescription;
157
158   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
159   fontClient.SetDpi( 96u, 96u );
160
161   // Validates the fonts. If there is a character with no assigned font it sets a default one.
162   // After this call, fonts are validated.
163   multilanguageSupport.ValidateFonts( utf32Characters,
164                                       scripts,
165                                       fontDescriptionRuns,
166                                       fontDescription,
167                                       TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
168                                       0u,
169                                       numberOfCharacters,
170                                       validFonts );
171
172   // 5) Set the bidirectional info per paragraph.
173   Vector<Character> mirroredUtf32Characters;
174   bool textMirrored = false;
175
176   // Reserve some space for the vector of paragraph's bidirectional info.
177   Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = logicalModel->mBidirectionalParagraphInfo;
178
179   // Calculates the bidirectional info for the whole paragraph if it contains right to left scripts.
180   SetBidirectionalInfo( utf32Characters,
181                         scripts,
182                         lineBreakInfo,
183                         0u,
184                         numberOfCharacters,
185                         bidirectionalInfo );
186
187   // Create the paragraph info.
188   logicalModel->CreateParagraphInfo( 0u,
189                                      numberOfCharacters );
190
191   // 6) Set character directions.
192   Vector<CharacterDirection>& characterDirections = logicalModel->mCharacterDirections;
193   if( 0u != bidirectionalInfo.Count() )
194   {
195     // Only set the character directions if there is right to left characters.
196     GetCharactersDirection( bidirectionalInfo,
197                             numberOfCharacters,
198                             0u,
199                             numberOfCharacters,
200                             characterDirections );
201
202
203     // This paragraph has right to left text. Some characters may need to be mirrored.
204     textMirrored = GetMirroredText( utf32Characters,
205                                     characterDirections,
206                                     bidirectionalInfo,
207                                     0u,
208                                     numberOfCharacters,
209                                     mirroredUtf32Characters );
210   }
211   else
212   {
213     // There is no right to left characters. Clear the directions vector.
214     characterDirections.Clear();
215   }
216
217   // 7) Shape the text.
218
219   Vector<GlyphInfo>& glyphs = visualModel->mGlyphs;
220   Vector<CharacterIndex>& glyphsToCharactersMap = visualModel->mGlyphsToCharacters;
221   Vector<Length>& charactersPerGlyph = visualModel->mCharactersPerGlyph;
222   Vector<GlyphIndex> newParagraphGlyphs;
223
224   const Vector<Character>& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters;
225
226   ShapeText( textToShape,
227              lineBreakInfo,
228              scripts,
229              validFonts,
230              0u,
231              0u,
232              numberOfCharacters,
233              glyphs,
234              glyphsToCharactersMap,
235              charactersPerGlyph,
236              newParagraphGlyphs );
237
238   // Create the 'number of glyphs' per character and the glyph to character conversion tables.
239   visualModel->CreateGlyphsPerCharacterTable( 0u, 0u, numberOfCharacters );
240   visualModel->CreateCharacterToGlyphTable( 0u, 0u, numberOfCharacters );
241
242   const Length numberOfGlyphs = glyphs.Count();
243
244   // 8) Get the glyph metrics
245   metrics = Metrics::New( fontClient );
246
247   GlyphInfo* glyphsBuffer = glyphs.Begin();
248   metrics->GetGlyphMetrics( glyphsBuffer, numberOfGlyphs );
249
250   // Update the width and advance of all new paragraph characters.
251   for( Vector<GlyphIndex>::ConstIterator it = newParagraphGlyphs.Begin(),
252          endIt = newParagraphGlyphs.End();
253        it != endIt;
254        ++it )
255   {
256     const GlyphIndex index = *it;
257     GlyphInfo& glyph = *( glyphsBuffer + index );
258
259     glyph.xBearing = 0.f;
260     glyph.width = 0.f;
261     glyph.advance = 0.f;
262   }
263
264   // 9) Layout the text
265   Layout::Engine layoutEngine;
266   layoutEngine.SetMetrics( metrics );
267   layoutEngine.SetLayout( Layout::Engine::MULTI_LINE_BOX );
268
269   // Set the layout parameters.
270   const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
271   const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
272   float outlineWidth = visualModel->GetOutlineWidth();
273   Layout::Parameters layoutParameters( textArea,
274                                        utf32Characters.Begin(),
275                                        lineBreakInfo.Begin(),
276                                        wordBreakInfo.Begin(),
277                                        ( 0u != characterDirections.Count() ) ? characterDirections.Begin() : NULL,
278                                        glyphs.Begin(),
279                                        glyphsToCharactersMap.Begin(),
280                                        charactersPerGlyph.Begin(),
281                                        charactersToGlyph.Begin(),
282                                        glyphsPerCharacter.Begin(),
283                                        numberOfGlyphs,
284                                        Text::HorizontalAlignment::BEGIN,
285                                        Text::LineWrap::WORD,
286                                        outlineWidth );
287
288   Vector<LineRun>& lines = visualModel->mLines;
289
290   Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
291   glyphPositions.Resize( numberOfGlyphs );
292
293   layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( utf32Characters.Begin() + ( numberOfCharacters - 1u ) ) );
294
295   // The initial glyph and the number of glyphs to layout.
296   layoutParameters.startGlyphIndex = 0u;
297   layoutParameters.numberOfGlyphs = numberOfGlyphs;
298   layoutParameters.startLineIndex = 0u;
299   layoutParameters.estimatedNumberOfLines = logicalModel->mParagraphInfo.Count();
300
301   layoutEngine.LayoutText( layoutParameters,
302                            glyphPositions,
303                            lines,
304                            layoutSize,
305                            false );
306
307   // 10) Reorder the lines
308   if( 0u != bidirectionalInfo.Count() )
309   {
310     Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = logicalModel->mBidirectionalLineInfo;
311
312     // Get the lines
313     const Length numberOfLines = lines.Count();
314
315     // Reorder the lines.
316     bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
317     ReorderLines( bidirectionalInfo,
318                   0u,
319                   numberOfCharacters,
320                   lines,
321                   bidirectionalLineInfo );
322
323     // Set the bidirectional info per line into the layout parameters.
324     layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
325     layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
326
327     if( options.reorder )
328     {
329       // Re-layout the text. Reorder those lines with right to left characters.
330       layoutEngine.ReLayoutRightToLeftLines( layoutParameters,
331                                              0u,
332                                              numberOfCharacters,
333                                              glyphPositions );
334     }
335   }
336
337   if( options.align )
338   {
339     float alignmentOffset = 0.f;
340     layoutEngine.Align( textArea,
341                         0u,
342                         numberOfCharacters,
343                         Text::HorizontalAlignment::BEGIN,
344                         lines,
345                         alignmentOffset );
346   }
347 }
348
349 void ConfigureTextLabel( ControllerPtr controller )
350 {
351   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
352   fontClient.SetDpi( 93u, 93u );
353
354   // Set the text layout as multi-line.
355   controller->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX );
356
357   // Set cursor's width to zero.
358   controller->GetLayoutEngine().SetCursorWidth( 0 );
359
360   // Disables the text input.
361   controller->EnableTextInput( NULL );
362
363   // Disables the vertical scrolling.
364   controller->SetVerticalScrollEnabled( false );
365
366   // Disables the horizontal scrolling.
367   controller->SetHorizontalScrollEnabled( false );
368
369   // Enable the text elide.
370   controller->SetTextElideEnabled( true );
371 }
372
373 void ConfigureTextField( ControllerPtr controller )
374 {
375   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
376   fontClient.SetDpi( 93u, 93u );
377
378   // Creates a decorator.
379   Text::DecoratorPtr decorator = Text::Decorator::New( *controller,
380                                                        *controller );
381
382   // Set the text layout as multi-line.
383   controller->GetLayoutEngine().SetLayout( Layout::Engine::SINGLE_LINE_BOX );
384
385   // Enables the text input.
386   controller->EnableTextInput( decorator );
387
388   // Enables the vertical scrolling after the text input has been enabled.
389   controller->SetVerticalScrollEnabled( false );
390
391   // Disables the horizontal scrolling.
392   controller->SetHorizontalScrollEnabled( true );
393
394   // No maximum number of characters.
395   controller->SetMaximumNumberOfCharacters( 50u );
396
397   // Disable the text elide.
398   controller->SetTextElideEnabled( false );
399 }
400
401 void ConfigureTextEditor( ControllerPtr controller )
402 {
403   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
404   fontClient.SetDpi( 93u, 93u );
405
406   // Creates a decorator.
407   Text::DecoratorPtr decorator = Text::Decorator::New( *controller,
408                                                        *controller );
409
410   // Set the text layout as multi-line.
411   controller->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX );
412
413   // Enables the text input.
414   controller->EnableTextInput( decorator );
415
416   // Enables the vertical scrolling after the text input has been enabled.
417   controller->SetVerticalScrollEnabled( true );
418
419   // Disables the horizontal scrolling.
420   controller->SetHorizontalScrollEnabled( false );
421
422   // No maximum number of characters.
423   controller->SetMaximumNumberOfCharacters( std::numeric_limits<Length>::max() );
424
425   // Disable the text elide.
426   controller->SetTextElideEnabled( false );
427 }
428
429 } // namespace Text
430
431 } // namespace Toolkit
432
433 } // namespace Dali