Merge "Allow Large font size in dali" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller-relayouter.cpp
1 /*
2  * Copyright (c) 2021 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 // CLASS HEADER
19 #include <dali-toolkit/internal/text/text-controller-relayouter.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <limits>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
27 #include <dali-toolkit/internal/text/text-controller-impl.h>
28
29 namespace
30 {
31 #if defined(DEBUG_ENABLED)
32 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
33 #endif
34
35 constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
36
37 float ConvertToEven(float value)
38 {
39   int intValue(static_cast<int>(value));
40   return static_cast<float>(intValue + (intValue & 1));
41 }
42
43 } // namespace
44
45 namespace Dali
46 {
47 namespace Toolkit
48 {
49 namespace Text
50 {
51 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
52 {
53   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
54   Vector3 naturalSize;
55
56   // Make sure the model is up-to-date before layouting
57   controller.ProcessModifyEvents();
58
59   Controller::Impl& impl        = *controller.mImpl;
60   ModelPtr&         model       = impl.mModel;
61   VisualModelPtr&   visualModel = model->mVisualModel;
62   if(impl.mRecalculateNaturalSize)
63   {
64     // Store the pending operations mask so that it can be restored later on with no modifications made on it
65     // while getting the natural size were reflected on the original mask.
66     OperationsMask operationsPendingBackUp = static_cast<OperationsMask>(impl.mOperationsPending);
67     // Operations that can be done only once until the text changes.
68     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
69                                                                           GET_SCRIPTS |
70                                                                           VALIDATE_FONTS |
71                                                                           GET_LINE_BREAKS |
72                                                                           BIDI_INFO |
73                                                                           SHAPE_TEXT |
74                                                                           GET_GLYPH_METRICS);
75
76     // Set the update info to relayout the whole text.
77     TextUpdateInfo& textUpdateInfo              = impl.mTextUpdateInfo;
78     textUpdateInfo.mParagraphCharacterIndex     = 0u;
79     textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
80
81     // Make sure the model is up-to-date before layouting
82     impl.UpdateModel(onlyOnceOperations);
83
84     // Get a reference to the pending operations member
85     OperationsMask& operationsPending = impl.mOperationsPending;
86
87     // Layout the text for the new width.
88     operationsPending = static_cast<OperationsMask>(operationsPending | LAYOUT | REORDER);
89
90     // Store the actual control's size to restore later.
91     const Size actualControlSize = visualModel->mControlSize;
92
93     DoRelayout(controller,
94                Size(MAX_FLOAT, MAX_FLOAT),
95                static_cast<OperationsMask>(onlyOnceOperations |
96                                            LAYOUT | REORDER),
97                naturalSize.GetVectorXY());
98
99     // Stores the natural size to avoid recalculate it again
100     // unless the text/style changes.
101     visualModel->SetNaturalSize(naturalSize.GetVectorXY());
102
103     impl.mRecalculateNaturalSize = false;
104
105     // Clear the update info. This info will be set the next time the text is updated.
106     textUpdateInfo.Clear();
107     textUpdateInfo.mClearAll = true;
108
109     // Restore the actual control's size.
110     visualModel->mControlSize = actualControlSize;
111     // Restore the previously backed-up pending operations' mask without the only once operations.
112     impl.mOperationsPending = static_cast<OperationsMask>(operationsPendingBackUp & ~onlyOnceOperations);
113     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z);
114   }
115   else
116   {
117     naturalSize = visualModel->GetNaturalSize();
118
119     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z);
120   }
121
122   naturalSize.x = ConvertToEven(naturalSize.x);
123   naturalSize.y = ConvertToEven(naturalSize.y);
124
125   return naturalSize;
126 }
127
128 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
129 {
130   Size              textSize;
131   Controller::Impl& impl            = *controller.mImpl;
132   TextUpdateInfo&   textUpdateInfo  = impl.mTextUpdateInfo;
133   impl.mFontDefaults->mFitPointSize = pointSize;
134   impl.mFontDefaults->sizeDefined   = true;
135   controller.ClearFontData();
136
137   // Operations that can be done only once until the text changes.
138   const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
139                                                                         GET_SCRIPTS |
140                                                                         VALIDATE_FONTS |
141                                                                         GET_LINE_BREAKS |
142                                                                         BIDI_INFO |
143                                                                         SHAPE_TEXT |
144                                                                         GET_GLYPH_METRICS);
145
146   textUpdateInfo.mParagraphCharacterIndex     = 0u;
147   textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
148
149   // Make sure the model is up-to-date before layouting
150   impl.UpdateModel(onlyOnceOperations);
151
152   DoRelayout(controller,
153              Size(layoutSize.width, MAX_FLOAT),
154              static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
155              textSize);
156
157   // Clear the update info. This info will be set the next time the text is updated.
158   textUpdateInfo.Clear();
159   textUpdateInfo.mClearAll = true;
160
161   if(textSize.width > layoutSize.width || textSize.height > layoutSize.height)
162   {
163     return false;
164   }
165   return true;
166 }
167
168 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
169 {
170   Controller::Impl& impl = *controller.mImpl;
171
172   const OperationsMask operations = impl.mOperationsPending;
173   if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
174   {
175     ModelPtr& model = impl.mModel;
176
177     bool  actualellipsis = model->mElideEnabled;
178     float minPointSize   = impl.mTextFitMinSize;
179     float maxPointSize   = impl.mTextFitMaxSize;
180     float pointInterval  = impl.mTextFitStepSize;
181
182     model->mElideEnabled = false;
183     Vector<float> pointSizeArray;
184
185     // check zero value
186     if(pointInterval < 1.f)
187     {
188       impl.mTextFitStepSize = pointInterval = 1.0f;
189     }
190
191     pointSizeArray.Reserve(static_cast<unsigned int>(ceil((maxPointSize - minPointSize) / pointInterval)));
192
193     for(float i = minPointSize; i < maxPointSize; i += pointInterval)
194     {
195       pointSizeArray.PushBack(i);
196     }
197
198     pointSizeArray.PushBack(maxPointSize);
199
200     int bestSizeIndex = 0;
201     int min           = bestSizeIndex + 1;
202     int max           = pointSizeArray.Size() - 1;
203     while(min <= max)
204     {
205       int destI = (min + max) / 2;
206
207       if(CheckForTextFit(controller, pointSizeArray[destI], layoutSize))
208       {
209         bestSizeIndex = min;
210         min           = destI + 1;
211       }
212       else
213       {
214         max           = destI - 1;
215         bestSizeIndex = max;
216       }
217     }
218
219     model->mElideEnabled              = actualellipsis;
220     impl.mFontDefaults->mFitPointSize = pointSizeArray[bestSizeIndex];
221     impl.mFontDefaults->sizeDefined   = true;
222     controller.ClearFontData();
223   }
224 }
225
226 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
227 {
228   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
229   // Make sure the model is up-to-date before layouting
230   controller.ProcessModifyEvents();
231
232   Controller::Impl& impl           = *controller.mImpl;
233   ModelPtr&         model          = impl.mModel;
234   VisualModelPtr&   visualModel    = model->mVisualModel;
235   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
236
237   Size layoutSize;
238   if(fabsf(width - visualModel->mControlSize.width) > Math::MACHINE_EPSILON_1000 ||
239      textUpdateInfo.mFullRelayoutNeeded ||
240      textUpdateInfo.mClearAll)
241   {
242     // Store the pending operations mask so that it can be restored later on with no modifications made on it
243     // while getting the natural size were reflected on the original mask.
244     OperationsMask operationsPendingBackUp = static_cast<OperationsMask>(impl.mOperationsPending);
245     // Operations that can be done only once until the text changes.
246     const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
247                                                                           GET_SCRIPTS |
248                                                                           VALIDATE_FONTS |
249                                                                           GET_LINE_BREAKS |
250                                                                           BIDI_INFO |
251                                                                           SHAPE_TEXT |
252                                                                           GET_GLYPH_METRICS);
253
254     // Set the update info to relayout the whole text.
255     textUpdateInfo.mParagraphCharacterIndex     = 0u;
256     textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
257
258     // Make sure the model is up-to-date before layouting
259     impl.UpdateModel(onlyOnceOperations);
260
261     // Get a reference to the pending operations member
262     OperationsMask& operationsPending = impl.mOperationsPending;
263
264     // Layout the text for the new width.
265     operationsPending = static_cast<OperationsMask>(operationsPending | LAYOUT);
266
267     // Store the actual control's width.
268     const float actualControlWidth = visualModel->mControlSize.width;
269
270     DoRelayout(controller,
271                Size(width, MAX_FLOAT),
272                static_cast<OperationsMask>(onlyOnceOperations |
273                                            LAYOUT),
274                layoutSize);
275
276     // Clear the update info. This info will be set the next time the text is updated.
277     textUpdateInfo.Clear();
278     textUpdateInfo.mClearAll = true;
279
280     // Restore the actual control's width.
281     visualModel->mControlSize.width = actualControlWidth;
282     // Restore the previously backed-up pending operations' mask without the only once operations.
283     impl.mOperationsPending = static_cast<OperationsMask>(operationsPendingBackUp & ~onlyOnceOperations);
284     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
285   }
286   else
287   {
288     layoutSize = visualModel->GetLayoutSize();
289     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
290   }
291
292   return layoutSize.height;
293 }
294
295 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
296 {
297   Controller::Impl& impl           = *controller.mImpl;
298   ModelPtr&         model          = impl.mModel;
299   VisualModelPtr&   visualModel    = model->mVisualModel;
300   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
301
302   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
303
304   UpdateTextType updateTextType = NONE_UPDATED;
305
306   if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
307   {
308     if(0u != visualModel->mGlyphPositions.Count())
309     {
310       visualModel->mGlyphPositions.Clear();
311       updateTextType = MODEL_UPDATED;
312     }
313
314     // Clear the update info. This info will be set the next time the text is updated.
315     textUpdateInfo.Clear();
316
317     // Not worth to relayout if width or height is equal to zero.
318     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
319
320     return updateTextType;
321   }
322
323   // Whether a new size has been set.
324   const bool newSize = (size != visualModel->mControlSize);
325
326   // Get a reference to the pending operations member
327   OperationsMask& operationsPending = impl.mOperationsPending;
328
329   if(newSize)
330   {
331     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
332
333     if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
334        (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
335        ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
336     {
337       textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
338     }
339
340     // Layout operations that need to be done if the size changes.
341     operationsPending = static_cast<OperationsMask>(operationsPending |
342                                                     LAYOUT |
343                                                     ALIGN |
344                                                     UPDATE_LAYOUT_SIZE |
345                                                     REORDER);
346     // Set the update info to relayout the whole text.
347     textUpdateInfo.mFullRelayoutNeeded = true;
348     textUpdateInfo.mCharacterIndex     = 0u;
349
350     // Store the size used to layout the text.
351     visualModel->mControlSize = size;
352   }
353
354   // Whether there are modify events.
355   if(0u != impl.mModifyEvents.Count())
356   {
357     // Style operations that need to be done if the text is modified.
358     operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
359   }
360
361   // Set the update info to elide the text.
362   if(model->mElideEnabled ||
363      ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
364   {
365     // Update Text layout for applying elided
366     operationsPending                  = static_cast<OperationsMask>(operationsPending |
367                                                     ALIGN |
368                                                     LAYOUT |
369                                                     UPDATE_LAYOUT_SIZE |
370                                                     REORDER);
371     textUpdateInfo.mFullRelayoutNeeded = true;
372     textUpdateInfo.mCharacterIndex     = 0u;
373   }
374
375   if(model->mMatchSystemLanguageDirection && impl.mLayoutDirection != layoutDirection)
376   {
377     // Clear the update info. This info will be set the next time the text is updated.
378     textUpdateInfo.mClearAll = true;
379     // Apply modifications to the model
380     // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
381     operationsPending     = static_cast<OperationsMask>(operationsPending |
382                                                     GET_GLYPH_METRICS |
383                                                     SHAPE_TEXT |
384                                                     UPDATE_DIRECTION |
385                                                     LAYOUT |
386                                                     BIDI_INFO |
387                                                     REORDER);
388     impl.mLayoutDirection = layoutDirection;
389   }
390
391   // Make sure the model is up-to-date before layouting.
392   controller.ProcessModifyEvents();
393   bool updated = impl.UpdateModel(operationsPending);
394
395   // Layout the text.
396   Size layoutSize;
397   updated = DoRelayout(controller, size, operationsPending, layoutSize) || updated;
398
399   if(updated)
400   {
401     updateTextType = MODEL_UPDATED;
402   }
403
404   // Do not re-do any operation until something changes.
405   operationsPending          = NO_OPERATION;
406   model->mScrollPositionLast = model->mScrollPosition;
407
408   // Whether the text control is editable
409   const bool isEditable = NULL != impl.mEventData;
410
411   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
412   Vector2 offset;
413   if(newSize && isEditable)
414   {
415     offset = model->mScrollPosition;
416   }
417
418   if(!isEditable || !controller.IsMultiLineEnabled())
419   {
420     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
421     controller.CalculateVerticalOffset(size);
422   }
423
424   if(isEditable)
425   {
426     if(newSize)
427     {
428       // If there is a new size, the scroll position needs to be clamped.
429       impl.ClampHorizontalScroll(layoutSize);
430
431       // Update the decorator's positions is needed if there is a new size.
432       impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
433     }
434
435     // Move the cursor, grab handle etc.
436     if(impl.ProcessInputEvents())
437     {
438       updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
439     }
440   }
441
442   // Clear the update info. This info will be set the next time the text is updated.
443   textUpdateInfo.Clear();
444   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
445
446   return updateTextType;
447 }
448
449 bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
450 {
451   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", &controller, size.width, size.height);
452   bool viewUpdated(false);
453
454   Controller::Impl& impl = *controller.mImpl;
455
456   // Calculate the operations to be done.
457   const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
458
459   TextUpdateInfo&      textUpdateInfo              = impl.mTextUpdateInfo;
460   const CharacterIndex startIndex                  = textUpdateInfo.mParagraphCharacterIndex;
461   const Length         requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
462
463   // Get the current layout size.
464   VisualModelPtr& visualModel = impl.mModel->mVisualModel;
465   layoutSize                  = visualModel->GetLayoutSize();
466
467   if(NO_OPERATION != (LAYOUT & operations))
468   {
469     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
470
471     // Some vectors with data needed to layout and reorder may be void
472     // after the first time the text has been laid out.
473     // Fill the vectors again.
474
475     // Calculate the number of glyphs to layout.
476     const Vector<GlyphIndex>& charactersToGlyph        = visualModel->mCharactersToGlyph;
477     const Vector<Length>&     glyphsPerCharacter       = visualModel->mGlyphsPerCharacter;
478     const GlyphIndex* const   charactersToGlyphBuffer  = charactersToGlyph.Begin();
479     const Length* const       glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
480
481     const CharacterIndex lastIndex       = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
482     const GlyphIndex     startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
483
484     // Make sure the index is not out of bound
485     if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
486        requestedNumberOfCharacters > charactersToGlyph.Count() ||
487        (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
488     {
489       std::string currentText;
490       controller.GetText(currentText);
491
492       DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
493       DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
494       DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
495
496       return false;
497     }
498
499     const Length numberOfGlyphs      = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
500     const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
501
502     if(0u == totalNumberOfGlyphs)
503     {
504       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
505       {
506         visualModel->SetLayoutSize(Size::ZERO);
507       }
508
509       // Nothing else to do if there is no glyphs.
510       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
511       return true;
512     }
513
514     // Set the layout parameters.
515     Layout::Parameters layoutParameters(size, impl.mModel);
516
517     // Resize the vector of positions to have the same size than the vector of glyphs.
518     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
519     glyphPositions.Resize(totalNumberOfGlyphs);
520
521     // Whether the last character is a new paragraph character.
522     const Character* const textBuffer           = impl.mModel->mLogicalModel->mText.Begin();
523     textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
524     layoutParameters.isLastNewParagraph         = textUpdateInfo.mIsLastCharacterNewParagraph;
525
526     // The initial glyph and the number of glyphs to layout.
527     layoutParameters.startGlyphIndex        = startGlyphIndex;
528     layoutParameters.numberOfGlyphs         = numberOfGlyphs;
529     layoutParameters.startLineIndex         = textUpdateInfo.mStartLineIndex;
530     layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
531
532     // Update the ellipsis
533     bool elideTextEnabled = impl.mModel->mElideEnabled;
534
535     if(NULL != impl.mEventData)
536     {
537       if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
538       {
539         elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
540       }
541       else if(EventData::INACTIVE != impl.mEventData->mState)
542       {
543         // Disable ellipsis when editing
544         elideTextEnabled = false;
545       }
546
547       // Reset the scroll position in inactive state
548       if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
549       {
550         controller.ResetScrollPosition();
551       }
552     }
553
554     // Update the visual model.
555     bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
556     Size newLayoutSize;
557     viewUpdated               = impl.mLayoutEngine.LayoutText(layoutParameters,
558                                                 newLayoutSize,
559                                                 elideTextEnabled,
560                                                 isAutoScrollEnabled);
561     impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
562
563     viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
564
565     if(viewUpdated)
566     {
567       layoutSize = newLayoutSize;
568
569       if(NO_OPERATION != (UPDATE_DIRECTION & operations))
570       {
571         impl.mIsTextDirectionRTL = false;
572       }
573
574       if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
575       {
576         impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
577       }
578
579       // Sets the layout size.
580       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
581       {
582         visualModel->SetLayoutSize(layoutSize);
583       }
584     } // view updated
585   }
586
587   if(NO_OPERATION != (ALIGN & operations))
588   {
589     // The laid-out lines.
590     Vector<LineRun>& lines = visualModel->mLines;
591
592     CharacterIndex alignStartIndex                  = startIndex;
593     Length         alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
594
595     // the whole text needs to be full aligned.
596     // If you do not do a full aligned, only the last line of the multiline input is aligned.
597     if(impl.mEventData && impl.mEventData->mUpdateAlignment)
598     {
599       alignStartIndex                   = 0u;
600       alignRequestedNumberOfCharacters  = impl.mModel->mLogicalModel->mText.Count();
601       impl.mEventData->mUpdateAlignment = false;
602     }
603
604     // Need to align with the control's size as the text may contain lines
605     // starting either with left to right text or right to left.
606     impl.mLayoutEngine.Align(size,
607                              alignStartIndex,
608                              alignRequestedNumberOfCharacters,
609                              impl.mModel->mHorizontalAlignment,
610                              lines,
611                              impl.mModel->mAlignmentOffset,
612                              impl.mLayoutDirection,
613                              impl.mModel->mMatchSystemLanguageDirection);
614
615     viewUpdated = true;
616   }
617 #if defined(DEBUG_ENABLED)
618   std::string currentText;
619   controller.GetText(currentText);
620   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &controller, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
621 #endif
622   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
623   return viewUpdated;
624 }
625
626 void Controller::Relayouter::CalculateVerticalOffset(Controller& controller, const Size& controlSize)
627 {
628   Controller::Impl& impl          = *controller.mImpl;
629   ModelPtr&         model         = impl.mModel;
630   VisualModelPtr&   visualModel   = model->mVisualModel;
631   Size              layoutSize    = model->mVisualModel->GetLayoutSize();
632   Size              oldLayoutSize = layoutSize;
633   float             offsetY       = 0.f;
634   bool              needRecalc    = false;
635   float             defaultFontLineHeight = impl.GetDefaultFontLineHeight();
636
637   if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
638   {
639     // Get the line height of the default font.
640     layoutSize.height = defaultFontLineHeight;
641   }
642
643   // Whether the text control is editable
644   const bool isEditable = NULL != impl.mEventData;
645   if (isEditable && layoutSize.height != defaultFontLineHeight)
646   {
647     // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
648     // This situation occurs when the size of placeholder text is different from the default text.
649     layoutSize.height = defaultFontLineHeight;
650     needRecalc = true;
651   }
652
653   switch(model->mVerticalAlignment)
654   {
655     case VerticalAlignment::TOP:
656     {
657       model->mScrollPosition.y = 0.f;
658       offsetY = 0.f;
659       break;
660     }
661     case VerticalAlignment::CENTER:
662     {
663       model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
664       if (needRecalc) offsetY  = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
665       break;
666     }
667     case VerticalAlignment::BOTTOM:
668     {
669       model->mScrollPosition.y = controlSize.height - layoutSize.height;
670       if (needRecalc) offsetY  = layoutSize.height - oldLayoutSize.height;
671       break;
672     }
673   }
674
675   if (needRecalc)
676   {
677     // Update glyphPositions according to recalculation.
678     const Length positionCount = visualModel->mGlyphPositions.Count();
679     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
680     for(Length index = 0u; index < positionCount; index++)
681     {
682       glyphPositions[index].y += offsetY;
683     }
684   }
685
686 }
687
688 } // namespace Text
689
690 } // namespace Toolkit
691
692 } // namespace Dali