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>
44 // Used to queue input events until DoRelayout()
52 LEFT_SELECTION_HANDLE_EVENT,
53 RIGHT_SELECTION_HANDLE_EVENT,
65 Event( Type eventType )
86 primaryCursorHeight( 0.f ),
87 secondaryCursorHeight( 0.f ),
88 isSecondaryCursor( false )
94 Vector2 primaryPosition; ///< The primary cursor's position.
95 Vector2 secondaryPosition; ///< The secondary cursor's position.
96 float lineOffset; ///< The vertical offset where the line containing the cursor starts.
97 float lineHeight; ///< The height of the line where the cursor is placed.
98 float primaryCursorHeight; ///< The primary cursor's height.
99 float secondaryCursorHeight; ///< The secondary cursor's height.
100 bool isSecondaryCursor; ///< Whether the secondary cursor is valid.
112 EDITING_WITH_GRAB_HANDLE,
113 EDITING_WITH_PASTE_POPUP,
115 SELECTION_HANDLE_PANNING
118 EventData( DecoratorPtr decorator );
122 static bool IsEditingState( State stateToCheck )
124 return ( stateToCheck == EDITING || stateToCheck == EDITING_WITH_POPUP || stateToCheck == EDITING_WITH_GRAB_HANDLE || stateToCheck == EDITING_WITH_PASTE_POPUP );
127 DecoratorPtr mDecorator; ///< Pointer to the decorator.
128 ImfManager mImfManager; ///< The Input Method Framework Manager.
129 std::string mPlaceholderTextActive; ///< The text to display when the TextField is empty with key-input focus.
130 std::string mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive.
131 Vector4 mPlaceholderTextColor; ///< The in/active placeholder text color.
134 * This is used to delay handling events until after the model has been updated.
135 * The number of updates to the model is minimized to improve performance.
137 std::vector<Event> mEventQueue; ///< The queue of touch events etc.
139 InputStyle mInputStyle; ///< The style to be set to the new inputed text.
142 * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
143 * Typically this will have a negative value with scrolling occurs.
145 Vector2 mScrollPosition; ///< The text is offset by this position when scrolling.
147 State mState; ///< Selection mode, edit mode etc.
149 CharacterIndex mPrimaryCursorPosition; ///< Index into logical model for primary cursor.
150 CharacterIndex mLeftSelectionPosition; ///< Index into logical model for left selection handle.
151 CharacterIndex mRightSelectionPosition; ///< Index into logical model for right selection handle.
153 CharacterIndex mPreEditStartPosition; ///< Used to remove the pre-edit text if necessary.
154 Length mPreEditLength; ///< Used to remove the pre-edit text if necessary.
156 bool mIsShowingPlaceholderText : 1; ///< True if the place-holder text is being displayed.
157 bool mPreEditFlag : 1; ///< True if the model contains text in pre-edit state.
158 bool mDecoratorUpdated : 1; ///< True if the decorator was updated during event processing.
159 bool mCursorBlinkEnabled : 1; ///< True if cursor should blink when active.
160 bool mGrabHandleEnabled : 1; ///< True if grab handle is enabled.
161 bool mGrabHandlePopupEnabled : 1; ///< True if the grab handle popu-up should be shown.
162 bool mSelectionEnabled : 1; ///< True if selection handles, highlight etc. are enabled.
163 bool mHorizontalScrollingEnabled : 1; ///< True if horizontal scrolling is enabled.
164 bool mVerticalScrollingEnabled : 1; ///< True if vertical scrolling is enabled.
165 bool mUpdateCursorPosition : 1; ///< True if the visual position of the cursor must be recalculated.
166 bool mUpdateLeftSelectionPosition : 1; ///< True if the visual position of the left selection handle must be recalculated.
167 bool mUpdateRightSelectionPosition : 1; ///< True if the visual position of the right selection handle must be recalculated.
168 bool mScrollAfterUpdatePosition : 1; ///< Whether to scroll after the cursor position is updated.
169 bool mScrollAfterDelete : 1; ///< Whether to scroll after delete characters.
170 bool mAllTextSelected : 1; ///< True if the selection handles are selecting all the text.
171 bool mUpdateInputStyle : 1; ///< Whether to update the input style after moving the cursor.
178 TEXT_REPLACED, ///< The entire text was replaced
179 TEXT_INSERTED, ///< Insert characters at the current cursor position
180 TEXT_DELETED ///< Characters were deleted
189 : mFontDescription(),
191 mDefaultPointSize( 0.f ),
193 familyDefined( false ),
194 weightDefined( false ),
195 widthDefined( false ),
196 slantDefined( false ),
199 // Initially use the default platform font
200 TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
201 fontClient.GetDefaultPlatformFontDescription( mFontDescription );
204 FontId GetFontId( TextAbstraction::FontClient& fontClient )
208 const PointSize26Dot6 pointSize = static_cast<PointSize26Dot6>( mDefaultPointSize * 64.f );
209 mFontId = fontClient.GetFontId( mFontDescription, pointSize );
215 TextAbstraction::FontDescription mFontDescription; ///< The default font's description.
216 std::string mFontStyle; ///< The font's style string set through the property system.
217 float mDefaultPointSize; ///< The default font's point size.
218 FontId mFontId; ///< The font's id of the default font.
219 bool familyDefined:1; ///< Whether the default font's family name is defined.
220 bool weightDefined:1; ///< Whether the default font's weight is defined.
221 bool widthDefined:1; ///< Whether the default font's width is defined.
222 bool slantDefined:1; ///< Whether the default font's slant is defined.
223 bool sizeDefined:1; ///< Whether the default font's point size is defined.
227 * @brief Stores indices used to update the text.
228 * Stores the character index where the text is updated and the number of characters removed and added.
229 * Stores as well indices to the first and the last paragraphs to be updated.
231 struct TextUpdateInfo
234 : mCharacterIndex( 0u ),
235 mNumberOfCharactersToRemove( 0u ),
236 mNumberOfCharactersToAdd( 0u ),
237 mPreviousNumberOfCharacters( 0u ),
238 mParagraphCharacterIndex( 0u ),
239 mRequestedNumberOfCharacters( 0u ),
240 mStartGlyphIndex( 0u ),
241 mStartLineIndex( 0u ),
242 mEstimatedNumberOfLines( 0u ),
244 mFullRelayoutNeeded( true ),
245 mIsLastCharacterNewParagraph( false )
251 CharacterIndex mCharacterIndex; ///< Index to the first character to be updated.
252 Length mNumberOfCharactersToRemove; ///< The number of characters to be removed.
253 Length mNumberOfCharactersToAdd; ///< The number of characters to be added.
254 Length mPreviousNumberOfCharacters; ///< The number of characters before the text update.
256 CharacterIndex mParagraphCharacterIndex; ///< Index of the first character of the first paragraph to be updated.
257 Length mRequestedNumberOfCharacters; ///< The requested number of characters.
258 GlyphIndex mStartGlyphIndex;
259 LineIndex mStartLineIndex;
260 Length mEstimatedNumberOfLines; ///< The estimated number of lines. Used to avoid reallocations when layouting.
262 bool mClearAll:1; ///< Whether the whole text is cleared. i.e. when the text is reset.
263 bool mFullRelayoutNeeded:1; ///< Whether a full re-layout is needed. i.e. when a new size is set to the text control.
264 bool mIsLastCharacterNewParagraph:1; ///< Whether the last character is a new paragraph character.
268 // Clear all info except the mPreviousNumberOfCharacters member.
269 mCharacterIndex = static_cast<CharacterIndex>( -1 );
270 mNumberOfCharactersToRemove = 0u;
271 mNumberOfCharactersToAdd = 0u;
272 mParagraphCharacterIndex = 0u;
273 mRequestedNumberOfCharacters = 0u;
274 mStartGlyphIndex = 0u;
275 mStartLineIndex = 0u;
276 mEstimatedNumberOfLines = 0u;
278 mFullRelayoutNeeded = false;
279 mIsLastCharacterNewParagraph = false;
283 struct Controller::Impl
285 Impl( ControlInterface& controlInterface )
286 : mControlInterface( controlInterface ),
289 mFontDefaults( NULL ),
297 mTextColor( Color::BLACK ),
300 mOperationsPending( NO_OPERATION ),
301 mMaximumNumberOfCharacters( 50u ),
302 mRecalculateNaturalSize( true ),
303 mMarkupProcessorEnabled( false ),
304 mClipboardHideEnabled( true ),
305 mAutoScrollEnabled( false ),
306 mAutoScrollDirectionRTL( false )
308 mLogicalModel = LogicalModel::New();
309 mVisualModel = VisualModel::New();
311 mFontClient = TextAbstraction::FontClient::Get();
312 mClipboard = Clipboard::Get();
314 mView.SetVisualModel( mVisualModel );
316 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
317 mMetrics = Metrics::New( mFontClient );
318 mLayoutEngine.SetMetrics( mMetrics );
320 // Set the text properties to default
321 mVisualModel->SetUnderlineEnabled( false );
322 mVisualModel->SetUnderlineHeight( 0.0f );
327 delete mFontDefaults;
332 * @brief Request a relayout using the ControlInterface.
334 void RequestRelayout();
337 * @brief Request a relayout using the ControlInterface.
339 void QueueModifyEvent( ModifyEvent::Type type )
341 if( ModifyEvent::TEXT_REPLACED == type)
343 // Cancel previously queued inserts etc.
344 mModifyEvents.Clear();
349 mModifyEvents.PushBack( event );
351 // The event will be processed during relayout
356 * @brief Helper to move the cursor, grab handle etc.
358 bool ProcessInputEvents();
361 * @brief Helper to check whether any place-holder text is available.
363 bool IsPlaceholderAvailable() const
365 return ( mEventData &&
366 ( !mEventData->mPlaceholderTextInactive.empty() ||
367 !mEventData->mPlaceholderTextActive.empty() )
371 bool IsShowingPlaceholderText() const
373 return ( mEventData && mEventData->mIsShowingPlaceholderText );
377 * @brief Helper to check whether active place-holder text is available.
379 bool IsFocusedPlaceholderAvailable() const
381 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
384 bool IsShowingRealText() const
386 return ( !IsShowingPlaceholderText() &&
387 0u != mLogicalModel->mText.Count() );
391 * @brief Called when placeholder-text is hidden
393 void PlaceholderCleared()
397 mEventData->mIsShowingPlaceholderText = false;
399 // Remove mPlaceholderTextColor
400 mVisualModel->SetTextColor( mTextColor );
404 void ClearPreEditFlag()
408 mEventData->mPreEditFlag = false;
409 mEventData->mPreEditStartPosition = 0;
410 mEventData->mPreEditLength = 0;
414 void ResetImfManager()
418 // Reset incase we are in a pre-edit state.
419 if( mEventData->mImfManager )
421 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
428 bool IsClipboardEmpty()
430 bool result( mClipboard && mClipboard.NumberOfItems() );
431 return !result; // If NumberOfItems greater than 0, return false
435 * @brief Calculates the start character index of the first paragraph to be updated and
436 * the end character index of the last paragraph to be updated.
438 * @param[out] numberOfCharacters The number of characters to be updated.
440 void CalculateTextUpdateIndices( Length& numberOfCharacters );
443 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
445 * @note It never clears the text stored in utf32.
447 void ClearFullModelData( OperationsMask operations );
450 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
452 * @note It never clears the text stored in utf32.
454 * @param[in] startIndex Index to the first character to be cleared.
455 * @param[in] endIndex Index to the last character to be cleared.
456 * @param[in] operations The operations required.
458 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
461 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
463 * @note It never clears the text stored in utf32.
464 * @note Character indices are transformed to glyph indices.
466 * @param[in] startIndex Index to the first character to be cleared.
467 * @param[in] endIndex Index to the last character to be cleared.
468 * @param[in] operations The operations required.
470 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
473 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
475 * @note It never clears the text stored in utf32.
477 * @param[in] startIndex Index to the first character to be cleared.
478 * @param[in] endIndex Index to the last character to be cleared.
479 * @param[in] operations The operations required.
481 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
484 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
486 * When text or style changes the model is set with some operations pending.
487 * When i.e. the text's size or a relayout is required this method is called
488 * with a given @p operationsRequired parameter. The operations required are
489 * matched with the operations pending to perform the minimum number of operations.
491 * @param[in] operationsRequired The operations required.
493 * @return @e true if the model has been modified.
495 bool UpdateModel( OperationsMask operationsRequired );
498 * @brief Retreieves the default style.
500 * @param[out] inputStyle The default style.
502 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
505 * @brief Retrieve the line height of the default font.
507 float GetDefaultFontLineHeight();
509 void OnCursorKeyEvent( const Event& event );
511 void OnTapEvent( const Event& event );
513 void OnPanEvent( const Event& event );
515 void OnLongPressEvent( const Event& event );
517 void OnHandleEvent( const Event& event );
519 void OnSelectEvent( const Event& event );
521 void OnSelectAllEvent();
523 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
525 void ShowClipboard();
527 void HideClipboard();
529 void SetClipboardHideEnable(bool enable);
531 bool CopyStringToClipboard( std::string& source );
533 void SendSelectionToClipboard( bool deleteAfterSending );
535 void GetTextFromClipboard( unsigned int itemIndex, std::string& retrievedString );
537 void RepositionSelectionHandles();
538 void RepositionSelectionHandles( float visualX, float visualY );
540 void SetPopupButtons();
542 void ChangeState( EventData::State newState );
543 LineIndex GetClosestLine( float y ) const;
545 void FindSelectionIndices( float visualX, float visualY, CharacterIndex& startIndex, CharacterIndex& endIndex );
548 * @brief Retrieves the cursor's logical position for a given touch point x,y
550 * @param[in] visualX The touch point x.
551 * @param[in] visualY The touch point y.
553 * @return 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.
555 CharacterIndex GetClosestCursorIndex( float visualX,
559 * @brief Calculates the cursor's position for a given character index in the logical order.
561 * It retrieves as well the line's height and the cursor's height and
562 * if there is a valid alternative cursor, its position and height.
564 * @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.
565 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
567 void GetCursorPosition( CharacterIndex logical,
568 CursorInfo& cursorInfo );
571 * @brief Calculates the new cursor index.
573 * It takes into account that in some scripts multiple characters can form a glyph and all of them
574 * need to be jumped with one key event.
576 * @param[in] index The initial new index.
578 * @return The new cursor index.
580 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
583 * @brief Updates the cursor position.
585 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
586 * It sets the position of the secondary cursor if it's a valid one.
587 * Sets which cursors are active.
589 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
592 void UpdateCursorPosition( const CursorInfo& cursorInfo );
595 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
597 * @param[in] handleType One of the selection handles.
598 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
600 void UpdateSelectionHandle( HandleType handleType,
601 const CursorInfo& cursorInfo );
604 * @biref Clamps the horizontal scrolling to get the control always filled with text.
606 * @param[in] actualSize The size of the laid out text.
608 void ClampHorizontalScroll( const Vector2& actualSize );
611 * @biref Clamps the vertical scrolling to get the control always filled with text.
613 * @param[in] actualSize The size of the laid out text.
615 void ClampVerticalScroll( const Vector2& actualSize );
618 * @brief Scrolls the text to make a position visible.
620 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
622 * @param[in] position A position in text coords.
624 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
625 * or moving the selection handles.
627 void ScrollToMakePositionVisible( const Vector2& position );
630 * @brief Scrolls the text to make the cursor visible.
632 * This method is called after deleting text.
634 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
637 // Declared private and left undefined to avoid copies.
639 // Declared private and left undefined to avoid copies.
640 Impl& operator=( const Impl& );
644 ControlInterface& mControlInterface; ///< Reference to the text controller.
645 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
646 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
647 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
648 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
649 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
650 Clipboard mClipboard; ///< Handle to the system clipboard
651 View mView; ///< The view interface to the rendering back-end.
652 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
653 LayoutEngine mLayoutEngine; ///< The layout engine.
654 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
655 Vector4 mTextColor; ///< The regular text color
656 Vector2 mAlignmentOffset; ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
657 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
658 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
659 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
661 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
662 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
663 bool mClipboardHideEnabled:1; ///< Whether the ClipboardHide function work or not
664 bool mAutoScrollEnabled:1; ///< Whether auto text scrolling is enabled.
665 CharacterDirection mAutoScrollDirectionRTL:1; ///< Direction of auto scrolling, true if rtl
671 } // namespace Toolkit
675 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__