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