Support anchor to TextLabel, TextField, TextEditor
[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->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                       ModelPtr& textModel,
102                       MetricsPtr& metrics,
103                       bool markupProcessorEnabled )
104 {
105   textModel = Model::New(); ///< Pointer to the text's model.
106   LogicalModelPtr logicalModel = textModel->mLogicalModel;
107   VisualModelPtr visualModel = textModel->mVisualModel;
108
109   MarkupProcessData markupProcessData( logicalModel->mColorRuns,
110                                        logicalModel->mFontDescriptionRuns,
111                                        logicalModel->mEmbeddedItems,
112                                        logicalModel->mAnchors );
113
114   Length textSize = 0u;
115   const uint8_t* utf8 = NULL;
116   if( markupProcessorEnabled )
117   {
118     ProcessMarkupString( text, markupProcessData );
119     textSize = markupProcessData.markupProcessedText.size();
120
121     // This is a bit horrible but std::string returns a (signed) char*
122     utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
123   }
124   else
125   {
126     textSize = text.size();
127
128     // This is a bit horrible but std::string returns a (signed) char*
129     utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
130   }
131
132   // 1) Convert to utf32
133   Vector<Character>& utf32Characters = logicalModel->mText;
134   utf32Characters.Resize( textSize );
135
136   // Transform a text array encoded in utf8 into an array encoded in utf32.
137   // It returns the actual number of characters.
138   Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
139   utf32Characters.Resize( characterCount );
140
141   // 2) Set the break and paragraph info.
142   Vector<LineBreakInfo>& lineBreakInfo = logicalModel->mLineBreakInfo;
143   lineBreakInfo.Resize( characterCount );
144
145   SetLineBreakInfo( utf32Characters,
146                     0u,
147                     characterCount,
148                     lineBreakInfo );
149
150   if( 0u == characterCount )
151   {
152     // Nothing else to do if the number of characters is zero.
153     return;
154   }
155
156   // 3) Set the script info.
157   MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
158
159   Vector<ScriptRun>& scripts = logicalModel->mScriptRuns;
160   multilanguageSupport.SetScripts( utf32Characters,
161                                    0u,
162                                    characterCount,
163                                    scripts );
164
165   // 4) Set the font info
166   Vector<FontDescriptionRun>& fontDescriptionRuns = logicalModel->mFontDescriptionRuns;
167   fontDescriptionRuns = fontDescriptions;
168   Vector<FontRun>& validFonts = logicalModel->mFontRuns;
169
170   // The default font description.
171   TextAbstraction::FontDescription fontDescription;
172
173   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
174   fontClient.SetDpi( 96u, 96u );
175
176   // Validates the fonts. If there is a character with no assigned font it sets a default one.
177   // After this call, fonts are validated.
178   multilanguageSupport.ValidateFonts( utf32Characters,
179                                       scripts,
180                                       fontDescriptionRuns,
181                                       fontDescription,
182                                       TextAbstraction::FontClient::DEFAULT_POINT_SIZE,
183                                       0u,
184                                       characterCount,
185                                       validFonts );
186
187   // 5) Set the bidirectional info per paragraph.
188   Vector<Character> mirroredUtf32Characters;
189   bool textMirrored = false;
190
191   // Reserve some space for the vector of paragraph's bidirectional info.
192   Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = logicalModel->mBidirectionalParagraphInfo;
193
194   // Calculates the bidirectional info for the whole paragraph if it contains right to left scripts.
195   SetBidirectionalInfo( utf32Characters,
196                         scripts,
197                         lineBreakInfo,
198                         0u,
199                         characterCount,
200                         bidirectionalInfo );
201
202   // Create the paragraph info.
203   logicalModel->CreateParagraphInfo( 0u,
204                                      characterCount );
205
206   // 6) Set character directions.
207   Vector<CharacterDirection>& characterDirections = logicalModel->mCharacterDirections;
208   if( 0u != bidirectionalInfo.Count() )
209   {
210     // Only set the character directions if there is right to left characters.
211     GetCharactersDirection( bidirectionalInfo,
212                             characterCount,
213                             0u,
214                             characterCount,
215                             characterDirections );
216
217
218     // This paragraph has right to left text. Some characters may need to be mirrored.
219     textMirrored = GetMirroredText( utf32Characters,
220                                     characterDirections,
221                                     bidirectionalInfo,
222                                     0u,
223                                     characterCount,
224                                     mirroredUtf32Characters );
225   }
226   else
227   {
228     // There is no right to left characters. Clear the directions vector.
229     characterDirections.Clear();
230   }
231
232   // 7) Shape the text.
233
234   Vector<GlyphInfo>& glyphs = visualModel->mGlyphs;
235   Vector<CharacterIndex>& glyphsToCharactersMap = visualModel->mGlyphsToCharacters;
236   Vector<Length>& charactersPerGlyph = visualModel->mCharactersPerGlyph;
237   Vector<GlyphIndex> newParagraphGlyphs;
238
239   const Vector<Character>& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters;
240
241   ShapeText( textToShape,
242              lineBreakInfo,
243              scripts,
244              validFonts,
245              0u,
246              0u,
247              characterCount,
248              glyphs,
249              glyphsToCharactersMap,
250              charactersPerGlyph,
251              newParagraphGlyphs );
252
253   // Create the 'number of glyphs' per character and the glyph to character conversion tables.
254   visualModel->CreateGlyphsPerCharacterTable( 0u, 0u, characterCount );
255   visualModel->CreateCharacterToGlyphTable( 0u, 0u, characterCount );
256
257   const Length numberOfGlyphs = glyphs.Count();
258
259   // 8) Get the glyph metrics
260   metrics = Metrics::New( fontClient );
261
262   GlyphInfo* glyphsBuffer = glyphs.Begin();
263   metrics->GetGlyphMetrics( glyphsBuffer, numberOfGlyphs );
264
265   // Update the width and advance of all new paragraph characters.
266   for( Vector<GlyphIndex>::ConstIterator it = newParagraphGlyphs.Begin(),
267          endIt = newParagraphGlyphs.End();
268        it != endIt;
269        ++it )
270   {
271     const GlyphIndex index = *it;
272     GlyphInfo& glyph = *( glyphsBuffer + index );
273
274     glyph.xBearing = 0.f;
275     glyph.width = 0.f;
276     glyph.advance = 0.f;
277   }
278
279   // 9) Layout the text
280   Layout::Engine layoutEngine;
281   layoutEngine.SetMetrics( metrics );
282   layoutEngine.SetLayout( Layout::Engine::MULTI_LINE_BOX );
283
284   // Set the layout parameters.
285   textModel->mHorizontalAlignment = Text::HorizontalAlignment::BEGIN;
286   textModel->mLineWrapMode = LineWrap::WORD;
287   textModel->mIgnoreSpacesAfterText = true;
288   textModel->mMatchSystemLanguageDirection = false;
289   Layout::Parameters layoutParameters( textArea,
290                                        textModel );
291
292   Vector<LineRun>& lines = visualModel->mLines;
293
294   Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
295   glyphPositions.Resize( numberOfGlyphs );
296
297   layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( utf32Characters.Begin() + ( characterCount - 1u ) ) );
298
299   // The initial glyph and the number of glyphs to layout.
300   layoutParameters.startGlyphIndex = 0u;
301   layoutParameters.numberOfGlyphs = numberOfGlyphs;
302   layoutParameters.startLineIndex = 0u;
303   layoutParameters.estimatedNumberOfLines = logicalModel->mParagraphInfo.Count();
304
305   bool isAutoScroll = false;
306   layoutEngine.LayoutText( layoutParameters,
307                            layoutSize,
308                            false,
309                            isAutoScroll );
310
311   if( options.align )
312   {
313     float alignmentOffset = 0.f;
314     layoutEngine.Align( textArea,
315                         0u,
316                         characterCount,
317                         Text::HorizontalAlignment::BEGIN,
318                         lines,
319                         alignmentOffset,
320                         Dali::LayoutDirection::LEFT_TO_RIGHT,
321                         false );
322   }
323 }
324
325 void ConfigureTextLabel( ControllerPtr controller )
326 {
327   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
328   fontClient.SetDpi( 93u, 93u );
329
330   // Set the text layout as multi-line.
331   controller->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX );
332
333   // Set cursor's width to zero.
334   controller->GetLayoutEngine().SetCursorWidth( 0 );
335
336   InputMethodContext inputMethodContext = InputMethodContext::New();
337   // Disables the text input.
338   controller->EnableTextInput( NULL, inputMethodContext );
339
340   // Disables the vertical scrolling.
341   controller->SetVerticalScrollEnabled( false );
342
343   // Disables the horizontal scrolling.
344   controller->SetHorizontalScrollEnabled( false );
345
346   // Enable the text elide.
347   controller->SetTextElideEnabled( true );
348 }
349
350 void ConfigureTextField( ControllerPtr controller )
351 {
352   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
353   fontClient.SetDpi( 93u, 93u );
354
355   // Creates a decorator.
356   Text::DecoratorPtr decorator = Text::Decorator::New( *controller,
357                                                        *controller );
358
359   // Set the text layout as multi-line.
360   controller->GetLayoutEngine().SetLayout( Layout::Engine::SINGLE_LINE_BOX );
361
362   InputMethodContext inputMethodContext = InputMethodContext::New();
363   // Enables the text input.
364   controller->EnableTextInput( decorator, inputMethodContext );
365
366   // Enables the vertical scrolling after the text input has been enabled.
367   controller->SetVerticalScrollEnabled( false );
368
369   // Disables the horizontal scrolling.
370   controller->SetHorizontalScrollEnabled( true );
371
372   // No maximum number of characters.
373   controller->SetMaximumNumberOfCharacters( 50u );
374
375   // Disable the text elide.
376   controller->SetTextElideEnabled( false );
377 }
378
379 void ConfigureTextEditor( ControllerPtr controller )
380 {
381   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
382   fontClient.SetDpi( 93u, 93u );
383
384   // Creates a decorator.
385   Text::DecoratorPtr decorator = Text::Decorator::New( *controller,
386                                                        *controller );
387
388   // Set the text layout as multi-line.
389   controller->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX );
390
391   InputMethodContext inputMethodContext = InputMethodContext::New();
392   // Enables the text input.
393   controller->EnableTextInput( decorator, inputMethodContext );
394
395   // Enables the vertical scrolling after the text input has been enabled.
396   controller->SetVerticalScrollEnabled( true );
397
398   // Disables the horizontal scrolling.
399   controller->SetHorizontalScrollEnabled( false );
400
401   // No maximum number of characters.
402   controller->SetMaximumNumberOfCharacters( std::numeric_limits<Length>::max() );
403
404   // Disable the text elide.
405   controller->SetTextElideEnabled( false );
406 }
407
408 } // namespace Text
409
410 } // namespace Toolkit
411
412 } // namespace Dali