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