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