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