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