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_PERFORMANCE_MARKER, false);
40 constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
42 float ConvertToEven(float value)
44 int intValue(static_cast<int>(value));
45 return static_cast<float>(intValue + (intValue & 1));
56 Size Controller::Relayouter::CalculateLayoutSizeOnRequiredControllerSize(Controller& controller, const Size& requestedControllerSize, const OperationsMask& requestedOperationsMask)
58 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->CalculateLayoutSizeOnRequiredControllerSize\n");
59 Size calculatedLayoutSize;
61 Controller::Impl& impl = *controller.mImpl;
62 ModelPtr& model = impl.mModel;
63 VisualModelPtr& visualModel = model->mVisualModel;
65 // Operations that can be done only once until the text changes.
66 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
74 const OperationsMask sizeOperations = static_cast<OperationsMask>(LAYOUT | ALIGN | REORDER);
76 // Set the update info to relayout the whole text.
77 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
78 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
79 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
80 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
82 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
84 textUpdateInfo.mParagraphCharacterIndex = 0u;
85 textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
87 // Get a reference to the pending operations member
88 OperationsMask& operationsPending = impl.mOperationsPending;
90 // Store the actual control's size to restore later.
91 const Size actualControlSize = visualModel->mControlSize;
93 // This is to keep Index to the first character to be updated.
94 // Then restore it after calling Clear method.
95 auto updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
97 // Whether the text control is editable
98 const bool isEditable = NULL != impl.mEventData;
102 impl.UpdateModel(onlyOnceOperations);
104 // Layout the text for the new width.
105 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask);
108 requestedControllerSize,
109 static_cast<OperationsMask>(onlyOnceOperations | requestedOperationsMask),
110 calculatedLayoutSize);
112 textUpdateInfo.Clear();
113 textUpdateInfo.mClearAll = true;
115 // Do not do again the only once operations.
116 operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
120 // Layout the text for the new width.
121 // Apply the pending operations, requested operations and the only once operations.
122 // Then remove onlyOnceOperations
123 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask | onlyOnceOperations);
125 // Make sure the model is up-to-date before layouting
126 impl.UpdateModel(static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE));
129 requestedControllerSize,
130 static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE),
131 calculatedLayoutSize);
133 // Clear the update info. This info will be set the next time the text is updated.
134 textUpdateInfo.Clear();
136 //TODO: Refactor "DoRelayout" and extract common code of size calculation without modifying attributes of mVisualModel,
137 //TODO: then calculate GlyphPositions. Lines, Size, Layout for Natural-Size
138 //TODO: and utilize the values in OperationsPending and TextUpdateInfo without changing the original one.
139 //TODO: Also it will improve performance because there is no need todo FullRelyout on the next need for layouting.
142 // FullRelayoutNeeded should be true because DoRelayout is MAX_FLOAT, MAX_FLOAT.
143 // By this no need to take backup and restore it.
144 textUpdateInfo.mFullRelayoutNeeded = true;
146 // Restore mCharacterIndex. Because "Clear" set it to the maximum integer.
147 // The "CalculateTextUpdateIndices" does not work proprely because the mCharacterIndex will be greater than mPreviousNumberOfCharacters.
148 // Which apply an assumption to update only the last paragraph. That could cause many of out of index crashes.
149 textUpdateInfo.mCharacterIndex = updateInfoCharIndexBackup;
151 // Do the size related operations again.
152 operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
154 // Restore the actual control's size.
155 visualModel->mControlSize = actualControlSize;
157 return calculatedLayoutSize;
160 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
162 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
163 DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_GET_NATURAL_SIZE");
164 Vector3 naturalSizeVec3;
166 // Make sure the model is up-to-date before layouting
167 EventHandler::ProcessModifyEvents(controller);
169 Controller::Impl& impl = *controller.mImpl;
170 ModelPtr& model = impl.mModel;
171 VisualModelPtr& visualModel = model->mVisualModel;
173 if(impl.mRecalculateNaturalSize)
177 // Layout the text for the new width.
178 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT | REORDER);
179 Size sizeMaxWidthAndMaxHeight = Size(MAX_FLOAT, MAX_FLOAT);
181 naturalSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeMaxWidthAndMaxHeight, requestedOperationsMask);
183 // Stores the natural size to avoid recalculate it again
184 // unless the text/style changes.
185 visualModel->SetNaturalSize(naturalSize);
186 naturalSizeVec3 = naturalSize;
188 impl.mRecalculateNaturalSize = false;
190 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
194 naturalSizeVec3 = visualModel->GetNaturalSize();
196 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
199 naturalSizeVec3.x = ConvertToEven(naturalSizeVec3.x);
200 naturalSizeVec3.y = ConvertToEven(naturalSizeVec3.y);
202 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_GET_NATURAL_SIZE");
204 return naturalSizeVec3;
207 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
210 Controller::Impl& impl = *controller.mImpl;
211 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
212 impl.mFontDefaults->mFitPointSize = pointSize;
213 impl.mFontDefaults->sizeDefined = true;
214 impl.ClearFontData();
216 // Operations that can be done only once until the text changes.
217 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
225 textUpdateInfo.mParagraphCharacterIndex = 0u;
226 textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
228 // Make sure the model is up-to-date before layouting
229 impl.UpdateModel(onlyOnceOperations);
232 Size(layoutSize.width, MAX_FLOAT),
233 static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
236 // Clear the update info. This info will be set the next time the text is updated.
237 textUpdateInfo.Clear();
238 textUpdateInfo.mClearAll = true;
240 if(textSize.width >= layoutSize.width || textSize.height >= layoutSize.height)
247 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
249 Controller::Impl& impl = *controller.mImpl;
251 const OperationsMask operations = impl.mOperationsPending;
252 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
254 DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
255 ModelPtr& model = impl.mModel;
257 bool actualellipsis = model->mElideEnabled;
258 float minPointSize = impl.mTextFitMinSize;
259 float maxPointSize = impl.mTextFitMaxSize;
260 float pointInterval = impl.mTextFitStepSize;
261 float currentFitPointSize = impl.mFontDefaults->mFitPointSize;
263 model->mElideEnabled = false;
266 if(pointInterval < 1.f)
268 impl.mTextFitStepSize = pointInterval = 1.0f;
270 uint32_t pointSizeRange = static_cast<uint32_t>(ceil((maxPointSize - minPointSize) / pointInterval));
272 // Ensure minPointSize + pointSizeRange * pointInverval >= maxPointSize
273 while(minPointSize + static_cast<float>(pointSizeRange) * pointInterval < maxPointSize)
278 uint32_t bestSizeIndex = 0;
279 uint32_t minIndex = bestSizeIndex + 1u;
280 uint32_t maxIndex = pointSizeRange + 1u;
282 bool bestSizeUpdatedLatest = false;
283 // Find best size as binary search.
284 // Range format as [l r). (left closed, right opened)
285 // It mean, we already check all i < l is valid, and r <= i is invalid.
286 // Below binary search will check m = (l+r)/2 point.
287 // Search area sperate as [l m) or [m+1 r)
289 // Basically, we can assume that 0 (minPointSize) is always valid.
290 // Now, we will check [1 pointSizeRange] range s.t. pointSizeRange mean the maxPointSize
291 while(minIndex < maxIndex)
293 uint32_t testIndex = minIndex + ((maxIndex - minIndex) >> 1u);
294 const float testPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(testIndex) * pointInterval);
296 if(CheckForTextFit(controller, testPointSize, layoutSize))
298 bestSizeUpdatedLatest = true;
300 bestSizeIndex = testIndex;
301 minIndex = testIndex + 1u;
305 bestSizeUpdatedLatest = false;
306 maxIndex = testIndex;
309 const float bestPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(bestSizeIndex) * pointInterval);
311 // Best point size was not updated. re-run so the TextFit should be fitted really.
312 if(!bestSizeUpdatedLatest)
314 CheckForTextFit(controller, bestPointSize, layoutSize);
317 model->mElideEnabled = actualellipsis;
318 if(!Dali::Equals(currentFitPointSize, bestPointSize))
320 impl.mTextFitChanged = true;
322 impl.mFontDefaults->mFitPointSize = bestPointSize;
323 impl.mFontDefaults->sizeDefined = true;
324 impl.ClearFontData();
326 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
330 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
332 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
333 DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
335 // Make sure the model is up-to-date before layouting
336 EventHandler::ProcessModifyEvents(controller);
338 Controller::Impl& impl = *controller.mImpl;
339 ModelPtr& model = impl.mModel;
340 VisualModelPtr& visualModel = model->mVisualModel;
341 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
345 if(fabsf(width - visualModel->mControlSize.width) > Math::MACHINE_EPSILON_1000 ||
346 textUpdateInfo.mFullRelayoutNeeded ||
347 textUpdateInfo.mClearAll)
349 // Layout the text for the new width.
350 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT);
351 Size sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
353 layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
355 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
359 layoutSize = visualModel->GetLayoutSize();
360 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
363 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
365 return layoutSize.height;
368 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
370 Controller::Impl& impl = *controller.mImpl;
371 ModelPtr& model = impl.mModel;
372 VisualModelPtr& visualModel = model->mVisualModel;
373 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
375 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
376 DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_RELAYOUT");
378 UpdateTextType updateTextType = NONE_UPDATED;
380 if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
382 if(0u != visualModel->mGlyphPositions.Count())
384 visualModel->mGlyphPositions.Clear();
385 updateTextType = MODEL_UPDATED;
388 // Clear the update info. This info will be set the next time the text is updated.
389 textUpdateInfo.Clear();
391 // Not worth to relayout if width or height is equal to zero.
392 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
393 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_RELAYOUT");
395 return updateTextType;
398 // Whether a new size has been set.
399 const bool newSize = (size != visualModel->mControlSize);
401 // Get a reference to the pending operations member
402 OperationsMask& operationsPending = impl.mOperationsPending;
406 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
408 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
409 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
410 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
412 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
415 // Layout operations that need to be done if the size changes.
416 operationsPending = static_cast<OperationsMask>(operationsPending |
421 // Set the update info to relayout the whole text.
422 textUpdateInfo.mFullRelayoutNeeded = true;
423 textUpdateInfo.mCharacterIndex = 0u;
425 // Store the size used to layout the text.
426 visualModel->mControlSize = size;
429 // Whether there are modify events.
430 if(0u != impl.mModifyEvents.Count())
432 // Style operations that need to be done if the text is modified.
433 operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
436 // Set the update info to elide the text.
437 if(model->mElideEnabled ||
438 ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
440 // Update Text layout for applying elided
441 operationsPending = static_cast<OperationsMask>(operationsPending |
446 textUpdateInfo.mFullRelayoutNeeded = true;
447 textUpdateInfo.mCharacterIndex = 0u;
450 bool layoutDirectionChanged = false;
451 if(impl.mLayoutDirection != layoutDirection)
453 // Flag to indicate that the layout direction has changed.
454 layoutDirectionChanged = true;
455 // Clear the update info. This info will be set the next time the text is updated.
456 textUpdateInfo.mClearAll = true;
457 // Apply modifications to the model
458 // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
459 operationsPending = static_cast<OperationsMask>(operationsPending |
467 impl.mLayoutDirection = layoutDirection;
470 // Make sure the model is up-to-date before layouting.
471 EventHandler::ProcessModifyEvents(controller);
472 bool updated = impl.UpdateModel(operationsPending);
476 updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
480 updateTextType = MODEL_UPDATED;
483 // Do not re-do any operation until something changes.
484 operationsPending = NO_OPERATION;
485 model->mScrollPositionLast = model->mScrollPosition;
487 // Whether the text control is editable
488 const bool isEditable = NULL != impl.mEventData;
490 // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
492 if(newSize && isEditable)
494 offset = model->mScrollPosition;
497 if(!isEditable || !controller.IsMultiLineEnabled())
499 // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
500 CalculateVerticalOffset(impl, size);
504 // If layoutSize is bigger than size, vertical align has no meaning.
505 if(layoutSize.y < size.y)
507 CalculateVerticalOffset(impl, size);
510 impl.mEventData->mScrollAfterDelete = false;
517 if(newSize || layoutDirectionChanged)
519 // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
520 impl.ClampHorizontalScroll(layoutSize);
522 // Update the decorator's positions is needed if there is a new size.
523 impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
525 // All decorator elements need to be updated.
526 if(EventData::IsEditingState(impl.mEventData->mState))
528 impl.mEventData->mScrollAfterUpdatePosition = true;
529 impl.mEventData->mUpdateCursorPosition = true;
530 impl.mEventData->mUpdateGrabHandlePosition = true;
532 else if(impl.mEventData->mState == EventData::SELECTING)
534 impl.mEventData->mUpdateHighlightBox = true;
538 // Move the cursor, grab handle etc.
539 if(impl.ProcessInputEvents())
541 updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
545 // Clear the update info. This info will be set the next time the text is updated.
546 textUpdateInfo.Clear();
547 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
548 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_RELAYOUT");
550 return updateTextType;
553 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
555 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
556 DALI_TRACE_BEGIN(gTraceFilter, "DALI_TEXT_DORELAYOUT");
557 bool viewUpdated(false);
559 // Calculate the operations to be done.
560 const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
562 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
563 const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
564 const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
566 // Get the current layout size.
567 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
568 layoutSize = visualModel->GetLayoutSize();
570 if(NO_OPERATION != (LAYOUT & operations))
572 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
574 // Some vectors with data needed to layout and reorder may be void
575 // after the first time the text has been laid out.
576 // Fill the vectors again.
578 // Calculate the number of glyphs to layout.
579 const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
580 const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
581 const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
582 const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
584 const CharacterIndex lastIndex = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
585 const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
587 // Make sure the index is not out of bound
588 if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
589 requestedNumberOfCharacters > charactersToGlyph.Count() ||
590 (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
592 std::string currentText;
593 impl.GetText(currentText);
595 DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
596 DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
597 DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
599 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_DORELAYOUT");
604 const Length numberOfGlyphs = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
605 const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
607 if(0u == totalNumberOfGlyphs)
609 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
611 visualModel->SetLayoutSize(Size::ZERO);
614 // Nothing else to do if there is no glyphs.
615 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
616 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_DORELAYOUT");
620 // Set the layout parameters.
621 Layout::Parameters layoutParameters(size, impl.mModel);
623 // Resize the vector of positions to have the same size than the vector of glyphs.
624 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
625 glyphPositions.Resize(totalNumberOfGlyphs);
627 // Whether the last character is a new paragraph character.
628 const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
629 textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
630 layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
632 // The initial glyph and the number of glyphs to layout.
633 layoutParameters.startGlyphIndex = startGlyphIndex;
634 layoutParameters.numberOfGlyphs = numberOfGlyphs;
635 layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
636 layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
638 // Update the ellipsis
639 bool elideTextEnabled = impl.mModel->mElideEnabled;
640 auto ellipsisPosition = impl.mModel->mEllipsisPosition;
642 if(NULL != impl.mEventData)
644 if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
646 elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
648 else if(EventData::INACTIVE != impl.mEventData->mState)
650 // Disable ellipsis when editing
651 elideTextEnabled = false;
654 // Reset the scroll position in inactive state
655 if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
657 impl.ResetScrollPosition();
661 // Update the visual model.
662 bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
663 bool isAutoScrollMaxTextureExceeded = impl.mIsAutoScrollMaxTextureExceeded;
664 bool isHiddenInputEnabled = false;
665 if(impl.mHiddenInput && impl.mEventData != nullptr && impl.mHiddenInput->GetHideMode() != Toolkit::HiddenInput::Mode::HIDE_NONE)
667 isHiddenInputEnabled = true;
671 viewUpdated = impl.mLayoutEngine.LayoutText(layoutParameters,
675 isAutoScrollMaxTextureExceeded,
676 isHiddenInputEnabled,
678 impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
680 viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
684 layoutSize = newLayoutSize;
686 if(NO_OPERATION != (UPDATE_DIRECTION & operations))
688 impl.mIsTextDirectionRTL = false;
691 if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
693 impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
696 // Sets the layout size.
697 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
699 visualModel->SetLayoutSize(layoutSize);
704 if(NO_OPERATION != (ALIGN & operations))
706 DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
709 #if defined(DEBUG_ENABLED)
710 std::string currentText;
711 impl.GetText(currentText);
712 DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
714 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
715 DALI_TRACE_END(gTraceFilter, "DALI_TEXT_DORELAYOUT");
719 void Controller::Relayouter::DoRelayoutHorizontalAlignment(Controller::Impl& impl,
721 const CharacterIndex startIndex,
722 const Length requestedNumberOfCharacters)
725 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
727 // The laid-out lines.
728 Vector<LineRun>& lines = visualModel->mLines;
730 CharacterIndex alignStartIndex = startIndex;
731 Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
733 // the whole text needs to be full aligned.
734 // If you do not do a full aligned, only the last line of the multiline input is aligned.
735 if(impl.mEventData && impl.mEventData->mUpdateAlignment)
737 alignStartIndex = 0u;
738 alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
739 impl.mEventData->mUpdateAlignment = false;
742 // If there is no BoundedParagraphRuns then apply the alignment of controller.
743 // Check whether the layout is single line. It's needed to apply one alignment for single-line.
744 // In single-line layout case we need to check whether to follow the alignment of controller or the first BoundedParagraph.
745 // Apply BoundedParagraph's alignment if and only if there is one BoundedParagraph contains all characters. Otherwise follow controller's alignment.
746 const bool isFollowControllerAlignment = ((impl.mModel->GetNumberOfBoundedParagraphRuns() == 0u) ||
747 ((Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) &&
748 (impl.mModel->GetBoundedParagraphRuns()[0].characterRun.numberOfCharacters != impl.mModel->mLogicalModel->mText.Count())));
750 if(isFollowControllerAlignment)
752 // Need to align with the control's size as the text may contain lines
753 // starting either with left to right text or right to left.
754 impl.mLayoutEngine.Align(size,
756 alignRequestedNumberOfCharacters,
757 impl.mModel->mHorizontalAlignment,
759 impl.mModel->mAlignmentOffset,
760 impl.mLayoutDirection,
761 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
765 //Override the controller horizontal-alignment by horizontal-alignment of bounded paragraph.
766 const Length& numberOfBoundedParagraphRuns = impl.mModel->GetNumberOfBoundedParagraphRuns();
767 const Vector<BoundedParagraphRun>& boundedParagraphRuns = impl.mModel->GetBoundedParagraphRuns();
768 const CharacterIndex alignEndIndex = alignStartIndex + alignRequestedNumberOfCharacters - 1u;
770 Length alignIndex = alignStartIndex;
771 Length boundedParagraphRunIndex = 0u;
773 while(alignIndex <= alignEndIndex && boundedParagraphRunIndex < numberOfBoundedParagraphRuns)
775 //BP: BoundedParagraph
776 const BoundedParagraphRun& boundedParagraphRun = boundedParagraphRuns[boundedParagraphRunIndex];
777 const CharacterIndex& characterStartIndexBP = boundedParagraphRun.characterRun.characterIndex;
778 const Length& numberOfCharactersBP = boundedParagraphRun.characterRun.numberOfCharacters;
779 const CharacterIndex characterEndIndexBP = characterStartIndexBP + numberOfCharactersBP - 1u;
781 CharacterIndex decidedAlignStartIndex = alignIndex;
782 Length decidedAlignNumberOfCharacters = alignEndIndex - alignIndex + 1u;
783 Text::HorizontalAlignment::Type decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
786 * Shortcuts to explain indexes cases:
788 * AS: Alignment Start Index
789 * AE: Alignment End Index
790 * PS: Paragraph Start Index
791 * PE: Paragraph End Index
792 * B: BoundedParagraph Alignment
797 if(alignIndex < characterStartIndexBP && characterStartIndexBP <= alignEndIndex) /// AS.MMMMMM.PS--------AE
799 // Alignment from "Alignment Start Index" to index before "Paragraph Start Index" according to "Model Alignment"
800 decidedAlignStartIndex = alignIndex;
801 decidedAlignNumberOfCharacters = characterStartIndexBP - alignIndex;
802 decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
804 // Need to re-heck the case of current bounded paragraph
805 alignIndex = characterStartIndexBP; // Shift AS to be PS
807 else if((characterStartIndexBP <= alignIndex && alignIndex <= characterEndIndexBP) || /// ---PS.BBBBBBB.AS.BBBBBBB.PE---
808 (characterStartIndexBP <= alignEndIndex && alignEndIndex <= characterEndIndexBP)) /// ---PS.BBBBBB.AE.BBBBBBB.PE---
810 // Alignment from "Paragraph Start Index" to "Paragraph End Index" according to "BoundedParagraph Alignment"
811 decidedAlignStartIndex = characterStartIndexBP;
812 decidedAlignNumberOfCharacters = numberOfCharactersBP;
813 decidedHorizontalAlignment = boundedParagraphRun.horizontalAlignmentDefined ? boundedParagraphRun.horizontalAlignment : impl.mModel->mHorizontalAlignment;
815 alignIndex = characterEndIndexBP + 1u; // Shift AS to be after PE direct
816 boundedParagraphRunIndex++; // Align then check the case of next bounded paragraph
820 boundedParagraphRunIndex++; // Check the case of next bounded paragraph
824 impl.mLayoutEngine.Align(size,
825 decidedAlignStartIndex,
826 decidedAlignNumberOfCharacters,
827 decidedHorizontalAlignment,
829 impl.mModel->mAlignmentOffset,
830 impl.mLayoutDirection,
831 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
834 //Align the remaining that is not aligned
835 if(alignIndex <= alignEndIndex)
837 impl.mLayoutEngine.Align(size,
839 (alignEndIndex - alignIndex + 1u),
840 impl.mModel->mHorizontalAlignment,
842 impl.mModel->mAlignmentOffset,
843 impl.mLayoutDirection,
844 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
849 void Controller::Relayouter::CalculateVerticalOffset(Controller::Impl& impl, const Size& controlSize)
851 ModelPtr& model = impl.mModel;
852 VisualModelPtr& visualModel = model->mVisualModel;
853 Size layoutSize = model->mVisualModel->GetLayoutSize();
854 Size oldLayoutSize = layoutSize;
856 bool needRecalc = false;
857 float defaultFontLineHeight = impl.GetDefaultFontLineHeight();
859 if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
861 // Get the line height of the default font.
862 layoutSize.height = defaultFontLineHeight;
865 // Whether the text control is editable
866 const bool isEditable = NULL != impl.mEventData;
867 if(isEditable && !Dali::Equals(layoutSize.height, defaultFontLineHeight) && impl.IsShowingPlaceholderText())
869 // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
870 // This situation occurs when the size of placeholder text is different from the default text.
871 layoutSize.height = defaultFontLineHeight;
875 switch(model->mVerticalAlignment)
877 case VerticalAlignment::TOP:
879 model->mScrollPosition.y = 0.f;
883 case VerticalAlignment::CENTER:
885 model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
886 if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
889 case VerticalAlignment::BOTTOM:
891 model->mScrollPosition.y = controlSize.height - layoutSize.height;
892 if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
899 // Update glyphPositions according to recalculation.
900 const Length positionCount = visualModel->mGlyphPositions.Count();
901 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
902 for(Length index = 0u; index < positionCount; index++)
904 glyphPositions[index].y += offsetY;
911 } // namespace Toolkit