2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali-toolkit/internal/text/controller/text-controller-relayouter.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/integration-api/trace.h>
24 #include <dali/public-api/math/math-utils.h>
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>
34 #if defined(DEBUG_ENABLED)
35 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
38 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_TEXT_PERFORMANCE_MARKER, false);
39 DALI_INIT_TRACE_FILTER(gTraceFilter2, DALI_TRACE_PERFORMANCE_MARKER, false);
41 constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
43 float ConvertToEven(float value)
45 int intValue(static_cast<int>(value));
46 return static_cast<float>(intValue + (intValue & 1));
57 Size Controller::Relayouter::CalculateLayoutSizeOnRequiredControllerSize(Controller& controller, const Size& requestedControllerSize, const OperationsMask& requestedOperationsMask)
59 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->CalculateLayoutSizeOnRequiredControllerSize\n");
60 Size calculatedLayoutSize;
62 Controller::Impl& impl = *controller.mImpl;
63 ModelPtr& model = impl.mModel;
64 VisualModelPtr& visualModel = model->mVisualModel;
66 // Operations that can be done only once until the text changes.
67 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
75 const OperationsMask sizeOperations = static_cast<OperationsMask>(LAYOUT | ALIGN | REORDER);
77 // Set the update info to relayout the whole text.
78 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
79 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
80 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
81 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
83 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
85 textUpdateInfo.mParagraphCharacterIndex = 0u;
86 textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
88 // Get a reference to the pending operations member
89 OperationsMask& operationsPending = impl.mOperationsPending;
91 // Store the actual control's size to restore later.
92 const Size actualControlSize = visualModel->mControlSize;
94 // This is to keep Index to the first character to be updated.
95 // Then restore it after calling Clear method.
96 auto updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
98 // Whether the text control is editable
99 const bool isEditable = NULL != impl.mEventData;
103 if(NO_OPERATION != (VALIDATE_FONTS & operationsPending) &&
104 textUpdateInfo.mCharacterIndex == static_cast<CharacterIndex>(-1))
106 impl.ClearFontData();
107 updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
110 impl.UpdateModel(onlyOnceOperations);
112 // Layout the text for the new width.
113 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask);
116 requestedControllerSize,
117 static_cast<OperationsMask>(onlyOnceOperations | requestedOperationsMask),
118 calculatedLayoutSize);
120 textUpdateInfo.Clear();
121 textUpdateInfo.mClearAll = true;
123 // Do not do again the only once operations.
124 operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
128 // Layout the text for the new width.
129 // Apply the pending operations, requested operations and the only once operations.
130 // Then remove onlyOnceOperations
131 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask | onlyOnceOperations);
133 // Make sure the model is up-to-date before layouting
134 impl.UpdateModel(static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE));
137 requestedControllerSize,
138 static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE),
139 calculatedLayoutSize);
141 // Clear the update info. This info will be set the next time the text is updated.
142 textUpdateInfo.Clear();
144 //TODO: Refactor "DoRelayout" and extract common code of size calculation without modifying attributes of mVisualModel,
145 //TODO: then calculate GlyphPositions. Lines, Size, Layout for Natural-Size
146 //TODO: and utilize the values in OperationsPending and TextUpdateInfo without changing the original one.
147 //TODO: Also it will improve performance because there is no need todo FullRelyout on the next need for layouting.
150 // FullRelayoutNeeded should be true because DoRelayout is MAX_FLOAT, MAX_FLOAT.
151 // By this no need to take backup and restore it.
152 textUpdateInfo.mFullRelayoutNeeded = true;
154 // Restore mCharacterIndex. Because "Clear" set it to the maximum integer.
155 // The "CalculateTextUpdateIndices" does not work proprely because the mCharacterIndex will be greater than mPreviousNumberOfCharacters.
156 // Which apply an assumption to update only the last paragraph. That could cause many of out of index crashes.
157 textUpdateInfo.mCharacterIndex = updateInfoCharIndexBackup;
159 // Do the size related operations again.
160 operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
162 // Restore the actual control's size.
163 visualModel->mControlSize = actualControlSize;
165 return calculatedLayoutSize;
168 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
170 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
171 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_NATURAL_SIZE");
172 Vector3 naturalSizeVec3;
174 // Make sure the model is up-to-date before layouting
175 EventHandler::ProcessModifyEvents(controller);
177 Controller::Impl& impl = *controller.mImpl;
178 ModelPtr& model = impl.mModel;
179 VisualModelPtr& visualModel = model->mVisualModel;
181 if(impl.mRecalculateNaturalSize)
185 // Layout the text for the new width.
186 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT | REORDER);
187 Size sizeMaxWidthAndMaxHeight = Size(MAX_FLOAT, MAX_FLOAT);
189 naturalSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeMaxWidthAndMaxHeight, requestedOperationsMask);
191 // Stores the natural size to avoid recalculate it again
192 // unless the text/style changes.
193 visualModel->SetNaturalSize(naturalSize);
194 naturalSizeVec3 = naturalSize;
196 impl.mRecalculateNaturalSize = false;
198 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
202 naturalSizeVec3 = visualModel->GetNaturalSize();
204 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
207 naturalSizeVec3.x = ConvertToEven(naturalSizeVec3.x);
208 naturalSizeVec3.y = ConvertToEven(naturalSizeVec3.y);
210 return naturalSizeVec3;
213 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
216 Controller::Impl& impl = *controller.mImpl;
217 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
218 impl.mFontDefaults->mFitPointSize = pointSize;
219 impl.mFontDefaults->sizeDefined = true;
220 impl.ClearFontData();
222 // Operations that can be done only once until the text changes.
223 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
231 textUpdateInfo.mParagraphCharacterIndex = 0u;
232 textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
234 // Make sure the model is up-to-date before layouting
235 impl.UpdateModel(onlyOnceOperations);
238 Size(layoutSize.width, MAX_FLOAT),
239 static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
242 // Clear the update info. This info will be set the next time the text is updated.
243 textUpdateInfo.Clear();
244 textUpdateInfo.mClearAll = true;
246 if(textSize.width > layoutSize.width || textSize.height > layoutSize.height)
253 void Controller::Relayouter::FitArrayPointSizeforLayout(Controller& controller, const Size& layoutSize)
255 Controller::Impl& impl = *controller.mImpl;
257 const OperationsMask operations = impl.mOperationsPending;
258 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
260 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_ARRAY_LAYOUT");
261 std::vector<Toolkit::DevelTextLabel::FitOption> fitOptions = impl.mTextFitArray;
262 int numberOfFitOptions = static_cast<int>(fitOptions.size());
263 if(numberOfFitOptions == 0)
265 DALI_LOG_ERROR("fitOptions is empty\n");
269 ModelPtr& model = impl.mModel;
270 bool actualellipsis = model->mElideEnabled;
271 model->mElideEnabled = false;
273 // Sort in ascending order by PointSize.
274 std::sort(fitOptions.begin(), fitOptions.end(), compareByPointSize);
276 // Decide whether to use binary search.
277 // If MinLineSize is not sorted in ascending order,
278 // binary search cannot guarantee that it will always find the best value.
279 bool binarySearch = true;
280 float prevMinLineSize = 0.0f;
281 for(Toolkit::DevelTextLabel::FitOption& option : fitOptions)
283 float optionMinLineSize = option.GetMinLineSize();
284 if(prevMinLineSize > optionMinLineSize)
286 binarySearch = false;
289 prevMinLineSize = optionMinLineSize;
292 // Set the first FitOption(Minimum PointSize) to the best value.
293 // If the search does not find an optimal value, the minimum PointSize will be used to text fit.
294 Toolkit::DevelTextLabel::FitOption firstOption = fitOptions.front();
295 bool bestSizeUpdatedLatest = false;
296 float bestPointSize = firstOption.GetPointSize();
297 float bestMinLineSize = firstOption.GetMinLineSize();
302 int right = numberOfFitOptions - 1;
304 while (left <= right)
306 int mid = left + (right - left) / 2;
307 Toolkit::DevelTextLabel::FitOption option = fitOptions[mid];
308 float testPointSize = option.GetPointSize();
309 float testMinLineSize = option.GetMinLineSize();
310 impl.SetDefaultLineSize(testMinLineSize);
312 if(CheckForTextFit(controller, testPointSize, layoutSize))
314 bestSizeUpdatedLatest = true;
315 bestPointSize = testPointSize;
316 bestMinLineSize = testMinLineSize;
321 bestSizeUpdatedLatest = false;
328 // If binary search is not possible, search sequentially starting from the largest PointSize.
329 for(auto it = fitOptions.rbegin(); it != fitOptions.rend(); ++it)
331 Toolkit::DevelTextLabel::FitOption option = *it;
332 float testPointSize = option.GetPointSize();
333 float testMinLineSize = option.GetMinLineSize();
334 impl.SetDefaultLineSize(testMinLineSize);
336 if(CheckForTextFit(controller, testPointSize, layoutSize))
338 bestSizeUpdatedLatest = true;
339 bestPointSize = testPointSize;
340 bestMinLineSize = testMinLineSize;
345 bestSizeUpdatedLatest = false;
350 // Best point size was not updated. re-run so the TextFit should be fitted really.
351 if(!bestSizeUpdatedLatest)
353 impl.SetDefaultLineSize(bestMinLineSize);
354 CheckForTextFit(controller, bestPointSize, layoutSize);
357 model->mElideEnabled = actualellipsis;
358 impl.mFontDefaults->mFitPointSize = bestPointSize;
359 impl.mFontDefaults->sizeDefined = true;
360 impl.ClearFontData();
364 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
366 Controller::Impl& impl = *controller.mImpl;
368 const OperationsMask operations = impl.mOperationsPending;
369 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
371 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
372 ModelPtr& model = impl.mModel;
374 bool actualellipsis = model->mElideEnabled;
375 float minPointSize = impl.mTextFitMinSize;
376 float maxPointSize = impl.mTextFitMaxSize;
377 float pointInterval = impl.mTextFitStepSize;
378 float currentFitPointSize = impl.mFontDefaults->mFitPointSize;
379 float currentDefaultLineSize = impl.mLayoutEngine.GetDefaultLineSize();
380 // Instead of using the LineSize of the current TextLabel, the LineSize set in TextFit is used.
381 impl.SetDefaultLineSize(impl.mTextFitLineSize);
383 model->mElideEnabled = false;
386 if(pointInterval < 1.f)
388 impl.mTextFitStepSize = pointInterval = 1.0f;
390 uint32_t pointSizeRange = static_cast<uint32_t>(ceil((maxPointSize - minPointSize) / pointInterval));
392 // Ensure minPointSize + pointSizeRange * pointInverval >= maxPointSize
393 while(minPointSize + static_cast<float>(pointSizeRange) * pointInterval < maxPointSize)
398 uint32_t bestSizeIndex = 0;
399 uint32_t minIndex = bestSizeIndex + 1u;
400 uint32_t maxIndex = pointSizeRange + 1u;
402 bool bestSizeUpdatedLatest = false;
403 // Find best size as binary search.
404 // Range format as [l r). (left closed, right opened)
405 // It mean, we already check all i < l is valid, and r <= i is invalid.
406 // Below binary search will check m = (l+r)/2 point.
407 // Search area sperate as [l m) or [m+1 r)
409 // Basically, we can assume that 0 (minPointSize) is always valid.
410 // Now, we will check [1 pointSizeRange] range s.t. pointSizeRange mean the maxPointSize
411 while(minIndex < maxIndex)
413 uint32_t testIndex = minIndex + ((maxIndex - minIndex) >> 1u);
414 const float testPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(testIndex) * pointInterval);
416 if(CheckForTextFit(controller, testPointSize, layoutSize))
418 bestSizeUpdatedLatest = true;
420 bestSizeIndex = testIndex;
421 minIndex = testIndex + 1u;
425 bestSizeUpdatedLatest = false;
426 maxIndex = testIndex;
429 const float bestPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(bestSizeIndex) * pointInterval);
431 // Best point size was not updated. re-run so the TextFit should be fitted really.
432 if(!bestSizeUpdatedLatest)
434 CheckForTextFit(controller, bestPointSize, layoutSize);
437 model->mElideEnabled = actualellipsis;
438 if(!Dali::Equals(currentFitPointSize, bestPointSize))
440 impl.mTextFitChanged = true;
442 // Revert back to the original TextLabel LineSize.
443 impl.SetDefaultLineSize(currentDefaultLineSize);
444 impl.mFontDefaults->mFitPointSize = bestPointSize;
445 impl.mFontDefaults->sizeDefined = true;
446 impl.ClearFontData();
450 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
452 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
453 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
455 // Make sure the model is up-to-date before layouting
456 EventHandler::ProcessModifyEvents(controller);
458 Controller::Impl& impl = *controller.mImpl;
459 ModelPtr& model = impl.mModel;
460 VisualModelPtr& visualModel = model->mVisualModel;
461 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
464 Size layoutSize = visualModel->GetHeightForWidth();
466 if(fabsf(width - layoutSize.width) > Math::MACHINE_EPSILON_1000 ||
467 textUpdateInfo.mFullRelayoutNeeded ||
468 textUpdateInfo.mClearAll)
470 // Layout the text for the new width.
471 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT);
472 Size sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
474 layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
476 // The calculated layout width may not be the same as the requested width.
477 // For cache efficiency, the requested width is stored.
478 layoutSize.width = width;
479 visualModel->SetHeightForWidth(layoutSize);
481 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
485 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
488 return layoutSize.height;
491 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
493 Controller::Impl& impl = *controller.mImpl;
494 ModelPtr& model = impl.mModel;
495 VisualModelPtr& visualModel = model->mVisualModel;
496 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
498 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
499 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_RELAYOUT");
501 UpdateTextType updateTextType = NONE_UPDATED;
503 if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
505 if(0u != visualModel->mGlyphPositions.Count())
507 visualModel->mGlyphPositions.Clear();
508 updateTextType = MODEL_UPDATED;
511 // Clear the update info. This info will be set the next time the text is updated.
512 textUpdateInfo.Clear();
514 // Not worth to relayout if width or height is equal to zero.
515 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
517 return updateTextType;
520 // Whether a new size has been set.
521 const bool newSize = (size != visualModel->mControlSize);
523 // Get a reference to the pending operations member
524 OperationsMask& operationsPending = impl.mOperationsPending;
528 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
530 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
531 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
532 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
534 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
537 // Layout operations that need to be done if the size changes.
538 operationsPending = static_cast<OperationsMask>(operationsPending |
543 // Set the update info to relayout the whole text.
544 textUpdateInfo.mFullRelayoutNeeded = true;
545 textUpdateInfo.mCharacterIndex = 0u;
547 // Store the size used to layout the text.
548 visualModel->mControlSize = size;
551 // Whether there are modify events.
552 if(0u != impl.mModifyEvents.Count())
554 // Style operations that need to be done if the text is modified.
555 operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
558 // Set the update info to elide the text.
559 if(model->mElideEnabled ||
560 ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
562 // Update Text layout for applying elided
563 operationsPending = static_cast<OperationsMask>(operationsPending |
568 textUpdateInfo.mFullRelayoutNeeded = true;
569 textUpdateInfo.mCharacterIndex = 0u;
572 bool layoutDirectionChanged = false;
573 if(impl.mLayoutDirection != layoutDirection)
575 // Flag to indicate that the layout direction has changed.
576 layoutDirectionChanged = true;
577 // Clear the update info. This info will be set the next time the text is updated.
578 textUpdateInfo.mClearAll = true;
579 // Apply modifications to the model
580 // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
581 operationsPending = static_cast<OperationsMask>(operationsPending |
589 impl.mLayoutDirection = layoutDirection;
592 // Make sure the model is up-to-date before layouting.
593 EventHandler::ProcessModifyEvents(controller);
594 bool updated = impl.UpdateModel(operationsPending);
598 updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
602 updateTextType = MODEL_UPDATED;
605 // Do not re-do any operation until something changes.
606 operationsPending = NO_OPERATION;
607 model->mScrollPositionLast = model->mScrollPosition;
609 // Whether the text control is editable
610 const bool isEditable = NULL != impl.mEventData;
612 // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
614 if(newSize && isEditable)
616 offset = model->mScrollPosition;
619 if(!isEditable || !controller.IsMultiLineEnabled())
621 // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
622 CalculateVerticalOffset(impl, size);
626 // If layoutSize is bigger than size, vertical align has no meaning.
627 if(layoutSize.y < size.y)
629 CalculateVerticalOffset(impl, size);
632 impl.mEventData->mScrollAfterDelete = false;
639 if(newSize || layoutDirectionChanged)
641 // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
642 impl.ClampHorizontalScroll(layoutSize);
644 // Update the decorator's positions is needed if there is a new size.
645 impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
647 // All decorator elements need to be updated.
648 if(EventData::IsEditingState(impl.mEventData->mState))
650 impl.mEventData->mScrollAfterUpdatePosition = true;
651 impl.mEventData->mUpdateCursorPosition = true;
652 impl.mEventData->mUpdateGrabHandlePosition = true;
654 else if(impl.mEventData->mState == EventData::SELECTING)
656 impl.mEventData->mUpdateHighlightBox = true;
660 // Move the cursor, grab handle etc.
661 if(impl.ProcessInputEvents())
663 updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
667 // Clear the update info. This info will be set the next time the text is updated.
668 textUpdateInfo.Clear();
669 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
671 return updateTextType;
674 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
676 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
677 DALI_TRACE_SCOPE(gTraceFilter2, "DALI_TEXT_DORELAYOUT");
678 bool viewUpdated(false);
680 // Calculate the operations to be done.
681 const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
683 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
684 const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
685 const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
687 // Get the current layout size.
688 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
689 layoutSize = visualModel->GetLayoutSize();
691 if(NO_OPERATION != (LAYOUT & operations))
693 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
695 // Some vectors with data needed to layout and reorder may be void
696 // after the first time the text has been laid out.
697 // Fill the vectors again.
699 // Calculate the number of glyphs to layout.
700 const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
701 const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
702 const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
703 const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
705 const CharacterIndex lastIndex = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
706 const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
708 // Make sure the index is not out of bound
709 if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
710 requestedNumberOfCharacters > charactersToGlyph.Count() ||
711 (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
713 std::string currentText;
714 impl.GetText(currentText);
716 DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
717 DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
718 DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
723 const Length numberOfGlyphs = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
724 const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
726 if(0u == totalNumberOfGlyphs)
728 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
730 visualModel->SetLayoutSize(Size::ZERO);
733 // Nothing else to do if there is no glyphs.
734 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
738 // Set the layout parameters.
739 Layout::Parameters layoutParameters(size, impl.mModel);
741 // Resize the vector of positions to have the same size than the vector of glyphs.
742 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
743 glyphPositions.Resize(totalNumberOfGlyphs);
745 // Whether the last character is a new paragraph character.
746 const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
747 textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
748 layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
750 // The initial glyph and the number of glyphs to layout.
751 layoutParameters.startGlyphIndex = startGlyphIndex;
752 layoutParameters.numberOfGlyphs = numberOfGlyphs;
753 layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
754 layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
756 // Update the ellipsis
757 bool elideTextEnabled = impl.mModel->mElideEnabled;
758 auto ellipsisPosition = impl.mModel->mEllipsisPosition;
760 if(NULL != impl.mEventData)
762 if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
764 elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
766 else if(EventData::INACTIVE != impl.mEventData->mState)
768 // Disable ellipsis when editing
769 elideTextEnabled = false;
772 // Reset the scroll position in inactive state
773 if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
775 impl.ResetScrollPosition();
779 // Update the visual model.
780 bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
781 bool isAutoScrollMaxTextureExceeded = impl.mIsAutoScrollMaxTextureExceeded;
782 bool isHiddenInputEnabled = false;
783 if(impl.mHiddenInput && impl.mEventData != nullptr && impl.mHiddenInput->GetHideMode() != Toolkit::HiddenInput::Mode::HIDE_NONE)
785 isHiddenInputEnabled = true;
789 viewUpdated = impl.mLayoutEngine.LayoutText(layoutParameters,
793 isAutoScrollMaxTextureExceeded,
794 isHiddenInputEnabled,
796 impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
798 viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
802 layoutSize = newLayoutSize;
804 if(NO_OPERATION != (UPDATE_DIRECTION & operations))
806 impl.mIsTextDirectionRTL = false;
809 if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
811 impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
814 // Sets the layout size.
815 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
817 visualModel->SetLayoutSize(layoutSize);
822 if(NO_OPERATION != (ALIGN & operations))
824 DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
827 #if defined(DEBUG_ENABLED)
828 std::string currentText;
829 impl.GetText(currentText);
830 DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
832 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
836 void Controller::Relayouter::DoRelayoutHorizontalAlignment(Controller::Impl& impl,
838 const CharacterIndex startIndex,
839 const Length requestedNumberOfCharacters)
842 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
844 // The laid-out lines.
845 Vector<LineRun>& lines = visualModel->mLines;
847 CharacterIndex alignStartIndex = startIndex;
848 Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
850 // the whole text needs to be full aligned.
851 // If you do not do a full aligned, only the last line of the multiline input is aligned.
852 if(impl.mEventData && impl.mEventData->mUpdateAlignment)
854 alignStartIndex = 0u;
855 alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
856 impl.mEventData->mUpdateAlignment = false;
859 // If there is no BoundedParagraphRuns then apply the alignment of controller.
860 // Check whether the layout is single line. It's needed to apply one alignment for single-line.
861 // In single-line layout case we need to check whether to follow the alignment of controller or the first BoundedParagraph.
862 // Apply BoundedParagraph's alignment if and only if there is one BoundedParagraph contains all characters. Otherwise follow controller's alignment.
863 const bool isFollowControllerAlignment = ((impl.mModel->GetNumberOfBoundedParagraphRuns() == 0u) ||
864 ((Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) &&
865 (impl.mModel->GetBoundedParagraphRuns()[0].characterRun.numberOfCharacters != impl.mModel->mLogicalModel->mText.Count())));
867 if(isFollowControllerAlignment)
869 // Need to align with the control's size as the text may contain lines
870 // starting either with left to right text or right to left.
871 impl.mLayoutEngine.Align(size,
873 alignRequestedNumberOfCharacters,
874 impl.mModel->mHorizontalAlignment,
876 impl.mModel->mAlignmentOffset,
877 impl.mLayoutDirection,
878 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
882 //Override the controller horizontal-alignment by horizontal-alignment of bounded paragraph.
883 const Length& numberOfBoundedParagraphRuns = impl.mModel->GetNumberOfBoundedParagraphRuns();
884 const Vector<BoundedParagraphRun>& boundedParagraphRuns = impl.mModel->GetBoundedParagraphRuns();
885 const CharacterIndex alignEndIndex = alignStartIndex + alignRequestedNumberOfCharacters - 1u;
887 Length alignIndex = alignStartIndex;
888 Length boundedParagraphRunIndex = 0u;
890 while(alignIndex <= alignEndIndex && boundedParagraphRunIndex < numberOfBoundedParagraphRuns)
892 //BP: BoundedParagraph
893 const BoundedParagraphRun& boundedParagraphRun = boundedParagraphRuns[boundedParagraphRunIndex];
894 const CharacterIndex& characterStartIndexBP = boundedParagraphRun.characterRun.characterIndex;
895 const Length& numberOfCharactersBP = boundedParagraphRun.characterRun.numberOfCharacters;
896 const CharacterIndex characterEndIndexBP = characterStartIndexBP + numberOfCharactersBP - 1u;
898 CharacterIndex decidedAlignStartIndex = alignIndex;
899 Length decidedAlignNumberOfCharacters = alignEndIndex - alignIndex + 1u;
900 Text::HorizontalAlignment::Type decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
903 * Shortcuts to explain indexes cases:
905 * AS: Alignment Start Index
906 * AE: Alignment End Index
907 * PS: Paragraph Start Index
908 * PE: Paragraph End Index
909 * B: BoundedParagraph Alignment
914 if(alignIndex < characterStartIndexBP && characterStartIndexBP <= alignEndIndex) /// AS.MMMMMM.PS--------AE
916 // Alignment from "Alignment Start Index" to index before "Paragraph Start Index" according to "Model Alignment"
917 decidedAlignStartIndex = alignIndex;
918 decidedAlignNumberOfCharacters = characterStartIndexBP - alignIndex;
919 decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
921 // Need to re-heck the case of current bounded paragraph
922 alignIndex = characterStartIndexBP; // Shift AS to be PS
924 else if((characterStartIndexBP <= alignIndex && alignIndex <= characterEndIndexBP) || /// ---PS.BBBBBBB.AS.BBBBBBB.PE---
925 (characterStartIndexBP <= alignEndIndex && alignEndIndex <= characterEndIndexBP)) /// ---PS.BBBBBB.AE.BBBBBBB.PE---
927 // Alignment from "Paragraph Start Index" to "Paragraph End Index" according to "BoundedParagraph Alignment"
928 decidedAlignStartIndex = characterStartIndexBP;
929 decidedAlignNumberOfCharacters = numberOfCharactersBP;
930 decidedHorizontalAlignment = boundedParagraphRun.horizontalAlignmentDefined ? boundedParagraphRun.horizontalAlignment : impl.mModel->mHorizontalAlignment;
932 alignIndex = characterEndIndexBP + 1u; // Shift AS to be after PE direct
933 boundedParagraphRunIndex++; // Align then check the case of next bounded paragraph
937 boundedParagraphRunIndex++; // Check the case of next bounded paragraph
941 impl.mLayoutEngine.Align(size,
942 decidedAlignStartIndex,
943 decidedAlignNumberOfCharacters,
944 decidedHorizontalAlignment,
946 impl.mModel->mAlignmentOffset,
947 impl.mLayoutDirection,
948 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
951 //Align the remaining that is not aligned
952 if(alignIndex <= alignEndIndex)
954 impl.mLayoutEngine.Align(size,
956 (alignEndIndex - alignIndex + 1u),
957 impl.mModel->mHorizontalAlignment,
959 impl.mModel->mAlignmentOffset,
960 impl.mLayoutDirection,
961 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
966 void Controller::Relayouter::CalculateVerticalOffset(Controller::Impl& impl, const Size& controlSize)
968 ModelPtr& model = impl.mModel;
969 VisualModelPtr& visualModel = model->mVisualModel;
970 Size layoutSize = model->mVisualModel->GetLayoutSize();
971 Size oldLayoutSize = layoutSize;
973 bool needRecalc = false;
974 float defaultFontLineHeight = impl.GetDefaultFontLineHeight();
976 if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
978 // Get the line height of the default font.
979 layoutSize.height = defaultFontLineHeight;
982 // Whether the text control is editable
983 const bool isEditable = NULL != impl.mEventData;
984 if(isEditable && !Dali::Equals(layoutSize.height, defaultFontLineHeight) && impl.IsShowingPlaceholderText())
986 // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
987 // This situation occurs when the size of placeholder text is different from the default text.
988 layoutSize.height = defaultFontLineHeight;
992 switch(model->mVerticalAlignment)
994 case VerticalAlignment::TOP:
996 model->mScrollPosition.y = 0.f;
1000 case VerticalAlignment::CENTER:
1002 model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
1003 if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
1006 case VerticalAlignment::BOTTOM:
1008 model->mScrollPosition.y = controlSize.height - layoutSize.height;
1009 if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
1016 // Update glyphPositions according to recalculation.
1017 const Length positionCount = visualModel->mGlyphPositions.Count();
1018 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
1019 for(Length index = 0u; index < positionCount; index++)
1021 glyphPositions[index].y += offsetY;
1028 } // namespace Toolkit