2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali-toolkit/internal/text/controller/text-controller-relayouter.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/integration-api/trace.h>
24 #include <dali/public-api/math/math-utils.h>
28 #include <dali-toolkit/internal/text/controller/text-controller-event-handler.h>
29 #include <dali-toolkit/internal/text/controller/text-controller-impl.h>
30 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
34 #if defined(DEBUG_ENABLED)
35 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
38 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_TEXT_PERFORMANCE_MARKER, false);
39 DALI_INIT_TRACE_FILTER(gTraceFilter2, DALI_TRACE_PERFORMANCE_MARKER, false);
41 constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
43 float ConvertToEven(float value)
45 int intValue(static_cast<int>(value));
46 return static_cast<float>(intValue + (intValue & 1));
57 Size Controller::Relayouter::CalculateLayoutSizeOnRequiredControllerSize(Controller& controller, const Size& requestedControllerSize, const OperationsMask& requestedOperationsMask)
59 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->CalculateLayoutSizeOnRequiredControllerSize\n");
60 Size calculatedLayoutSize;
62 Controller::Impl& impl = *controller.mImpl;
63 ModelPtr& model = impl.mModel;
64 VisualModelPtr& visualModel = model->mVisualModel;
66 // Operations that can be done only once until the text changes.
67 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
75 const OperationsMask sizeOperations = static_cast<OperationsMask>(LAYOUT | ALIGN | REORDER);
77 // Set the update info to relayout the whole text.
78 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
79 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
80 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
81 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
83 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
85 textUpdateInfo.mParagraphCharacterIndex = 0u;
86 textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
88 // Get a reference to the pending operations member
89 OperationsMask& operationsPending = impl.mOperationsPending;
91 // Store the actual control's size to restore later.
92 const Size actualControlSize = visualModel->mControlSize;
94 // This is to keep Index to the first character to be updated.
95 // Then restore it after calling Clear method.
96 auto updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
98 // Whether the text control is editable
99 const bool isEditable = NULL != impl.mEventData;
103 if(NO_OPERATION != (VALIDATE_FONTS & operationsPending) &&
104 textUpdateInfo.mCharacterIndex == static_cast<CharacterIndex>(-1))
106 impl.ClearFontData();
107 updateInfoCharIndexBackup = textUpdateInfo.mCharacterIndex;
110 impl.UpdateModel(onlyOnceOperations);
112 // Layout the text for the new width.
113 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask);
116 requestedControllerSize,
117 static_cast<OperationsMask>(onlyOnceOperations | requestedOperationsMask),
118 calculatedLayoutSize);
120 textUpdateInfo.Clear();
121 textUpdateInfo.mClearAll = true;
123 // Do not do again the only once operations.
124 operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
128 // Layout the text for the new width.
129 // Apply the pending operations, requested operations and the only once operations.
130 // Then remove onlyOnceOperations
131 operationsPending = static_cast<OperationsMask>(operationsPending | requestedOperationsMask | onlyOnceOperations);
133 // Make sure the model is up-to-date before layouting
134 impl.UpdateModel(static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE));
137 requestedControllerSize,
138 static_cast<OperationsMask>(operationsPending & ~UPDATE_LAYOUT_SIZE),
139 calculatedLayoutSize);
141 // Clear the update info. This info will be set the next time the text is updated.
142 textUpdateInfo.Clear();
144 //TODO: Refactor "DoRelayout" and extract common code of size calculation without modifying attributes of mVisualModel,
145 //TODO: then calculate GlyphPositions. Lines, Size, Layout for Natural-Size
146 //TODO: and utilize the values in OperationsPending and TextUpdateInfo without changing the original one.
147 //TODO: Also it will improve performance because there is no need todo FullRelyout on the next need for layouting.
150 // FullRelayoutNeeded should be true because DoRelayout is MAX_FLOAT, MAX_FLOAT.
151 // By this no need to take backup and restore it.
152 textUpdateInfo.mFullRelayoutNeeded = true;
154 // Restore mCharacterIndex. Because "Clear" set it to the maximum integer.
155 // The "CalculateTextUpdateIndices" does not work proprely because the mCharacterIndex will be greater than mPreviousNumberOfCharacters.
156 // Which apply an assumption to update only the last paragraph. That could cause many of out of index crashes.
157 textUpdateInfo.mCharacterIndex = updateInfoCharIndexBackup;
159 // Do the size related operations again.
160 operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
162 // Restore the actual control's size.
163 visualModel->mControlSize = actualControlSize;
165 return calculatedLayoutSize;
168 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
170 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
171 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_NATURAL_SIZE");
172 Vector3 naturalSizeVec3;
174 // Make sure the model is up-to-date before layouting
175 EventHandler::ProcessModifyEvents(controller);
177 Controller::Impl& impl = *controller.mImpl;
178 ModelPtr& model = impl.mModel;
179 VisualModelPtr& visualModel = model->mVisualModel;
181 if(impl.mRecalculateNaturalSize)
185 // Layout the text for the new width.
186 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT | REORDER);
187 Size sizeMaxWidthAndMaxHeight = Size(MAX_FLOAT, MAX_FLOAT);
189 naturalSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeMaxWidthAndMaxHeight, requestedOperationsMask);
191 // Stores the natural size to avoid recalculate it again
192 // unless the text/style changes.
193 visualModel->SetNaturalSize(naturalSize);
194 naturalSizeVec3 = naturalSize;
196 impl.mRecalculateNaturalSize = false;
198 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
202 naturalSizeVec3 = visualModel->GetNaturalSize();
204 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSizeVec3.x, naturalSizeVec3.y, naturalSizeVec3.z);
207 naturalSizeVec3.x = ConvertToEven(naturalSizeVec3.x);
208 naturalSizeVec3.y = ConvertToEven(naturalSizeVec3.y);
210 return naturalSizeVec3;
213 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
216 Controller::Impl& impl = *controller.mImpl;
217 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
218 impl.mFontDefaults->mFitPointSize = pointSize;
219 impl.mFontDefaults->sizeDefined = true;
220 impl.ClearFontData();
222 // Operations that can be done only once until the text changes.
223 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
231 textUpdateInfo.mParagraphCharacterIndex = 0u;
232 textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
234 // Make sure the model is up-to-date before layouting
235 impl.UpdateModel(onlyOnceOperations);
238 Size(layoutSize.width, MAX_FLOAT),
239 static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
242 // Clear the update info. This info will be set the next time the text is updated.
243 textUpdateInfo.Clear();
244 textUpdateInfo.mClearAll = true;
246 if(textSize.width > layoutSize.width || textSize.height > layoutSize.height)
253 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
255 Controller::Impl& impl = *controller.mImpl;
257 const OperationsMask operations = impl.mOperationsPending;
258 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
260 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_FIT_LAYOUT");
261 ModelPtr& model = impl.mModel;
263 bool actualellipsis = model->mElideEnabled;
264 float minPointSize = impl.mTextFitMinSize;
265 float maxPointSize = impl.mTextFitMaxSize;
266 float pointInterval = impl.mTextFitStepSize;
267 float currentFitPointSize = impl.mFontDefaults->mFitPointSize;
268 float currentDefaultLineSize = impl.mLayoutEngine.GetDefaultLineSize();
269 // Instead of using the LineSize of the current TextLabel, the LineSize set in TextFit is used.
270 impl.SetDefaultLineSize(impl.mTextFitLineSize);
272 model->mElideEnabled = false;
275 if(pointInterval < 1.f)
277 impl.mTextFitStepSize = pointInterval = 1.0f;
279 uint32_t pointSizeRange = static_cast<uint32_t>(ceil((maxPointSize - minPointSize) / pointInterval));
281 // Ensure minPointSize + pointSizeRange * pointInverval >= maxPointSize
282 while(minPointSize + static_cast<float>(pointSizeRange) * pointInterval < maxPointSize)
287 uint32_t bestSizeIndex = 0;
288 uint32_t minIndex = bestSizeIndex + 1u;
289 uint32_t maxIndex = pointSizeRange + 1u;
291 bool bestSizeUpdatedLatest = false;
292 // Find best size as binary search.
293 // Range format as [l r). (left closed, right opened)
294 // It mean, we already check all i < l is valid, and r <= i is invalid.
295 // Below binary search will check m = (l+r)/2 point.
296 // Search area sperate as [l m) or [m+1 r)
298 // Basically, we can assume that 0 (minPointSize) is always valid.
299 // Now, we will check [1 pointSizeRange] range s.t. pointSizeRange mean the maxPointSize
300 while(minIndex < maxIndex)
302 uint32_t testIndex = minIndex + ((maxIndex - minIndex) >> 1u);
303 const float testPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(testIndex) * pointInterval);
305 if(CheckForTextFit(controller, testPointSize, layoutSize))
307 bestSizeUpdatedLatest = true;
309 bestSizeIndex = testIndex;
310 minIndex = testIndex + 1u;
314 bestSizeUpdatedLatest = false;
315 maxIndex = testIndex;
318 const float bestPointSize = std::min(maxPointSize, minPointSize + static_cast<float>(bestSizeIndex) * pointInterval);
320 // Best point size was not updated. re-run so the TextFit should be fitted really.
321 if(!bestSizeUpdatedLatest)
323 CheckForTextFit(controller, bestPointSize, layoutSize);
326 model->mElideEnabled = actualellipsis;
327 if(!Dali::Equals(currentFitPointSize, bestPointSize))
329 impl.mTextFitChanged = true;
331 // Revert back to the original TextLabel LineSize.
332 impl.SetDefaultLineSize(currentDefaultLineSize);
333 impl.mFontDefaults->mFitPointSize = bestPointSize;
334 impl.mFontDefaults->sizeDefined = true;
335 impl.ClearFontData();
339 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
341 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
342 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_GET_HEIGHT_FOR_WIDTH");
344 // Make sure the model is up-to-date before layouting
345 EventHandler::ProcessModifyEvents(controller);
347 Controller::Impl& impl = *controller.mImpl;
348 ModelPtr& model = impl.mModel;
349 VisualModelPtr& visualModel = model->mVisualModel;
350 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
353 Size layoutSize = visualModel->GetHeightForWidth();
355 if(fabsf(width - layoutSize.width) > Math::MACHINE_EPSILON_1000 ||
356 textUpdateInfo.mFullRelayoutNeeded ||
357 textUpdateInfo.mClearAll)
359 // Layout the text for the new width.
360 OperationsMask requestedOperationsMask = static_cast<OperationsMask>(LAYOUT);
361 Size sizeRequestedWidthAndMaxHeight = Size(width, MAX_FLOAT);
363 layoutSize = CalculateLayoutSizeOnRequiredControllerSize(controller, sizeRequestedWidthAndMaxHeight, requestedOperationsMask);
365 // The calculated layout width may not be the same as the requested width.
366 // For cache efficiency, the requested width is stored.
367 layoutSize.width = width;
368 visualModel->SetHeightForWidth(layoutSize);
370 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
374 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
377 return layoutSize.height;
380 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
382 Controller::Impl& impl = *controller.mImpl;
383 ModelPtr& model = impl.mModel;
384 VisualModelPtr& visualModel = model->mVisualModel;
385 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
387 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
388 DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_RELAYOUT");
390 UpdateTextType updateTextType = NONE_UPDATED;
392 if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
394 if(0u != visualModel->mGlyphPositions.Count())
396 visualModel->mGlyphPositions.Clear();
397 updateTextType = MODEL_UPDATED;
400 // Clear the update info. This info will be set the next time the text is updated.
401 textUpdateInfo.Clear();
403 // Not worth to relayout if width or height is equal to zero.
404 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
406 return updateTextType;
409 // Whether a new size has been set.
410 const bool newSize = (size != visualModel->mControlSize);
412 // Get a reference to the pending operations member
413 OperationsMask& operationsPending = impl.mOperationsPending;
417 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
419 if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
420 (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
421 ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
423 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
426 // Layout operations that need to be done if the size changes.
427 operationsPending = static_cast<OperationsMask>(operationsPending |
432 // Set the update info to relayout the whole text.
433 textUpdateInfo.mFullRelayoutNeeded = true;
434 textUpdateInfo.mCharacterIndex = 0u;
436 // Store the size used to layout the text.
437 visualModel->mControlSize = size;
440 // Whether there are modify events.
441 if(0u != impl.mModifyEvents.Count())
443 // Style operations that need to be done if the text is modified.
444 operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
447 // Set the update info to elide the text.
448 if(model->mElideEnabled ||
449 ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
451 // Update Text layout for applying elided
452 operationsPending = static_cast<OperationsMask>(operationsPending |
457 textUpdateInfo.mFullRelayoutNeeded = true;
458 textUpdateInfo.mCharacterIndex = 0u;
461 bool layoutDirectionChanged = false;
462 if(impl.mLayoutDirection != layoutDirection)
464 // Flag to indicate that the layout direction has changed.
465 layoutDirectionChanged = true;
466 // Clear the update info. This info will be set the next time the text is updated.
467 textUpdateInfo.mClearAll = true;
468 // Apply modifications to the model
469 // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
470 operationsPending = static_cast<OperationsMask>(operationsPending |
478 impl.mLayoutDirection = layoutDirection;
481 // Make sure the model is up-to-date before layouting.
482 EventHandler::ProcessModifyEvents(controller);
483 bool updated = impl.UpdateModel(operationsPending);
487 updated = DoRelayout(impl, size, operationsPending, layoutSize) || updated;
491 updateTextType = MODEL_UPDATED;
494 // Do not re-do any operation until something changes.
495 operationsPending = NO_OPERATION;
496 model->mScrollPositionLast = model->mScrollPosition;
498 // Whether the text control is editable
499 const bool isEditable = NULL != impl.mEventData;
501 // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
503 if(newSize && isEditable)
505 offset = model->mScrollPosition;
508 if(!isEditable || !controller.IsMultiLineEnabled())
510 // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
511 CalculateVerticalOffset(impl, size);
515 // If layoutSize is bigger than size, vertical align has no meaning.
516 if(layoutSize.y < size.y)
518 CalculateVerticalOffset(impl, size);
521 impl.mEventData->mScrollAfterDelete = false;
528 if(newSize || layoutDirectionChanged)
530 // If there is a new size or layout direction is changed, the scroll position needs to be clamped.
531 impl.ClampHorizontalScroll(layoutSize);
533 // Update the decorator's positions is needed if there is a new size.
534 impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
536 // All decorator elements need to be updated.
537 if(EventData::IsEditingState(impl.mEventData->mState))
539 impl.mEventData->mScrollAfterUpdatePosition = true;
540 impl.mEventData->mUpdateCursorPosition = true;
541 impl.mEventData->mUpdateGrabHandlePosition = true;
543 else if(impl.mEventData->mState == EventData::SELECTING)
545 impl.mEventData->mUpdateHighlightBox = true;
549 // Move the cursor, grab handle etc.
550 if(impl.ProcessInputEvents())
552 updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
556 // Clear the update info. This info will be set the next time the text is updated.
557 textUpdateInfo.Clear();
558 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
560 return updateTextType;
563 bool Controller::Relayouter::DoRelayout(Controller::Impl& impl, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
565 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayouter::DoRelayout %p size %f,%f\n", &impl, size.width, size.height);
566 DALI_TRACE_SCOPE(gTraceFilter2, "DALI_TEXT_DORELAYOUT");
567 bool viewUpdated(false);
569 // Calculate the operations to be done.
570 const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
572 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
573 const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
574 const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
576 // Get the current layout size.
577 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
578 layoutSize = visualModel->GetLayoutSize();
580 if(NO_OPERATION != (LAYOUT & operations))
582 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
584 // Some vectors with data needed to layout and reorder may be void
585 // after the first time the text has been laid out.
586 // Fill the vectors again.
588 // Calculate the number of glyphs to layout.
589 const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
590 const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
591 const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
592 const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
594 const CharacterIndex lastIndex = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
595 const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
597 // Make sure the index is not out of bound
598 if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
599 requestedNumberOfCharacters > charactersToGlyph.Count() ||
600 (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
602 std::string currentText;
603 impl.GetText(currentText);
605 DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
606 DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
607 DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
612 const Length numberOfGlyphs = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
613 const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
615 if(0u == totalNumberOfGlyphs)
617 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
619 visualModel->SetLayoutSize(Size::ZERO);
622 // Nothing else to do if there is no glyphs.
623 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
627 // Set the layout parameters.
628 Layout::Parameters layoutParameters(size, impl.mModel);
630 // Resize the vector of positions to have the same size than the vector of glyphs.
631 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
632 glyphPositions.Resize(totalNumberOfGlyphs);
634 // Whether the last character is a new paragraph character.
635 const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
636 textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
637 layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
639 // The initial glyph and the number of glyphs to layout.
640 layoutParameters.startGlyphIndex = startGlyphIndex;
641 layoutParameters.numberOfGlyphs = numberOfGlyphs;
642 layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
643 layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
645 // Update the ellipsis
646 bool elideTextEnabled = impl.mModel->mElideEnabled;
647 auto ellipsisPosition = impl.mModel->mEllipsisPosition;
649 if(NULL != impl.mEventData)
651 if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
653 elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
655 else if(EventData::INACTIVE != impl.mEventData->mState)
657 // Disable ellipsis when editing
658 elideTextEnabled = false;
661 // Reset the scroll position in inactive state
662 if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
664 impl.ResetScrollPosition();
668 // Update the visual model.
669 bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
670 bool isAutoScrollMaxTextureExceeded = impl.mIsAutoScrollMaxTextureExceeded;
671 bool isHiddenInputEnabled = false;
672 if(impl.mHiddenInput && impl.mEventData != nullptr && impl.mHiddenInput->GetHideMode() != Toolkit::HiddenInput::Mode::HIDE_NONE)
674 isHiddenInputEnabled = true;
678 viewUpdated = impl.mLayoutEngine.LayoutText(layoutParameters,
682 isAutoScrollMaxTextureExceeded,
683 isHiddenInputEnabled,
685 impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
687 viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
691 layoutSize = newLayoutSize;
693 if(NO_OPERATION != (UPDATE_DIRECTION & operations))
695 impl.mIsTextDirectionRTL = false;
698 if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
700 impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
703 // Sets the layout size.
704 if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
706 visualModel->SetLayoutSize(layoutSize);
711 if(NO_OPERATION != (ALIGN & operations))
713 DoRelayoutHorizontalAlignment(impl, size, startIndex, requestedNumberOfCharacters);
716 #if defined(DEBUG_ENABLED)
717 std::string currentText;
718 impl.GetText(currentText);
719 DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::Relayouter::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &impl, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
721 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayouter::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
725 void Controller::Relayouter::DoRelayoutHorizontalAlignment(Controller::Impl& impl,
727 const CharacterIndex startIndex,
728 const Length requestedNumberOfCharacters)
731 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
733 // The laid-out lines.
734 Vector<LineRun>& lines = visualModel->mLines;
736 CharacterIndex alignStartIndex = startIndex;
737 Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
739 // the whole text needs to be full aligned.
740 // If you do not do a full aligned, only the last line of the multiline input is aligned.
741 if(impl.mEventData && impl.mEventData->mUpdateAlignment)
743 alignStartIndex = 0u;
744 alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
745 impl.mEventData->mUpdateAlignment = false;
748 // If there is no BoundedParagraphRuns then apply the alignment of controller.
749 // Check whether the layout is single line. It's needed to apply one alignment for single-line.
750 // In single-line layout case we need to check whether to follow the alignment of controller or the first BoundedParagraph.
751 // Apply BoundedParagraph's alignment if and only if there is one BoundedParagraph contains all characters. Otherwise follow controller's alignment.
752 const bool isFollowControllerAlignment = ((impl.mModel->GetNumberOfBoundedParagraphRuns() == 0u) ||
753 ((Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) &&
754 (impl.mModel->GetBoundedParagraphRuns()[0].characterRun.numberOfCharacters != impl.mModel->mLogicalModel->mText.Count())));
756 if(isFollowControllerAlignment)
758 // Need to align with the control's size as the text may contain lines
759 // starting either with left to right text or right to left.
760 impl.mLayoutEngine.Align(size,
762 alignRequestedNumberOfCharacters,
763 impl.mModel->mHorizontalAlignment,
765 impl.mModel->mAlignmentOffset,
766 impl.mLayoutDirection,
767 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
771 //Override the controller horizontal-alignment by horizontal-alignment of bounded paragraph.
772 const Length& numberOfBoundedParagraphRuns = impl.mModel->GetNumberOfBoundedParagraphRuns();
773 const Vector<BoundedParagraphRun>& boundedParagraphRuns = impl.mModel->GetBoundedParagraphRuns();
774 const CharacterIndex alignEndIndex = alignStartIndex + alignRequestedNumberOfCharacters - 1u;
776 Length alignIndex = alignStartIndex;
777 Length boundedParagraphRunIndex = 0u;
779 while(alignIndex <= alignEndIndex && boundedParagraphRunIndex < numberOfBoundedParagraphRuns)
781 //BP: BoundedParagraph
782 const BoundedParagraphRun& boundedParagraphRun = boundedParagraphRuns[boundedParagraphRunIndex];
783 const CharacterIndex& characterStartIndexBP = boundedParagraphRun.characterRun.characterIndex;
784 const Length& numberOfCharactersBP = boundedParagraphRun.characterRun.numberOfCharacters;
785 const CharacterIndex characterEndIndexBP = characterStartIndexBP + numberOfCharactersBP - 1u;
787 CharacterIndex decidedAlignStartIndex = alignIndex;
788 Length decidedAlignNumberOfCharacters = alignEndIndex - alignIndex + 1u;
789 Text::HorizontalAlignment::Type decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
792 * Shortcuts to explain indexes cases:
794 * AS: Alignment Start Index
795 * AE: Alignment End Index
796 * PS: Paragraph Start Index
797 * PE: Paragraph End Index
798 * B: BoundedParagraph Alignment
803 if(alignIndex < characterStartIndexBP && characterStartIndexBP <= alignEndIndex) /// AS.MMMMMM.PS--------AE
805 // Alignment from "Alignment Start Index" to index before "Paragraph Start Index" according to "Model Alignment"
806 decidedAlignStartIndex = alignIndex;
807 decidedAlignNumberOfCharacters = characterStartIndexBP - alignIndex;
808 decidedHorizontalAlignment = impl.mModel->mHorizontalAlignment;
810 // Need to re-heck the case of current bounded paragraph
811 alignIndex = characterStartIndexBP; // Shift AS to be PS
813 else if((characterStartIndexBP <= alignIndex && alignIndex <= characterEndIndexBP) || /// ---PS.BBBBBBB.AS.BBBBBBB.PE---
814 (characterStartIndexBP <= alignEndIndex && alignEndIndex <= characterEndIndexBP)) /// ---PS.BBBBBB.AE.BBBBBBB.PE---
816 // Alignment from "Paragraph Start Index" to "Paragraph End Index" according to "BoundedParagraph Alignment"
817 decidedAlignStartIndex = characterStartIndexBP;
818 decidedAlignNumberOfCharacters = numberOfCharactersBP;
819 decidedHorizontalAlignment = boundedParagraphRun.horizontalAlignmentDefined ? boundedParagraphRun.horizontalAlignment : impl.mModel->mHorizontalAlignment;
821 alignIndex = characterEndIndexBP + 1u; // Shift AS to be after PE direct
822 boundedParagraphRunIndex++; // Align then check the case of next bounded paragraph
826 boundedParagraphRunIndex++; // Check the case of next bounded paragraph
830 impl.mLayoutEngine.Align(size,
831 decidedAlignStartIndex,
832 decidedAlignNumberOfCharacters,
833 decidedHorizontalAlignment,
835 impl.mModel->mAlignmentOffset,
836 impl.mLayoutDirection,
837 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
840 //Align the remaining that is not aligned
841 if(alignIndex <= alignEndIndex)
843 impl.mLayoutEngine.Align(size,
845 (alignEndIndex - alignIndex + 1u),
846 impl.mModel->mHorizontalAlignment,
848 impl.mModel->mAlignmentOffset,
849 impl.mLayoutDirection,
850 (impl.mModel->mMatchLayoutDirection != DevelText::MatchLayoutDirection::CONTENTS));
855 void Controller::Relayouter::CalculateVerticalOffset(Controller::Impl& impl, const Size& controlSize)
857 ModelPtr& model = impl.mModel;
858 VisualModelPtr& visualModel = model->mVisualModel;
859 Size layoutSize = model->mVisualModel->GetLayoutSize();
860 Size oldLayoutSize = layoutSize;
862 bool needRecalc = false;
863 float defaultFontLineHeight = impl.GetDefaultFontLineHeight();
865 if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
867 // Get the line height of the default font.
868 layoutSize.height = defaultFontLineHeight;
871 // Whether the text control is editable
872 const bool isEditable = NULL != impl.mEventData;
873 if(isEditable && !Dali::Equals(layoutSize.height, defaultFontLineHeight) && impl.IsShowingPlaceholderText())
875 // This code prevents the wrong positioning of cursor when the layout size is bigger/smaller than defaultFontLineHeight.
876 // This situation occurs when the size of placeholder text is different from the default text.
877 layoutSize.height = defaultFontLineHeight;
881 switch(model->mVerticalAlignment)
883 case VerticalAlignment::TOP:
885 model->mScrollPosition.y = 0.f;
889 case VerticalAlignment::CENTER:
891 model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
892 if(needRecalc) offsetY = floorf(0.5f * (layoutSize.height - oldLayoutSize.height));
895 case VerticalAlignment::BOTTOM:
897 model->mScrollPosition.y = controlSize.height - layoutSize.height;
898 if(needRecalc) offsetY = layoutSize.height - oldLayoutSize.height;
905 // Update glyphPositions according to recalculation.
906 const Length positionCount = visualModel->mGlyphPositions.Count();
907 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
908 for(Length index = 0u; index < positionCount; index++)
910 glyphPositions[index].y += offsetY;
917 } // namespace Toolkit