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