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