[Text] Add some more trace marker for text
[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_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     impl.UpdateModel(onlyOnceOperations);
103
104     // Layout the text for the new width.
105     operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask);
106
107     DoRelayout(impl,
108                requestedControllerSize,
109                static_cast<OperationsMask>(onlyOnceOperations | requestedOperationsMask),
110                calculatedLayoutSize);
111
112     textUpdateInfo.Clear();
113     textUpdateInfo.mClearAll = true;
114
115     // Do not do again the only once operations.
116     operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
117   }
118   else
119   {
120     // Layout the text for the new width.
121     // Apply the pending operations, requested operations and the only once operations.
122     // Then remove onlyOnceOperations
123     operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask | onlyOnceOperations);
124
125     // Make sure the model is up-to-date before layouting
126     impl.UpdateModel(static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE));
127
128     DoRelayout(impl,
129                requestedControllerSize,
130                static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE),
131                calculatedLayoutSize);
132
133     // Clear the update info. This info will be set the next time the text is updated.
134     textUpdateInfo.Clear();
135
136     //TODO: Refactor "DoRelayout" and extract common code of size calculation without modifying attributes of mVisualModel,
137     //TODO: then calculate GlyphPositions. Lines, Size, Layout for Natural-Size
138     //TODO: and utilize the values in OperationsPending and TextUpdateInfo without changing the original one.
139     //TODO: Also it will improve performance because there is no need todo FullRelyout on the next need for layouting.
140   }
141
142   // FullRelayoutNeeded should be true because DoRelayout is MAX_FLOAT, MAX_FLOAT.
143   // By this no need to take backup and restore it.
144   textUpdateInfo.mFullRelayoutNeeded = true;
145
146   // Restore mCharacterIndex. Because "Clear" set it to the maximum integer.
147   // The "CalculateTextUpdateIndices" does not work proprely because the mCharacterIndex will be greater than mPreviousNumberOfCharacters.
148   // Which apply an assumption to update only the last  paragraph. That could cause many of out of index crashes.
149   textUpdateInfo.mCharacterIndex = updateInfoCharIndexBackup;
150
151   // Do the size related operations again.
152   operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
153
154   // Restore the actual control's size.
155   visualModel->mControlSize = actualControlSize;
156
157   return calculatedLayoutSize;
158 }
159
160 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
161 {
162   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
163   DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_GET_NATURAL_SIZE");
164   Vector3 naturalSizeVec3;
165
166   // Make sure the model is up-to-date before layouting
167   EventHandler::ProcessModifyEvents(controller);
168
169   Controller::Impl& impl        = *controller.mImpl;
170   ModelPtr&         model       = impl.mModel;
171   VisualModelPtr&   visualModel = model->mVisualModel;
172
173   if(impl.mRecalculateNaturalSize)
174   {
175     Size naturalSize;
176
177     // Layout the text for the new width.
178     OperationsMask requestedOperationsMask  = static_cast<OperationsMask>(LAYOUT | REORDER);
179     Size           sizeMaxWidthAndMaxHeight = Size(MAX_FLOAT, MAX_FLOAT);
180
181     naturalSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeMaxWidthAndMaxHeight, requestedOperationsMask);
182
183     // Stores the natural size to avoid recalculate it again
184     // unless the text/style changes.
185     visualModel->SetNaturalSize(naturalSize);
186     naturalSizeVec3 = naturalSize;
187
188     impl.mRecalculateNaturalSize = false;
189
190     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
191   }
192   else
193   {
194     naturalSizeVec3 = visualModel->GetNaturalSize();
195
196     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
197   }
198
199   naturalSizeVec3.x = ConvertToEven(naturalSizeVec3.x);
200   naturalSizeVec3.y = ConvertToEven(naturalSizeVec3.y);
201
202   DALI_TRACE_END(gTraceFilter, "DALI_TEXT_GET_NATURAL_SIZE");
203
204   return naturalSizeVec3;
205 }
206
207 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
208 {
209   Size              textSize;
210   Controller::Impl& impl            = *controller.mImpl;
211   TextUpdateInfo&   textUpdateInfo  = impl.mTextUpdateInfo;
212   impl.mFontDefaults->mFitPointSize = pointSize;
213   impl.mFontDefaults->sizeDefined   = true;
214   impl.ClearFontData();
215
216   // Operations that can be done only once until the text changes.
217   const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
218                                                                         GET_SCRIPTS |
219                                                                         VALIDATE_FONTS |
220                                                                         GET_LINE_BREAKS |
221                                                                         BIDI_INFO |
222                                                                         SHAPE_TEXT |
223                                                                         GET_GLYPH_METRICS);
224
225   textUpdateInfo.mParagraphCharacterIndex     = 0u;
226   textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
227
228   // Make sure the model is up-to-date before layouting
229   impl.UpdateModel(onlyOnceOperations);
230
231   DoRelayout(impl,
232              Size(layoutSize.width, MAX_FLOAT),
233              static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
234              textSize);
235
236   // Clear the update info. This info will be set the next time the text is updated.
237   textUpdateInfo.Clear();
238   textUpdateInfo.mClearAll = true;
239
240   if(textSize.width >= layoutSize.width || textSize.height >= layoutSize.height)
241   {
242     return false;
243   }
244   return true;
245 }
246
247 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
248 {
249   Controller::Impl& impl = *controller.mImpl;
250
251   const OperationsMask operations = impl.mOperationsPending;
252   if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
253   {
254     DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
255     ModelPtr& model = impl.mModel;
256
257     bool  actualellipsis      = model->mElideEnabled;
258     float minPointSize        = impl.mTextFitMinSize;
259     float maxPointSize        = impl.mTextFitMaxSize;
260     float pointInterval       = impl.mTextFitStepSize;
261     float currentFitPointSize = impl.mFontDefaults->mFitPointSize;
262
263     model->mElideEnabled = false;
264
265     // check zero value
266     if(pointInterval < 1.f)
267     {
268       impl.mTextFitStepSize = pointInterval = 1.0f;
269     }
270     uint32_t pointSizeRange = static_cast<uint32_t>(ceil((maxPointSize - minPointSize) / pointInterval));
271
272     // Ensure minPointSize + pointSizeRange * pointInverval >= maxPointSize
273     while(minPointSize + static_cast<float>(pointSizeRange) * pointInterval < maxPointSize)
274     {
275       ++pointSizeRange;
276     }
277
278     uint32_t bestSizeIndex = 0;
279     uint32_t minIndex      = bestSizeIndex + 1u;
280     uint32_t maxIndex      = pointSizeRange + 1u;
281
282     bool bestSizeUpdatedLatest = false;
283     // Find best size as binary search.
284     // Range format as [l r). (left closed, right opened)
285     // It mean, we already check all i < l is valid, and r <= i is invalid.
286     // Below binary search will check m = (l+r)/2 point.
287     // Search area sperate as [l m) or [m+1 r)
288     //
289     // Basically, we can assume that 0 (minPointSize) is always valid.
290     // Now, we will check [1 pointSizeRange] range s.t. pointSizeRange mean the maxPointSize
291     while(minIndex < maxIndex)
292     {
293       uint32_t    testIndex     = minIndex + ((maxIndex - minIndex) >> 1u);
294       const float testPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(testIndex) * pointInterval);
295
296       if(CheckForTextFit(controller, testPointSize, layoutSize))
297       {
298         bestSizeUpdatedLatest = true;
299
300         bestSizeIndex = testIndex;
301         minIndex      = testIndex + 1u;
302       }
303       else
304       {
305         bestSizeUpdatedLatest = false;
306         maxIndex              = testIndex;
307       }
308     }
309     const float bestPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(bestSizeIndex) * pointInterval);
310
311     // Best point size was not updated. re-run so the TextFit should be fitted really.
312     if(!bestSizeUpdatedLatest)
313     {
314       CheckForTextFit(controller, bestPointSize, layoutSize);
315     }
316
317     model->mElideEnabled = actualellipsis;
318     if(!Dali::Equals(currentFitPointSize, bestPointSize))
319     {
320       impl.mTextFitChanged = true;
321     }
322     impl.mFontDefaults->mFitPointSize = bestPointSize;
323     impl.mFontDefaults->sizeDefined   = true;
324     impl.ClearFontData();
325
326     DALI_TRACE_END(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
327   }
328 }
329
330 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
331 {
332   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
333   DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
334
335   // Make sure the model is up-to-date before layouting
336   EventHandler::ProcessModifyEvents(controller);
337
338   Controller::Impl& impl           = *controller.mImpl;
339   ModelPtr&         model          = impl.mModel;
340   VisualModelPtr&   visualModel    = model->mVisualModel;
341   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
342
343   Size layoutSize;
344
345   if(fabsf(width - visualModel->mControlSize.width) > Math::MACHINE_EPSILON_1000 ||
346      textUpdateInfo.mFullRelayoutNeeded ||
347      textUpdateInfo.mClearAll)
348   {
349     // Layout the text for the new width.
350     OperationsMask requestedOperationsMask        = static_cast<OperationsMask>(LAYOUT);
351     Size           sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
352
353     layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
354
355     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
356   }
357   else
358   {
359     layoutSize = visualModel->GetLayoutSize();
360     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
361   }
362
363   DALI_TRACE_END(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
364
365   return layoutSize.height;
366 }
367
368 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
369 {
370   Controller::Impl& impl           = *controller.mImpl;
371   ModelPtr&         model          = impl.mModel;
372   VisualModelPtr&   visualModel    = model->mVisualModel;
373   TextUpdateInfo&   textUpdateInfo = impl.mTextUpdateInfo;
374
375   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
376   DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_RELAYOUT");
377
378   UpdateTextType updateTextType = NONE_UPDATED;
379
380   if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
381   {
382     if(0u != visualModel->mGlyphPositions.Count())
383     {
384       visualModel->mGlyphPositions.Clear();
385       updateTextType = MODEL_UPDATED;
386     }
387
388     // Clear the update info. This info will be set the next time the text is updated.
389     textUpdateInfo.Clear();
390
391     // Not worth to relayout if width or height is equal to zero.
392     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
393     DALI_TRACE_END(gTraceFilter, "DALI_TEXT_RELAYOUT");
394
395     return updateTextType;
396   }
397
398   // Whether a new size has been set.
399   const bool newSize = (size != visualModel->mControlSize);
400
401   // Get a reference to the pending operations member
402   OperationsMask& operationsPending = impl.mOperationsPending;
403
404   if(newSize)
405   {
406     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
407
408     if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
409        (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
410        ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
411     {
412       textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
413     }
414
415     // Layout operations that need to be done if the size changes.
416     operationsPending = static_cast<OperationsMask>(operationsPending |
417                                                     LAYOUT |
418                                                     ALIGN |
419                                                     UPDATE_LAYOUT_SIZE |
420                                                     REORDER);
421     // Set the update info to relayout the whole text.
422     textUpdateInfo.mFullRelayoutNeeded = true;
423     textUpdateInfo.mCharacterIndex     = 0u;
424
425     // Store the size used to layout the text.
426     visualModel->mControlSize = size;
427   }
428
429   // Whether there are modify events.
430   if(0u != impl.mModifyEvents.Count())
431   {
432     // Style operations that need to be done if the text is modified.
433     operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
434   }
435
436   // Set the update info to elide the text.
437   if(model->mElideEnabled ||
438      ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
439   {
440     // Update Text layout for applying elided
441     operationsPending                  = static_cast<OperationsMask>(operationsPending |
442                                                     ALIGN |
443                                                     LAYOUT |
444                                                     UPDATE_LAYOUT_SIZE |
445                                                     REORDER);
446     textUpdateInfo.mFullRelayoutNeeded = true;
447     textUpdateInfo.mCharacterIndex     = 0u;
448   }
449
450   bool layoutDirectionChanged = false;
451   if(impl.mLayoutDirection != layoutDirection)
452   {
453     // Flag to indicate that the layout direction has changed.
454     layoutDirectionChanged = true;
455     // Clear the update info. This info will be set the next time the text is updated.
456     textUpdateInfo.mClearAll = true;
457     // Apply modifications to the model
458     // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
459     operationsPending     = static_cast<OperationsMask>(operationsPending |
460                                                     GET_GLYPH_METRICS |
461                                                     SHAPE_TEXT |
462                                                     UPDATE_DIRECTION |
463                                                     ALIGN |
464                                                     LAYOUT |
465                                                     BIDI_INFO |
466                                                     REORDER);
467     impl.mLayoutDirection = layoutDirection;
468   }
469
470   // Make sure the model is up-to-date before layouting.
471   EventHandler::ProcessModifyEvents(controller);
472   bool updated = impl.UpdateModel(operationsPending);
473
474   // Layout the text.
475   Size layoutSize;
476   updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
477
478   if(updated)
479   {
480     updateTextType = MODEL_UPDATED;
481   }
482
483   // Do not re-do any operation until something changes.
484   operationsPending          = NO_OPERATION;
485   model->mScrollPositionLast = model->mScrollPosition;
486
487   // Whether the text control is editable
488   const bool isEditable = NULL != impl.mEventData;
489
490   // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
491   Vector2 offset;
492   if(newSize && isEditable)
493   {
494     offset = model->mScrollPosition;
495   }
496
497   if(!isEditable || !controller.IsMultiLineEnabled())
498   {
499     // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
500     CalculateVerticalOffset(impl, size);
501   }
502   else // TextEditor
503   {
504     // If layoutSize is bigger than size, vertical align has no meaning.
505     if(layoutSize.y < size.y)
506     {
507       CalculateVerticalOffset(impl, size);
508       if(impl.mEventData)
509       {
510         impl.mEventData->mScrollAfterDelete = false;
511       }
512     }
513   }
514
515   if(isEditable)
516   {
517     if(newSize || layoutDirectionChanged)
518     {
519       // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
520       impl.ClampHorizontalScroll(layoutSize);
521
522       // Update the decorator's positions is needed if there is a new size.
523       impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
524
525       // All decorator elements need to be updated.
526       if(EventData::IsEditingState(impl.mEventData->mState))
527       {
528         impl.mEventData->mScrollAfterUpdatePosition = true;
529         impl.mEventData->mUpdateCursorPosition      = true;
530         impl.mEventData->mUpdateGrabHandlePosition  = true;
531       }
532       else if(impl.mEventData->mState == EventData::SELECTING)
533       {
534         impl.mEventData->mUpdateHighlightBox = true;
535       }
536     }
537
538     // Move the cursor, grab handle etc.
539     if(impl.ProcessInputEvents())
540     {
541       updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
542     }
543   }
544
545   // Clear the update info. This info will be set the next time the text is updated.
546   textUpdateInfo.Clear();
547   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
548   DALI_TRACE_END(gTraceFilter, "DALI_TEXT_RELAYOUT");
549
550   return updateTextType;
551 }
552
553 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
554 {
555   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
556   DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_DORELAYOUT");
557   bool viewUpdated(false);
558
559   // Calculate the operations to be done.
560   const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
561
562   TextUpdateInfo&      textUpdateInfo              = impl.mTextUpdateInfo;
563   const CharacterIndex startIndex                  = textUpdateInfo.mParagraphCharacterIndex;
564   const Length         requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
565
566   // Get the current layout size.
567   VisualModelPtr& visualModel = impl.mModel->mVisualModel;
568   layoutSize                  = visualModel->GetLayoutSize();
569
570   if(NO_OPERATION != (LAYOUT & operations))
571   {
572     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
573
574     // Some vectors with data needed to layout and reorder may be void
575     // after the first time the text has been laid out.
576     // Fill the vectors again.
577
578     // Calculate the number of glyphs to layout.
579     const Vector<GlyphIndex>& charactersToGlyph        = visualModel->mCharactersToGlyph;
580     const Vector<Length>&     glyphsPerCharacter       = visualModel->mGlyphsPerCharacter;
581     const GlyphIndex* const   charactersToGlyphBuffer  = charactersToGlyph.Begin();
582     const Length* const       glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
583
584     const CharacterIndex lastIndex       = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
585     const GlyphIndex     startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
586
587     // Make sure the index is not out of bound
588     if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
589        requestedNumberOfCharacters > charactersToGlyph.Count() ||
590        (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
591     {
592       std::string currentText;
593       impl.GetText(currentText);
594
595       DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
596       DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
597       DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
598
599       DALI_TRACE_END(gTraceFilter, "DALI_TEXT_DORELAYOUT");
600
601       return false;
602     }
603
604     const Length numberOfGlyphs      = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
605     const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
606
607     if(0u == totalNumberOfGlyphs)
608     {
609       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
610       {
611         visualModel->SetLayoutSize(Size::ZERO);
612       }
613
614       // Nothing else to do if there is no glyphs.
615       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
616       DALI_TRACE_END(gTraceFilter, "DALI_TEXT_DORELAYOUT");
617       return true;
618     }
619
620     // Set the layout parameters.
621     Layout::Parameters layoutParameters(size, impl.mModel);
622
623     // Resize the vector of positions to have the same size than the vector of glyphs.
624     Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
625     glyphPositions.Resize(totalNumberOfGlyphs);
626
627     // Whether the last character is a new paragraph character.
628     const Character* const textBuffer           = impl.mModel->mLogicalModel->mText.Begin();
629     textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
630     layoutParameters.isLastNewParagraph         = textUpdateInfo.mIsLastCharacterNewParagraph;
631
632     // The initial glyph and the number of glyphs to layout.
633     layoutParameters.startGlyphIndex        = startGlyphIndex;
634     layoutParameters.numberOfGlyphs         = numberOfGlyphs;
635     layoutParameters.startLineIndex         = textUpdateInfo.mStartLineIndex;
636     layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
637
638     // Update the ellipsis
639     bool elideTextEnabled = impl.mModel->mElideEnabled;
640     auto ellipsisPosition = impl.mModel->mEllipsisPosition;
641
642     if(NULL != impl.mEventData)
643     {
644       if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
645       {
646         elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
647       }
648       else if(EventData::INACTIVE != impl.mEventData->mState)
649       {
650         // Disable ellipsis when editing
651         elideTextEnabled = false;
652       }
653
654       // Reset the scroll position in inactive state
655       if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
656       {
657         impl.ResetScrollPosition();
658       }
659     }
660
661     // Update the visual model.
662     bool isAutoScrollEnabled            = impl.mIsAutoScrollEnabled;
663     bool isAutoScrollMaxTextureExceeded = impl.mIsAutoScrollMaxTextureExceeded;
664     bool isHiddenInputEnabled           = false;
665     if(impl.mHiddenInput && impl.mEventData != nullptr && impl.mHiddenInput->GetHideMode() != Toolkit::HiddenInput::Mode::HIDE_NONE)
666     {
667       isHiddenInputEnabled = true;
668     }
669
670     Size newLayoutSize;
671     viewUpdated               = impl.mLayoutEngine.LayoutText(layoutParameters,
672                                                 newLayoutSize,
673                                                 elideTextEnabled,
674                                                 isAutoScrollEnabled,
675                                                 isAutoScrollMaxTextureExceeded,
676                                                 isHiddenInputEnabled,
677                                                 ellipsisPosition);
678     impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
679
680     viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
681
682     if(viewUpdated)
683     {
684       layoutSize = newLayoutSize;
685
686       if(NO_OPERATION != (UPDATE_DIRECTION & operations))
687       {
688         impl.mIsTextDirectionRTL = false;
689       }
690
691       if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
692       {
693         impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
694       }
695
696       // Sets the layout size.
697       if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
698       {
699         visualModel->SetLayoutSize(layoutSize);
700       }
701     } // view updated
702   }
703
704   if(NO_OPERATION != (ALIGN & operations))
705   {
706     DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
707     viewUpdated = true;
708   }
709 #if defined(DEBUG_ENABLED)
710   std::string currentText;
711   impl.GetText(currentText);
712   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
713 #endif
714   DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
715   DALI_TRACE_END(gTraceFilter, "DALI_TEXT_DORELAYOUT");
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