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