Fix TextFit do not work properly
[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   bool layoutTooSmall = false;
238   DoRelayout(impl,
239              Size(layoutSize.width, MAX_FLOAT),
240              static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
241              textSize,
242              layoutTooSmall);
243
244   // Clear the update info. This info will be set the next time the text is updated.
245   textUpdateInfo.Clear();
246   textUpdateInfo.mClearAll = true;
247
248   if(layoutTooSmall || textSize.width > layoutSize.width || textSize.height > layoutSize.height)
249   {
250     return false;
251   }
252   return true;
253 }
254
255 void Controller::Relayouter::FitArrayPointSizeforLayout(Controller& controller, const Size& layoutSize)
256 {
257   Controller::Impl& impl = *controller.mImpl;
258
259   const OperationsMask operations = impl.mOperationsPending;
260   if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
261   {
262     DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_ARRAY_LAYOUT");
263     std::vector<Toolkit::DevelTextLabel::FitOption> fitOptions = impl.mTextFitArray;
264     int numberOfFitOptions = static_cast<int>(fitOptions.size());
265     if(numberOfFitOptions == 0)
266     {
267       DALI_LOG_ERROR("fitOptions is empty\n");
268       return;
269     }
270
271     ModelPtr& model          = impl.mModel;
272     bool      actualellipsis = model->mElideEnabled;
273     model->mElideEnabled     = false;
274
275     // Sort in ascending order by PointSize.
276     std::sort(fitOptions.begin(), fitOptions.end(), compareByPointSize);
277
278     // Decide whether to use binary search.
279     // If MinLineSize is not sorted in ascending order,
280     // binary search cannot guarantee that it will always find the best value.
281     bool  binarySearch    = true;
282     float prevMinLineSize = 0.0f;
283     for(Toolkit::DevelTextLabel::FitOption& option : fitOptions)
284     {
285       float optionMinLineSize = option.GetMinLineSize();
286       if(prevMinLineSize > optionMinLineSize)
287       {
288         binarySearch = false;
289         break;
290       }
291       prevMinLineSize = optionMinLineSize;
292     }
293
294     // Set the first FitOption(Minimum PointSize) to the best value.
295     // If the search does not find an optimal value, the minimum PointSize will be used to text fit.
296     Toolkit::DevelTextLabel::FitOption firstOption = fitOptions.front();
297     bool  bestSizeUpdatedLatest = false;
298     float bestPointSize         = firstOption.GetPointSize();
299     float bestMinLineSize       = firstOption.GetMinLineSize();
300
301     if(binarySearch)
302     {
303       int left = 0u;
304       int right = numberOfFitOptions - 1;
305
306       while (left <= right)
307       {
308         int mid = left + (right - left) / 2;
309         Toolkit::DevelTextLabel::FitOption option = fitOptions[mid];
310         float testPointSize   = option.GetPointSize();
311         float testMinLineSize = option.GetMinLineSize();
312         impl.SetDefaultLineSize(testMinLineSize);
313
314         if(CheckForTextFit(controller, testPointSize, layoutSize))
315         {
316           bestSizeUpdatedLatest = true;
317           bestPointSize   = testPointSize;
318           bestMinLineSize = testMinLineSize;
319           left = mid + 1;
320         }
321         else
322         {
323           bestSizeUpdatedLatest = false;
324           right = mid - 1;
325         }
326       }
327     }
328     else
329     {
330       // If binary search is not possible, search sequentially starting from the largest PointSize.
331       for(auto it = fitOptions.rbegin(); it != fitOptions.rend(); ++it)
332       {
333         Toolkit::DevelTextLabel::FitOption option = *it;
334         float testPointSize   = option.GetPointSize();
335         float testMinLineSize = option.GetMinLineSize();
336         impl.SetDefaultLineSize(testMinLineSize);
337
338         if(CheckForTextFit(controller, testPointSize, layoutSize))
339         {
340           bestSizeUpdatedLatest = true;
341           bestPointSize   = testPointSize;
342           bestMinLineSize = testMinLineSize;
343           break;
344         }
345         else
346         {
347           bestSizeUpdatedLatest = false;
348         }
349       }
350     }
351
352     // Best point size was not updated. re-run so the TextFit should be fitted really.
353     if(!bestSizeUpdatedLatest)
354     {
355       impl.SetDefaultLineSize(bestMinLineSize);
356       CheckForTextFit(controller, bestPointSize, layoutSize);
357     }
358
359     model->mElideEnabled              = actualellipsis;
360     impl.mFontDefaults->mFitPointSize = bestPointSize;
361     impl.mFontDefaults->sizeDefined   = true;
362     impl.ClearFontData();
363   }
364 }
365
366 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
367 {
368   Controller::Impl& impl = *controller.mImpl;
369
370   const OperationsMask operations = impl.mOperationsPending;
371   if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
372   {
373     DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
374     ModelPtr& model = impl.mModel;
375
376     bool  actualellipsis         = model->mElideEnabled;
377     float minPointSize           = impl.mTextFitMinSize;
378     float maxPointSize           = impl.mTextFitMaxSize;
379     float pointInterval          = impl.mTextFitStepSize;
380     float currentFitPointSize    = impl.mFontDefaults->mFitPointSize;
381     float currentDefaultLineSize = impl.mLayoutEngine.GetDefaultLineSize();
382     // Instead of using the LineSize of the current TextLabel, the LineSize set in TextFit is used.
383     impl.SetDefaultLineSize(impl.mTextFitLineSize);
384
385     model->mElideEnabled = false;
386
387     // check zero value
388     if(pointInterval < 1.f)
389     {
390       impl.mTextFitStepSize = pointInterval = 1.0f;
391     }
392     uint32_t pointSizeRange = static_cast<uint32_t>(ceil((maxPointSize - minPointSize) / pointInterval));
393
394     // Ensure minPointSize + pointSizeRange * pointInverval >= maxPointSize
395     while(minPointSize + static_cast<float>(pointSizeRange) * pointInterval < maxPointSize)
396     {
397       ++pointSizeRange;
398     }
399
400     uint32_t bestSizeIndex = 0;
401     uint32_t minIndex      = bestSizeIndex + 1u;
402     uint32_t maxIndex      = pointSizeRange + 1u;
403
404     bool bestSizeUpdatedLatest = false;
405     // Find best size as binary search.
406     // Range format as [l r). (left closed, right opened)
407     // It mean, we already check all i < l is valid, and r <= i is invalid.
408     // Below binary search will check m = (l+r)/2 point.
409     // Search area sperate as [l m) or [m+1 r)
410     //
411     // Basically, we can assume that 0 (minPointSize) is always valid.
412     // Now, we will check [1 pointSizeRange] range s.t. pointSizeRange mean the maxPointSize
413     while(minIndex < maxIndex)
414     {
415       uint32_t    testIndex     = minIndex + ((maxIndex - minIndex) >> 1u);
416       const float testPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(testIndex) * pointInterval);
417
418       if(CheckForTextFit(controller, testPointSize, layoutSize))
419       {
420         bestSizeUpdatedLatest = true;
421
422         bestSizeIndex = testIndex;
423         minIndex      = testIndex + 1u;
424       }
425       else
426       {
427         bestSizeUpdatedLatest = false;
428         maxIndex              = testIndex;
429       }
430     }
431     const float bestPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(bestSizeIndex) * pointInterval);
432
433     // Best point size was not updated. re-run so the TextFit should be fitted really.
434     if(!bestSizeUpdatedLatest)
435     {
436       CheckForTextFit(controller, bestPointSize, layoutSize);
437     }
438
439     model->mElideEnabled = actualellipsis;
440     if(!Dali::Equals(currentFitPointSize, bestPointSize))
441     {
442       impl.mTextFitChanged = true;
443     }
444     // Revert back to the original TextLabel LineSize.
445     impl.SetDefaultLineSize(currentDefaultLineSize);
446     impl.mFontDefaults->mFitPointSize = bestPointSize;
447     impl.mFontDefaults->sizeDefined   = true;
448     impl.ClearFontData();
449   }
450 }
451
452 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
453 {
454   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
455   DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
456
457   // Make sure the model is up-to-date before layouting
458   EventHandler::ProcessModifyEvents(controller);
459
460   Controller::Impl& impl           = *controller.mImpl;
461   ModelPtr&         model          = impl.mModel;
462   VisualModelPtr&   visualModel    = model->mVisualModel;
463   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
464
465   // Get cached value.
466   Size layoutSize = visualModel->GetHeightForWidth();
467
468   if(fabsf(width - layoutSize.width) > Math::MACHINE_EPSILON_1000 ||
469      textUpdateInfo.mFullRelayoutNeeded ||
470      textUpdateInfo.mClearAll)
471   {
472     // Layout the text for the new width.
473     OperationsMask requestedOperationsMask        = static_cast<OperationsMask>(LAYOUT);
474     Size           sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
475
476     layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
477
478     // The calculated layout width may not be the same as the requested width.
479     // For cache efficiency, the requested width is stored.
480     layoutSize.width = width;
481     visualModel->SetHeightForWidth(layoutSize);
482
483     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
484   }
485   else
486   {
487     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
488   }
489
490   return layoutSize.height;
491 }
492
493 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
494 {
495   Controller::Impl& impl           = *controller.mImpl;
496   ModelPtr&         model          = impl.mModel;
497   VisualModelPtr&   visualModel    = model->mVisualModel;
498   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
499
500   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
501   DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_RELAYOUT");
502
503   UpdateTextType updateTextType = NONE_UPDATED;
504
505   if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
506   {
507     if(0u != visualModel->mGlyphPositions.Count())
508     {
509       visualModel->mGlyphPositions.Clear();
510       updateTextType = MODEL_UPDATED;
511     }
512
513     // Clear the update info. This info will be set the next time the text is updated.
514     textUpdateInfo.Clear();
515
516     // Not worth to relayout if width or height is equal to zero.
517     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
518
519     return updateTextType;
520   }
521
522   // Whether a new size has been set.
523   const bool newSize = (size != visualModel->mControlSize);
524
525   // Get a reference to the pending operations member
526   OperationsMask& operationsPending = impl.mOperationsPending;
527
528   if(newSize)
529   {
530     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
531
532     if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
533        (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
534        ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
535     {
536       textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
537     }
538
539     // Layout operations that need to be done if the size changes.
540     operationsPending = static_cast<OperationsMask>(operationsPending |
541                                                     LAYOUT |
542                                                     ALIGN |
543                                                     UPDATE_LAYOUT_SIZE |
544                                                     REORDER);
545     // Set the update info to relayout the whole text.
546     textUpdateInfo.mFullRelayoutNeeded = true;
547     textUpdateInfo.mCharacterIndex     = 0u;
548
549     // Store the size used to layout the text.
550     visualModel->mControlSize = size;
551   }
552
553   // Whether there are modify events.
554   if(0u != impl.mModifyEvents.Count())
555   {
556     // Style operations that need to be done if the text is modified.
557     operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
558   }
559
560   // Set the update info to elide the text.
561   if(model->mElideEnabled ||
562      ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
563   {
564     // Update Text layout for applying elided
565     operationsPending                  = static_cast<OperationsMask>(operationsPending |
566                                                     ALIGN |
567                                                     LAYOUT |
568                                                     UPDATE_LAYOUT_SIZE |
569                                                     REORDER);
570     textUpdateInfo.mFullRelayoutNeeded = true;
571     textUpdateInfo.mCharacterIndex     = 0u;
572   }
573
574   bool layoutDirectionChanged = false;
575   if(impl.mLayoutDirection != layoutDirection)
576   {
577     // Flag to indicate that the layout direction has changed.
578     layoutDirectionChanged = true;
579     // Clear the update info. This info will be set the next time the text is updated.
580     textUpdateInfo.mClearAll = true;
581     // Apply modifications to the model
582     // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
583     operationsPending     = static_cast<OperationsMask>(operationsPending |
584                                                     GET_GLYPH_METRICS |
585                                                     SHAPE_TEXT |
586                                                     UPDATE_DIRECTION |
587                                                     ALIGN |
588                                                     LAYOUT |
589                                                     BIDI_INFO |
590                                                     REORDER);
591     impl.mLayoutDirection = layoutDirection;
592   }
593
594   // Make sure the model is up-to-date before layouting.
595   EventHandler::ProcessModifyEvents(controller);
596   bool updated = impl.UpdateModel(operationsPending);
597
598   // Layout the text.
599   Size layoutSize;
600   updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
601
602   if(updated)
603   {
604     updateTextType = MODEL_UPDATED;
605   }
606
607   // Do not re-do any operation until something changes.
608   operationsPending          = NO_OPERATION;
609   model->mScrollPositionLast = model->mScrollPosition;
610
611   // Whether the text control is editable
612   const bool isEditable = NULL != impl.mEventData;
613
614   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
615   Vector2 offset;
616   if(newSize && isEditable)
617   {
618     offset = model->mScrollPosition;
619   }
620
621   if(!isEditable || !controller.IsMultiLineEnabled())
622   {
623     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
624     CalculateVerticalOffset(impl, size);
625   }
626   else // TextEditor
627   {
628     // If layoutSize is bigger than size, vertical align has no meaning.
629     if(layoutSize.y < size.y)
630     {
631       CalculateVerticalOffset(impl, size);
632       if(impl.mEventData)
633       {
634         impl.mEventData->mScrollAfterDelete = false;
635       }
636     }
637   }
638
639   if(isEditable)
640   {
641     if(newSize || layoutDirectionChanged)
642     {
643       // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
644       impl.ClampHorizontalScroll(layoutSize);
645
646       // Update the decorator's positions is needed if there is a new size.
647       impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
648
649       // All decorator elements need to be updated.
650       if(EventData::IsEditingState(impl.mEventData->mState))
651       {
652         impl.mEventData->mScrollAfterUpdatePosition = true;
653         impl.mEventData->mUpdateCursorPosition      = true;
654         impl.mEventData->mUpdateGrabHandlePosition  = true;
655       }
656       else if(impl.mEventData->mState == EventData::SELECTING)
657       {
658         impl.mEventData->mUpdateHighlightBox = true;
659       }
660     }
661
662     // Move the cursor, grab handle etc.
663     if(impl.ProcessInputEvents())
664     {
665       updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
666     }
667   }
668
669   // Clear the update info. This info will be set the next time the text is updated.
670   textUpdateInfo.Clear();
671   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
672
673   return updateTextType;
674 }
675
676 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
677 {
678   bool layoutTooSmall = false;
679   return DoRelayout(impl, size, operationsRequired, layoutSize, layoutTooSmall);
680 }
681
682 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize, bool& layoutTooSmall)
683 {
684   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
685   DALI_TRACE_SCOPE(gTraceFilter2, "DALI_TEXT_DORELAYOUT");
686   bool viewUpdated(false);
687
688   // Calculate the operations to be done.
689   const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
690
691   TextUpdateInfo&      textUpdateInfo              = impl.mTextUpdateInfo;
692   const CharacterIndex startIndex                  = textUpdateInfo.mParagraphCharacterIndex;
693   const Length         requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
694
695   // Get the current layout size.
696   VisualModelPtr& visualModel = impl.mModel->mVisualModel;
697   layoutSize                  = visualModel->GetLayoutSize();
698
699   if(NO_OPERATION != (LAYOUT & operations))
700   {
701     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
702
703     // Some vectors with data needed to layout and reorder may be void
704     // after the first time the text has been laid out.
705     // Fill the vectors again.
706
707     // Calculate the number of glyphs to layout.
708     const Vector<GlyphIndex>& charactersToGlyph        = visualModel->mCharactersToGlyph;
709     const Vector<Length>&     glyphsPerCharacter       = visualModel->mGlyphsPerCharacter;
710     const GlyphIndex* const   charactersToGlyphBuffer  = charactersToGlyph.Begin();
711     const Length* const       glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
712
713     const CharacterIndex lastIndex       = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
714     const GlyphIndex     startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
715
716     // Make sure the index is not out of bound
717     if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
718        requestedNumberOfCharacters > charactersToGlyph.Count() ||
719        (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
720     {
721       std::string currentText;
722       impl.GetText(currentText);
723
724       DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
725       DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
726       DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
727
728       return false;
729     }
730
731     const Length numberOfGlyphs      = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
732     const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
733
734     if(0u == totalNumberOfGlyphs)
735     {
736       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
737       {
738         visualModel->SetLayoutSize(Size::ZERO);
739       }
740
741       // Nothing else to do if there is no glyphs.
742       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
743       return true;
744     }
745
746     // Set the layout parameters.
747     Layout::Parameters layoutParameters(size, impl.mModel);
748
749     // Resize the vector of positions to have the same size than the vector of glyphs.
750     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
751     glyphPositions.Resize(totalNumberOfGlyphs);
752
753     // Whether the last character is a new paragraph character.
754     const Character* const textBuffer           = impl.mModel->mLogicalModel->mText.Begin();
755     textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
756     layoutParameters.isLastNewParagraph         = textUpdateInfo.mIsLastCharacterNewParagraph;
757
758     // The initial glyph and the number of glyphs to layout.
759     layoutParameters.startGlyphIndex        = startGlyphIndex;
760     layoutParameters.numberOfGlyphs         = numberOfGlyphs;
761     layoutParameters.startLineIndex         = textUpdateInfo.mStartLineIndex;
762     layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
763
764     // Update the ellipsis
765     bool elideTextEnabled = impl.mModel->mElideEnabled;
766     auto ellipsisPosition = impl.mModel->mEllipsisPosition;
767
768     if(NULL != impl.mEventData)
769     {
770       if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
771       {
772         elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
773       }
774       else if(EventData::INACTIVE != impl.mEventData->mState)
775       {
776         // Disable ellipsis when editing
777         elideTextEnabled = false;
778       }
779
780       // Reset the scroll position in inactive state
781       if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
782       {
783         impl.ResetScrollPosition();
784       }
785     }
786
787     // Update the visual model.
788     bool isAutoScrollEnabled            = impl.mIsAutoScrollEnabled;
789     bool isAutoScrollMaxTextureExceeded = impl.mIsAutoScrollMaxTextureExceeded;
790     bool isHiddenInputEnabled           = false;
791     if(impl.mHiddenInput && impl.mEventData != nullptr && impl.mHiddenInput->GetHideMode() != Toolkit::HiddenInput::Mode::HIDE_NONE)
792     {
793       isHiddenInputEnabled = true;
794     }
795
796     Size newLayoutSize;
797     viewUpdated               = impl.mLayoutEngine.LayoutText(layoutParameters,
798                                                 newLayoutSize,
799                                                 elideTextEnabled,
800                                                 isAutoScrollEnabled,
801                                                 isAutoScrollMaxTextureExceeded,
802                                                 isHiddenInputEnabled,
803                                                 ellipsisPosition);
804     impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
805     layoutTooSmall = !viewUpdated;
806
807     viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
808
809     if(viewUpdated)
810     {
811       layoutSize = newLayoutSize;
812
813       if(NO_OPERATION != (UPDATE_DIRECTION & operations))
814       {
815         impl.mIsTextDirectionRTL = false;
816       }
817
818       if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
819       {
820         impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
821       }
822
823       // Sets the layout size.
824       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
825       {
826         visualModel->SetLayoutSize(layoutSize);
827       }
828     } // view updated
829   }
830
831   if(NO_OPERATION != (ALIGN & operations))
832   {
833     DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
834     viewUpdated = true;
835   }
836 #if defined(DEBUG_ENABLED)
837   std::string currentText;
838   impl.GetText(currentText);
839   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
840 #endif
841   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
842   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, layout too small %s\n", (layoutTooSmall ? "true" : "false"));
843   return viewUpdated;
844 }
845
846 void Controller::Relayouter::DoRelayoutHorizontalAlignment(Controller::Impl&    impl,
847                                                            const Size&          size,
848                                                            const CharacterIndex startIndex,
849                                                            const Length         requestedNumberOfCharacters)
850 {
851   // The visualModel
852   VisualModelPtr& visualModel = impl.mModel->mVisualModel;
853
854   // The laid-out lines.
855   Vector<LineRun>& lines = visualModel->mLines;
856
857   CharacterIndex alignStartIndex                  = startIndex;
858   Length         alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
859
860   // the whole text needs to be full aligned.
861   // If you do not do a full aligned, only the last line of the multiline input is aligned.
862   if(impl.mEventData && impl.mEventData->mUpdateAlignment)
863   {
864     alignStartIndex                   = 0u;
865     alignRequestedNumberOfCharacters  = impl.mModel->mLogicalModel->mText.Count();
866     impl.mEventData->mUpdateAlignment = false;
867   }
868
869   // If there is no BoundedParagraphRuns then apply the alignment of controller.
870   // Check whether the layout is single line. It's needed to apply one alignment for single-line.
871   // In single-line layout case we need to check whether to follow the alignment of controller or the first BoundedParagraph.
872   // Apply BoundedParagraph's alignment if and only if there is one BoundedParagraph contains all characters. Otherwise follow controller's alignment.
873   const bool isFollowControllerAlignment = ((impl.mModel->GetNumberOfBoundedParagraphRuns() == 0u) ||
874                                             ((Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) &&
875                                              (impl.mModel->GetBoundedParagraphRuns()[0].characterRun.numberOfCharacters != impl.mModel->mLogicalModel->mText.Count())));
876
877   if(isFollowControllerAlignment)
878   {
879     // Need to align with the control's size as the text may contain lines
880     // starting either with left to right text or right to left.
881     impl.mLayoutEngine.Align(size,
882                              alignStartIndex,
883                              alignRequestedNumberOfCharacters,
884                              impl.mModel->mHorizontalAlignment,
885                              lines,
886                              impl.mModel->mAlignmentOffset,
887                              impl.mLayoutDirection,
888                              (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
889   }
890   else
891   {
892     //Override the controller horizontal-alignment by horizontal-alignment of bounded paragraph.
893     const Length&                      numberOfBoundedParagraphRuns = impl.mModel->GetNumberOfBoundedParagraphRuns();
894     const Vector<BoundedParagraphRun>& boundedParagraphRuns         = impl.mModel->GetBoundedParagraphRuns();
895     const CharacterIndex               alignEndIndex                = alignStartIndex + alignRequestedNumberOfCharacters - 1u;
896
897     Length alignIndex               = alignStartIndex;
898     Length boundedParagraphRunIndex = 0u;
899
900     while(alignIndex <= alignEndIndex && boundedParagraphRunIndex < numberOfBoundedParagraphRuns)
901     {
902       //BP: BoundedParagraph
903       const BoundedParagraphRun& boundedParagraphRun   = boundedParagraphRuns[boundedParagraphRunIndex];
904       const CharacterIndex&      characterStartIndexBP = boundedParagraphRun.characterRun.characterIndex;
905       const Length&              numberOfCharactersBP  = boundedParagraphRun.characterRun.numberOfCharacters;
906       const CharacterIndex       characterEndIndexBP   = characterStartIndexBP + numberOfCharactersBP - 1u;
907
908       CharacterIndex                  decidedAlignStartIndex         = alignIndex;
909       Length                          decidedAlignNumberOfCharacters = alignEndIndex - alignIndex + 1u;
910       Text::HorizontalAlignment::Type decidedHorizontalAlignment     = impl.mModel->mHorizontalAlignment;
911
912       /*
913          * Shortcuts to explain indexes cases:
914          *
915          * AS: Alignment Start Index
916          * AE: Alignment End Index
917          * PS: Paragraph Start Index
918          * PE: Paragraph End Index
919          * B: BoundedParagraph Alignment
920          * M: Model Alignment
921          *
922          */
923
924       if(alignIndex < characterStartIndexBP && characterStartIndexBP <= alignEndIndex) /// AS.MMMMMM.PS--------AE
925       {
926         // Alignment from "Alignment Start Index" to index before "Paragraph Start Index" according to "Model Alignment"
927         decidedAlignStartIndex         = alignIndex;
928         decidedAlignNumberOfCharacters = characterStartIndexBP - alignIndex;
929         decidedHorizontalAlignment     = impl.mModel->mHorizontalAlignment;
930
931         // Need to re-heck the case of current bounded paragraph
932         alignIndex = characterStartIndexBP; // Shift AS to be PS
933       }
934       else if((characterStartIndexBP <= alignIndex && alignIndex <= characterEndIndexBP) ||     /// ---PS.BBBBBBB.AS.BBBBBBB.PE---
935               (characterStartIndexBP <= alignEndIndex && alignEndIndex <= characterEndIndexBP)) /// ---PS.BBBBBB.AE.BBBBBBB.PE---
936       {
937         // Alignment from "Paragraph Start Index" to "Paragraph End Index" according to "BoundedParagraph Alignment"
938         decidedAlignStartIndex         = characterStartIndexBP;
939         decidedAlignNumberOfCharacters = numberOfCharactersBP;
940         decidedHorizontalAlignment     = boundedParagraphRun.horizontalAlignmentDefined ? boundedParagraphRun.horizontalAlignment : impl.mModel->mHorizontalAlignment;
941
942         alignIndex = characterEndIndexBP + 1u; // Shift AS to be after PE direct
943         boundedParagraphRunIndex++;            // Align then check the case of next bounded paragraph
944       }
945       else
946       {
947         boundedParagraphRunIndex++; // Check the case of next bounded paragraph
948         continue;
949       }
950
951       impl.mLayoutEngine.Align(size,
952                                decidedAlignStartIndex,
953                                decidedAlignNumberOfCharacters,
954                                decidedHorizontalAlignment,
955                                lines,
956                                impl.mModel->mAlignmentOffset,
957                                impl.mLayoutDirection,
958                                (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
959     }
960
961     //Align the remaining that is not aligned
962     if(alignIndex <= alignEndIndex)
963     {
964       impl.mLayoutEngine.Align(size,
965                                alignIndex,
966                                (alignEndIndex - alignIndex + 1u),
967                                impl.mModel->mHorizontalAlignment,
968                                lines,
969                                impl.mModel->mAlignmentOffset,
970                                impl.mLayoutDirection,
971                                (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
972     }
973   }
974 }
975
976 void Controller::Relayouter::CalculateVerticalOffset(Controller::Impl& impl, const Size& controlSize)
977 {
978   ModelPtr&       model                 = impl.mModel;
979   VisualModelPtr& visualModel           = model->mVisualModel;
980   Size            layoutSize            = model->mVisualModel->GetLayoutSize();
981   Size            oldLayoutSize         = layoutSize;
982   float           offsetY               = 0.f;
983   bool            needRecalc            = false;
984   float           defaultFontLineHeight = impl.GetDefaultFontLineHeight();
985
986   if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
987   {
988     // Get the line height of the default font.
989     layoutSize.height = defaultFontLineHeight;
990   }
991
992   // Whether the text control is editable
993   const bool isEditable = NULL != impl.mEventData;
994   if(isEditable && !Dali::Equals(layoutSize.height, defaultFontLineHeight) && impl.IsShowingPlaceholderText())
995   {
996     // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
997     // This situation occurs when the size of placeholder text is different from the default text.
998     layoutSize.height = defaultFontLineHeight;
999     needRecalc        = true;
1000   }
1001
1002   switch(model->mVerticalAlignment)
1003   {
1004     case VerticalAlignment::TOP:
1005     {
1006       model->mScrollPosition.y = 0.f;
1007       offsetY                  = 0.f;
1008       break;
1009     }
1010     case VerticalAlignment::CENTER:
1011     {
1012       model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
1013       if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
1014       break;
1015     }
1016     case VerticalAlignment::BOTTOM:
1017     {
1018       model->mScrollPosition.y = controlSize.height - layoutSize.height;
1019       if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
1020       break;
1021     }
1022   }
1023
1024   if(needRecalc)
1025   {
1026     // Update glyphPositions according to recalculation.
1027     const Length     positionCount  = visualModel->mGlyphPositions.Count();
1028     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
1029     for(Length index = 0u; index < positionCount; index++)
1030     {
1031       glyphPositions[index].y += offsetY;
1032     }
1033   }
1034 }
1035
1036 } // namespace Text
1037
1038 } // namespace Toolkit
1039
1040 } // namespace Dali