1 #ifndef __DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H__
2 #define __DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H__
5 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
22 #include <dali/devel-api/adaptor-framework/clipboard.h>
23 #include <dali/devel-api/text-abstraction/font-client.h>
26 #include <dali-toolkit/internal/text/input-style.h>
27 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
28 #include <dali-toolkit/internal/text/logical-model-impl.h>
29 #include <dali-toolkit/internal/text/text-controller.h>
30 #include <dali-toolkit/internal/text/text-view.h>
31 #include <dali-toolkit/internal/text/visual-model-impl.h>
42 //Forward declarations
47 // Used to queue input events until DoRelayout()
55 LEFT_SELECTION_HANDLE_EVENT,
56 RIGHT_SELECTION_HANDLE_EVENT,
68 Event( Type eventType )
91 EDITING_WITH_GRAB_HANDLE,
92 EDITING_WITH_PASTE_POPUP,
94 SELECTION_HANDLE_PANNING
97 EventData( DecoratorPtr decorator );
101 static bool IsEditingState( State stateToCheck )
103 return ( stateToCheck == EDITING || stateToCheck == EDITING_WITH_POPUP || stateToCheck == EDITING_WITH_GRAB_HANDLE || stateToCheck == EDITING_WITH_PASTE_POPUP );
106 DecoratorPtr mDecorator; ///< Pointer to the decorator.
107 ImfManager mImfManager; ///< The Input Method Framework Manager.
108 std::string mPlaceholderTextActive; ///< The text to display when the TextField is empty with key-input focus.
109 std::string mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive.
110 Vector4 mPlaceholderTextColor; ///< The in/active placeholder text color.
113 * This is used to delay handling events until after the model has been updated.
114 * The number of updates to the model is minimized to improve performance.
116 std::vector<Event> mEventQueue; ///< The queue of touch events etc.
118 InputStyle mInputStyle; ///< The style to be set to the new inputed text.
120 State mState; ///< Selection mode, edit mode etc.
122 CharacterIndex mPrimaryCursorPosition; ///< Index into logical model for primary cursor.
123 CharacterIndex mLeftSelectionPosition; ///< Index into logical model for left selection handle.
124 CharacterIndex mRightSelectionPosition; ///< Index into logical model for right selection handle.
126 CharacterIndex mPreEditStartPosition; ///< Used to remove the pre-edit text if necessary.
127 Length mPreEditLength; ///< Used to remove the pre-edit text if necessary.
129 float mCursorHookPositionX; ///< Used to move the cursor with the keys or when scrolling the text vertically with the handles.
131 bool mIsShowingPlaceholderText : 1; ///< True if the place-holder text is being displayed.
132 bool mPreEditFlag : 1; ///< True if the model contains text in pre-edit state.
133 bool mDecoratorUpdated : 1; ///< True if the decorator was updated during event processing.
134 bool mCursorBlinkEnabled : 1; ///< True if cursor should blink when active.
135 bool mGrabHandleEnabled : 1; ///< True if grab handle is enabled.
136 bool mGrabHandlePopupEnabled : 1; ///< True if the grab handle popu-up should be shown.
137 bool mSelectionEnabled : 1; ///< True if selection handles, highlight etc. are enabled.
138 bool mUpdateCursorHookPosition : 1; ///< True if the cursor hook position must be updated. Used to move the cursor with the keys 'up' and 'down'.
139 bool mUpdateCursorPosition : 1; ///< True if the visual position of the cursor must be recalculated.
140 bool mUpdateGrabHandlePosition : 1; ///< True if the visual position of the grab handle must be recalculated.
141 bool mUpdateLeftSelectionPosition : 1; ///< True if the visual position of the left selection handle must be recalculated.
142 bool mUpdateRightSelectionPosition : 1; ///< True if the visual position of the right selection handle must be recalculated.
143 bool mUpdateHighlightBox : 1; ///< True if the text selection high light box must be updated.
144 bool mScrollAfterUpdatePosition : 1; ///< Whether to scroll after the cursor position is updated.
145 bool mScrollAfterDelete : 1; ///< Whether to scroll after delete characters.
146 bool mAllTextSelected : 1; ///< True if the selection handles are selecting all the text.
147 bool mUpdateInputStyle : 1; ///< Whether to update the input style after moving the cursor.
154 TEXT_REPLACED, ///< The entire text was replaced
155 TEXT_INSERTED, ///< Insert characters at the current cursor position
156 TEXT_DELETED ///< Characters were deleted
165 : mFontDescription(),
167 mDefaultPointSize( 0.f ),
169 familyDefined( false ),
170 weightDefined( false ),
171 widthDefined( false ),
172 slantDefined( false ),
175 // Initially use the default platform font
176 TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
177 fontClient.GetDefaultPlatformFontDescription( mFontDescription );
180 FontId GetFontId( TextAbstraction::FontClient& fontClient )
184 const PointSize26Dot6 pointSize = static_cast<PointSize26Dot6>( mDefaultPointSize * 64.f );
185 mFontId = fontClient.GetFontId( mFontDescription, pointSize );
191 TextAbstraction::FontDescription mFontDescription; ///< The default font's description.
192 std::string mFontStyle; ///< The font's style string set through the property system.
193 float mDefaultPointSize; ///< The default font's point size.
194 FontId mFontId; ///< The font's id of the default font.
195 bool familyDefined:1; ///< Whether the default font's family name is defined.
196 bool weightDefined:1; ///< Whether the default font's weight is defined.
197 bool widthDefined:1; ///< Whether the default font's width is defined.
198 bool slantDefined:1; ///< Whether the default font's slant is defined.
199 bool sizeDefined:1; ///< Whether the default font's point size is defined.
203 * @brief Stores indices used to update the text.
204 * Stores the character index where the text is updated and the number of characters removed and added.
205 * Stores as well indices to the first and the last paragraphs to be updated.
207 struct TextUpdateInfo
210 : mCharacterIndex( 0u ),
211 mNumberOfCharactersToRemove( 0u ),
212 mNumberOfCharactersToAdd( 0u ),
213 mPreviousNumberOfCharacters( 0u ),
214 mParagraphCharacterIndex( 0u ),
215 mRequestedNumberOfCharacters( 0u ),
216 mStartGlyphIndex( 0u ),
217 mStartLineIndex( 0u ),
218 mEstimatedNumberOfLines( 0u ),
220 mFullRelayoutNeeded( true ),
221 mIsLastCharacterNewParagraph( false )
227 CharacterIndex mCharacterIndex; ///< Index to the first character to be updated.
228 Length mNumberOfCharactersToRemove; ///< The number of characters to be removed.
229 Length mNumberOfCharactersToAdd; ///< The number of characters to be added.
230 Length mPreviousNumberOfCharacters; ///< The number of characters before the text update.
232 CharacterIndex mParagraphCharacterIndex; ///< Index of the first character of the first paragraph to be updated.
233 Length mRequestedNumberOfCharacters; ///< The requested number of characters.
234 GlyphIndex mStartGlyphIndex;
235 LineIndex mStartLineIndex;
236 Length mEstimatedNumberOfLines; ///< The estimated number of lines. Used to avoid reallocations when layouting.
238 bool mClearAll:1; ///< Whether the whole text is cleared. i.e. when the text is reset.
239 bool mFullRelayoutNeeded:1; ///< Whether a full re-layout is needed. i.e. when a new size is set to the text control.
240 bool mIsLastCharacterNewParagraph:1; ///< Whether the last character is a new paragraph character.
244 // Clear all info except the mPreviousNumberOfCharacters member.
245 mCharacterIndex = static_cast<CharacterIndex>( -1 );
246 mNumberOfCharactersToRemove = 0u;
247 mNumberOfCharactersToAdd = 0u;
248 mParagraphCharacterIndex = 0u;
249 mRequestedNumberOfCharacters = 0u;
250 mStartGlyphIndex = 0u;
251 mStartLineIndex = 0u;
252 mEstimatedNumberOfLines = 0u;
254 mFullRelayoutNeeded = false;
255 mIsLastCharacterNewParagraph = false;
259 struct UnderlineDefaults
261 std::string properties;
262 // TODO: complete with underline parameters.
265 struct ShadowDefaults
267 std::string properties;
268 // TODO: complete with shadow parameters.
271 struct EmbossDefaults
273 std::string properties;
274 // TODO: complete with emboss parameters.
277 struct OutlineDefaults
279 std::string properties;
280 // TODO: complete with outline parameters.
283 struct Controller::Impl
285 Impl( ControlInterface& controlInterface )
286 : mControlInterface( controlInterface ),
289 mFontDefaults( NULL ),
290 mUnderlineDefaults( NULL ),
291 mShadowDefaults( NULL ),
292 mEmbossDefaults( NULL ),
293 mOutlineDefaults( NULL ),
301 mTextColor( Color::BLACK ),
303 mOperationsPending( NO_OPERATION ),
304 mMaximumNumberOfCharacters( 50u ),
305 mRecalculateNaturalSize( true ),
306 mMarkupProcessorEnabled( false ),
307 mClipboardHideEnabled( true ),
308 mAutoScrollEnabled( false ),
309 mAutoScrollDirectionRTL( false )
311 mLogicalModel = LogicalModel::New();
312 mVisualModel = VisualModel::New();
314 mFontClient = TextAbstraction::FontClient::Get();
315 mClipboard = Clipboard::Get();
317 mView.SetVisualModel( mVisualModel );
319 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
320 mMetrics = Metrics::New( mFontClient );
321 mLayoutEngine.SetMetrics( mMetrics );
323 // Set the text properties to default
324 mVisualModel->SetUnderlineEnabled( false );
325 mVisualModel->SetUnderlineHeight( 0.0f );
330 delete mFontDefaults;
331 delete mUnderlineDefaults;
332 delete mShadowDefaults;
333 delete mEmbossDefaults;
334 delete mOutlineDefaults;
339 * @brief Request a relayout using the ControlInterface.
341 void RequestRelayout();
344 * @brief Request a relayout using the ControlInterface.
346 void QueueModifyEvent( ModifyEvent::Type type )
348 if( ModifyEvent::TEXT_REPLACED == type)
350 // Cancel previously queued inserts etc.
351 mModifyEvents.Clear();
356 mModifyEvents.PushBack( event );
358 // The event will be processed during relayout
363 * @brief Helper to move the cursor, grab handle etc.
365 bool ProcessInputEvents();
368 * @brief Helper to check whether any place-holder text is available.
370 bool IsPlaceholderAvailable() const
372 return ( mEventData &&
373 ( !mEventData->mPlaceholderTextInactive.empty() ||
374 !mEventData->mPlaceholderTextActive.empty() )
378 bool IsShowingPlaceholderText() const
380 return ( mEventData && mEventData->mIsShowingPlaceholderText );
384 * @brief Helper to check whether active place-holder text is available.
386 bool IsFocusedPlaceholderAvailable() const
388 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
391 bool IsShowingRealText() const
393 return ( !IsShowingPlaceholderText() &&
394 0u != mLogicalModel->mText.Count() );
398 * @brief Called when placeholder-text is hidden
400 void PlaceholderCleared()
404 mEventData->mIsShowingPlaceholderText = false;
406 // Remove mPlaceholderTextColor
407 mVisualModel->SetTextColor( mTextColor );
411 void ClearPreEditFlag()
415 mEventData->mPreEditFlag = false;
416 mEventData->mPreEditStartPosition = 0;
417 mEventData->mPreEditLength = 0;
421 void ResetImfManager()
425 // Reset incase we are in a pre-edit state.
426 if( mEventData->mImfManager )
428 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
436 * @brief Helper to notify IMF manager with surrounding text & cursor changes.
438 void NotifyImfManager();
441 * @brief Retrieve the current cursor position.
443 * @return The cursor position.
445 CharacterIndex GetLogicalCursorPosition() const;
448 * @brief Retrieves the number of consecutive white spaces starting from the given @p index.
450 * @param[in] index The character index from where to count the number of consecutive white spaces.
452 * @return The number of consecutive white spaces.
454 Length GetNumberOfWhiteSpaces( CharacterIndex index ) const;
457 * @brief Retrieve any text previously set starting from the given @p index.
459 * @param[in] index The character index from where to retrieve the text.
460 * @param[out] text A string of UTF-8 characters.
462 * @see Dali::Toolkit::Text::Controller::GetText()
464 void GetText( CharacterIndex index, std::string& text ) const;
466 bool IsClipboardEmpty()
468 bool result( mClipboard && mClipboard.NumberOfItems() );
469 return !result; // If NumberOfItems greater than 0, return false
473 * @brief Calculates the start character index of the first paragraph to be updated and
474 * the end character index of the last paragraph to be updated.
476 * @param[out] numberOfCharacters The number of characters to be updated.
478 void CalculateTextUpdateIndices( Length& numberOfCharacters );
481 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
483 * @note It never clears the text stored in utf32.
485 void ClearFullModelData( OperationsMask operations );
488 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
490 * @note It never clears the text stored in utf32.
492 * @param[in] startIndex Index to the first character to be cleared.
493 * @param[in] endIndex Index to the last character to be cleared.
494 * @param[in] operations The operations required.
496 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
499 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
501 * @note It never clears the text stored in utf32.
502 * @note Character indices are transformed to glyph indices.
504 * @param[in] startIndex Index to the first character to be cleared.
505 * @param[in] endIndex Index to the last character to be cleared.
506 * @param[in] operations The operations required.
508 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
511 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
513 * @note It never clears the text stored in utf32.
515 * @param[in] startIndex Index to the first character to be cleared.
516 * @param[in] endIndex Index to the last character to be cleared.
517 * @param[in] operations The operations required.
519 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
522 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
524 * When text or style changes the model is set with some operations pending.
525 * When i.e. the text's size or a relayout is required this method is called
526 * with a given @p operationsRequired parameter. The operations required are
527 * matched with the operations pending to perform the minimum number of operations.
529 * @param[in] operationsRequired The operations required.
531 * @return @e true if the model has been modified.
533 bool UpdateModel( OperationsMask operationsRequired );
536 * @brief Retreieves the default style.
538 * @param[out] inputStyle The default style.
540 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
543 * @brief Retrieve the line height of the default font.
545 float GetDefaultFontLineHeight();
547 void OnCursorKeyEvent( const Event& event );
549 void OnTapEvent( const Event& event );
551 void OnPanEvent( const Event& event );
553 void OnLongPressEvent( const Event& event );
555 void OnHandleEvent( const Event& event );
557 void OnSelectEvent( const Event& event );
559 void OnSelectAllEvent();
562 * @brief Retrieves the selected text. It removes the text if the @p deleteAfterRetrieval parameter is @e true.
564 * @param[out] selectedText The selected text encoded in utf8.
565 * @param[in] deleteAfterRetrieval Whether the text should be deleted after retrieval.
567 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
569 void ShowClipboard();
571 void HideClipboard();
573 void SetClipboardHideEnable(bool enable);
575 bool CopyStringToClipboard( std::string& source );
577 void SendSelectionToClipboard( bool deleteAfterSending );
579 void GetTextFromClipboard( unsigned int itemIndex, std::string& retrievedString );
581 void RepositionSelectionHandles();
582 void RepositionSelectionHandles( float visualX, float visualY );
584 void SetPopupButtons();
586 void ChangeState( EventData::State newState );
589 * @brief Calculates the cursor's position for a given character index in the logical order.
591 * It retrieves as well the line's height and the cursor's height and
592 * if there is a valid alternative cursor, its position and height.
594 * @param[in] logical The logical cursor position (in characters). 0 is just before the first character, a value equal to the number of characters is just after the last character.
595 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
597 void GetCursorPosition( CharacterIndex logical,
598 CursorInfo& cursorInfo );
601 * @brief Calculates the new cursor index.
603 * It takes into account that in some scripts multiple characters can form a glyph and all of them
604 * need to be jumped with one key event.
606 * @param[in] index The initial new index.
608 * @return The new cursor index.
610 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
613 * @brief Updates the cursor position.
615 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
616 * It sets the position of the secondary cursor if it's a valid one.
617 * Sets which cursors are active.
619 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
622 void UpdateCursorPosition( const CursorInfo& cursorInfo );
625 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
627 * @param[in] handleType One of the selection handles.
628 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
630 void UpdateSelectionHandle( HandleType handleType,
631 const CursorInfo& cursorInfo );
634 * @biref Clamps the horizontal scrolling to get the control always filled with text.
636 * @param[in] layoutSize The size of the laid out text.
638 void ClampHorizontalScroll( const Vector2& layoutSize );
641 * @biref Clamps the vertical scrolling to get the control always filled with text.
643 * @param[in] layoutSize The size of the laid out text.
645 void ClampVerticalScroll( const Vector2& layoutSize );
648 * @brief Scrolls the text to make a position visible.
650 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
652 * @param[in] position A position in text coords.
653 * @param[in] lineHeight The line height for the given position.
655 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
656 * or moving the selection handles.
658 void ScrollToMakePositionVisible( const Vector2& position, float lineHeight );
661 * @brief Scrolls the text to make the cursor visible.
663 * This method is called after deleting text.
665 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
668 // Declared private and left undefined to avoid copies.
670 // Declared private and left undefined to avoid copies.
671 Impl& operator=( const Impl& );
675 ControlInterface& mControlInterface; ///< Reference to the text controller.
676 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
677 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
678 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
679 UnderlineDefaults* mUnderlineDefaults; ///< Avoid allocating this when the user does not specify underline parameters.
680 ShadowDefaults* mShadowDefaults; ///< Avoid allocating this when the user does not specify shadow parameters.
681 EmbossDefaults* mEmbossDefaults; ///< Avoid allocating this when the user does not specify emboss parameters.
682 OutlineDefaults* mOutlineDefaults; ///< Avoid allocating this when the user does not specify outline parameters.
683 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
684 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
685 Clipboard mClipboard; ///< Handle to the system clipboard
686 View mView; ///< The view interface to the rendering back-end.
687 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
688 LayoutEngine mLayoutEngine; ///< The layout engine.
689 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
690 Vector4 mTextColor; ///< The regular text color
692 * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
693 * Typically this will have a negative value with scrolling occurs.
695 Vector2 mScrollPosition; ///< The text is offset by this position when scrolling.
696 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
697 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
698 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
700 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
701 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
702 bool mClipboardHideEnabled:1; ///< Whether the ClipboardHide function work or not
703 bool mAutoScrollEnabled:1; ///< Whether auto text scrolling is enabled.
704 CharacterDirection mAutoScrollDirectionRTL:1; ///< Direction of auto scrolling, true if rtl
710 } // namespace Toolkit
714 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__