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