2 * Copyright (c) 2015 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.h>
24 #include <dali/public-api/adaptor-framework/key.h>
25 #include <dali/public-api/text-abstraction/font-client.h>
28 #include <dali-toolkit/internal/text/bidirectional-support.h>
29 #include <dali-toolkit/internal/text/character-set-conversion.h>
30 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
31 #include <dali-toolkit/internal/text/layouts/layout-parameters.h>
32 #include <dali-toolkit/internal/text/logical-model-impl.h>
33 #include <dali-toolkit/internal/text/multi-language-support.h>
34 #include <dali-toolkit/internal/text/script-run.h>
35 #include <dali-toolkit/internal/text/segmentation.h>
36 #include <dali-toolkit/internal/text/shaper.h>
37 #include <dali-toolkit/internal/text/text-io.h>
38 #include <dali-toolkit/internal/text/text-view.h>
39 #include <dali-toolkit/internal/text/visual-model-impl.h>
46 const float MAX_FLOAT = std::numeric_limits<float>::max();
47 const std::string EMPTY_STRING;
51 REPLACE_TEXT, ///< Replace the entire text
52 INSERT_TEXT, ///< Insert characters at the current cursor position
53 DELETE_TEXT ///< Delete a character at the current cursor position
73 struct Controller::TextInput
75 // Used to queue input events until DoRelayout()
78 KEYBOARD_FOCUS_GAIN_EVENT,
79 KEYBOARD_FOCUS_LOST_EVENT,
94 Event( EventType eventType )
114 TextInput( LogicalModelPtr logicalModel,
115 VisualModelPtr visualModel,
116 DecoratorPtr decorator )
117 : mLogicalModel( logicalModel ),
118 mVisualModel( visualModel ),
119 mDecorator( decorator ),
121 mPrimaryCursorPosition( 0u ),
122 mSecondaryCursorPosition( 0u ),
123 mDecoratorUpdated( false ),
124 mCursorBlinkEnabled( true )
129 * @brief Helper to move the cursor, grab handle etc.
131 bool ProcessInputEvents()
133 mDecoratorUpdated = false;
137 for( vector<TextInput::Event>::iterator iter = mEventQueue.begin(); iter != mEventQueue.end(); ++iter )
141 case KEYBOARD_FOCUS_GAIN_EVENT:
143 OnKeyboardFocus( true );
146 case KEYBOARD_FOCUS_LOST_EVENT:
148 OnKeyboardFocus( false );
151 case CURSOR_KEY_EVENT:
153 OnCursorKeyEvent( *iter );
161 case GRAB_HANDLE_EVENT:
163 OnGrabHandleEvent( *iter );
172 return mDecoratorUpdated;
175 void OnKeyboardFocus( bool hasFocus )
179 ChangeState( INACTIVE );
183 ChangeState( EDITING );
187 void OnCursorKeyEvent( const Event& event )
189 int keyCode = event.p1.mInt;
191 if( Dali::DALI_KEY_CURSOR_LEFT == keyCode )
195 else if( Dali::DALI_KEY_CURSOR_RIGHT == keyCode )
199 else if( Dali::DALI_KEY_CURSOR_UP == keyCode )
203 else if( Dali::DALI_KEY_CURSOR_DOWN == keyCode )
209 void HandleBackspaceKey()
214 void HandleCursorKey( int keyCode )
219 void HandleKeyString( const char* keyString )
224 void OnTapEvent( const Event& event )
226 unsigned int tapCount = event.p1.mUint;
230 ChangeState( EDITING );
232 float xPosition = event.p2.mFloat;
233 float yPosition = event.p3.mFloat;
235 GetClosestCursorPosition( xPosition, yPosition, height );
236 mDecorator->SetPosition( PRIMARY_CURSOR, xPosition, yPosition, height );
238 mDecoratorUpdated = true;
240 else if( 2u == tapCount )
242 ChangeState( SELECTING );
246 void OnGrabHandleEvent( const Event& event )
248 unsigned int state = event.p1.mUint;
250 if( GRAB_HANDLE_PRESSED == state )
252 float xPosition = event.p2.mFloat;
253 float yPosition = event.p3.mFloat;
256 GetClosestCursorPosition( xPosition, yPosition, height );
258 mDecorator->SetPosition( PRIMARY_CURSOR, xPosition, yPosition, height );
259 mDecorator->HidePopup();
260 mDecoratorUpdated = true;
262 else if ( GRAB_HANDLE_RELEASED == state )
264 mDecorator->ShowPopup();
269 void ChangeState( State newState )
271 if( mState != newState )
275 if( INACTIVE == mState )
277 mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE );
278 mDecorator->StopCursorBlink();
279 mDecorator->SetGrabHandleActive( false );
280 mDecorator->SetSelectionActive( false );
281 mDecorator->HidePopup();
282 mDecoratorUpdated = true;
284 else if ( SELECTING == mState )
286 mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE );
287 mDecorator->StopCursorBlink();
288 mDecorator->SetGrabHandleActive( false );
289 mDecorator->SetSelectionActive( true );
290 mDecoratorUpdated = true;
292 else if( EDITING == mState )
294 mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
295 if( mCursorBlinkEnabled )
297 mDecorator->StartCursorBlink();
299 mDecorator->SetGrabHandleActive( true );
300 mDecorator->SetSelectionActive( false );
301 mDecoratorUpdated = true;
306 void GetClosestCursorPosition( float& x, float& y, float& height )
308 // TODO - Look at LineRuns first
310 Text::Length numberOfGlyphs = mVisualModel->GetNumberOfGlyphs();
311 if( 0 == numberOfGlyphs )
316 Vector<GlyphInfo>& glyphs = mVisualModel->mGlyphs;
317 const GlyphInfo* const glyphsBuffer = glyphs.Begin();
319 Vector<Vector2>& positions = mVisualModel->mGlyphPositions;
320 const Vector2* const positionsBuffer = positions.Begin();
322 unsigned int closestGlyph = 0;
323 float closestDistance = MAX_FLOAT;
325 for( unsigned int i = 0, numberOfGLyphs = glyphs.Count(); i < numberOfGLyphs; ++i )
327 const GlyphInfo& glyphInfo = *( glyphsBuffer + i );
328 const Vector2& position = *( positionsBuffer + i );
329 float glyphX = position.x + glyphInfo.width*0.5f;
330 float glyphY = position.y + glyphInfo.height*0.5f;
332 float distanceToGlyph = fabsf( glyphX - x ) + fabsf( glyphY - y );
334 if( distanceToGlyph < closestDistance )
336 closestDistance = distanceToGlyph;
341 // TODO - Consider RTL languages
342 x = positions[closestGlyph].x + glyphs[closestGlyph].width;
346 TextAbstraction::FontClient::Get().GetFontMetrics( glyphs[closestGlyph].fontId, metrics );
347 height = metrics.height; // TODO - Fix for multi-line
350 LogicalModelPtr mLogicalModel;
351 VisualModelPtr mVisualModel;
352 DecoratorPtr mDecorator;
354 std::string mPlaceholderText;
357 * This is used to delay handling events until after the model has been updated.
358 * The number of updates to the model is minimized to improve performance.
360 vector<Event> mEventQueue; ///< The queue of touch events etc.
362 State mState; ///< Selection mode, edit mode etc.
364 CharacterIndex mPrimaryCursorPosition; ///< Index into logical model for primary cursor
365 CharacterIndex mSecondaryCursorPosition; ///< Index into logical model for secondary cursor
367 bool mDecoratorUpdated : 1; ///< True if the decorator was updated during event processing
368 bool mCursorBlinkEnabled : 1; ///< True if cursor should blink when active
371 struct Controller::FontDefaults
374 : mDefaultPointSize(0.0f),
379 FontId GetFontId( TextAbstraction::FontClient& fontClient )
383 Dali::TextAbstraction::PointSize26Dot6 pointSize = mDefaultPointSize*64;
384 mFontId = fontClient.GetFontId( mDefaultFontFamily, mDefaultFontStyle, pointSize );
390 std::string mDefaultFontFamily;
391 std::string mDefaultFontStyle;
392 float mDefaultPointSize;
396 struct Controller::Impl
398 Impl( ControlInterface& controlInterface )
399 : mControlInterface( controlInterface ),
402 mFontDefaults( NULL ),
409 mOperationsPending( NO_OPERATION ),
410 mRecalculateNaturalSize( true )
412 mLogicalModel = LogicalModel::New();
413 mVisualModel = VisualModel::New();
415 mFontClient = TextAbstraction::FontClient::Get();
417 mView.SetVisualModel( mVisualModel );
425 ControlInterface& mControlInterface; ///< Reference to the text controller.
426 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
427 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
428 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
429 Controller::TextInput* mTextInput; ///< Avoid allocating everything for text input until EnableTextInput().
430 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
431 View mView; ///< The view interface to the rendering back-end.
432 LayoutEngine mLayoutEngine; ///< The layout engine.
433 std::vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
434 Size mControlSize; ///< The size of the control.
435 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
436 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
439 ControllerPtr Controller::New( ControlInterface& controlInterface )
441 return ControllerPtr( new Controller( controlInterface ) );
444 void Controller::SetText( const std::string& text )
446 // Cancel previously queued inserts etc.
447 mImpl->mModifyEvents.clear();
449 // Keep until size negotiation
451 event.type = REPLACE_TEXT;
453 mImpl->mModifyEvents.push_back( event );
455 if( mImpl->mTextInput )
457 // Cancel previously queued events
458 mImpl->mTextInput->mEventQueue.clear();
460 // TODO - Hide selection decorations
464 void Controller::GetText( std::string& text ) const
466 if( !mImpl->mModifyEvents.empty() &&
467 REPLACE_TEXT == mImpl->mModifyEvents[0].type )
469 text = mImpl->mModifyEvents[0].text;
473 // TODO - Convert from UTF-32
477 void Controller::SetPlaceholderText( const std::string& text )
479 if( !mImpl->mTextInput )
481 mImpl->mTextInput->mPlaceholderText = text;
485 void Controller::GetPlaceholderText( std::string& text ) const
487 if( !mImpl->mTextInput )
489 text = mImpl->mTextInput->mPlaceholderText;
493 void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
495 if( !mImpl->mFontDefaults )
497 mImpl->mFontDefaults = new Controller::FontDefaults();
500 mImpl->mFontDefaults->mDefaultFontFamily = defaultFontFamily;
501 mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
502 mImpl->mOperationsPending = ALL_OPERATIONS;
503 mImpl->mRecalculateNaturalSize = true;
506 const std::string& Controller::GetDefaultFontFamily() const
508 if( mImpl->mFontDefaults )
510 return mImpl->mFontDefaults->mDefaultFontFamily;
516 void Controller::SetDefaultFontStyle( const std::string& defaultFontStyle )
518 if( !mImpl->mFontDefaults )
520 mImpl->mFontDefaults = new Controller::FontDefaults();
523 mImpl->mFontDefaults->mDefaultFontStyle = defaultFontStyle;
524 mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
525 mImpl->mOperationsPending = ALL_OPERATIONS;
526 mImpl->mRecalculateNaturalSize = true;
529 const std::string& Controller::GetDefaultFontStyle() const
531 if( mImpl->mFontDefaults )
533 return mImpl->mFontDefaults->mDefaultFontStyle;
539 void Controller::SetDefaultPointSize( float pointSize )
541 if( !mImpl->mFontDefaults )
543 mImpl->mFontDefaults = new Controller::FontDefaults();
546 mImpl->mFontDefaults->mDefaultPointSize = pointSize;
547 mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
548 mImpl->mOperationsPending = ALL_OPERATIONS;
549 mImpl->mRecalculateNaturalSize = true;
552 float Controller::GetDefaultPointSize() const
554 if( mImpl->mFontDefaults )
556 return mImpl->mFontDefaults->mDefaultPointSize;
562 void Controller::GetDefaultFonts( Vector<FontRun>& fonts, Length numberOfCharacters )
564 if( mImpl->mFontDefaults )
567 fontRun.characterRun.characterIndex = 0;
568 fontRun.characterRun.numberOfCharacters = numberOfCharacters;
569 fontRun.fontId = mImpl->mFontDefaults->GetFontId( mImpl->mFontClient );
570 fontRun.isDefault = true;
572 fonts.PushBack( fontRun );
576 void Controller::EnableTextInput( DecoratorPtr decorator )
578 if( !mImpl->mTextInput )
580 mImpl->mTextInput = new TextInput( mImpl->mLogicalModel, mImpl->mVisualModel, decorator );
584 void Controller::SetEnableCursorBlink( bool enable )
586 DALI_ASSERT_DEBUG( NULL != mImpl->mTextInput && "TextInput disabled" );
588 if( mImpl->mTextInput )
590 mImpl->mTextInput->mCursorBlinkEnabled = enable;
593 mImpl->mTextInput->mDecorator )
595 mImpl->mTextInput->mDecorator->StopCursorBlink();
600 bool Controller::GetEnableCursorBlink() const
602 if( mImpl->mTextInput )
604 return mImpl->mTextInput->mCursorBlinkEnabled;
610 Vector3 Controller::GetNaturalSize()
614 // Make sure the model is up-to-date before layouting
615 ProcessModifyEvents();
617 if( mImpl->mRecalculateNaturalSize )
619 // Operations that can be done only once until the text changes.
620 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
628 // Make sure the model is up-to-date before layouting
629 UpdateModel( onlyOnceOperations );
631 // Operations that need to be done if the size changes.
632 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
635 DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
636 static_cast<OperationsMask>( onlyOnceOperations |
638 naturalSize.GetVectorXY() );
640 // Do not do again the only once operations.
641 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
643 // Do the size related operations again.
644 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
646 // Stores the natural size to avoid recalculate it again
647 // unless the text/style changes.
648 mImpl->mVisualModel->SetNaturalSize( naturalSize.GetVectorXY() );
650 mImpl->mRecalculateNaturalSize = false;
654 naturalSize = mImpl->mVisualModel->GetNaturalSize();
660 float Controller::GetHeightForWidth( float width )
662 // Make sure the model is up-to-date before layouting
663 ProcessModifyEvents();
666 if( width != mImpl->mControlSize.width )
668 // Operations that can be done only once until the text changes.
669 const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
677 // Make sure the model is up-to-date before layouting
678 UpdateModel( onlyOnceOperations );
680 // Operations that need to be done if the size changes.
681 const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
684 DoRelayout( Size( width, MAX_FLOAT ),
685 static_cast<OperationsMask>( onlyOnceOperations |
689 // Do not do again the only once operations.
690 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
692 // Do the size related operations again.
693 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | sizeOperations );
697 layoutSize = mImpl->mVisualModel->GetActualSize();
700 return layoutSize.height;
703 bool Controller::Relayout( const Vector2& size )
705 if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
707 bool glyphsRemoved( false );
708 if( 0u != mImpl->mVisualModel->GetNumberOfGlyphPositions() )
710 mImpl->mVisualModel->SetGlyphPositions( NULL, 0u );
711 glyphsRemoved = true;
714 // Not worth to relayout if width or height is equal to zero.
715 return glyphsRemoved;
718 if( size != mImpl->mControlSize )
720 // Operations that need to be done if the size changes.
721 mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
726 mImpl->mControlSize = size;
729 // Make sure the model is up-to-date before layouting
730 ProcessModifyEvents();
731 UpdateModel( mImpl->mOperationsPending );
734 bool updated = DoRelayout( mImpl->mControlSize,
735 mImpl->mOperationsPending,
738 // Do not re-do any operation until something changes.
739 mImpl->mOperationsPending = NO_OPERATION;
741 if( mImpl->mTextInput )
743 // Move the cursor, grab handle etc.
744 updated = mImpl->mTextInput->ProcessInputEvents() || updated;
750 void Controller::ProcessModifyEvents()
752 std::vector<ModifyEvent>& events = mImpl->mModifyEvents;
754 for( unsigned int i=0; i<events.size(); ++i )
756 if( REPLACE_TEXT == events[0].type )
758 // A (single) replace event should come first, otherwise we wasted time processing NOOP events
759 DALI_ASSERT_DEBUG( 0 == i && "Unexpected REPLACE event" );
761 ReplaceTextEvent( events[0].text );
763 else if( INSERT_TEXT == events[0].type )
765 InsertTextEvent( events[0].text );
767 else if( DELETE_TEXT == events[0].type )
773 // Discard temporary text
777 void Controller::ReplaceTextEvent( const std::string& text )
780 mImpl->mLogicalModel->mScriptRuns.Clear();
781 mImpl->mLogicalModel->mFontRuns.Clear();
782 mImpl->mLogicalModel->mLineBreakInfo.Clear();
783 mImpl->mLogicalModel->mWordBreakInfo.Clear();
784 mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
785 mImpl->mVisualModel->mGlyphs.Clear();
787 // Convert text into UTF-32
788 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
789 utf32Characters.Resize( text.size() );
791 // This is a bit horrible but std::string returns a (signed) char*
792 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
794 // Transform a text array encoded in utf8 into an array encoded in utf32.
795 // It returns the actual number of characters.
796 Length characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
797 utf32Characters.Resize( characterCount );
799 // Reset the cursor position
800 if( mImpl->mTextInput )
802 mImpl->mTextInput->mPrimaryCursorPosition = characterCount;
803 // TODO - handle secondary cursor
806 // The natural size needs to be re-calculated.
807 mImpl->mRecalculateNaturalSize = true;
809 // Apply modifications to the model
810 mImpl->mOperationsPending = ALL_OPERATIONS;
811 UpdateModel( ALL_OPERATIONS );
812 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
817 void Controller::InsertTextEvent( const std::string& text )
819 DALI_ASSERT_DEBUG( NULL != mImpl->mTextInput && "Unexpected InsertTextEvent" );
821 // TODO - Optimize this
822 mImpl->mLogicalModel->mScriptRuns.Clear();
823 mImpl->mLogicalModel->mFontRuns.Clear();
824 mImpl->mLogicalModel->mLineBreakInfo.Clear();
825 mImpl->mLogicalModel->mWordBreakInfo.Clear();
826 mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
827 mImpl->mVisualModel->mGlyphs.Clear();
829 // Convert text into UTF-32
830 Vector<Character> utf32Characters;
831 utf32Characters.Resize( text.size() );
833 // This is a bit horrible but std::string returns a (signed) char*
834 const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
836 // Transform a text array encoded in utf8 into an array encoded in utf32.
837 // It returns the actual number of characters.
838 Length characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
839 utf32Characters.Resize( characterCount );
841 // Insert at current cursor position
842 Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
843 CharacterIndex& cursorIndex = mImpl->mTextInput->mPrimaryCursorPosition;
845 if( cursorIndex < modifyText.Count() )
847 modifyText.Insert( modifyText.Begin() + cursorIndex, utf32Characters.Begin(), utf32Characters.End() );
851 modifyText.Insert( modifyText.End(), utf32Characters.Begin(), utf32Characters.End() );
854 // Advance the cursor position
857 // The natural size needs to be re-calculated.
858 mImpl->mRecalculateNaturalSize = true;
860 // Apply modifications to the model; TODO - Optimize this
861 mImpl->mOperationsPending = ALL_OPERATIONS;
862 UpdateModel( ALL_OPERATIONS );
863 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
868 void Controller::DeleteTextEvent()
870 DALI_ASSERT_DEBUG( NULL != mImpl->mTextInput && "Unexpected InsertTextEvent" );
872 // TODO - Optimize this
873 mImpl->mLogicalModel->mScriptRuns.Clear();
874 mImpl->mLogicalModel->mFontRuns.Clear();
875 mImpl->mLogicalModel->mLineBreakInfo.Clear();
876 mImpl->mLogicalModel->mWordBreakInfo.Clear();
877 mImpl->mLogicalModel->mBidirectionalParagraphInfo.Clear();
878 mImpl->mVisualModel->mGlyphs.Clear();
880 // Delte at current cursor position
881 Vector<Character>& modifyText = mImpl->mLogicalModel->mText;
882 CharacterIndex& cursorIndex = mImpl->mTextInput->mPrimaryCursorPosition;
884 if( cursorIndex > 0 &&
885 cursorIndex-1 < modifyText.Count() )
887 modifyText.Remove( modifyText.Begin() + cursorIndex - 1 );
889 // Cursor position retreat
893 // The natural size needs to be re-calculated.
894 mImpl->mRecalculateNaturalSize = true;
896 // Apply modifications to the model; TODO - Optimize this
897 mImpl->mOperationsPending = ALL_OPERATIONS;
898 UpdateModel( ALL_OPERATIONS );
899 mImpl->mOperationsPending = static_cast<OperationsMask>( LAYOUT |
904 void Controller::UpdateModel( OperationsMask operationsRequired )
906 // Calculate the operations to be done.
907 const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
909 Vector<Character>& utf32Characters = mImpl->mLogicalModel->mText;
911 const Length numberOfCharacters = mImpl->mLogicalModel->GetNumberOfCharacters();
913 Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
914 if( GET_LINE_BREAKS & operations )
916 // Retrieves the line break info. The line break info is used to split the text in 'paragraphs' to
917 // calculate the bidirectional info for each 'paragraph'.
918 // It's also used to layout the text (where it should be a new line) or to shape the text (text in different lines
919 // is not shaped together).
920 lineBreakInfo.Resize( numberOfCharacters, TextAbstraction::LINE_NO_BREAK );
922 SetLineBreakInfo( utf32Characters,
926 Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
927 if( GET_WORD_BREAKS & operations )
929 // Retrieves the word break info. The word break info is used to layout the text (where to wrap the text in lines).
930 wordBreakInfo.Resize( numberOfCharacters, TextAbstraction::WORD_NO_BREAK );
932 SetWordBreakInfo( utf32Characters,
936 const bool getScripts = GET_SCRIPTS & operations;
937 const bool validateFonts = VALIDATE_FONTS & operations;
939 Vector<ScriptRun>& scripts = mImpl->mLogicalModel->mScriptRuns;
940 Vector<FontRun>& validFonts = mImpl->mLogicalModel->mFontRuns;
942 if( getScripts || validateFonts )
944 // Validates the fonts assigned by the application or assigns default ones.
945 // It makes sure all the characters are going to be rendered by the correct font.
946 MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
950 // Retrieves the scripts used in the text.
951 multilanguageSupport.SetScripts( utf32Characters,
958 if( 0u == validFonts.Count() )
960 // Copy the requested font defaults received via the property system.
961 // These may not be valid i.e. may not contain glyphs for the necessary scripts.
962 GetDefaultFonts( validFonts, numberOfCharacters );
965 // Validates the fonts. If there is a character with no assigned font it sets a default one.
966 // After this call, fonts are validated.
967 multilanguageSupport.ValidateFonts( utf32Characters,
973 Vector<Character> mirroredUtf32Characters;
974 bool textMirrored = false;
975 if( BIDI_INFO & operations )
977 // Count the number of LINE_NO_BREAK to reserve some space for the vector of paragraph's
978 // bidirectional info.
980 Length numberOfParagraphs = 0u;
982 const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer = lineBreakInfo.Begin();
983 for( Length index = 0u; index < numberOfCharacters; ++index )
985 if( TextAbstraction::LINE_NO_BREAK == *( lineBreakInfoBuffer + index ) )
987 ++numberOfParagraphs;
991 Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
992 bidirectionalInfo.Reserve( numberOfParagraphs );
994 // Calculates the bidirectional info for the whole paragraph if it contains right to left scripts.
995 SetBidirectionalInfo( utf32Characters,
1000 if( 0u != bidirectionalInfo.Count() )
1002 // This paragraph has right to left text. Some characters may need to be mirrored.
1003 // TODO: consider if the mirrored string can be stored as well.
1005 textMirrored = GetMirroredText( utf32Characters, mirroredUtf32Characters );
1009 Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1010 Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1011 Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1012 if( SHAPE_TEXT & operations )
1014 const Vector<Character>& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters;
1016 ShapeText( textToShape,
1021 glyphsToCharactersMap,
1022 charactersPerGlyph );
1025 const Length numberOfGlyphs = glyphs.Count();
1027 if( GET_GLYPH_METRICS & operations )
1029 mImpl->mFontClient.GetGlyphMetrics( glyphs.Begin(), numberOfGlyphs );
1032 if( 0u != numberOfGlyphs )
1034 // Create the glyph to character conversion table and the 'number of glyphs' per character.
1035 mImpl->mVisualModel->CreateCharacterToGlyphTable(numberOfCharacters );
1036 mImpl->mVisualModel->CreateGlyphsPerCharacterTable( numberOfCharacters );
1040 bool Controller::DoRelayout( const Vector2& size,
1041 OperationsMask operationsRequired,
1044 bool viewUpdated( false );
1046 // Calculate the operations to be done.
1047 const OperationsMask operations = static_cast<OperationsMask>( mImpl->mOperationsPending & operationsRequired );
1049 if( LAYOUT & operations )
1051 // Some vectors with data needed to layout and reorder may be void
1052 // after the first time the text has been laid out.
1053 // Fill the vectors again.
1055 const Length numberOfCharacters = mImpl->mLogicalModel->GetNumberOfCharacters();
1056 Length numberOfGlyphs = mImpl->mVisualModel->GetNumberOfGlyphs();
1058 Vector<LineBreakInfo>& lineBreakInfo = mImpl->mLogicalModel->mLineBreakInfo;
1059 Vector<WordBreakInfo>& wordBreakInfo = mImpl->mLogicalModel->mWordBreakInfo;
1060 Vector<GlyphInfo>& glyphs = mImpl->mVisualModel->mGlyphs;
1061 Vector<CharacterIndex>& glyphsToCharactersMap = mImpl->mVisualModel->mGlyphsToCharacters;
1062 Vector<Length>& charactersPerGlyph = mImpl->mVisualModel->mCharactersPerGlyph;
1064 // Set the layout parameters.
1065 LayoutParameters layoutParameters( size,
1066 lineBreakInfo.Begin(),
1067 wordBreakInfo.Begin(),
1070 glyphsToCharactersMap.Begin(),
1071 charactersPerGlyph.Begin() );
1073 // The laid-out lines.
1074 // It's not possible to know in how many lines the text is going to be laid-out,
1075 // but it can be resized at least with the number of 'paragraphs' to avoid
1076 // some re-allocations.
1077 Vector<LineRun>& lines = mImpl->mVisualModel->mLines;
1079 // Resize the vector of positions to have the same size than the vector of glyphs.
1080 Vector<Vector2>& glyphPositions = mImpl->mVisualModel->mGlyphPositions;
1081 glyphPositions.Resize( numberOfGlyphs );
1083 BidirectionalRunIndex firstBidiRunIndex = 0u;
1084 Length numberOfBidiRuns = 0u;
1085 mImpl->mLogicalModel->GetNumberOfBidirectionalInfoRuns( 0u, numberOfCharacters, firstBidiRunIndex, numberOfBidiRuns );
1087 // Delete any previous laid out lines before setting the new ones.
1089 lines.Reserve( numberOfBidiRuns );
1091 // Update the visual model.
1092 viewUpdated = mImpl->mLayoutEngine.LayoutText( layoutParameters,
1099 // Reorder the lines
1100 if( REORDER & operations )
1102 Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mImpl->mLogicalModel->mBidirectionalParagraphInfo;
1104 // Check first if there are paragraphs with bidirectional info.
1105 if( 0u != bidirectionalInfo.Count() )
1108 const Length numberOfLines = mImpl->mVisualModel->GetNumberOfLines();
1110 // Reorder the lines.
1111 Vector<BidirectionalLineInfoRun> lineBidirectionalInfoRuns;
1112 lineBidirectionalInfoRuns.Reserve( numberOfLines ); // Reserve because is not known yet how many lines have right to left characters.
1113 ReorderLines( bidirectionalInfo,
1115 lineBidirectionalInfoRuns );
1117 // Set the bidirectional info into the model.
1118 const Length numberOfBidirectionalInfoRuns = lineBidirectionalInfoRuns.Count();
1119 mImpl->mLogicalModel->SetVisualToLogicalMap( lineBidirectionalInfoRuns.Begin(),
1120 numberOfBidirectionalInfoRuns );
1122 // Set the bidirectional info per line into the layout parameters.
1123 layoutParameters.lineBidirectionalInfoRunsBuffer = lineBidirectionalInfoRuns.Begin();
1124 layoutParameters.numberOfBidirectionalInfoRuns = numberOfBidirectionalInfoRuns;
1126 // Get the character to glyph conversion table and set into the layout.
1127 layoutParameters.charactersToGlyphsBuffer = mImpl->mVisualModel->mCharactersToGlyph.Begin();
1129 // Get the glyphs per character table and set into the layout.
1130 layoutParameters.glyphsPerCharacterBuffer = mImpl->mVisualModel->mGlyphsPerCharacter.Begin();
1132 // Re-layout the text. Reorder those lines with right to left characters.
1133 mImpl->mLayoutEngine.ReLayoutRightToLeftLines( layoutParameters,
1136 // Free the allocated memory used to store the conversion table in the bidirectional line info run.
1137 for( Vector<BidirectionalLineInfoRun>::Iterator it = lineBidirectionalInfoRuns.Begin(),
1138 endIt = lineBidirectionalInfoRuns.End();
1142 BidirectionalLineInfoRun& bidiLineInfo = *it;
1144 free( bidiLineInfo.visualToLogicalMap );
1149 // Sets the actual size.
1150 if( UPDATE_ACTUAL_SIZE & operations )
1152 mImpl->mVisualModel->SetActualSize( layoutSize );
1158 layoutSize = mImpl->mVisualModel->GetActualSize();
1164 View& Controller::GetView()
1166 return mImpl->mView;
1169 LayoutEngine& Controller::GetLayoutEngine()
1171 return mImpl->mLayoutEngine;
1174 void Controller::RequestRelayout()
1176 mImpl->mControlInterface.RequestTextRelayout();
1179 void Controller::KeyboardFocusGainEvent()
1181 DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyboardFocusGainEvent" );
1183 if( mImpl->mTextInput )
1185 TextInput::Event event( TextInput::KEYBOARD_FOCUS_GAIN_EVENT );
1186 mImpl->mTextInput->mEventQueue.push_back( event );
1192 void Controller::KeyboardFocusLostEvent()
1194 DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyboardFocusLostEvent" );
1196 if( mImpl->mTextInput )
1198 TextInput::Event event( TextInput::KEYBOARD_FOCUS_LOST_EVENT );
1199 mImpl->mTextInput->mEventQueue.push_back( event );
1205 bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
1207 DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected KeyEvent" );
1209 if( mImpl->mTextInput &&
1210 keyEvent.state == KeyEvent::Down )
1212 int keyCode = keyEvent.keyCode;
1213 const std::string& keyString = keyEvent.keyPressed;
1215 // Pre-process to separate modifying events from non-modifying input events.
1216 if( Dali::DALI_KEY_ESCAPE == keyCode )
1218 // Escape key is a special case which causes focus loss
1219 KeyboardFocusLostEvent();
1221 else if( Dali::DALI_KEY_CURSOR_LEFT == keyCode ||
1222 Dali::DALI_KEY_CURSOR_RIGHT == keyCode ||
1223 Dali::DALI_KEY_CURSOR_UP == keyCode ||
1224 Dali::DALI_KEY_CURSOR_DOWN == keyCode )
1226 TextInput::Event event( TextInput::CURSOR_KEY_EVENT );
1227 event.p1.mInt = keyCode;
1228 mImpl->mTextInput->mEventQueue.push_back( event );
1230 else if( Dali::DALI_KEY_BACKSPACE == keyCode )
1232 // Queue a delete event
1234 event.type = DELETE_TEXT;
1235 mImpl->mModifyEvents.push_back( event );
1237 else if( !keyString.empty() )
1239 // Queue an insert event
1241 event.type = INSERT_TEXT;
1242 event.text = keyString;
1243 mImpl->mModifyEvents.push_back( event );
1252 void Controller::TapEvent( unsigned int tapCount, float x, float y )
1254 DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected TapEvent" );
1256 if( mImpl->mTextInput )
1258 TextInput::Event event( TextInput::TAP_EVENT );
1259 event.p1.mUint = tapCount;
1260 event.p2.mFloat = x;
1261 event.p3.mFloat = y;
1262 mImpl->mTextInput->mEventQueue.push_back( event );
1268 void Controller::GrabHandleEvent( GrabHandleState state, float x, float y )
1270 DALI_ASSERT_DEBUG( mImpl->mTextInput && "Unexpected GrabHandleEvent" );
1272 if( mImpl->mTextInput )
1274 TextInput::Event event( TextInput::GRAB_HANDLE_EVENT );
1275 event.p1.mUint = state;
1276 event.p2.mFloat = x;
1277 event.p3.mFloat = y;
1278 mImpl->mTextInput->mEventQueue.push_back( event );
1284 Controller::~Controller()
1289 Controller::Controller( ControlInterface& controlInterface )
1292 mImpl = new Controller::Impl( controlInterface );
1297 } // namespace Toolkit