2 * Copyright (c) 2020 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/text-controller-relayouter.h>
23 #include <dali/integration-api/debug.h>
26 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
27 #include <dali-toolkit/internal/text/text-controller-impl.h>
32 #if defined(DEBUG_ENABLED)
33 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
36 constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
38 float ConvertToEven( float value )
40 int intValue(static_cast<int>( value ));
41 return static_cast<float>( intValue + ( intValue & 1 ) );
55 Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
57 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
60 // Make sure the model is up-to-date before layouting
61 controller.ProcessModifyEvents();
63 Controller::Impl& impl = *controller.mImpl;
64 ModelPtr& model = impl.mModel;
65 VisualModelPtr& visualModel = model->mVisualModel;
66 if( impl.mRecalculateNaturalSize )
68 // Operations that can be done only once until the text changes.
69 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
77 // Set the update info to relayout the whole text.
78 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
79 textUpdateInfo.mParagraphCharacterIndex = 0u;
80 textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
82 // Make sure the model is up-to-date before layouting
83 impl.UpdateModel( onlyOnceOperations );
85 // Get a reference to the pending operations member
86 OperationsMask& operationsPending = impl.mOperationsPending;
88 // Layout the text for the new width.
89 operationsPending = static_cast<OperationsMask>( operationsPending | LAYOUT | REORDER );
91 // Store the actual control's size to restore later.
92 const Size actualControlSize = visualModel->mControlSize;
94 DoRelayout( controller,
95 Size( MAX_FLOAT, MAX_FLOAT ),
96 static_cast<OperationsMask>( onlyOnceOperations |
98 naturalSize.GetVectorXY() );
100 // Do not do again the only once operations.
101 operationsPending = static_cast<OperationsMask>( operationsPending & ~onlyOnceOperations );
103 // Do the size related operations again.
104 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
107 operationsPending = static_cast<OperationsMask>( operationsPending | sizeOperations );
109 // Stores the natural size to avoid recalculate it again
110 // unless the text/style changes.
111 visualModel->SetNaturalSize( naturalSize.GetVectorXY() );
113 impl.mRecalculateNaturalSize = false;
115 // Clear the update info. This info will be set the next time the text is updated.
116 textUpdateInfo.Clear();
117 textUpdateInfo.mClearAll = true;
119 // Restore the actual control's size.
120 visualModel->mControlSize = actualControlSize;
122 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
126 naturalSize = visualModel->GetNaturalSize();
128 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
131 naturalSize.x = ConvertToEven( naturalSize.x );
132 naturalSize.y = ConvertToEven( naturalSize.y );
137 bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
140 Controller::Impl& impl = *controller.mImpl;
141 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
142 impl.mFontDefaults->mFitPointSize = pointSize;
143 impl.mFontDefaults->sizeDefined = true;
144 controller.ClearFontData();
146 // Operations that can be done only once until the text changes.
147 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
155 textUpdateInfo.mParagraphCharacterIndex = 0u;
156 textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
158 // Make sure the model is up-to-date before layouting
159 impl.UpdateModel( onlyOnceOperations );
161 DoRelayout( controller,
162 Size( layoutSize.width, MAX_FLOAT ),
163 static_cast<OperationsMask>( onlyOnceOperations | LAYOUT),
166 // Clear the update info. This info will be set the next time the text is updated.
167 textUpdateInfo.Clear();
168 textUpdateInfo.mClearAll = true;
170 if( textSize.width > layoutSize.width || textSize.height > layoutSize.height )
177 void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const Size& layoutSize)
179 Controller::Impl& impl = *controller.mImpl;
181 const OperationsMask operations = impl.mOperationsPending;
182 if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) || impl.mTextFitContentSize != layoutSize )
184 ModelPtr& model = impl.mModel;
186 bool actualellipsis = model->mElideEnabled;
187 float minPointSize = impl.mTextFitMinSize;
188 float maxPointSize = impl.mTextFitMaxSize;
189 float pointInterval = impl.mTextFitStepSize;
191 model->mElideEnabled = false;
192 Vector<float> pointSizeArray;
195 if( pointInterval < 1.f )
197 impl.mTextFitStepSize = pointInterval = 1.0f;
200 pointSizeArray.Reserve( static_cast< unsigned int >( ceil( ( maxPointSize - minPointSize ) / pointInterval ) ) );
202 for( float i = minPointSize; i < maxPointSize; i += pointInterval )
204 pointSizeArray.PushBack( i );
207 pointSizeArray.PushBack( maxPointSize );
209 int bestSizeIndex = 0;
210 int min = bestSizeIndex + 1;
211 int max = pointSizeArray.Size() - 1;
214 int destI = ( min + max ) / 2;
216 if( CheckForTextFit( controller, pointSizeArray[destI], layoutSize ) )
228 model->mElideEnabled = actualellipsis;
229 impl.mFontDefaults->mFitPointSize = pointSizeArray[bestSizeIndex];
230 impl.mFontDefaults->sizeDefined = true;
231 controller.ClearFontData();
235 float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
237 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width );
238 // Make sure the model is up-to-date before layouting
239 controller.ProcessModifyEvents();
241 Controller::Impl& impl = *controller.mImpl;
242 ModelPtr& model = impl.mModel;
243 VisualModelPtr& visualModel = model->mVisualModel;
244 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
247 if( fabsf( width - visualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 ||
248 textUpdateInfo.mFullRelayoutNeeded ||
249 textUpdateInfo.mClearAll )
251 // Operations that can be done only once until the text changes.
252 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
260 // Set the update info to relayout the whole text.
261 textUpdateInfo.mParagraphCharacterIndex = 0u;
262 textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
264 // Make sure the model is up-to-date before layouting
265 impl.UpdateModel( onlyOnceOperations );
267 // Get a reference to the pending operations member
268 OperationsMask& operationsPending = impl.mOperationsPending;
270 // Layout the text for the new width.
271 operationsPending = static_cast<OperationsMask>( operationsPending | LAYOUT );
273 // Store the actual control's width.
274 const float actualControlWidth = visualModel->mControlSize.width;
276 DoRelayout( controller,
277 Size( width, MAX_FLOAT ),
278 static_cast<OperationsMask>( onlyOnceOperations |
282 // Do not do again the only once operations.
283 operationsPending = static_cast<OperationsMask>( operationsPending & ~onlyOnceOperations );
285 // Do the size related operations again.
286 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
290 operationsPending = static_cast<OperationsMask>( operationsPending | sizeOperations );
292 // Clear the update info. This info will be set the next time the text is updated.
293 textUpdateInfo.Clear();
294 textUpdateInfo.mClearAll = true;
296 // Restore the actual control's width.
297 visualModel->mControlSize.width = actualControlWidth;
299 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
303 layoutSize = visualModel->GetLayoutSize();
304 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
307 return layoutSize.height;
310 Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
312 Controller::Impl& impl = *controller.mImpl;
313 ModelPtr& model = impl.mModel;
314 VisualModelPtr& visualModel = model->mVisualModel;
315 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
317 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ?"true":"false" );
319 UpdateTextType updateTextType = NONE_UPDATED;
321 if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
323 if( 0u != visualModel->mGlyphPositions.Count() )
325 visualModel->mGlyphPositions.Clear();
326 updateTextType = MODEL_UPDATED;
329 // Clear the update info. This info will be set the next time the text is updated.
330 textUpdateInfo.Clear();
332 // Not worth to relayout if width or height is equal to zero.
333 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
335 return updateTextType;
338 // Whether a new size has been set.
339 const bool newSize = ( size != visualModel->mControlSize );
341 // Get a reference to the pending operations member
342 OperationsMask& operationsPending = impl.mOperationsPending;
346 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height );
348 if( ( 0 == textUpdateInfo.mNumberOfCharactersToAdd ) &&
349 ( 0 == textUpdateInfo.mPreviousNumberOfCharacters ) &&
350 ( ( visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000 ) || ( visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000 ) ) )
352 textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
355 // Layout operations that need to be done if the size changes.
356 operationsPending = static_cast<OperationsMask>( operationsPending |
361 // Set the update info to relayout the whole text.
362 textUpdateInfo.mFullRelayoutNeeded = true;
363 textUpdateInfo.mCharacterIndex = 0u;
365 // Store the size used to layout the text.
366 visualModel->mControlSize = size;
369 // Whether there are modify events.
370 if( 0u != impl.mModifyEvents.Count() )
372 // Style operations that need to be done if the text is modified.
373 operationsPending = static_cast<OperationsMask>( operationsPending | COLOR );
376 // Set the update info to elide the text.
377 if( model->mElideEnabled ||
378 ( ( NULL != impl.mEventData ) && impl.mEventData->mIsPlaceholderElideEnabled ) )
380 // Update Text layout for applying elided
381 operationsPending = static_cast<OperationsMask>( operationsPending |
386 textUpdateInfo.mFullRelayoutNeeded = true;
387 textUpdateInfo.mCharacterIndex = 0u;
390 if( model->mMatchSystemLanguageDirection && impl.mLayoutDirection != layoutDirection )
392 // Clear the update info. This info will be set the next time the text is updated.
393 textUpdateInfo.mClearAll = true;
394 // Apply modifications to the model
395 // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
396 operationsPending = static_cast<OperationsMask>( operationsPending |
403 impl.mLayoutDirection = layoutDirection;
406 // Make sure the model is up-to-date before layouting.
407 controller.ProcessModifyEvents();
408 bool updated = impl.UpdateModel( operationsPending );
412 updated = DoRelayout( controller, size, operationsPending, layoutSize ) || updated;
417 updateTextType = MODEL_UPDATED;
420 // Do not re-do any operation until something changes.
421 operationsPending = NO_OPERATION;
422 model->mScrollPositionLast = model->mScrollPosition;
424 // Whether the text control is editable
425 const bool isEditable = NULL != impl.mEventData;
427 // Keep the current offset as it will be used to update the decorator's positions (if the size changes).
429 if( newSize && isEditable )
431 offset = model->mScrollPosition;
434 if( !isEditable || !controller.IsMultiLineEnabled() )
436 // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
437 controller.CalculateVerticalOffset( size );
444 // If there is a new size, the scroll position needs to be clamped.
445 impl.ClampHorizontalScroll( layoutSize );
447 // Update the decorator's positions is needed if there is a new size.
448 impl.mEventData->mDecorator->UpdatePositions( model->mScrollPosition - offset );
451 // Move the cursor, grab handle etc.
452 if( impl.ProcessInputEvents() )
454 updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
458 // Clear the update info. This info will be set the next time the text is updated.
459 textUpdateInfo.Clear();
460 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
462 return updateTextType;
465 bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size, OperationsMask operationsRequired, Size& layoutSize )
467 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", &controller, size.width, size.height );
468 bool viewUpdated( false );
470 Controller::Impl& impl = *controller.mImpl;
472 // Calculate the operations to be done.
473 const OperationsMask operations = static_cast<OperationsMask>( impl.mOperationsPending & operationsRequired );
475 TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
476 const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
477 const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
479 // Get the current layout size.
480 VisualModelPtr& visualModel = impl.mModel->mVisualModel;
481 layoutSize = visualModel->GetLayoutSize();
483 if( NO_OPERATION != ( LAYOUT & operations ) )
485 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
487 // Some vectors with data needed to layout and reorder may be void
488 // after the first time the text has been laid out.
489 // Fill the vectors again.
491 // Calculate the number of glyphs to layout.
492 const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
493 const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
494 const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
495 const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
497 const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
498 const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
500 // Make sure the index is not out of bound
501 if ( charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
502 requestedNumberOfCharacters > charactersToGlyph.Count() ||
503 ( lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u ) )
505 std::string currentText;
506 controller.GetText( currentText );
508 DALI_LOG_ERROR( "Controller::DoRelayout: Attempting to access invalid buffer\n" );
509 DALI_LOG_ERROR( "Current text is: %s\n", currentText.c_str() );
510 DALI_LOG_ERROR( "startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
515 const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
516 const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
518 if( 0u == totalNumberOfGlyphs )
520 if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
522 visualModel->SetLayoutSize( Size::ZERO );
525 // Nothing else to do if there is no glyphs.
526 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
530 // Set the layout parameters.
531 Layout::Parameters layoutParameters( size, impl.mModel);
533 // Resize the vector of positions to have the same size than the vector of glyphs.
534 Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
535 glyphPositions.Resize( totalNumberOfGlyphs );
537 // Whether the last character is a new paragraph character.
538 const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
539 textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( impl.mModel->mLogicalModel->mText.Count() - 1u ) ) );
540 layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
542 // The initial glyph and the number of glyphs to layout.
543 layoutParameters.startGlyphIndex = startGlyphIndex;
544 layoutParameters.numberOfGlyphs = numberOfGlyphs;
545 layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
546 layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
548 // Update the ellipsis
549 bool elideTextEnabled = impl.mModel->mElideEnabled;
551 if( NULL != impl.mEventData )
553 if( impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText() )
555 elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
557 else if( EventData::INACTIVE != impl.mEventData->mState )
559 // Disable ellipsis when editing
560 elideTextEnabled = false;
563 // Reset the scroll position in inactive state
564 if( elideTextEnabled && ( impl.mEventData->mState == EventData::INACTIVE ) )
566 controller.ResetScrollPosition();
570 // Update the visual model.
571 bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
573 viewUpdated = impl.mLayoutEngine.LayoutText( layoutParameters,
576 isAutoScrollEnabled );
577 impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
579 viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
583 layoutSize = newLayoutSize;
585 if( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
587 impl.mIsTextDirectionRTL = false;
590 if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && !visualModel->mLines.Empty() )
592 impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
595 // Sets the layout size.
596 if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
598 visualModel->SetLayoutSize( layoutSize );
603 if( NO_OPERATION != ( ALIGN & operations ) )
605 // The laid-out lines.
606 Vector<LineRun>& lines = visualModel->mLines;
608 CharacterIndex alignStartIndex = startIndex;
609 Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
611 // the whole text needs to be full aligned.
612 // If you do not do a full aligned, only the last line of the multiline input is aligned.
613 if( impl.mEventData && impl.mEventData->mUpdateAlignment )
615 alignStartIndex = 0u;
616 alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
617 impl.mEventData->mUpdateAlignment = false;
620 // Need to align with the control's size as the text may contain lines
621 // starting either with left to right text or right to left.
622 impl.mLayoutEngine.Align( size,
624 alignRequestedNumberOfCharacters,
625 impl.mModel->mHorizontalAlignment,
627 impl.mModel->mAlignmentOffset,
628 impl.mLayoutDirection,
629 impl.mModel->mMatchSystemLanguageDirection );
633 #if defined(DEBUG_ENABLED)
634 std::string currentText;
635 controller.GetText( currentText );
636 DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &controller, (impl.mIsTextDirectionRTL)?"true":"false", currentText.c_str() );
638 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
642 void Controller::Relayouter::CalculateVerticalOffset(Controller& controller, const Size& controlSize)
644 Controller::Impl& impl = *controller.mImpl;
645 ModelPtr& model = impl.mModel;
646 Size layoutSize = model->mVisualModel->GetLayoutSize();
648 if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
650 // Get the line height of the default font.
651 layoutSize.height = impl.GetDefaultFontLineHeight();
654 switch( model->mVerticalAlignment )
656 case VerticalAlignment::TOP:
658 model->mScrollPosition.y = 0.f;
661 case VerticalAlignment::CENTER:
663 model->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
666 case VerticalAlignment::BOTTOM:
668 model->mScrollPosition.y = controlSize.height - layoutSize.height;
676 } // namespace Toolkit