1 #ifndef DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H
2 #define DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H
5 * Copyright (c) 2017 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/text-controller.h>
28 #include <dali-toolkit/internal/text/text-model.h>
29 #include <dali-toolkit/internal/text/text-view.h>
40 //Forward declarations
45 // Used to queue input events until DoRelayout()
53 LEFT_SELECTION_HANDLE_EVENT,
54 RIGHT_SELECTION_HANDLE_EVENT,
66 Event( Type eventType )
89 EDITING_WITH_GRAB_HANDLE,
90 EDITING_WITH_PASTE_POPUP,
92 SELECTION_HANDLE_PANNING,
96 EventData( DecoratorPtr decorator );
100 static bool IsEditingState( State stateToCheck )
102 return ( stateToCheck == EDITING || stateToCheck == EDITING_WITH_POPUP || stateToCheck == EDITING_WITH_GRAB_HANDLE || stateToCheck == EDITING_WITH_PASTE_POPUP );
105 DecoratorPtr mDecorator; ///< Pointer to the decorator.
106 ImfManager mImfManager; ///< The Input Method Framework Manager.
107 std::string mPlaceholderTextActive; ///< The text to display when the TextField is empty with key-input focus.
108 std::string mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive.
109 Vector4 mPlaceholderTextColor; ///< The in/active placeholder text color.
112 * This is used to delay handling events until after the model has been updated.
113 * The number of updates to the model is minimized to improve performance.
115 std::vector<Event> mEventQueue; ///< The queue of touch events etc.
117 Vector<InputStyle::Mask> mInputStyleChangedQueue; ///< Queue of changes in the input style. Used to emit the signal in the iddle callback.
119 InputStyle mInputStyle; ///< The style to be set to the new inputed text.
121 State mPreviousState; ///< Stores the current state before it's updated with the new one.
122 State mState; ///< Selection mode, edit mode etc.
124 CharacterIndex mPrimaryCursorPosition; ///< Index into logical model for primary cursor.
125 CharacterIndex mLeftSelectionPosition; ///< Index into logical model for left selection handle.
126 CharacterIndex mRightSelectionPosition; ///< Index into logical model for right selection handle.
128 CharacterIndex mPreEditStartPosition; ///< Used to remove the pre-edit text if necessary.
129 Length mPreEditLength; ///< Used to remove the pre-edit text if necessary.
131 float mCursorHookPositionX; ///< Used to move the cursor with the keys or when scrolling the text vertically with the handles.
133 Controller::NoTextTap::Action mDoubleTapAction; ///< Action to be done when there is a double tap on top of 'no text'
134 Controller::NoTextTap::Action mLongPressAction; ///< Action to be done when there is a long press on top of 'no text'
136 bool mIsShowingPlaceholderText : 1; ///< True if the place-holder text is being displayed.
137 bool mPreEditFlag : 1; ///< True if the model contains text in pre-edit state.
138 bool mDecoratorUpdated : 1; ///< True if the decorator was updated during event processing.
139 bool mCursorBlinkEnabled : 1; ///< True if cursor should blink when active.
140 bool mGrabHandleEnabled : 1; ///< True if grab handle is enabled.
141 bool mGrabHandlePopupEnabled : 1; ///< True if the grab handle popu-up should be shown.
142 bool mSelectionEnabled : 1; ///< True if selection handles, highlight etc. are enabled.
143 bool mUpdateCursorHookPosition : 1; ///< True if the cursor hook position must be updated. Used to move the cursor with the keys 'up' and 'down'.
144 bool mUpdateCursorPosition : 1; ///< True if the visual position of the cursor must be recalculated.
145 bool mUpdateGrabHandlePosition : 1; ///< True if the visual position of the grab handle must be recalculated.
146 bool mUpdateLeftSelectionPosition : 1; ///< True if the visual position of the left selection handle must be recalculated.
147 bool mUpdateRightSelectionPosition : 1; ///< True if the visual position of the right selection handle must be recalculated.
148 bool mIsLeftHandleSelected : 1; ///< Whether is the left handle the one which is selected.
149 bool mIsRightHandleSelected : 1; ///< Whether is the right handle the one which is selected.
150 bool mUpdateHighlightBox : 1; ///< True if the text selection high light box must be updated.
151 bool mScrollAfterUpdatePosition : 1; ///< Whether to scroll after the cursor position is updated.
152 bool mScrollAfterDelete : 1; ///< Whether to scroll after delete characters.
153 bool mAllTextSelected : 1; ///< True if the selection handles are selecting all the text.
154 bool mUpdateInputStyle : 1; ///< Whether to update the input style after moving the cursor.
155 bool mPasswordInput : 1; ///< True if password input is enabled.
156 bool mCheckScrollAmount : 1; ///< Whether to check scrolled amount after updating the position
163 TEXT_REPLACED, ///< The entire text was replaced
164 TEXT_INSERTED, ///< Insert characters at the current cursor position
165 TEXT_DELETED ///< Characters were deleted
174 : mFontDescription(),
175 mDefaultPointSize( 0.f ),
177 familyDefined( false ),
178 weightDefined( false ),
179 widthDefined( false ),
180 slantDefined( false ),
183 // Initially use the default platform font
184 TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
185 fontClient.GetDefaultPlatformFontDescription( mFontDescription );
188 FontId GetFontId( TextAbstraction::FontClient& fontClient )
192 const PointSize26Dot6 pointSize = static_cast<PointSize26Dot6>( mDefaultPointSize * 64.f );
193 mFontId = fontClient.GetFontId( mFontDescription, pointSize );
199 TextAbstraction::FontDescription mFontDescription; ///< The default font's description.
200 float mDefaultPointSize; ///< The default font's point size.
201 FontId mFontId; ///< The font's id of the default font.
202 bool familyDefined:1; ///< Whether the default font's family name is defined.
203 bool weightDefined:1; ///< Whether the default font's weight is defined.
204 bool widthDefined:1; ///< Whether the default font's width is defined.
205 bool slantDefined:1; ///< Whether the default font's slant is defined.
206 bool sizeDefined:1; ///< Whether the default font's point size is defined.
210 * @brief Stores indices used to update the text.
211 * Stores the character index where the text is updated and the number of characters removed and added.
212 * Stores as well indices to the first and the last paragraphs to be updated.
214 struct TextUpdateInfo
217 : mCharacterIndex( 0u ),
218 mNumberOfCharactersToRemove( 0u ),
219 mNumberOfCharactersToAdd( 0u ),
220 mPreviousNumberOfCharacters( 0u ),
221 mParagraphCharacterIndex( 0u ),
222 mRequestedNumberOfCharacters( 0u ),
223 mStartGlyphIndex( 0u ),
224 mStartLineIndex( 0u ),
225 mEstimatedNumberOfLines( 0u ),
227 mFullRelayoutNeeded( true ),
228 mIsLastCharacterNewParagraph( false )
234 CharacterIndex mCharacterIndex; ///< Index to the first character to be updated.
235 Length mNumberOfCharactersToRemove; ///< The number of characters to be removed.
236 Length mNumberOfCharactersToAdd; ///< The number of characters to be added.
237 Length mPreviousNumberOfCharacters; ///< The number of characters before the text update.
239 CharacterIndex mParagraphCharacterIndex; ///< Index of the first character of the first paragraph to be updated.
240 Length mRequestedNumberOfCharacters; ///< The requested number of characters.
241 GlyphIndex mStartGlyphIndex;
242 LineIndex mStartLineIndex;
243 Length mEstimatedNumberOfLines; ///< The estimated number of lines. Used to avoid reallocations when layouting.
245 bool mClearAll:1; ///< Whether the whole text is cleared. i.e. when the text is reset.
246 bool mFullRelayoutNeeded:1; ///< Whether a full re-layout is needed. i.e. when a new size is set to the text control.
247 bool mIsLastCharacterNewParagraph:1; ///< Whether the last character is a new paragraph character.
251 // Clear all info except the mPreviousNumberOfCharacters member.
252 mCharacterIndex = static_cast<CharacterIndex>( -1 );
253 mNumberOfCharactersToRemove = 0u;
254 mNumberOfCharactersToAdd = 0u;
255 mParagraphCharacterIndex = 0u;
256 mRequestedNumberOfCharacters = 0u;
257 mStartGlyphIndex = 0u;
258 mStartLineIndex = 0u;
259 mEstimatedNumberOfLines = 0u;
261 mFullRelayoutNeeded = false;
262 mIsLastCharacterNewParagraph = false;
266 struct UnderlineDefaults
268 std::string properties;
269 // TODO: complete with underline parameters.
272 struct ShadowDefaults
274 std::string properties;
275 // TODO: complete with shadow parameters.
278 struct EmbossDefaults
280 std::string properties;
281 // TODO: complete with emboss parameters.
284 struct OutlineDefaults
286 std::string properties;
287 // TODO: complete with outline parameters.
290 struct Controller::Impl
292 Impl( ControlInterface* controlInterface,
293 EditableControlInterface* editableControlInterface )
294 : mControlInterface( controlInterface ),
295 mEditableControlInterface( editableControlInterface ),
297 mFontDefaults( NULL ),
298 mUnderlineDefaults( NULL ),
299 mShadowDefaults( NULL ),
300 mEmbossDefaults( NULL ),
301 mOutlineDefaults( NULL ),
308 mTextColor( Color::BLACK ),
310 mOperationsPending( NO_OPERATION ),
311 mMaximumNumberOfCharacters( 50u ),
312 mHiddenInput( NULL ),
313 mRecalculateNaturalSize( true ),
314 mMarkupProcessorEnabled( false ),
315 mClipboardHideEnabled( true ),
316 mIsAutoScrollEnabled( false ),
317 mAutoScrollDirectionRTL( false ),
318 mUnderlineSetByString( false ),
319 mShadowSetByString( false ),
320 mFontStyleSetByString( false )
322 mModel = Model::New();
324 mFontClient = TextAbstraction::FontClient::Get();
325 mClipboard = Clipboard::Get();
327 mView.SetVisualModel( mModel->mVisualModel );
329 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
330 mMetrics = Metrics::New( mFontClient );
331 mLayoutEngine.SetMetrics( mMetrics );
333 // Set the text properties to default
334 mModel->mVisualModel->SetUnderlineEnabled( false );
335 mModel->mVisualModel->SetUnderlineHeight( 0.0f );
342 delete mFontDefaults;
343 delete mUnderlineDefaults;
344 delete mShadowDefaults;
345 delete mEmbossDefaults;
346 delete mOutlineDefaults;
350 // Text Controller Implementation.
353 * @copydoc Text::Controller::RequestRelayout()
355 void RequestRelayout();
358 * @brief Request a relayout using the ControlInterface.
360 void QueueModifyEvent( ModifyEvent::Type type )
362 if( ModifyEvent::TEXT_REPLACED == type)
364 // Cancel previously queued inserts etc.
365 mModifyEvents.Clear();
370 mModifyEvents.PushBack( event );
372 // The event will be processed during relayout
377 * @brief Helper to move the cursor, grab handle etc.
379 bool ProcessInputEvents();
382 * @brief Helper to check whether any place-holder text is available.
384 bool IsPlaceholderAvailable() const
386 return ( mEventData &&
387 ( !mEventData->mPlaceholderTextInactive.empty() ||
388 !mEventData->mPlaceholderTextActive.empty() )
392 bool IsShowingPlaceholderText() const
394 return ( mEventData && mEventData->mIsShowingPlaceholderText );
398 * @brief Helper to check whether active place-holder text is available.
400 bool IsFocusedPlaceholderAvailable() const
402 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
405 bool IsShowingRealText() const
407 return ( !IsShowingPlaceholderText() &&
408 0u != mModel->mLogicalModel->mText.Count() );
412 * @brief Called when placeholder-text is hidden
414 void PlaceholderCleared()
418 mEventData->mIsShowingPlaceholderText = false;
420 // Remove mPlaceholderTextColor
421 mModel->mVisualModel->SetTextColor( mTextColor );
425 void ClearPreEditFlag()
429 mEventData->mPreEditFlag = false;
430 mEventData->mPreEditStartPosition = 0;
431 mEventData->mPreEditLength = 0;
435 void ResetImfManager()
439 // Reset incase we are in a pre-edit state.
440 if( mEventData->mImfManager )
442 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
450 * @brief Helper to notify IMF manager with surrounding text & cursor changes.
452 void NotifyImfManager();
455 * @brief Helper to notify IMF manager with multi line status.
457 void NotifyImfMultiLineStatus();
460 * @brief Retrieve the current cursor position.
462 * @return The cursor position.
464 CharacterIndex GetLogicalCursorPosition() const;
467 * @brief Retrieves the number of consecutive white spaces starting from the given @p index.
469 * @param[in] index The character index from where to count the number of consecutive white spaces.
471 * @return The number of consecutive white spaces.
473 Length GetNumberOfWhiteSpaces( CharacterIndex index ) const;
476 * @brief Retrieve any text previously set starting from the given @p index.
478 * @param[in] index The character index from where to retrieve the text.
479 * @param[out] text A string of UTF-8 characters.
481 * @see Dali::Toolkit::Text::Controller::GetText()
483 void GetText( CharacterIndex index, std::string& text ) const;
485 bool IsClipboardEmpty()
487 bool result( mClipboard && mClipboard.NumberOfItems() );
488 return !result; // If NumberOfItems greater than 0, return false
491 bool IsClipboardVisible()
493 bool result( mClipboard && mClipboard.IsVisible() );
498 * @brief Calculates the start character index of the first paragraph to be updated and
499 * the end character index of the last paragraph to be updated.
501 * @param[out] numberOfCharacters The number of characters to be updated.
503 void CalculateTextUpdateIndices( Length& numberOfCharacters );
506 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
508 * @note It never clears the text stored in utf32.
510 void ClearFullModelData( OperationsMask operations );
513 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
515 * @note It never clears the text stored in utf32.
517 * @param[in] startIndex Index to the first character to be cleared.
518 * @param[in] endIndex Index to the last character to be cleared.
519 * @param[in] operations The operations required.
521 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
524 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
526 * @note It never clears the text stored in utf32.
527 * @note Character indices are transformed to glyph indices.
529 * @param[in] startIndex Index to the first character to be cleared.
530 * @param[in] endIndex Index to the last character to be cleared.
531 * @param[in] operations The operations required.
533 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
536 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
538 * @note It never clears the text stored in utf32.
540 * @param[in] startIndex Index to the first character to be cleared.
541 * @param[in] endIndex Index to the last character to be cleared.
542 * @param[in] operations The operations required.
544 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
547 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
549 * When text or style changes the model is set with some operations pending.
550 * When i.e. the text's size or a relayout is required this method is called
551 * with a given @p operationsRequired parameter. The operations required are
552 * matched with the operations pending to perform the minimum number of operations.
554 * @param[in] operationsRequired The operations required.
556 * @return @e true if the model has been modified.
558 bool UpdateModel( OperationsMask operationsRequired );
561 * @brief Retreieves the default style.
563 * @param[out] inputStyle The default style.
565 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
568 * @brief Retrieve the line height of the default font.
570 float GetDefaultFontLineHeight();
572 void OnCursorKeyEvent( const Event& event );
574 void OnTapEvent( const Event& event );
576 void OnPanEvent( const Event& event );
578 void OnLongPressEvent( const Event& event );
580 void OnHandleEvent( const Event& event );
582 void OnSelectEvent( const Event& event );
584 void OnSelectAllEvent();
587 * @brief Retrieves the selected text. It removes the text if the @p deleteAfterRetrieval parameter is @e true.
589 * @param[out] selectedText The selected text encoded in utf8.
590 * @param[in] deleteAfterRetrieval Whether the text should be deleted after retrieval.
592 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
594 void ShowClipboard();
596 void HideClipboard();
598 void SetClipboardHideEnable(bool enable);
600 bool CopyStringToClipboard( std::string& source );
602 void SendSelectionToClipboard( bool deleteAfterSending );
604 void RequestGetTextFromClipboard();
606 void RepositionSelectionHandles();
607 void RepositionSelectionHandles( float visualX, float visualY, Controller::NoTextTap::Action action );
609 void SetPopupButtons();
611 void ChangeState( EventData::State newState );
614 * @brief Calculates the cursor's position for a given character index in the logical order.
616 * It retrieves as well the line's height and the cursor's height and
617 * if there is a valid alternative cursor, its position and height.
619 * @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.
620 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
622 void GetCursorPosition( CharacterIndex logical,
623 CursorInfo& cursorInfo );
626 * @brief Calculates the new cursor index.
628 * It takes into account that in some scripts multiple characters can form a glyph and all of them
629 * need to be jumped with one key event.
631 * @param[in] index The initial new index.
633 * @return The new cursor index.
635 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
638 * @brief Updates the cursor position.
640 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
641 * It sets the position of the secondary cursor if it's a valid one.
642 * Sets which cursors are active.
644 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
647 void UpdateCursorPosition( const CursorInfo& cursorInfo );
650 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
652 * @param[in] handleType One of the selection handles.
653 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
655 void UpdateSelectionHandle( HandleType handleType,
656 const CursorInfo& cursorInfo );
659 * @biref Clamps the horizontal scrolling to get the control always filled with text.
661 * @param[in] layoutSize The size of the laid out text.
663 void ClampHorizontalScroll( const Vector2& layoutSize );
666 * @biref Clamps the vertical scrolling to get the control always filled with text.
668 * @param[in] layoutSize The size of the laid out text.
670 void ClampVerticalScroll( const Vector2& layoutSize );
673 * @brief Scrolls the text to make a position visible.
675 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
677 * @param[in] position A position in text coords.
678 * @param[in] lineHeight The line height for the given position.
680 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
681 * or moving the selection handles.
683 void ScrollToMakePositionVisible( const Vector2& position, float lineHeight );
686 * @brief Scrolls the text to make the cursor visible.
688 * This method is called after deleting text.
690 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
693 // Declared private and left undefined to avoid copies.
695 // Declared private and left undefined to avoid copies.
696 Impl& operator=( const Impl& );
700 ControlInterface* mControlInterface; ///< Reference to the text controller.
701 EditableControlInterface* mEditableControlInterface; ///< Reference to the editable text controller.
702 ModelPtr mModel; ///< Pointer to the text's model.
703 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
704 UnderlineDefaults* mUnderlineDefaults; ///< Avoid allocating this when the user does not specify underline parameters.
705 ShadowDefaults* mShadowDefaults; ///< Avoid allocating this when the user does not specify shadow parameters.
706 EmbossDefaults* mEmbossDefaults; ///< Avoid allocating this when the user does not specify emboss parameters.
707 OutlineDefaults* mOutlineDefaults; ///< Avoid allocating this when the user does not specify outline parameters.
708 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
709 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
710 Clipboard mClipboard; ///< Handle to the system clipboard
711 View mView; ///< The view interface to the rendering back-end.
712 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
713 Layout::Engine mLayoutEngine; ///< The layout engine.
714 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
715 Vector4 mTextColor; ///< The regular text color
716 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
717 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
718 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
719 HiddenText* mHiddenInput; ///< Avoid allocating this when the user does not specify hidden input mode.
721 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
722 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
723 bool mClipboardHideEnabled:1; ///< Whether the ClipboardHide function work or not
724 bool mIsAutoScrollEnabled:1; ///< Whether auto text scrolling is enabled.
725 CharacterDirection mAutoScrollDirectionRTL:1; ///< Direction of auto scrolling, true if rtl
727 bool mUnderlineSetByString:1; ///< Set when underline is set by string (legacy) instead of map
728 bool mShadowSetByString:1; ///< Set when shadow is set by string (legacy) instead of map
729 bool mFontStyleSetByString:1; ///< Set when font style is set by string (legacy) instead of map
734 } // namespace Toolkit
738 #endif // DALI_TOOLKIT_TEXT_CONTROLLER_H