(Text Controller) Moved some input properties into a different class & some functiona...
[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   controller.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
220     model->mElideEnabled = false;
221     Vector<float> pointSizeArray;
222
223     // check zero value
224     if(pointInterval < 1.f)
225     {
226       impl.mTextFitStepSize = pointInterval = 1.0f;
227     }
228
229     pointSizeArray.Reserve(static_cast<unsigned int>(ceil((maxPointSize - minPointSize) / pointInterval)));
230
231     for(float i = minPointSize; i < maxPointSize; i += pointInterval)
232     {
233       pointSizeArray.PushBack(i);
234     }
235
236     pointSizeArray.PushBack(maxPointSize);
237
238     int bestSizeIndex = 0;
239     int min           = bestSizeIndex + 1;
240     int max           = pointSizeArray.Size() - 1;
241     while(min <= max)
242     {
243       int destI = (min + max) / 2;
244
245       if(CheckForTextFit(controller, pointSizeArray[destI], layoutSize))
246       {
247         bestSizeIndex = min;
248         min           = destI + 1;
249       }
250       else
251       {
252         max           = destI - 1;
253         bestSizeIndex = max;
254       }
255     }
256
257     model->mElideEnabled              = actualellipsis;
258     impl.mFontDefaults->mFitPointSize = pointSizeArray[bestSizeIndex];
259     impl.mFontDefaults->sizeDefined   = true;
260     controller.ClearFontData();
261   }
262 }
263
264 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
265 {
266   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
267
268   // Make sure the model is up-to-date before layouting
269   controller.ProcessModifyEvents();
270
271   Controller::Impl& impl           = *controller.mImpl;
272   ModelPtr&         model          = impl.mModel;
273   VisualModelPtr&   visualModel    = model->mVisualModel;
274   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
275
276   Size layoutSize;
277
278   if(fabsf(width - visualModel->mControlSize.width) > Math::MACHINE_EPSILON_1000 ||
279      textUpdateInfo.mFullRelayoutNeeded ||
280      textUpdateInfo.mClearAll)
281   {
282     // Layout the text for the new width.
283     OperationsMask requestedOperationsMask        = static_cast<OperationsMask>(LAYOUT);
284     Size           sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
285
286     // Skip restore, because if GetHeightForWidth called before rendering and layouting then visualModel->mControlSize will be zero which will make LineCount zero.
287     // The implementation of Get LineCount property depends on calling GetHeightForWidth then read mLines.Count() from visualModel direct.
288     // If the LineCount property is requested before rendering and layouting then the value will be zero, which is incorrect.
289     // So we will not restore the previously backed-up mLines and mGlyphPositions from visualModel in such case.
290     // 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.
291     // For example, when the text is changed.
292     bool restoreLinesAndGlyphPositions = (visualModel->mControlSize.width > 0 && visualModel->mControlSize.height > 0) && (visualModel->mControlSize.width != width);
293
294     layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask, restoreLinesAndGlyphPositions);
295
296     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
297   }
298   else
299   {
300     layoutSize = visualModel->GetLayoutSize();
301     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
302   }
303
304   return layoutSize.height;
305 }
306
307 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
308 {
309   Controller::Impl& impl           = *controller.mImpl;
310   ModelPtr&         model          = impl.mModel;
311   VisualModelPtr&   visualModel    = model->mVisualModel;
312   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
313
314   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
315
316   UpdateTextType updateTextType = NONE_UPDATED;
317
318   if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
319   {
320     if(0u != visualModel->mGlyphPositions.Count())
321     {
322       visualModel->mGlyphPositions.Clear();
323       updateTextType = MODEL_UPDATED;
324     }
325
326     // Clear the update info. This info will be set the next time the text is updated.
327     textUpdateInfo.Clear();
328
329     // Not worth to relayout if width or height is equal to zero.
330     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
331
332     return updateTextType;
333   }
334
335   // Whether a new size has been set.
336   const bool newSize = (size != visualModel->mControlSize);
337
338   // Get a reference to the pending operations member
339   OperationsMask& operationsPending = impl.mOperationsPending;
340
341   if(newSize)
342   {
343     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
344
345     if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
346        (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
347        ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
348     {
349       textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
350     }
351
352     // Layout operations that need to be done if the size changes.
353     operationsPending = static_cast<OperationsMask>(operationsPending |
354                                                     LAYOUT |
355                                                     ALIGN |
356                                                     UPDATE_LAYOUT_SIZE |
357                                                     REORDER);
358     // Set the update info to relayout the whole text.
359     textUpdateInfo.mFullRelayoutNeeded = true;
360     textUpdateInfo.mCharacterIndex     = 0u;
361
362     // Store the size used to layout the text.
363     visualModel->mControlSize = size;
364   }
365
366   // Whether there are modify events.
367   if(0u != impl.mModifyEvents.Count())
368   {
369     // Style operations that need to be done if the text is modified.
370     operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
371   }
372
373   // Set the update info to elide the text.
374   if(model->mElideEnabled ||
375      ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
376   {
377     // Update Text layout for applying elided
378     operationsPending                  = static_cast<OperationsMask>(operationsPending |
379                                                     ALIGN |
380                                                     LAYOUT |
381                                                     UPDATE_LAYOUT_SIZE |
382                                                     REORDER);
383     textUpdateInfo.mFullRelayoutNeeded = true;
384     textUpdateInfo.mCharacterIndex     = 0u;
385   }
386
387   if(impl.mLayoutDirection != layoutDirection)
388   {
389     // Clear the update info. This info will be set the next time the text is updated.
390     textUpdateInfo.mClearAll = true;
391     // Apply modifications to the model
392     // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
393     operationsPending     = static_cast<OperationsMask>(operationsPending |
394                                                     GET_GLYPH_METRICS |
395                                                     SHAPE_TEXT |
396                                                     UPDATE_DIRECTION |
397                                                     ALIGN |
398                                                     LAYOUT |
399                                                     BIDI_INFO |
400                                                     REORDER);
401     impl.mLayoutDirection = layoutDirection;
402   }
403
404   // Make sure the model is up-to-date before layouting.
405   controller.ProcessModifyEvents();
406   bool updated = impl.UpdateModel(operationsPending);
407
408   // Layout the text.
409   Size layoutSize;
410   updated = DoRelayout(controller, size, operationsPending, layoutSize) || updated;
411
412   if(updated)
413   {
414     updateTextType = MODEL_UPDATED;
415   }
416
417   // Do not re-do any operation until something changes.
418   operationsPending          = NO_OPERATION;
419   model->mScrollPositionLast = model->mScrollPosition;
420
421   // Whether the text control is editable
422   const bool isEditable = NULL != impl.mEventData;
423
424   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
425   Vector2 offset;
426   if(newSize && isEditable)
427   {
428     offset = model->mScrollPosition;
429   }
430
431   if(!isEditable || !controller.IsMultiLineEnabled())
432   {
433     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
434     controller.CalculateVerticalOffset(size);
435   }
436
437   if(isEditable)
438   {
439     if(newSize)
440     {
441       // If there is a new size, the scroll position needs to be clamped.
442       impl.ClampHorizontalScroll(layoutSize);
443
444       // Update the decorator's positions is needed if there is a new size.
445       impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
446     }
447
448     // Move the cursor, grab handle etc.
449     if(impl.ProcessInputEvents())
450     {
451       updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
452     }
453   }
454
455   // Clear the update info. This info will be set the next time the text is updated.
456   textUpdateInfo.Clear();
457   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
458
459   return updateTextType;
460 }
461
462 bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
463 {
464   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", &controller, size.width, size.height);
465   bool viewUpdated(false);
466
467   Controller::Impl& impl = *controller.mImpl;
468
469   // Calculate the operations to be done.
470   const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
471
472   TextUpdateInfo&      textUpdateInfo              = impl.mTextUpdateInfo;
473   const CharacterIndex startIndex                  = textUpdateInfo.mParagraphCharacterIndex;
474   const Length         requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
475
476   // Get the current layout size.
477   VisualModelPtr& visualModel = impl.mModel->mVisualModel;
478   layoutSize                  = visualModel->GetLayoutSize();
479
480   if(NO_OPERATION != (LAYOUT & operations))
481   {
482     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
483
484     // Some vectors with data needed to layout and reorder may be void
485     // after the first time the text has been laid out.
486     // Fill the vectors again.
487
488     // Calculate the number of glyphs to layout.
489     const Vector<GlyphIndex>& charactersToGlyph        = visualModel->mCharactersToGlyph;
490     const Vector<Length>&     glyphsPerCharacter       = visualModel->mGlyphsPerCharacter;
491     const GlyphIndex* const   charactersToGlyphBuffer  = charactersToGlyph.Begin();
492     const Length* const       glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
493
494     const CharacterIndex lastIndex       = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
495     const GlyphIndex     startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
496
497     // Make sure the index is not out of bound
498     if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
499        requestedNumberOfCharacters > charactersToGlyph.Count() ||
500        (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
501     {
502       std::string currentText;
503       controller.GetText(currentText);
504
505       DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
506       DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
507       DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
508
509       return false;
510     }
511
512     const Length numberOfGlyphs      = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
513     const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
514
515     if(0u == totalNumberOfGlyphs)
516     {
517       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
518       {
519         visualModel->SetLayoutSize(Size::ZERO);
520       }
521
522       // Nothing else to do if there is no glyphs.
523       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
524       return true;
525     }
526
527     // Set the layout parameters.
528     Layout::Parameters layoutParameters(size, impl.mModel);
529
530     // Resize the vector of positions to have the same size than the vector of glyphs.
531     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
532     glyphPositions.Resize(totalNumberOfGlyphs);
533
534     // Whether the last character is a new paragraph character.
535     const Character* const textBuffer           = impl.mModel->mLogicalModel->mText.Begin();
536     textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
537     layoutParameters.isLastNewParagraph         = textUpdateInfo.mIsLastCharacterNewParagraph;
538
539     // The initial glyph and the number of glyphs to layout.
540     layoutParameters.startGlyphIndex        = startGlyphIndex;
541     layoutParameters.numberOfGlyphs         = numberOfGlyphs;
542     layoutParameters.startLineIndex         = textUpdateInfo.mStartLineIndex;
543     layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
544
545     // Update the ellipsis
546     bool elideTextEnabled = impl.mModel->mElideEnabled;
547     auto ellipsisPosition = impl.mModel->mEllipsisPosition;
548
549     if(NULL != impl.mEventData)
550     {
551       if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
552       {
553         elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
554       }
555       else if(EventData::INACTIVE != impl.mEventData->mState)
556       {
557         // Disable ellipsis when editing
558         elideTextEnabled = false;
559       }
560
561       // Reset the scroll position in inactive state
562       if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
563       {
564         controller.ResetScrollPosition();
565       }
566     }
567
568     // Update the visual model.
569     bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
570     Size newLayoutSize;
571     viewUpdated               = impl.mLayoutEngine.LayoutText(layoutParameters,
572                                                 newLayoutSize,
573                                                 elideTextEnabled,
574                                                 isAutoScrollEnabled,
575                                                 ellipsisPosition);
576     impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
577
578     viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
579
580     if(viewUpdated)
581     {
582       layoutSize = newLayoutSize;
583
584       if(NO_OPERATION != (UPDATE_DIRECTION & operations))
585       {
586         impl.mIsTextDirectionRTL = false;
587       }
588
589       if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
590       {
591         impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
592       }
593
594       // Sets the layout size.
595       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
596       {
597         visualModel->SetLayoutSize(layoutSize);
598       }
599     } // view updated
600   }
601
602   if(NO_OPERATION != (ALIGN & operations))
603   {
604     // The laid-out lines.
605     Vector<LineRun>& lines = visualModel->mLines;
606
607     CharacterIndex alignStartIndex                  = startIndex;
608     Length         alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
609
610     // the whole text needs to be full aligned.
611     // If you do not do a full aligned, only the last line of the multiline input is aligned.
612     if(impl.mEventData && impl.mEventData->mUpdateAlignment)
613     {
614       alignStartIndex                   = 0u;
615       alignRequestedNumberOfCharacters  = impl.mModel->mLogicalModel->mText.Count();
616       impl.mEventData->mUpdateAlignment = false;
617     }
618
619     // Need to align with the control's size as the text may contain lines
620     // starting either with left to right text or right to left.
621     impl.mLayoutEngine.Align(size,
622                              alignStartIndex,
623                              alignRequestedNumberOfCharacters,
624                              impl.mModel->mHorizontalAlignment,
625                              lines,
626                              impl.mModel->mAlignmentOffset,
627                              impl.mLayoutDirection,
628                              (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
629
630     viewUpdated = true;
631   }
632 #if defined(DEBUG_ENABLED)
633   std::string currentText;
634   controller.GetText(currentText);
635   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &controller, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
636 #endif
637   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
638   return viewUpdated;
639 }
640
641 void Controller::Relayouter::CalculateVerticalOffset(Controller& controller, const Size& controlSize)
642 {
643   Controller::Impl& impl                  = *controller.mImpl;
644   ModelPtr&         model                 = impl.mModel;
645   VisualModelPtr&   visualModel           = model->mVisualModel;
646   Size              layoutSize            = model->mVisualModel->GetLayoutSize();
647   Size              oldLayoutSize         = layoutSize;
648   float             offsetY               = 0.f;
649   bool              needRecalc            = false;
650   float             defaultFontLineHeight = impl.GetDefaultFontLineHeight();
651
652   if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
653   {
654     // Get the line height of the default font.
655     layoutSize.height = defaultFontLineHeight;
656   }
657
658   // Whether the text control is editable
659   const bool isEditable = NULL != impl.mEventData;
660   if(isEditable && layoutSize.height != defaultFontLineHeight && impl.IsShowingPlaceholderText())
661   {
662     // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
663     // This situation occurs when the size of placeholder text is different from the default text.
664     layoutSize.height = defaultFontLineHeight;
665     needRecalc        = true;
666   }
667
668   switch(model->mVerticalAlignment)
669   {
670     case VerticalAlignment::TOP:
671     {
672       model->mScrollPosition.y = 0.f;
673       offsetY                  = 0.f;
674       break;
675     }
676     case VerticalAlignment::CENTER:
677     {
678       model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
679       if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
680       break;
681     }
682     case VerticalAlignment::BOTTOM:
683     {
684       model->mScrollPosition.y = controlSize.height - layoutSize.height;
685       if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
686       break;
687     }
688   }
689
690   if(needRecalc)
691   {
692     // Update glyphPositions according to recalculation.
693     const Length     positionCount  = visualModel->mGlyphPositions.Count();
694     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
695     for(Length index = 0u; index < positionCount; index++)
696     {
697       glyphPositions[index].y += offsetY;
698     }
699   }
700 }
701
702 } // namespace Text
703
704 } // namespace Toolkit
705
706 } // namespace Dali