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