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