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