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);
237 bool layoutTooSmall = false;
239 Size(layoutSize.width, MAX_FLOAT),
240 static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
244 // Clear the update info. This info will be set the next time the text is updated.
245 textUpdateInfo.Clear();
246 textUpdateInfo.mClearAll = true;
248 if(layoutTooSmall || textSize.width > layoutSize.width || textSize.height > layoutSize.height)
255 void Controller::Relayouter::FitArrayPointSizeforLayout(Controller& controller, const Size& layoutSize)
257 Controller::Impl& impl = *controller.mImpl;
259 const OperationsMask operations = impl.mOperationsPending;
260 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
262 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_ARRAY_LAYOUT");
263 std::vector<Toolkit::DevelTextLabel::FitOption> fitOptions = impl.mTextFitArray;
264 int numberOfFitOptions = static_cast<int>(fitOptions.size());
265 if(numberOfFitOptions == 0)
267 DALI_LOG_ERROR("fitOptions is empty\n");
271 ModelPtr& model = impl.mModel;
272 bool actualellipsis = model->mElideEnabled;
273 model->mElideEnabled = false;
275 // Sort in ascending order by PointSize.
276 std::sort(fitOptions.begin(), fitOptions.end(), compareByPointSize);
278 // Decide whether to use binary search.
279 // If MinLineSize is not sorted in ascending order,
280 // binary search cannot guarantee that it will always find the best value.
281 bool binarySearch = true;
282 float prevMinLineSize = 0.0f;
283 for(Toolkit::DevelTextLabel::FitOption& option : fitOptions)
285 float optionMinLineSize = option.GetMinLineSize();
286 if(prevMinLineSize > optionMinLineSize)
288 binarySearch = false;
291 prevMinLineSize = optionMinLineSize;
294 // Set the first FitOption(Minimum PointSize) to the best value.
295 // If the search does not find an optimal value, the minimum PointSize will be used to text fit.
296 Toolkit::DevelTextLabel::FitOption firstOption = fitOptions.front();
297 bool bestSizeUpdatedLatest = false;
298 float bestPointSize = firstOption.GetPointSize();
299 float bestMinLineSize = firstOption.GetMinLineSize();
304 int right = numberOfFitOptions - 1;
306 while (left <= right)
308 int mid = left + (right - left) / 2;
309 Toolkit::DevelTextLabel::FitOption option = fitOptions[mid];
310 float testPointSize = option.GetPointSize();
311 float testMinLineSize = option.GetMinLineSize();
312 impl.SetDefaultLineSize(testMinLineSize);
314 if(CheckForTextFit(controller, testPointSize, layoutSize))
316 bestSizeUpdatedLatest = true;
317 bestPointSize = testPointSize;
318 bestMinLineSize = testMinLineSize;
323 bestSizeUpdatedLatest = false;
330 // If binary search is not possible, search sequentially starting from the largest PointSize.
331 for(auto it = fitOptions.rbegin(); it != fitOptions.rend(); ++it)
333 Toolkit::DevelTextLabel::FitOption option = *it;
334 float testPointSize = option.GetPointSize();
335 float testMinLineSize = option.GetMinLineSize();
336 impl.SetDefaultLineSize(testMinLineSize);
338 if(CheckForTextFit(controller, testPointSize, layoutSize))
340 bestSizeUpdatedLatest = true;
341 bestPointSize = testPointSize;
342 bestMinLineSize = testMinLineSize;
347 bestSizeUpdatedLatest = false;
352 // Best point size was not updated. re-run so the TextFit should be fitted really.
353 if(!bestSizeUpdatedLatest)
355 impl.SetDefaultLineSize(bestMinLineSize);
356 CheckForTextFit(controller, bestPointSize, layoutSize);
359 model->mElideEnabled = actualellipsis;
360 impl.mFontDefaults->mFitPointSize = bestPointSize;
361 impl.mFontDefaults->sizeDefined = true;
362 impl.ClearFontData();
366 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
368 Controller::Impl& impl = *controller.mImpl;
370 const OperationsMask operations = impl.mOperationsPending;
371 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
373 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
374 ModelPtr& model = impl.mModel;
376 bool actualellipsis = model->mElideEnabled;
377 float minPointSize = impl.mTextFitMinSize;
378 float maxPointSize = impl.mTextFitMaxSize;
379 float pointInterval = impl.mTextFitStepSize;
380 float currentFitPointSize = impl.mFontDefaults->mFitPointSize;
381 float currentDefaultLineSize = impl.mLayoutEngine.GetDefaultLineSize();
382 // Instead of using the LineSize of the current TextLabel, the LineSize set in TextFit is used.
383 impl.SetDefaultLineSize(impl.mTextFitLineSize);
385 model->mElideEnabled = false;
388 if(pointInterval < 1.f)
390 impl.mTextFitStepSize = pointInterval = 1.0f;
392 uint32_t pointSizeRange = static_cast<uint32_t>(ceil((maxPointSize - minPointSize) / pointInterval));
394 // Ensure minPointSize + pointSizeRange * pointInverval >= maxPointSize
395 while(minPointSize + static_cast<float>(pointSizeRange) * pointInterval < maxPointSize)
400 uint32_t bestSizeIndex = 0;
401 uint32_t minIndex = bestSizeIndex + 1u;
402 uint32_t maxIndex = pointSizeRange + 1u;
404 bool bestSizeUpdatedLatest = false;
405 // Find best size as binary search.
406 // Range format as [l r). (left closed, right opened)
407 // It mean, we already check all i < l is valid, and r <= i is invalid.
408 // Below binary search will check m = (l+r)/2 point.
409 // Search area sperate as [l m) or [m+1 r)
411 // Basically, we can assume that 0 (minPointSize) is always valid.
412 // Now, we will check [1 pointSizeRange] range s.t. pointSizeRange mean the maxPointSize
413 while(minIndex < maxIndex)
415 uint32_t testIndex = minIndex + ((maxIndex - minIndex) >> 1u);
416 const float testPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(testIndex) * pointInterval);
418 if(CheckForTextFit(controller, testPointSize, layoutSize))
420 bestSizeUpdatedLatest = true;
422 bestSizeIndex = testIndex;
423 minIndex = testIndex + 1u;
427 bestSizeUpdatedLatest = false;
428 maxIndex = testIndex;
431 const float bestPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(bestSizeIndex) * pointInterval);
433 // Best point size was not updated. re-run so the TextFit should be fitted really.
434 if(!bestSizeUpdatedLatest)
436 CheckForTextFit(controller, bestPointSize, layoutSize);
439 model->mElideEnabled = actualellipsis;
440 if(!Dali::Equals(currentFitPointSize, bestPointSize))
442 impl.mTextFitChanged = true;
444 // Revert back to the original TextLabel LineSize.
445 impl.SetDefaultLineSize(currentDefaultLineSize);
446 impl.mFontDefaults->mFitPointSize = bestPointSize;
447 impl.mFontDefaults->sizeDefined = true;
448 impl.ClearFontData();
452 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
454 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
455 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
457 // Make sure the model is up-to-date before layouting
458 EventHandler::ProcessModifyEvents(controller);
460 Controller::Impl& impl = *controller.mImpl;
461 ModelPtr& model = impl.mModel;
462 VisualModelPtr& visualModel = model->mVisualModel;
463 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
466 Size layoutSize = visualModel->GetHeightForWidth();
468 if(fabsf(width - layoutSize.width) > Math::MACHINE_EPSILON_1000 ||
469 textUpdateInfo.mFullRelayoutNeeded ||
470 textUpdateInfo.mClearAll)
472 // Layout the text for the new width.
473 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT);
474 Size sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
476 layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
478 // The calculated layout width may not be the same as the requested width.
479 // For cache efficiency, the requested width is stored.
480 layoutSize.width = width;
481 visualModel->SetHeightForWidth(layoutSize);
483 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
487 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
490 return layoutSize.height;
493 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
495 Controller::Impl& impl = *controller.mImpl;
496 ModelPtr& model = impl.mModel;
497 VisualModelPtr& visualModel = model->mVisualModel;
498 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
500 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
501 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_RELAYOUT");
503 UpdateTextType updateTextType = NONE_UPDATED;
505 if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
507 if(0u != visualModel->mGlyphPositions.Count())
509 visualModel->mGlyphPositions.Clear();
510 updateTextType = MODEL_UPDATED;
513 // Clear the update info. This info will be set the next time the text is updated.
514 textUpdateInfo.Clear();
516 // Not worth to relayout if width or height is equal to zero.
517 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
519 return updateTextType;
522 // Whether a new size has been set.
523 const bool newSize = (size != visualModel->mControlSize);
525 // Get a reference to the pending operations member
526 OperationsMask& operationsPending = impl.mOperationsPending;
530 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
532 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
533 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
534 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
536 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
539 // Layout operations that need to be done if the size changes.
540 operationsPending = static_cast<OperationsMask>(operationsPending |
545 // Set the update info to relayout the whole text.
546 textUpdateInfo.mFullRelayoutNeeded = true;
547 textUpdateInfo.mCharacterIndex = 0u;
549 // Store the size used to layout the text.
550 visualModel->mControlSize = size;
553 // Whether there are modify events.
554 if(0u != impl.mModifyEvents.Count())
556 // Style operations that need to be done if the text is modified.
557 operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
560 // Set the update info to elide the text.
561 if(model->mElideEnabled ||
562 ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
564 // Update Text layout for applying elided
565 operationsPending = static_cast<OperationsMask>(operationsPending |
570 textUpdateInfo.mFullRelayoutNeeded = true;
571 textUpdateInfo.mCharacterIndex = 0u;
574 bool layoutDirectionChanged = false;
575 if(impl.mLayoutDirection != layoutDirection)
577 // Flag to indicate that the layout direction has changed.
578 layoutDirectionChanged = true;
579 // Clear the update info. This info will be set the next time the text is updated.
580 textUpdateInfo.mClearAll = true;
581 // Apply modifications to the model
582 // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
583 operationsPending = static_cast<OperationsMask>(operationsPending |
591 impl.mLayoutDirection = layoutDirection;
594 // Make sure the model is up-to-date before layouting.
595 EventHandler::ProcessModifyEvents(controller);
596 bool updated = impl.UpdateModel(operationsPending);
600 updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
604 updateTextType = MODEL_UPDATED;
607 // Do not re-do any operation until something changes.
608 operationsPending = NO_OPERATION;
609 model->mScrollPositionLast = model->mScrollPosition;
611 // Whether the text control is editable
612 const bool isEditable = NULL != impl.mEventData;
614 // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
616 if(newSize && isEditable)
618 offset = model->mScrollPosition;
621 if(!isEditable || !controller.IsMultiLineEnabled())
623 // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
624 CalculateVerticalOffset(impl, size);
628 // If layoutSize is bigger than size, vertical align has no meaning.
629 if(layoutSize.y < size.y)
631 CalculateVerticalOffset(impl, size);
634 impl.mEventData->mScrollAfterDelete = false;
641 if(newSize || layoutDirectionChanged)
643 // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
644 impl.ClampHorizontalScroll(layoutSize);
646 // Update the decorator's positions is needed if there is a new size.
647 impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
649 // All decorator elements need to be updated.
650 if(EventData::IsEditingState(impl.mEventData->mState))
652 impl.mEventData->mScrollAfterUpdatePosition = true;
653 impl.mEventData->mUpdateCursorPosition = true;
654 impl.mEventData->mUpdateGrabHandlePosition = true;
656 else if(impl.mEventData->mState == EventData::SELECTING)
658 impl.mEventData->mUpdateHighlightBox = true;
662 // Move the cursor, grab handle etc.
663 if(impl.ProcessInputEvents())
665 updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
669 // Clear the update info. This info will be set the next time the text is updated.
670 textUpdateInfo.Clear();
671 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
673 return updateTextType;
676 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
678 bool layoutTooSmall = false;
679 return DoRelayout(impl, size, operationsRequired, layoutSize, layoutTooSmall);
682 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize, bool& layoutTooSmall)
684 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
685 DALI_TRACE_SCOPE(gTraceFilter2, "DALI_TEXT_DORELAYOUT");
686 bool viewUpdated(false);
688 // Calculate the operations to be done.
689 const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
691 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
692 const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
693 const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
695 // Get the current layout size.
696 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
697 layoutSize = visualModel->GetLayoutSize();
699 if(NO_OPERATION != (LAYOUT & operations))
701 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
703 // Some vectors with data needed to layout and reorder may be void
704 // after the first time the text has been laid out.
705 // Fill the vectors again.
707 // Calculate the number of glyphs to layout.
708 const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
709 const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
710 const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
711 const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
713 const CharacterIndex lastIndex = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
714 const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
716 // Make sure the index is not out of bound
717 if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
718 requestedNumberOfCharacters > charactersToGlyph.Count() ||
719 (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
721 std::string currentText;
722 impl.GetText(currentText);
724 DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
725 DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
726 DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
731 const Length numberOfGlyphs = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
732 const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
734 if(0u == totalNumberOfGlyphs)
736 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
738 visualModel->SetLayoutSize(Size::ZERO);
741 // Nothing else to do if there is no glyphs.
742 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
746 // Set the layout parameters.
747 Layout::Parameters layoutParameters(size, impl.mModel);
749 // Resize the vector of positions to have the same size than the vector of glyphs.
750 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
751 glyphPositions.Resize(totalNumberOfGlyphs);
753 // Whether the last character is a new paragraph character.
754 const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
755 textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
756 layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
758 // The initial glyph and the number of glyphs to layout.
759 layoutParameters.startGlyphIndex = startGlyphIndex;
760 layoutParameters.numberOfGlyphs = numberOfGlyphs;
761 layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
762 layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
764 // Update the ellipsis
765 bool elideTextEnabled = impl.mModel->mElideEnabled;
766 auto ellipsisPosition = impl.mModel->mEllipsisPosition;
768 if(NULL != impl.mEventData)
770 if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
772 elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
774 else if(EventData::INACTIVE != impl.mEventData->mState)
776 // Disable ellipsis when editing
777 elideTextEnabled = false;
780 // Reset the scroll position in inactive state
781 if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
783 impl.ResetScrollPosition();
787 // Update the visual model.
788 bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
789 bool isAutoScrollMaxTextureExceeded = impl.mIsAutoScrollMaxTextureExceeded;
790 bool isHiddenInputEnabled = false;
791 if(impl.mHiddenInput && impl.mEventData != nullptr && impl.mHiddenInput->GetHideMode() != Toolkit::HiddenInput::Mode::HIDE_NONE)
793 isHiddenInputEnabled = true;
797 viewUpdated = impl.mLayoutEngine.LayoutText(layoutParameters,
801 isAutoScrollMaxTextureExceeded,
802 isHiddenInputEnabled,
804 impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
805 layoutTooSmall = !viewUpdated;
807 viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
811 layoutSize = newLayoutSize;
813 if(NO_OPERATION != (UPDATE_DIRECTION & operations))
815 impl.mIsTextDirectionRTL = false;
818 if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
820 impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
823 // Sets the layout size.
824 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
826 visualModel->SetLayoutSize(layoutSize);
831 if(NO_OPERATION != (ALIGN & operations))
833 DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
836 #if defined(DEBUG_ENABLED)
837 std::string currentText;
838 impl.GetText(currentText);
839 DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
841 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
842 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, layout too small %s\n", (layoutTooSmall ? "true" : "false"));
846 void Controller::Relayouter::DoRelayoutHorizontalAlignment(Controller::Impl& impl,
848 const CharacterIndex startIndex,
849 const Length requestedNumberOfCharacters)
852 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
854 // The laid-out lines.
855 Vector<LineRun>& lines = visualModel->mLines;
857 CharacterIndex alignStartIndex = startIndex;
858 Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
860 // the whole text needs to be full aligned.
861 // If you do not do a full aligned, only the last line of the multiline input is aligned.
862 if(impl.mEventData && impl.mEventData->mUpdateAlignment)
864 alignStartIndex = 0u;
865 alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
866 impl.mEventData->mUpdateAlignment = false;
869 // If there is no BoundedParagraphRuns then apply the alignment of controller.
870 // Check whether the layout is single line. It's needed to apply one alignment for single-line.
871 // In single-line layout case we need to check whether to follow the alignment of controller or the first BoundedParagraph.
872 // Apply BoundedParagraph's alignment if and only if there is one BoundedParagraph contains all characters. Otherwise follow controller's alignment.
873 const bool isFollowControllerAlignment = ((impl.mModel->GetNumberOfBoundedParagraphRuns() == 0u) ||
874 ((Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) &&
875 (impl.mModel->GetBoundedParagraphRuns()[0].characterRun.numberOfCharacters != impl.mModel->mLogicalModel->mText.Count())));
877 if(isFollowControllerAlignment)
879 // Need to align with the control's size as the text may contain lines
880 // starting either with left to right text or right to left.
881 impl.mLayoutEngine.Align(size,
883 alignRequestedNumberOfCharacters,
884 impl.mModel->mHorizontalAlignment,
886 impl.mModel->mAlignmentOffset,
887 impl.mLayoutDirection,
888 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
892 //Override the controller horizontal-alignment by horizontal-alignment of bounded paragraph.
893 const Length& numberOfBoundedParagraphRuns = impl.mModel->GetNumberOfBoundedParagraphRuns();
894 const Vector<BoundedParagraphRun>& boundedParagraphRuns = impl.mModel->GetBoundedParagraphRuns();
895 const CharacterIndex alignEndIndex = alignStartIndex + alignRequestedNumberOfCharacters - 1u;
897 Length alignIndex = alignStartIndex;
898 Length boundedParagraphRunIndex = 0u;
900 while(alignIndex <= alignEndIndex && boundedParagraphRunIndex < numberOfBoundedParagraphRuns)
902 //BP: BoundedParagraph
903 const BoundedParagraphRun& boundedParagraphRun = boundedParagraphRuns[boundedParagraphRunIndex];
904 const CharacterIndex& characterStartIndexBP = boundedParagraphRun.characterRun.characterIndex;
905 const Length& numberOfCharactersBP = boundedParagraphRun.characterRun.numberOfCharacters;
906 const CharacterIndex characterEndIndexBP = characterStartIndexBP + numberOfCharactersBP - 1u;
908 CharacterIndex decidedAlignStartIndex = alignIndex;
909 Length decidedAlignNumberOfCharacters = alignEndIndex - alignIndex + 1u;
910 Text::HorizontalAlignment::Type decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
913 * Shortcuts to explain indexes cases:
915 * AS: Alignment Start Index
916 * AE: Alignment End Index
917 * PS: Paragraph Start Index
918 * PE: Paragraph End Index
919 * B: BoundedParagraph Alignment
924 if(alignIndex < characterStartIndexBP && characterStartIndexBP <= alignEndIndex) /// AS.MMMMMM.PS--------AE
926 // Alignment from "Alignment Start Index" to index before "Paragraph Start Index" according to "Model Alignment"
927 decidedAlignStartIndex = alignIndex;
928 decidedAlignNumberOfCharacters = characterStartIndexBP - alignIndex;
929 decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
931 // Need to re-heck the case of current bounded paragraph
932 alignIndex = characterStartIndexBP; // Shift AS to be PS
934 else if((characterStartIndexBP <= alignIndex && alignIndex <= characterEndIndexBP) || /// ---PS.BBBBBBB.AS.BBBBBBB.PE---
935 (characterStartIndexBP <= alignEndIndex && alignEndIndex <= characterEndIndexBP)) /// ---PS.BBBBBB.AE.BBBBBBB.PE---
937 // Alignment from "Paragraph Start Index" to "Paragraph End Index" according to "BoundedParagraph Alignment"
938 decidedAlignStartIndex = characterStartIndexBP;
939 decidedAlignNumberOfCharacters = numberOfCharactersBP;
940 decidedHorizontalAlignment = boundedParagraphRun.horizontalAlignmentDefined ? boundedParagraphRun.horizontalAlignment : impl.mModel->mHorizontalAlignment;
942 alignIndex = characterEndIndexBP + 1u; // Shift AS to be after PE direct
943 boundedParagraphRunIndex++; // Align then check the case of next bounded paragraph
947 boundedParagraphRunIndex++; // Check the case of next bounded paragraph
951 impl.mLayoutEngine.Align(size,
952 decidedAlignStartIndex,
953 decidedAlignNumberOfCharacters,
954 decidedHorizontalAlignment,
956 impl.mModel->mAlignmentOffset,
957 impl.mLayoutDirection,
958 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
961 //Align the remaining that is not aligned
962 if(alignIndex <= alignEndIndex)
964 impl.mLayoutEngine.Align(size,
966 (alignEndIndex - alignIndex + 1u),
967 impl.mModel->mHorizontalAlignment,
969 impl.mModel->mAlignmentOffset,
970 impl.mLayoutDirection,
971 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
976 void Controller::Relayouter::CalculateVerticalOffset(Controller::Impl& impl, const Size& controlSize)
978 ModelPtr& model = impl.mModel;
979 VisualModelPtr& visualModel = model->mVisualModel;
980 Size layoutSize = model->mVisualModel->GetLayoutSize();
981 Size oldLayoutSize = layoutSize;
983 bool needRecalc = false;
984 float defaultFontLineHeight = impl.GetDefaultFontLineHeight();
986 if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
988 // Get the line height of the default font.
989 layoutSize.height = defaultFontLineHeight;
992 // Whether the text control is editable
993 const bool isEditable = NULL != impl.mEventData;
994 if(isEditable && !Dali::Equals(layoutSize.height, defaultFontLineHeight) && impl.IsShowingPlaceholderText())
996 // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
997 // This situation occurs when the size of placeholder text is different from the default text.
998 layoutSize.height = defaultFontLineHeight;
1002 switch(model->mVerticalAlignment)
1004 case VerticalAlignment::TOP:
1006 model->mScrollPosition.y = 0.f;
1010 case VerticalAlignment::CENTER:
1012 model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
1013 if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
1016 case VerticalAlignment::BOTTOM:
1018 model->mScrollPosition.y = controlSize.height - layoutSize.height;
1019 if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
1026 // Update glyphPositions according to recalculation.
1027 const Length positionCount = visualModel->mGlyphPositions.Count();
1028 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
1029 for(Length index = 0u; index < positionCount; index++)
1031 glyphPositions[index].y += offsetY;
1038 } // namespace Toolkit