Merge " Calculate a new height when text was changed." into devel/master
[platform/core/uifw/dali-toolkit.git] / automated-tests / src / dali-toolkit-internal / dali-toolkit-test-utils / toolkit-text-utils.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 // 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
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                                        Layout::HORIZONTAL_ALIGN_BEGIN,
285                                        Layout::LineWrap::WORD );
286
287   Vector<LineRun>& lines = visualModel->mLines;
288
289   Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
290   glyphPositions.Resize( numberOfGlyphs );
291
292   layoutParameters.isLastNewParagraph = TextAbstraction::IsNewParagraph( *( utf32Characters.Begin() + ( numberOfCharacters - 1u ) ) );
293
294   // The initial glyph and the number of glyphs to layout.
295   layoutParameters.startGlyphIndex = 0u;
296   layoutParameters.numberOfGlyphs = numberOfGlyphs;
297   layoutParameters.startLineIndex = 0u;
298   layoutParameters.estimatedNumberOfLines = logicalModel->mParagraphInfo.Count();
299
300   layoutEngine.LayoutText( layoutParameters,
301                            glyphPositions,
302                            lines,
303                            layoutSize,
304                            false );
305
306   // 10) Reorder the lines
307   if( 0u != bidirectionalInfo.Count() )
308   {
309     Vector<BidirectionalLineInfoRun>& bidirectionalLineInfo = logicalModel->mBidirectionalLineInfo;
310
311     // Get the lines
312     const Length numberOfLines = lines.Count();
313
314     // Reorder the lines.
315     bidirectionalLineInfo.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
316     ReorderLines( bidirectionalInfo,
317                   0u,
318                   numberOfCharacters,
319                   lines,
320                   bidirectionalLineInfo );
321
322     // Set the bidirectional info per line into the layout parameters.
323     layoutParameters.lineBidirectionalInfoRunsBuffer = bidirectionalLineInfo.Begin();
324     layoutParameters.numberOfBidirectionalInfoRuns = bidirectionalLineInfo.Count();
325
326     if( options.reorder )
327     {
328       // Re-layout the text. Reorder those lines with right to left characters.
329       layoutEngine.ReLayoutRightToLeftLines( layoutParameters,
330                                              0u,
331                                              numberOfCharacters,
332                                              glyphPositions );
333     }
334   }
335
336   if( options.align )
337   {
338     float alignmentOffset = 0.f;
339     layoutEngine.Align( textArea,
340                         0u,
341                         numberOfCharacters,
342                         Layout::HORIZONTAL_ALIGN_BEGIN,
343                         lines,
344                         alignmentOffset );
345   }
346 }
347
348 void ConfigureTextLabel( ControllerPtr controller )
349 {
350   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
351   fontClient.SetDpi( 93u, 93u );
352
353   // Set the text layout as multi-line.
354   controller->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX );
355
356   // Set cursor's width to zero.
357   controller->GetLayoutEngine().SetCursorWidth( 0 );
358
359   // Disables the text input.
360   controller->EnableTextInput( NULL );
361
362   // Disables the vertical scrolling.
363   controller->SetVerticalScrollEnabled( false );
364
365   // Disables the horizontal scrolling.
366   controller->SetHorizontalScrollEnabled( false );
367
368   // Enable the text elide.
369   controller->SetTextElideEnabled( true );
370 }
371
372 void ConfigureTextField( ControllerPtr controller )
373 {
374   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
375   fontClient.SetDpi( 93u, 93u );
376
377   // Creates a decorator.
378   Text::DecoratorPtr decorator = Text::Decorator::New( *controller,
379                                                        *controller );
380
381   // Set the text layout as multi-line.
382   controller->GetLayoutEngine().SetLayout( Layout::Engine::SINGLE_LINE_BOX );
383
384   // Enables the text input.
385   controller->EnableTextInput( decorator );
386
387   // Enables the vertical scrolling after the text input has been enabled.
388   controller->SetVerticalScrollEnabled( false );
389
390   // Disables the horizontal scrolling.
391   controller->SetHorizontalScrollEnabled( true );
392
393   // No maximum number of characters.
394   controller->SetMaximumNumberOfCharacters( 50u );
395
396   // Disable the text elide.
397   controller->SetTextElideEnabled( false );
398 }
399
400 void ConfigureTextEditor( ControllerPtr controller )
401 {
402   TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
403   fontClient.SetDpi( 93u, 93u );
404
405   // Creates a decorator.
406   Text::DecoratorPtr decorator = Text::Decorator::New( *controller,
407                                                        *controller );
408
409   // Set the text layout as multi-line.
410   controller->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX );
411
412   // Enables the text input.
413   controller->EnableTextInput( decorator );
414
415   // Enables the vertical scrolling after the text input has been enabled.
416   controller->SetVerticalScrollEnabled( true );
417
418   // Disables the horizontal scrolling.
419   controller->SetHorizontalScrollEnabled( false );
420
421   // No maximum number of characters.
422   controller->SetMaximumNumberOfCharacters( std::numeric_limits<Length>::max() );
423
424   // Disable the text elide.
425   controller->SetTextElideEnabled( false );
426 }
427
428 } // namespace Text
429
430 } // namespace Toolkit
431
432 } // namespace Dali