Transfer uploadOnly flag to the core and update manager
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller-relayouter.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/text/text-controller-relayouter.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <limits>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
27 #include <dali-toolkit/internal/text/text-controller-event-handler.h>
28 #include <dali-toolkit/internal/text/text-controller-impl.h>
29
30 namespace
31 {
32 #if defined(DEBUG_ENABLED)
33 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
34 #endif
35
36 constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
37
38 float ConvertToEven(float value)
39 {
40   int intValue(static_cast<int>(value));
41   return static_cast<float>(intValue + (intValue & 1));
42 }
43
44 } // namespace
45
46 namespace Dali
47 {
48 namespace Toolkit
49 {
50 namespace Text
51 {
52 Size Controller::Relayouter::CalculateLayoutSizeOnRequiredControllerSize(Controller& controller, const Size& requestedControllerSize, const OperationsMask& requestedOperationsMask)
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   // Operations that can be done only once until the text changes.
62   const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
63                                                                         GET_SCRIPTS |
64                                                                         VALIDATE_FONTS |
65                                                                         GET_LINE_BREAKS |
66                                                                         BIDI_INFO |
67                                                                         SHAPE_TEXT |
68                                                                         GET_GLYPH_METRICS);
69
70   // Set the update info to relayout the whole text.
71   TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
72   if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
73      (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
74      ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
75   {
76     textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
77   }
78   textUpdateInfo.mParagraphCharacterIndex     = 0u;
79   textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
80
81   // This is to keep Index to the first character to be updated.
82   // Then restore it after calling Clear method.
83   auto updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
84
85   // Get a reference to the pending operations member
86   OperationsMask& operationsPending = impl.mOperationsPending;
87
88   // Layout the text for the new width.
89   // Apply the pending operations, requested operations and the only once operations.
90   // Then remove onlyOnceOperations
91   operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask | onlyOnceOperations);
92
93   // Make sure the model is up-to-date before layouting
94   impl.UpdateModel(static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE));
95
96   // Store the actual control's size to restore later.
97   const Size actualControlSize = visualModel->mControlSize;
98
99   DoRelayout(impl,
100              requestedControllerSize,
101              static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE),
102              calculatedLayoutSize);
103
104   // Clear the update info. This info will be set the next time the text is updated.
105   textUpdateInfo.Clear();
106
107   //TODO: Refactor "DoRelayout" and extract common code of size calculation without modifying attributes of mVisualModel,
108   //TODO: then calculate GlyphPositions. Lines, Size, Layout for Natural-Size
109   //TODO: and utilize the values in OperationsPending and TextUpdateInfo without changing the original one.
110   //TODO: Also it will improve performance because there is no need todo FullRelyout on the next need for layouting.
111
112   // FullRelayoutNeeded should be true because DoRelayout is MAX_FLOAT, MAX_FLOAT.
113   // By this no need to take backup and restore it.
114   textUpdateInfo.mFullRelayoutNeeded = true;
115
116   // Restore mCharacterIndex. Because "Clear" set it to the maximum integer.
117   // The "CalculateTextUpdateIndices" does not work proprely because the mCharacterIndex will be greater than mPreviousNumberOfCharacters.
118   // Which apply an assumption to update only the last  paragraph. That could cause many of out of index crashes.
119   textUpdateInfo.mCharacterIndex = updateInfoCharIndexBackup;
120
121   // Do not do again the only once operations.
122   operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
123
124   // Do the size related operations again.
125
126   const OperationsMask sizeOperations = static_cast<OperationsMask>(LAYOUT |
127                                                                     ALIGN |
128                                                                     REORDER);
129
130   operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
131
132   // Restore the actual control's size.
133   visualModel->mControlSize = actualControlSize;
134
135   return calculatedLayoutSize;
136 }
137
138 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
139 {
140   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
141   Vector3 naturalSizeVec3;
142
143   // Make sure the model is up-to-date before layouting
144   EventHandler::ProcessModifyEvents(controller);
145
146   Controller::Impl& impl        = *controller.mImpl;
147   ModelPtr&         model       = impl.mModel;
148   VisualModelPtr&   visualModel = model->mVisualModel;
149
150   if(impl.mRecalculateNaturalSize)
151   {
152     Size naturalSize;
153
154     // Layout the text for the new width.
155     OperationsMask requestedOperationsMask  = static_cast<OperationsMask>(LAYOUT | REORDER);
156     Size           sizeMaxWidthAndMaxHeight = Size(MAX_FLOAT, MAX_FLOAT);
157
158     naturalSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeMaxWidthAndMaxHeight, requestedOperationsMask);
159
160     // Stores the natural size to avoid recalculate it again
161     // unless the text/style changes.
162     visualModel->SetNaturalSize(naturalSize);
163     naturalSizeVec3 = naturalSize;
164
165     impl.mRecalculateNaturalSize = false;
166
167     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
168   }
169   else
170   {
171     naturalSizeVec3 = visualModel->GetNaturalSize();
172
173     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
174   }
175
176   naturalSizeVec3.x = ConvertToEven(naturalSizeVec3.x);
177   naturalSizeVec3.y = ConvertToEven(naturalSizeVec3.y);
178
179   return naturalSizeVec3;
180 }
181
182 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
183 {
184   Size              textSize;
185   Controller::Impl& impl            = *controller.mImpl;
186   TextUpdateInfo&   textUpdateInfo  = impl.mTextUpdateInfo;
187   impl.mFontDefaults->mFitPointSize = pointSize;
188   impl.mFontDefaults->sizeDefined   = true;
189   impl.ClearFontData();
190
191   // Operations that can be done only once until the text changes.
192   const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
193                                                                         GET_SCRIPTS |
194                                                                         VALIDATE_FONTS |
195                                                                         GET_LINE_BREAKS |
196                                                                         BIDI_INFO |
197                                                                         SHAPE_TEXT |
198                                                                         GET_GLYPH_METRICS);
199
200   textUpdateInfo.mParagraphCharacterIndex     = 0u;
201   textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
202
203   // Make sure the model is up-to-date before layouting
204   impl.UpdateModel(onlyOnceOperations);
205
206   DoRelayout(impl,
207              Size(layoutSize.width, MAX_FLOAT),
208              static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
209              textSize);
210
211   // Clear the update info. This info will be set the next time the text is updated.
212   textUpdateInfo.Clear();
213   textUpdateInfo.mClearAll = true;
214
215   if(textSize.width > layoutSize.width || textSize.height > layoutSize.height)
216   {
217     return false;
218   }
219   return true;
220 }
221
222 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
223 {
224   Controller::Impl& impl = *controller.mImpl;
225
226   const OperationsMask operations = impl.mOperationsPending;
227   if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
228   {
229     ModelPtr& model = impl.mModel;
230
231     bool  actualellipsis      = model->mElideEnabled;
232     float minPointSize        = impl.mTextFitMinSize;
233     float maxPointSize        = impl.mTextFitMaxSize;
234     float pointInterval       = impl.mTextFitStepSize;
235     float currentFitPointSize = impl.mFontDefaults->mFitPointSize;
236
237     model->mElideEnabled = false;
238     Vector<float> pointSizeArray;
239
240     // check zero value
241     if(pointInterval < 1.f)
242     {
243       impl.mTextFitStepSize = pointInterval = 1.0f;
244     }
245
246     pointSizeArray.Reserve(static_cast<unsigned int>(ceil((maxPointSize - minPointSize) / pointInterval)));
247
248     for(float i = minPointSize; i < maxPointSize; i += pointInterval)
249     {
250       pointSizeArray.PushBack(i);
251     }
252
253     pointSizeArray.PushBack(maxPointSize);
254
255     int bestSizeIndex = 0;
256     int min           = bestSizeIndex + 1;
257     int max           = pointSizeArray.Size() - 1;
258     while(min <= max)
259     {
260       int destI = (min + max) / 2;
261
262       if(CheckForTextFit(controller, pointSizeArray[destI], layoutSize))
263       {
264         bestSizeIndex = min;
265         min           = destI + 1;
266       }
267       else
268       {
269         max           = destI - 1;
270         bestSizeIndex = max;
271       }
272     }
273
274     model->mElideEnabled = actualellipsis;
275     if(currentFitPointSize != pointSizeArray[bestSizeIndex])
276     {
277       impl.mTextFitChanged = true;
278     }
279     impl.mFontDefaults->mFitPointSize = pointSizeArray[bestSizeIndex];
280     impl.mFontDefaults->sizeDefined   = true;
281     impl.ClearFontData();
282   }
283 }
284
285 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
286 {
287   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
288
289   // Make sure the model is up-to-date before layouting
290   EventHandler::ProcessModifyEvents(controller);
291
292   Controller::Impl& impl           = *controller.mImpl;
293   ModelPtr&         model          = impl.mModel;
294   VisualModelPtr&   visualModel    = model->mVisualModel;
295   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
296
297   Size layoutSize;
298
299   if(fabsf(width - visualModel->mControlSize.width) > Math::MACHINE_EPSILON_1000 ||
300      textUpdateInfo.mFullRelayoutNeeded ||
301      textUpdateInfo.mClearAll)
302   {
303     // Layout the text for the new width.
304     OperationsMask requestedOperationsMask        = static_cast<OperationsMask>(LAYOUT);
305     Size           sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
306
307     layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
308
309     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
310   }
311   else
312   {
313     layoutSize = visualModel->GetLayoutSize();
314     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
315   }
316
317   return layoutSize.height;
318 }
319
320 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
321 {
322   Controller::Impl& impl           = *controller.mImpl;
323   ModelPtr&         model          = impl.mModel;
324   VisualModelPtr&   visualModel    = model->mVisualModel;
325   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
326
327   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
328
329   UpdateTextType updateTextType = NONE_UPDATED;
330
331   if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
332   {
333     if(0u != visualModel->mGlyphPositions.Count())
334     {
335       visualModel->mGlyphPositions.Clear();
336       updateTextType = MODEL_UPDATED;
337     }
338
339     // Clear the update info. This info will be set the next time the text is updated.
340     textUpdateInfo.Clear();
341
342     // Not worth to relayout if width or height is equal to zero.
343     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
344
345     return updateTextType;
346   }
347
348   // Whether a new size has been set.
349   const bool newSize = (size != visualModel->mControlSize);
350
351   // Get a reference to the pending operations member
352   OperationsMask& operationsPending = impl.mOperationsPending;
353
354   if(newSize)
355   {
356     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
357
358     if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
359        (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
360        ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
361     {
362       textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
363     }
364
365     // Layout operations that need to be done if the size changes.
366     operationsPending = static_cast<OperationsMask>(operationsPending |
367                                                     LAYOUT |
368                                                     ALIGN |
369                                                     UPDATE_LAYOUT_SIZE |
370                                                     REORDER);
371     // Set the update info to relayout the whole text.
372     textUpdateInfo.mFullRelayoutNeeded = true;
373     textUpdateInfo.mCharacterIndex     = 0u;
374
375     // Store the size used to layout the text.
376     visualModel->mControlSize = size;
377   }
378
379   // Whether there are modify events.
380   if(0u != impl.mModifyEvents.Count())
381   {
382     // Style operations that need to be done if the text is modified.
383     operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
384   }
385
386   // Set the update info to elide the text.
387   if(model->mElideEnabled ||
388      ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
389   {
390     // Update Text layout for applying elided
391     operationsPending                  = static_cast<OperationsMask>(operationsPending |
392                                                     ALIGN |
393                                                     LAYOUT |
394                                                     UPDATE_LAYOUT_SIZE |
395                                                     REORDER);
396     textUpdateInfo.mFullRelayoutNeeded = true;
397     textUpdateInfo.mCharacterIndex     = 0u;
398   }
399
400   bool layoutDirectionChanged = false;
401   if(impl.mLayoutDirection != layoutDirection)
402   {
403     // Flag to indicate that the layout direction has changed.
404     layoutDirectionChanged = true;
405     // Clear the update info. This info will be set the next time the text is updated.
406     textUpdateInfo.mClearAll = true;
407     // Apply modifications to the model
408     // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
409     operationsPending     = static_cast<OperationsMask>(operationsPending |
410                                                     GET_GLYPH_METRICS |
411                                                     SHAPE_TEXT |
412                                                     UPDATE_DIRECTION |
413                                                     ALIGN |
414                                                     LAYOUT |
415                                                     BIDI_INFO |
416                                                     REORDER);
417     impl.mLayoutDirection = layoutDirection;
418   }
419
420   // Make sure the model is up-to-date before layouting.
421   EventHandler::ProcessModifyEvents(controller);
422   bool updated = impl.UpdateModel(operationsPending);
423
424   // Layout the text.
425   Size layoutSize;
426   updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
427
428   if(updated)
429   {
430     updateTextType = MODEL_UPDATED;
431   }
432
433   // Do not re-do any operation until something changes.
434   operationsPending          = NO_OPERATION;
435   model->mScrollPositionLast = model->mScrollPosition;
436
437   // Whether the text control is editable
438   const bool isEditable = NULL != impl.mEventData;
439
440   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
441   Vector2 offset;
442   if(newSize && isEditable)
443   {
444     offset = model->mScrollPosition;
445   }
446
447   if(!isEditable || !controller.IsMultiLineEnabled())
448   {
449     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
450     CalculateVerticalOffset(impl, size);
451   }
452   else // TextEditor
453   {
454     // If layoutSize is bigger than size, vertical align has no meaning.
455     if(layoutSize.y < size.y)
456     {
457       CalculateVerticalOffset(impl, size);
458       if(impl.mEventData)
459       {
460         impl.mEventData->mScrollAfterDelete = false;
461       }
462     }
463   }
464
465   if(isEditable)
466   {
467     if(newSize || layoutDirectionChanged)
468     {
469       // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
470       impl.ClampHorizontalScroll(layoutSize);
471
472       // Update the decorator's positions is needed if there is a new size.
473       impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
474
475       // All decorator elements need to be updated.
476       if(EventData::IsEditingState(impl.mEventData->mState))
477       {
478         impl.mEventData->mScrollAfterUpdatePosition = true;
479         impl.mEventData->mUpdateCursorPosition      = true;
480         impl.mEventData->mUpdateGrabHandlePosition  = true;
481       }
482       else if(impl.mEventData->mState == EventData::SELECTING)
483       {
484         impl.mEventData->mUpdateHighlightBox = true;
485       }
486     }
487
488     // Move the cursor, grab handle etc.
489     if(impl.ProcessInputEvents())
490     {
491       updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
492     }
493   }
494
495   // Clear the update info. This info will be set the next time the text is updated.
496   textUpdateInfo.Clear();
497   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
498
499   return updateTextType;
500 }
501
502 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
503 {
504   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
505   bool viewUpdated(false);
506
507   // Calculate the operations to be done.
508   const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
509
510   TextUpdateInfo&      textUpdateInfo              = impl.mTextUpdateInfo;
511   const CharacterIndex startIndex                  = textUpdateInfo.mParagraphCharacterIndex;
512   const Length         requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
513
514   // Get the current layout size.
515   VisualModelPtr& visualModel = impl.mModel->mVisualModel;
516   layoutSize                  = visualModel->GetLayoutSize();
517
518   if(NO_OPERATION != (LAYOUT & operations))
519   {
520     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
521
522     // Some vectors with data needed to layout and reorder may be void
523     // after the first time the text has been laid out.
524     // Fill the vectors again.
525
526     // Calculate the number of glyphs to layout.
527     const Vector<GlyphIndex>& charactersToGlyph        = visualModel->mCharactersToGlyph;
528     const Vector<Length>&     glyphsPerCharacter       = visualModel->mGlyphsPerCharacter;
529     const GlyphIndex* const   charactersToGlyphBuffer  = charactersToGlyph.Begin();
530     const Length* const       glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
531
532     const CharacterIndex lastIndex       = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
533     const GlyphIndex     startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
534
535     // Make sure the index is not out of bound
536     if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
537        requestedNumberOfCharacters > charactersToGlyph.Count() ||
538        (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
539     {
540       std::string currentText;
541       impl.GetText(currentText);
542
543       DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
544       DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
545       DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
546
547       return false;
548     }
549
550     const Length numberOfGlyphs      = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
551     const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
552
553     if(0u == totalNumberOfGlyphs)
554     {
555       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
556       {
557         visualModel->SetLayoutSize(Size::ZERO);
558       }
559
560       // Nothing else to do if there is no glyphs.
561       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
562       return true;
563     }
564
565     // Set the layout parameters.
566     Layout::Parameters layoutParameters(size, impl.mModel);
567
568     // Resize the vector of positions to have the same size than the vector of glyphs.
569     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
570     glyphPositions.Resize(totalNumberOfGlyphs);
571
572     // Whether the last character is a new paragraph character.
573     const Character* const textBuffer           = impl.mModel->mLogicalModel->mText.Begin();
574     textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
575     layoutParameters.isLastNewParagraph         = textUpdateInfo.mIsLastCharacterNewParagraph;
576
577     // The initial glyph and the number of glyphs to layout.
578     layoutParameters.startGlyphIndex        = startGlyphIndex;
579     layoutParameters.numberOfGlyphs         = numberOfGlyphs;
580     layoutParameters.startLineIndex         = textUpdateInfo.mStartLineIndex;
581     layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
582
583     // Update the ellipsis
584     bool elideTextEnabled = impl.mModel->mElideEnabled;
585     auto ellipsisPosition = impl.mModel->mEllipsisPosition;
586
587     if(NULL != impl.mEventData)
588     {
589       if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
590       {
591         elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
592       }
593       else if(EventData::INACTIVE != impl.mEventData->mState)
594       {
595         // Disable ellipsis when editing
596         elideTextEnabled = false;
597       }
598
599       // Reset the scroll position in inactive state
600       if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
601       {
602         impl.ResetScrollPosition();
603       }
604     }
605
606     // Update the visual model.
607     bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
608     Size newLayoutSize;
609     viewUpdated               = impl.mLayoutEngine.LayoutText(layoutParameters,
610                                                 newLayoutSize,
611                                                 elideTextEnabled,
612                                                 isAutoScrollEnabled,
613                                                 ellipsisPosition);
614     impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
615
616     viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
617
618     if(viewUpdated)
619     {
620       layoutSize = newLayoutSize;
621
622       if(NO_OPERATION != (UPDATE_DIRECTION & operations))
623       {
624         impl.mIsTextDirectionRTL = false;
625       }
626
627       if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
628       {
629         impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
630       }
631
632       // Sets the layout size.
633       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
634       {
635         visualModel->SetLayoutSize(layoutSize);
636       }
637     } // view updated
638   }
639
640   if(NO_OPERATION != (ALIGN & operations))
641   {
642     DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
643     viewUpdated = true;
644   }
645 #if defined(DEBUG_ENABLED)
646   std::string currentText;
647   impl.GetText(currentText);
648   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
649 #endif
650   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
651   return viewUpdated;
652 }
653
654 void Controller::Relayouter::DoRelayoutHorizontalAlignment(Controller::Impl&    impl,
655                                                            const Size&          size,
656                                                            const CharacterIndex startIndex,
657                                                            const Length         requestedNumberOfCharacters)
658 {
659   // The visualModel
660   VisualModelPtr& visualModel = impl.mModel->mVisualModel;
661
662   // The laid-out lines.
663   Vector<LineRun>& lines = visualModel->mLines;
664
665   CharacterIndex alignStartIndex                  = startIndex;
666   Length         alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
667
668   // the whole text needs to be full aligned.
669   // If you do not do a full aligned, only the last line of the multiline input is aligned.
670   if(impl.mEventData && impl.mEventData->mUpdateAlignment)
671   {
672     alignStartIndex                   = 0u;
673     alignRequestedNumberOfCharacters  = impl.mModel->mLogicalModel->mText.Count();
674     impl.mEventData->mUpdateAlignment = false;
675   }
676
677   // If there is no BoundedParagraphRuns then apply the alignment of controller.
678   // Check whether the layout is single line. It's needed to apply one alignment for single-line.
679   // In single-line layout case we need to check whether to follow the alignment of controller or the first BoundedParagraph.
680   // Apply BoundedParagraph's alignment if and only if there is one BoundedParagraph contains all characters. Otherwise follow controller's alignment.
681   const bool isFollowControllerAlignment = ((impl.mModel->GetNumberOfBoundedParagraphRuns() == 0u) ||
682                                             ((Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) &&
683                                              (impl.mModel->GetBoundedParagraphRuns()[0].characterRun.numberOfCharacters != impl.mModel->mLogicalModel->mText.Count())));
684
685   if(isFollowControllerAlignment)
686   {
687     // Need to align with the control's size as the text may contain lines
688     // starting either with left to right text or right to left.
689     impl.mLayoutEngine.Align(size,
690                              alignStartIndex,
691                              alignRequestedNumberOfCharacters,
692                              impl.mModel->mHorizontalAlignment,
693                              lines,
694                              impl.mModel->mAlignmentOffset,
695                              impl.mLayoutDirection,
696                              (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
697   }
698   else
699   {
700     //Override the controller horizontal-alignment by horizontal-alignment of bounded paragraph.
701     const Length&                      numberOfBoundedParagraphRuns = impl.mModel->GetNumberOfBoundedParagraphRuns();
702     const Vector<BoundedParagraphRun>& boundedParagraphRuns         = impl.mModel->GetBoundedParagraphRuns();
703     const CharacterIndex               alignEndIndex                = alignStartIndex + alignRequestedNumberOfCharacters - 1u;
704
705     Length alignIndex               = alignStartIndex;
706     Length boundedParagraphRunIndex = 0u;
707
708     while(alignIndex <= alignEndIndex && boundedParagraphRunIndex < numberOfBoundedParagraphRuns)
709     {
710       //BP: BoundedParagraph
711       const BoundedParagraphRun& boundedParagraphRun   = boundedParagraphRuns[boundedParagraphRunIndex];
712       const CharacterIndex&      characterStartIndexBP = boundedParagraphRun.characterRun.characterIndex;
713       const Length&              numberOfCharactersBP  = boundedParagraphRun.characterRun.numberOfCharacters;
714       const CharacterIndex       characterEndIndexBP   = characterStartIndexBP + numberOfCharactersBP - 1u;
715
716       CharacterIndex                  decidedAlignStartIndex         = alignIndex;
717       Length                          decidedAlignNumberOfCharacters = alignEndIndex - alignIndex + 1u;
718       Text::HorizontalAlignment::Type decidedHorizontalAlignment     = impl.mModel->mHorizontalAlignment;
719
720       /*
721          * Shortcuts to explain indexes cases:
722          *
723          * AS: Alignment Start Index
724          * AE: Alignment End Index
725          * PS: Paragraph Start Index
726          * PE: Paragraph End Index
727          * B: BoundedParagraph Alignment
728          * M: Model Alignment
729          *
730          */
731
732       if(alignIndex < characterStartIndexBP && characterStartIndexBP <= alignEndIndex) /// AS.MMMMMM.PS--------AE
733       {
734         // Alignment from "Alignment Start Index" to index before "Paragraph Start Index" according to "Model Alignment"
735         decidedAlignStartIndex         = alignIndex;
736         decidedAlignNumberOfCharacters = characterStartIndexBP - alignIndex;
737         decidedHorizontalAlignment     = impl.mModel->mHorizontalAlignment;
738
739         // Need to re-heck the case of current bounded paragraph
740         alignIndex = characterStartIndexBP; // Shift AS to be PS
741       }
742       else if((characterStartIndexBP <= alignIndex && alignIndex <= characterEndIndexBP) ||     /// ---PS.BBBBBBB.AS.BBBBBBB.PE---
743               (characterStartIndexBP <= alignEndIndex && alignEndIndex <= characterEndIndexBP)) /// ---PS.BBBBBB.AE.BBBBBBB.PE---
744       {
745         // Alignment from "Paragraph Start Index" to "Paragraph End Index" according to "BoundedParagraph Alignment"
746         decidedAlignStartIndex         = characterStartIndexBP;
747         decidedAlignNumberOfCharacters = numberOfCharactersBP;
748         decidedHorizontalAlignment     = boundedParagraphRun.horizontalAlignmentDefined ? boundedParagraphRun.horizontalAlignment : impl.mModel->mHorizontalAlignment;
749
750         alignIndex = characterEndIndexBP + 1u; // Shift AS to be after PE direct
751         boundedParagraphRunIndex++;            // Align then check the case of next bounded paragraph
752       }
753       else
754       {
755         boundedParagraphRunIndex++; // Check the case of next bounded paragraph
756         continue;
757       }
758
759       impl.mLayoutEngine.Align(size,
760                                decidedAlignStartIndex,
761                                decidedAlignNumberOfCharacters,
762                                decidedHorizontalAlignment,
763                                lines,
764                                impl.mModel->mAlignmentOffset,
765                                impl.mLayoutDirection,
766                                (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
767     }
768
769     //Align the remaining that is not aligned
770     if(alignIndex <= alignEndIndex)
771     {
772       impl.mLayoutEngine.Align(size,
773                                alignIndex,
774                                (alignEndIndex - alignIndex + 1u),
775                                impl.mModel->mHorizontalAlignment,
776                                lines,
777                                impl.mModel->mAlignmentOffset,
778                                impl.mLayoutDirection,
779                                (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
780     }
781   }
782 }
783
784 void Controller::Relayouter::CalculateVerticalOffset(Controller::Impl& impl, const Size& controlSize)
785 {
786   ModelPtr&         model                 = impl.mModel;
787   VisualModelPtr&   visualModel           = model->mVisualModel;
788   Size              layoutSize            = model->mVisualModel->GetLayoutSize();
789   Size              oldLayoutSize         = layoutSize;
790   float             offsetY               = 0.f;
791   bool              needRecalc            = false;
792   float             defaultFontLineHeight = impl.GetDefaultFontLineHeight();
793
794   if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
795   {
796     // Get the line height of the default font.
797     layoutSize.height = defaultFontLineHeight;
798   }
799
800   // Whether the text control is editable
801   const bool isEditable = NULL != impl.mEventData;
802   if(isEditable && layoutSize.height != defaultFontLineHeight && impl.IsShowingPlaceholderText())
803   {
804     // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
805     // This situation occurs when the size of placeholder text is different from the default text.
806     layoutSize.height = defaultFontLineHeight;
807     needRecalc        = true;
808   }
809
810   switch(model->mVerticalAlignment)
811   {
812     case VerticalAlignment::TOP:
813     {
814       model->mScrollPosition.y = 0.f;
815       offsetY                  = 0.f;
816       break;
817     }
818     case VerticalAlignment::CENTER:
819     {
820       model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
821       if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
822       break;
823     }
824     case VerticalAlignment::BOTTOM:
825     {
826       model->mScrollPosition.y = controlSize.height - layoutSize.height;
827       if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
828       break;
829     }
830   }
831
832   if(needRecalc)
833   {
834     // Update glyphPositions according to recalculation.
835     const Length     positionCount  = visualModel->mGlyphPositions.Count();
836     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
837     for(Length index = 0u; index < positionCount; index++)
838     {
839       glyphPositions[index].y += offsetY;
840     }
841   }
842 }
843
844 } // namespace Text
845
846 } // namespace Toolkit
847
848 } // namespace Dali