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