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