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>
23 #include <dali/integration-api/debug.h>
24 #include <dali/integration-api/trace.h>
25 #include <dali/public-api/common/constants.h>
26 #include <dali/public-api/math/math-utils.h>
30 #include <dali-toolkit/internal/text/controller/text-controller-event-handler.h>
31 #include <dali-toolkit/internal/text/controller/text-controller-impl.h>
32 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
36 #if defined(DEBUG_ENABLED)
37 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
40 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_TEXT_PERFORMANCE_MARKER, false);
41 DALI_INIT_TRACE_FILTER(gTraceFilter2, DALI_TRACE_PERFORMANCE_MARKER, false);
43 constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
45 float ConvertToEven(float value)
47 int intValue(static_cast<int>(value));
48 return static_cast<float>(intValue + (intValue & 1));
59 Size Controller::Relayouter::CalculateLayoutSizeOnRequiredControllerSize(Controller& controller, const Size& requestedControllerSize, const OperationsMask& requestedOperationsMask)
61 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->CalculateLayoutSizeOnRequiredControllerSize\n");
62 Size calculatedLayoutSize;
64 Controller::Impl& impl = *controller.mImpl;
65 ModelPtr& model = impl.mModel;
66 VisualModelPtr& visualModel = model->mVisualModel;
68 // Operations that can be done only once until the text changes.
69 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
77 const OperationsMask sizeOperations = static_cast<OperationsMask>(LAYOUT | ALIGN | REORDER);
79 // Set the update info to relayout the whole text.
80 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
81 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
82 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
83 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
85 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
87 textUpdateInfo.mParagraphCharacterIndex = 0u;
88 textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
90 // Get a reference to the pending operations member
91 OperationsMask& operationsPending = impl.mOperationsPending;
93 // Store the actual control's size to restore later.
94 const Size actualControlSize = visualModel->mControlSize;
96 // This is to keep Index to the first character to be updated.
97 // Then restore it after calling Clear method.
98 auto updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
100 // Whether the text control is editable
101 const bool isEditable = NULL != impl.mEventData;
105 if(NO_OPERATION != (VALIDATE_FONTS & operationsPending) &&
106 textUpdateInfo.mCharacterIndex == static_cast<CharacterIndex>(-1))
108 impl.ClearFontData();
109 updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
112 impl.UpdateModel(onlyOnceOperations);
114 // Layout the text for the new width.
115 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask);
118 requestedControllerSize,
119 static_cast<OperationsMask>(onlyOnceOperations | requestedOperationsMask),
120 calculatedLayoutSize);
122 textUpdateInfo.Clear();
123 textUpdateInfo.mClearAll = true;
125 // Do not do again the only once operations.
126 operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
130 // Layout the text for the new width.
131 // Apply the pending operations, requested operations and the only once operations.
132 // Then remove onlyOnceOperations
133 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask | onlyOnceOperations);
135 // Make sure the model is up-to-date before layouting
136 impl.UpdateModel(static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE));
139 requestedControllerSize,
140 static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE),
141 calculatedLayoutSize);
143 // Clear the update info. This info will be set the next time the text is updated.
144 textUpdateInfo.Clear();
146 //TODO: Refactor "DoRelayout" and extract common code of size calculation without modifying attributes of mVisualModel,
147 //TODO: then calculate GlyphPositions. Lines, Size, Layout for Natural-Size
148 //TODO: and utilize the values in OperationsPending and TextUpdateInfo without changing the original one.
149 //TODO: Also it will improve performance because there is no need todo FullRelyout on the next need for layouting.
152 // FullRelayoutNeeded should be true because DoRelayout is MAX_FLOAT, MAX_FLOAT.
153 // By this no need to take backup and restore it.
154 textUpdateInfo.mFullRelayoutNeeded = true;
156 // Restore mCharacterIndex. Because "Clear" set it to the maximum integer.
157 // The "CalculateTextUpdateIndices" does not work proprely because the mCharacterIndex will be greater than mPreviousNumberOfCharacters.
158 // Which apply an assumption to update only the last paragraph. That could cause many of out of index crashes.
159 textUpdateInfo.mCharacterIndex = updateInfoCharIndexBackup;
161 // Do the size related operations again.
162 operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
164 // Restore the actual control's size.
165 visualModel->mControlSize = actualControlSize;
167 return calculatedLayoutSize;
170 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
172 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
173 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_NATURAL_SIZE");
174 Vector3 naturalSizeVec3;
176 // Make sure the model is up-to-date before layouting
177 EventHandler::ProcessModifyEvents(controller);
179 Controller::Impl& impl = *controller.mImpl;
180 ModelPtr& model = impl.mModel;
181 VisualModelPtr& visualModel = model->mVisualModel;
183 if(impl.mRecalculateNaturalSize)
187 // Layout the text for the new width.
188 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT | REORDER);
189 Size sizeMaxWidthAndMaxHeight = Size(MAX_FLOAT, MAX_FLOAT);
191 naturalSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeMaxWidthAndMaxHeight, requestedOperationsMask);
193 // Stores the natural size to avoid recalculate it again
194 // unless the text/style changes.
195 visualModel->SetNaturalSize(naturalSize);
196 naturalSizeVec3 = naturalSize;
198 impl.mRecalculateNaturalSize = false;
200 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
204 naturalSizeVec3 = visualModel->GetNaturalSize();
206 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
209 naturalSizeVec3.x = ConvertToEven(naturalSizeVec3.x);
210 naturalSizeVec3.y = ConvertToEven(naturalSizeVec3.y);
212 return naturalSizeVec3;
215 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
218 Controller::Impl& impl = *controller.mImpl;
219 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
220 impl.mFontDefaults->mFitPointSize = pointSize;
221 impl.mFontDefaults->sizeDefined = true;
222 impl.ClearFontData();
224 // Operations that can be done only once until the text changes.
225 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
233 textUpdateInfo.mParagraphCharacterIndex = 0u;
234 textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
236 // Make sure the model is up-to-date before layouting
237 impl.UpdateModel(onlyOnceOperations);
239 bool layoutTooSmall = false;
241 Size(layoutSize.width, MAX_FLOAT),
242 static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
246 // Clear the update info. This info will be set the next time the text is updated.
247 textUpdateInfo.Clear();
248 textUpdateInfo.mClearAll = true;
250 if(layoutTooSmall || textSize.width > layoutSize.width || textSize.height > layoutSize.height)
257 void Controller::Relayouter::FitArrayPointSizeforLayout(Controller& controller, const Size& layoutSize)
259 Controller::Impl& impl = *controller.mImpl;
261 const OperationsMask operations = impl.mOperationsPending;
262 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
264 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_ARRAY_LAYOUT");
265 std::vector<Toolkit::DevelTextLabel::FitOption> fitOptions = impl.mTextFitArray;
266 int numberOfFitOptions = static_cast<int>(fitOptions.size());
267 if(numberOfFitOptions == 0)
269 DALI_LOG_ERROR("fitOptions is empty\n");
273 ModelPtr& model = impl.mModel;
274 bool actualellipsis = model->mElideEnabled;
275 model->mElideEnabled = false;
277 // Sort in ascending order by PointSize.
278 std::sort(fitOptions.begin(), fitOptions.end(), compareByPointSize);
280 // Decide whether to use binary search.
281 // If MinLineSize is not sorted in ascending order,
282 // binary search cannot guarantee that it will always find the best value.
283 bool binarySearch = true;
284 float prevMinLineSize = 0.0f;
285 for(Toolkit::DevelTextLabel::FitOption& option : fitOptions)
287 float optionMinLineSize = option.GetMinLineSize();
288 if(prevMinLineSize > optionMinLineSize)
290 binarySearch = false;
293 prevMinLineSize = optionMinLineSize;
296 // Set the first FitOption(Minimum PointSize) to the best value.
297 // If the search does not find an optimal value, the minimum PointSize will be used to text fit.
298 Toolkit::DevelTextLabel::FitOption firstOption = fitOptions.front();
299 bool bestSizeUpdatedLatest = false;
300 float bestPointSize = firstOption.GetPointSize();
301 float bestMinLineSize = firstOption.GetMinLineSize();
306 int right = numberOfFitOptions - 1;
308 while (left <= right)
310 int mid = left + (right - left) / 2;
311 Toolkit::DevelTextLabel::FitOption option = fitOptions[mid];
312 float testPointSize = option.GetPointSize();
313 float testMinLineSize = option.GetMinLineSize();
314 impl.SetDefaultLineSize(testMinLineSize);
316 if(CheckForTextFit(controller, testPointSize, layoutSize))
318 bestSizeUpdatedLatest = true;
319 bestPointSize = testPointSize;
320 bestMinLineSize = testMinLineSize;
325 bestSizeUpdatedLatest = false;
332 // If binary search is not possible, search sequentially starting from the largest PointSize.
333 for(auto it = fitOptions.rbegin(); it != fitOptions.rend(); ++it)
335 Toolkit::DevelTextLabel::FitOption option = *it;
336 float testPointSize = option.GetPointSize();
337 float testMinLineSize = option.GetMinLineSize();
338 impl.SetDefaultLineSize(testMinLineSize);
340 if(CheckForTextFit(controller, testPointSize, layoutSize))
342 bestSizeUpdatedLatest = true;
343 bestPointSize = testPointSize;
344 bestMinLineSize = testMinLineSize;
349 bestSizeUpdatedLatest = false;
354 // Best point size was not updated. re-run so the TextFit should be fitted really.
355 if(!bestSizeUpdatedLatest)
357 impl.SetDefaultLineSize(bestMinLineSize);
358 CheckForTextFit(controller, bestPointSize, layoutSize);
361 model->mElideEnabled = actualellipsis;
362 impl.mFontDefaults->mFitPointSize = bestPointSize;
363 impl.mFontDefaults->sizeDefined = true;
364 impl.ClearFontData();
368 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
370 Controller::Impl& impl = *controller.mImpl;
372 const OperationsMask operations = impl.mOperationsPending;
373 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
375 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
376 ModelPtr& model = impl.mModel;
378 bool actualellipsis = model->mElideEnabled;
379 float minPointSize = impl.mTextFitMinSize;
380 float maxPointSize = impl.mTextFitMaxSize;
381 float pointInterval = impl.mTextFitStepSize;
382 float currentFitPointSize = impl.mFontDefaults->mFitPointSize;
383 float currentDefaultLineSize = impl.mLayoutEngine.GetDefaultLineSize();
384 bool isMultiLine = impl.mLayoutEngine.GetLayout() == Layout::Engine::MULTI_LINE_BOX;
385 // Instead of using the LineSize of the current TextLabel, the LineSize set in TextFit is used.
387 impl.SetDefaultLineSize(impl.mTextFitLineSize);
389 model->mElideEnabled = false;
390 float bestPointSize = minPointSize;
393 if(pointInterval < 1.f)
395 impl.mTextFitStepSize = pointInterval = 1.0f;
398 uint32_t pointSizeRange = static_cast<uint32_t>(ceil((maxPointSize - minPointSize) / pointInterval));
400 if(isMultiLine || pointSizeRange < 3)
402 // Ensure minPointSize + pointSizeRange * pointInverval >= maxPointSize
403 while(minPointSize + static_cast<float>(pointSizeRange) * pointInterval < maxPointSize)
408 uint32_t bestSizeIndex = 0;
409 uint32_t minIndex = bestSizeIndex + 1u;
410 uint32_t maxIndex = pointSizeRange + 1u;
412 bool bestSizeUpdatedLatest = false;
413 // Find best size as binary search.
414 // Range format as [l r). (left closed, right opened)
415 // It mean, we already check all i < l is valid, and r <= i is invalid.
416 // Below binary search will check m = (l+r)/2 point.
417 // Search area sperate as [l m) or [m+1 r)
419 // Basically, we can assume that 0 (minPointSize) is always valid.
420 // Now, we will check [1 pointSizeRange] range s.t. pointSizeRange mean the maxPointSize
421 while(minIndex < maxIndex)
423 uint32_t testIndex = minIndex + ((maxIndex - minIndex) >> 1u);
424 const float testPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(testIndex) * pointInterval);
426 if(CheckForTextFit(controller, testPointSize, layoutSize))
428 bestSizeUpdatedLatest = true;
430 bestSizeIndex = testIndex;
431 minIndex = testIndex + 1u;
435 bestSizeUpdatedLatest = false;
436 maxIndex = testIndex;
439 bestPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(bestSizeIndex) * pointInterval);
441 // Best point size was not updated. re-run so the TextFit should be fitted really.
442 if(!bestSizeUpdatedLatest)
444 CheckForTextFit(controller, bestPointSize, layoutSize);
449 // assume textSize = a * pointSize + b, finding a and b.
451 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
452 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
460 float resultBasedX[2];
461 float resultBasedY[2];
462 float tmpPointSize[2] = {minPointSize, maxPointSize};
464 // Calculate a and b by creating simultaneous equations with two calculations.
467 impl.mFontDefaults->mFitPointSize = tmpPointSize[i];
468 impl.mFontDefaults->sizeDefined = true;
469 impl.ClearFontData();
471 textUpdateInfo.mParagraphCharacterIndex = 0u;
472 textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
475 // Make sure the model is up-to-date before layouting
476 impl.UpdateModel(onlyOnceOperations);
479 Size(layoutSize.width, MAX_FLOAT),
480 static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
483 // Clear the update info. This info will be set the next time the text is updated.
484 textUpdateInfo.Clear();
485 textUpdateInfo.mClearAll = true;
487 resultBasedX[i] = textSize.x;
488 resultBasedY[i] = textSize.y;
491 float aBasedX = (resultBasedX[1] - resultBasedX[0]) / (tmpPointSize[1] - tmpPointSize[0]);
492 float bBasedX = resultBasedX[1] - aBasedX * tmpPointSize[1];
493 aBasedX = std::max(aBasedX, Dali::Math::MACHINE_EPSILON_1000);
495 float aBasedY = (resultBasedY[1] - resultBasedY[0]) / (tmpPointSize[1] - tmpPointSize[0]);
496 float bBasedY = resultBasedY[1] - aBasedY * tmpPointSize[1];
497 aBasedY = std::max(aBasedY, Dali::Math::MACHINE_EPSILON_1000);
499 float bestPointSizeBasedX = (layoutSize.x - bBasedX) / aBasedX;
500 float bestPointSizeBasedY = (layoutSize.y - bBasedY) / aBasedY;
502 bestPointSize = std::min(bestPointSizeBasedX, bestPointSizeBasedY);
503 bestPointSize = std::min(std::max(bestPointSize, minPointSize), maxPointSize);
504 bestPointSize = std::floor((bestPointSize - minPointSize) / pointInterval) * pointInterval + minPointSize;
506 if(CheckForTextFit(controller, bestPointSize, layoutSize))
508 while(bestPointSize + pointInterval <= maxPointSize && CheckForTextFit(controller, bestPointSize + pointInterval, layoutSize))
510 bestPointSize += pointInterval;
513 else if(bestPointSize - pointInterval >= minPointSize)
517 bestPointSize -= pointInterval;
518 } while(bestPointSize - pointInterval >= minPointSize && !CheckForTextFit(controller, bestPointSize, layoutSize));
522 model->mElideEnabled = actualellipsis;
523 if(!Dali::Equals(currentFitPointSize, bestPointSize))
525 impl.mTextFitChanged = true;
527 // Revert back to the original TextLabel LineSize.
528 impl.SetDefaultLineSize(currentDefaultLineSize);
529 impl.mFontDefaults->mFitPointSize = bestPointSize;
530 impl.mFontDefaults->sizeDefined = true;
531 impl.ClearFontData();
535 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
537 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
538 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
540 // Make sure the model is up-to-date before layouting
541 EventHandler::ProcessModifyEvents(controller);
543 Controller::Impl& impl = *controller.mImpl;
544 ModelPtr& model = impl.mModel;
545 VisualModelPtr& visualModel = model->mVisualModel;
546 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
549 Size layoutSize = visualModel->GetHeightForWidth();
551 if(fabsf(width - layoutSize.width) > Math::MACHINE_EPSILON_1000 ||
552 textUpdateInfo.mFullRelayoutNeeded ||
553 textUpdateInfo.mClearAll)
555 // Layout the text for the new width.
556 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT);
557 Size sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
559 layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
561 // The calculated layout width may not be the same as the requested width.
562 // For cache efficiency, the requested width is stored.
563 layoutSize.width = width;
564 visualModel->SetHeightForWidth(layoutSize);
566 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
570 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
573 return layoutSize.height;
576 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
578 Controller::Impl& impl = *controller.mImpl;
579 ModelPtr& model = impl.mModel;
580 VisualModelPtr& visualModel = model->mVisualModel;
581 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
583 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
584 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_RELAYOUT");
586 UpdateTextType updateTextType = NONE_UPDATED;
588 if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
590 if(0u != visualModel->mGlyphPositions.Count())
592 visualModel->mGlyphPositions.Clear();
593 updateTextType = MODEL_UPDATED;
596 // Clear the update info. This info will be set the next time the text is updated.
597 textUpdateInfo.Clear();
599 // Not worth to relayout if width or height is equal to zero.
600 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
602 return updateTextType;
605 // Whether a new size has been set.
606 const bool newSize = (size != visualModel->mControlSize);
608 // Get a reference to the pending operations member
609 OperationsMask& operationsPending = impl.mOperationsPending;
613 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
615 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
616 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
617 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
619 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
622 // Layout operations that need to be done if the size changes.
623 operationsPending = static_cast<OperationsMask>(operationsPending |
628 // Set the update info to relayout the whole text.
629 textUpdateInfo.mFullRelayoutNeeded = true;
630 textUpdateInfo.mCharacterIndex = 0u;
632 // Store the size used to layout the text.
633 visualModel->mControlSize = size;
636 // Whether there are modify events.
637 if(0u != impl.mModifyEvents.Count())
639 // Style operations that need to be done if the text is modified.
640 operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
643 // Set the update info to elide the text.
644 if(model->mElideEnabled ||
645 ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
647 // Update Text layout for applying elided
648 operationsPending = static_cast<OperationsMask>(operationsPending |
653 textUpdateInfo.mFullRelayoutNeeded = true;
654 textUpdateInfo.mCharacterIndex = 0u;
657 bool layoutDirectionChanged = false;
658 if(impl.mLayoutDirection != layoutDirection)
660 // Flag to indicate that the layout direction has changed.
661 layoutDirectionChanged = true;
662 // Clear the update info. This info will be set the next time the text is updated.
663 textUpdateInfo.mClearAll = true;
664 // Apply modifications to the model
665 // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
666 operationsPending = static_cast<OperationsMask>(operationsPending |
674 impl.mLayoutDirection = layoutDirection;
677 // Make sure the model is up-to-date before layouting.
678 EventHandler::ProcessModifyEvents(controller);
679 bool updated = impl.UpdateModel(operationsPending);
683 updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
687 updateTextType = MODEL_UPDATED;
690 // Do not re-do any operation until something changes.
691 operationsPending = NO_OPERATION;
692 model->mScrollPositionLast = model->mScrollPosition;
694 // Whether the text control is editable
695 const bool isEditable = NULL != impl.mEventData;
697 // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
699 if(newSize && isEditable)
701 offset = model->mScrollPosition;
704 if(!isEditable || !controller.IsMultiLineEnabled())
706 // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
707 CalculateVerticalOffset(impl, size);
711 // If layoutSize is bigger than size, vertical align has no meaning.
712 if(layoutSize.y < size.y)
714 CalculateVerticalOffset(impl, size);
717 impl.mEventData->mScrollAfterDelete = false;
724 if(newSize || layoutDirectionChanged)
726 // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
727 impl.ClampHorizontalScroll(layoutSize);
729 // Update the decorator's positions is needed if there is a new size.
730 impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
732 // All decorator elements need to be updated.
733 if(EventData::IsEditingState(impl.mEventData->mState))
735 impl.mEventData->mScrollAfterUpdatePosition = true;
736 impl.mEventData->mUpdateCursorPosition = true;
737 impl.mEventData->mUpdateGrabHandlePosition = true;
739 else if(impl.mEventData->mState == EventData::SELECTING)
741 impl.mEventData->mUpdateHighlightBox = true;
745 // Move the cursor, grab handle etc.
746 if(impl.ProcessInputEvents())
748 updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
752 // Clear the update info. This info will be set the next time the text is updated.
753 textUpdateInfo.Clear();
754 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
756 return updateTextType;
759 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
761 bool layoutTooSmall = false;
762 return DoRelayout(impl, size, operationsRequired, layoutSize, layoutTooSmall);
765 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize, bool& layoutTooSmall)
767 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
768 DALI_TRACE_SCOPE(gTraceFilter2, "DALI_TEXT_DORELAYOUT");
769 bool viewUpdated(false);
771 // Calculate the operations to be done.
772 const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
774 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
775 const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
776 const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
778 // Get the current layout size.
779 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
780 layoutSize = visualModel->GetLayoutSize();
782 if(NO_OPERATION != (LAYOUT & operations))
784 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
786 // Some vectors with data needed to layout and reorder may be void
787 // after the first time the text has been laid out.
788 // Fill the vectors again.
790 // Calculate the number of glyphs to layout.
791 const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
792 const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
793 const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
794 const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
796 const CharacterIndex lastIndex = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
797 const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
799 // Make sure the index is not out of bound
800 if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
801 requestedNumberOfCharacters > charactersToGlyph.Count() ||
802 (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
804 std::string currentText;
805 impl.GetText(currentText);
807 DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
808 DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
809 DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
814 const Length numberOfGlyphs = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
815 const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
817 if(0u == totalNumberOfGlyphs)
819 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
821 visualModel->SetLayoutSize(Size::ZERO);
824 // Nothing else to do if there is no glyphs.
825 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
829 // Set the layout parameters.
830 Layout::Parameters layoutParameters(size, impl.mModel);
832 // Resize the vector of positions to have the same size than the vector of glyphs.
833 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
834 glyphPositions.Resize(totalNumberOfGlyphs);
836 // Whether the last character is a new paragraph character.
837 const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
838 textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
839 layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
841 // The initial glyph and the number of glyphs to layout.
842 layoutParameters.startGlyphIndex = startGlyphIndex;
843 layoutParameters.numberOfGlyphs = numberOfGlyphs;
844 layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
845 layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
847 // Update the ellipsis
848 bool elideTextEnabled = impl.mModel->mElideEnabled;
849 auto ellipsisPosition = impl.mModel->mEllipsisPosition;
851 if(NULL != impl.mEventData)
853 if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
855 elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
857 else if(EventData::INACTIVE != impl.mEventData->mState)
859 // Disable ellipsis when editing
860 elideTextEnabled = false;
863 // Reset the scroll position in inactive state
864 if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
866 impl.ResetScrollPosition();
870 // Update the visual model.
871 bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
872 bool isAutoScrollMaxTextureExceeded = impl.mIsAutoScrollMaxTextureExceeded;
873 bool isHiddenInputEnabled = false;
874 if(impl.mHiddenInput && impl.mEventData != nullptr && impl.mHiddenInput->GetHideMode() != Toolkit::HiddenInput::Mode::HIDE_NONE)
876 isHiddenInputEnabled = true;
880 viewUpdated = impl.mLayoutEngine.LayoutText(layoutParameters,
884 isAutoScrollMaxTextureExceeded,
885 isHiddenInputEnabled,
887 impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
888 layoutTooSmall = !viewUpdated;
890 viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
894 layoutSize = newLayoutSize;
896 if(NO_OPERATION != (UPDATE_DIRECTION & operations))
898 impl.mIsTextDirectionRTL = false;
901 if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
903 impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
906 // Sets the layout size.
907 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
909 visualModel->SetLayoutSize(layoutSize);
914 if(NO_OPERATION != (ALIGN & operations))
916 DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
919 #if defined(DEBUG_ENABLED)
920 std::string currentText;
921 impl.GetText(currentText);
922 DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
924 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
925 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, layout too small %s\n", (layoutTooSmall ? "true" : "false"));
929 void Controller::Relayouter::DoRelayoutHorizontalAlignment(Controller::Impl& impl,
931 const CharacterIndex startIndex,
932 const Length requestedNumberOfCharacters)
935 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
937 // The laid-out lines.
938 Vector<LineRun>& lines = visualModel->mLines;
940 CharacterIndex alignStartIndex = startIndex;
941 Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
943 // the whole text needs to be full aligned.
944 // If you do not do a full aligned, only the last line of the multiline input is aligned.
945 if(impl.mEventData && impl.mEventData->mUpdateAlignment)
947 alignStartIndex = 0u;
948 alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
949 impl.mEventData->mUpdateAlignment = false;
952 // If there is no BoundedParagraphRuns then apply the alignment of controller.
953 // Check whether the layout is single line. It's needed to apply one alignment for single-line.
954 // In single-line layout case we need to check whether to follow the alignment of controller or the first BoundedParagraph.
955 // Apply BoundedParagraph's alignment if and only if there is one BoundedParagraph contains all characters. Otherwise follow controller's alignment.
956 const bool isFollowControllerAlignment = ((impl.mModel->GetNumberOfBoundedParagraphRuns() == 0u) ||
957 ((Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) &&
958 (impl.mModel->GetBoundedParagraphRuns()[0].characterRun.numberOfCharacters != impl.mModel->mLogicalModel->mText.Count())));
960 if(isFollowControllerAlignment)
962 // Need to align with the control's size as the text may contain lines
963 // starting either with left to right text or right to left.
964 impl.mLayoutEngine.Align(size,
966 alignRequestedNumberOfCharacters,
967 impl.mModel->mHorizontalAlignment,
969 impl.mModel->mAlignmentOffset,
970 impl.mLayoutDirection,
971 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
975 //Override the controller horizontal-alignment by horizontal-alignment of bounded paragraph.
976 const Length& numberOfBoundedParagraphRuns = impl.mModel->GetNumberOfBoundedParagraphRuns();
977 const Vector<BoundedParagraphRun>& boundedParagraphRuns = impl.mModel->GetBoundedParagraphRuns();
978 const CharacterIndex alignEndIndex = alignStartIndex + alignRequestedNumberOfCharacters - 1u;
980 Length alignIndex = alignStartIndex;
981 Length boundedParagraphRunIndex = 0u;
983 while(alignIndex <= alignEndIndex && boundedParagraphRunIndex < numberOfBoundedParagraphRuns)
985 //BP: BoundedParagraph
986 const BoundedParagraphRun& boundedParagraphRun = boundedParagraphRuns[boundedParagraphRunIndex];
987 const CharacterIndex& characterStartIndexBP = boundedParagraphRun.characterRun.characterIndex;
988 const Length& numberOfCharactersBP = boundedParagraphRun.characterRun.numberOfCharacters;
989 const CharacterIndex characterEndIndexBP = characterStartIndexBP + numberOfCharactersBP - 1u;
991 CharacterIndex decidedAlignStartIndex = alignIndex;
992 Length decidedAlignNumberOfCharacters = alignEndIndex - alignIndex + 1u;
993 Text::HorizontalAlignment::Type decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
996 * Shortcuts to explain indexes cases:
998 * AS: Alignment Start Index
999 * AE: Alignment End Index
1000 * PS: Paragraph Start Index
1001 * PE: Paragraph End Index
1002 * B: BoundedParagraph Alignment
1003 * M: Model Alignment
1007 if(alignIndex < characterStartIndexBP && characterStartIndexBP <= alignEndIndex) /// AS.MMMMMM.PS--------AE
1009 // Alignment from "Alignment Start Index" to index before "Paragraph Start Index" according to "Model Alignment"
1010 decidedAlignStartIndex = alignIndex;
1011 decidedAlignNumberOfCharacters = characterStartIndexBP - alignIndex;
1012 decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
1014 // Need to re-heck the case of current bounded paragraph
1015 alignIndex = characterStartIndexBP; // Shift AS to be PS
1017 else if((characterStartIndexBP <= alignIndex && alignIndex <= characterEndIndexBP) || /// ---PS.BBBBBBB.AS.BBBBBBB.PE---
1018 (characterStartIndexBP <= alignEndIndex && alignEndIndex <= characterEndIndexBP)) /// ---PS.BBBBBB.AE.BBBBBBB.PE---
1020 // Alignment from "Paragraph Start Index" to "Paragraph End Index" according to "BoundedParagraph Alignment"
1021 decidedAlignStartIndex = characterStartIndexBP;
1022 decidedAlignNumberOfCharacters = numberOfCharactersBP;
1023 decidedHorizontalAlignment = boundedParagraphRun.horizontalAlignmentDefined ? boundedParagraphRun.horizontalAlignment : impl.mModel->mHorizontalAlignment;
1025 alignIndex = characterEndIndexBP + 1u; // Shift AS to be after PE direct
1026 boundedParagraphRunIndex++; // Align then check the case of next bounded paragraph
1030 boundedParagraphRunIndex++; // Check the case of next bounded paragraph
1034 impl.mLayoutEngine.Align(size,
1035 decidedAlignStartIndex,
1036 decidedAlignNumberOfCharacters,
1037 decidedHorizontalAlignment,
1039 impl.mModel->mAlignmentOffset,
1040 impl.mLayoutDirection,
1041 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
1044 //Align the remaining that is not aligned
1045 if(alignIndex <= alignEndIndex)
1047 impl.mLayoutEngine.Align(size,
1049 (alignEndIndex - alignIndex + 1u),
1050 impl.mModel->mHorizontalAlignment,
1052 impl.mModel->mAlignmentOffset,
1053 impl.mLayoutDirection,
1054 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
1059 void Controller::Relayouter::CalculateVerticalOffset(Controller::Impl& impl, const Size& controlSize)
1061 ModelPtr& model = impl.mModel;
1062 VisualModelPtr& visualModel = model->mVisualModel;
1063 Size layoutSize = model->mVisualModel->GetLayoutSize();
1064 Size oldLayoutSize = layoutSize;
1065 float offsetY = 0.f;
1066 bool needRecalc = false;
1067 float defaultFontLineHeight = impl.GetDefaultFontLineHeight();
1069 if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
1071 // Get the line height of the default font.
1072 layoutSize.height = defaultFontLineHeight;
1075 // Whether the text control is editable
1076 const bool isEditable = NULL != impl.mEventData;
1077 if(isEditable && !Dali::Equals(layoutSize.height, defaultFontLineHeight) && impl.IsShowingPlaceholderText())
1079 // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
1080 // This situation occurs when the size of placeholder text is different from the default text.
1081 layoutSize.height = defaultFontLineHeight;
1085 switch(model->mVerticalAlignment)
1087 case VerticalAlignment::TOP:
1089 model->mScrollPosition.y = 0.f;
1093 case VerticalAlignment::CENTER:
1095 model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
1096 if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
1099 case VerticalAlignment::BOTTOM:
1101 model->mScrollPosition.y = controlSize.height - layoutSize.height;
1102 if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
1109 // Update glyphPositions according to recalculation.
1110 const Length positionCount = visualModel->mGlyphPositions.Count();
1111 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
1112 for(Length index = 0u; index < positionCount; index++)
1114 glyphPositions[index].y += offsetY;
1121 } // namespace Toolkit