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