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 )
306 mLogicalModel = LogicalModel::New();
307 mVisualModel = VisualModel::New();
309 mFontClient = TextAbstraction::FontClient::Get();
310 mClipboard = Clipboard::Get();
312 mView.SetVisualModel( mVisualModel );
314 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
315 mMetrics = Metrics::New( mFontClient );
316 mLayoutEngine.SetMetrics( mMetrics );
318 // Set the text properties to default
319 mVisualModel->SetUnderlineEnabled( false );
320 mVisualModel->SetUnderlineHeight( 0.0f );
325 delete mFontDefaults;
330 * @brief Request a relayout using the ControlInterface.
332 void RequestRelayout();
335 * @brief Request a relayout using the ControlInterface.
337 void QueueModifyEvent( ModifyEvent::Type type )
339 if( ModifyEvent::TEXT_REPLACED == type)
341 // Cancel previously queued inserts etc.
342 mModifyEvents.Clear();
347 mModifyEvents.PushBack( event );
349 // The event will be processed during relayout
354 * @brief Helper to move the cursor, grab handle etc.
356 bool ProcessInputEvents();
359 * @brief Helper to check whether any place-holder text is available.
361 bool IsPlaceholderAvailable() const
363 return ( mEventData &&
364 ( !mEventData->mPlaceholderTextInactive.empty() ||
365 !mEventData->mPlaceholderTextActive.empty() )
369 bool IsShowingPlaceholderText() const
371 return ( mEventData && mEventData->mIsShowingPlaceholderText );
375 * @brief Helper to check whether active place-holder text is available.
377 bool IsFocusedPlaceholderAvailable() const
379 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
382 bool IsShowingRealText() const
384 return ( !IsShowingPlaceholderText() &&
385 0u != mLogicalModel->mText.Count() );
389 * @brief Called when placeholder-text is hidden
391 void PlaceholderCleared()
395 mEventData->mIsShowingPlaceholderText = false;
397 // Remove mPlaceholderTextColor
398 mVisualModel->SetTextColor( mTextColor );
402 void ClearPreEditFlag()
406 mEventData->mPreEditFlag = false;
407 mEventData->mPreEditStartPosition = 0;
408 mEventData->mPreEditLength = 0;
412 void ResetImfManager()
416 // Reset incase we are in a pre-edit state.
417 if( mEventData->mImfManager )
419 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
426 bool IsClipboardEmpty()
428 bool result( mClipboard && mClipboard.NumberOfItems() );
429 return !result; // If NumberOfItems greater than 0, return false
433 * @brief Calculates the start character index of the first paragraph to be updated and
434 * the end character index of the last paragraph to be updated.
436 * @param[out] numberOfCharacters The number of characters to be updated.
438 void CalculateTextUpdateIndices( Length& numberOfCharacters );
441 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
443 * @note It never clears the text stored in utf32.
445 void ClearFullModelData( OperationsMask operations );
448 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
450 * @note It never clears the text stored in utf32.
452 * @param[in] startIndex Index to the first character to be cleared.
453 * @param[in] endIndex Index to the last character to be cleared.
454 * @param[in] operations The operations required.
456 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
459 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
461 * @note It never clears the text stored in utf32.
462 * @note Character indices are transformed to glyph indices.
464 * @param[in] startIndex Index to the first character to be cleared.
465 * @param[in] endIndex Index to the last character to be cleared.
466 * @param[in] operations The operations required.
468 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
471 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
473 * @note It never clears the text stored in utf32.
475 * @param[in] startIndex Index to the first character to be cleared.
476 * @param[in] endIndex Index to the last character to be cleared.
477 * @param[in] operations The operations required.
479 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
482 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
484 * When text or style changes the model is set with some operations pending.
485 * When i.e. the text's size or a relayout is required this method is called
486 * with a given @p operationsRequired parameter. The operations required are
487 * matched with the operations pending to perform the minimum number of operations.
489 * @param[in] operationsRequired The operations required.
491 * @return @e true if the model has been modified.
493 bool UpdateModel( OperationsMask operationsRequired );
496 * @brief Retreieves the default style.
498 * @param[out] inputStyle The default style.
500 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
503 * @brief Retrieve the line height of the default font.
505 float GetDefaultFontLineHeight();
507 void OnCursorKeyEvent( const Event& event );
509 void OnTapEvent( const Event& event );
511 void OnPanEvent( const Event& event );
513 void OnLongPressEvent( const Event& event );
515 void OnHandleEvent( const Event& event );
517 void OnSelectEvent( const Event& event );
519 void OnSelectAllEvent();
521 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
523 void ShowClipboard();
525 void HideClipboard();
527 void SetClipboardHideEnable(bool enable);
529 bool CopyStringToClipboard( std::string& source );
531 void SendSelectionToClipboard( bool deleteAfterSending );
533 void GetTextFromClipboard( unsigned int itemIndex, std::string& retrievedString );
535 void RepositionSelectionHandles();
536 void RepositionSelectionHandles( float visualX, float visualY );
538 void SetPopupButtons();
540 void ChangeState( EventData::State newState );
541 LineIndex GetClosestLine( float y ) const;
543 void FindSelectionIndices( float visualX, float visualY, CharacterIndex& startIndex, CharacterIndex& endIndex );
546 * @brief Retrieves the cursor's logical position for a given touch point x,y
548 * @param[in] visualX The touch point x.
549 * @param[in] visualY The touch point y.
551 * @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.
553 CharacterIndex GetClosestCursorIndex( float visualX,
557 * @brief Calculates the cursor's position for a given character index in the logical order.
559 * It retrieves as well the line's height and the cursor's height and
560 * if there is a valid alternative cursor, its position and height.
562 * @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.
563 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
565 void GetCursorPosition( CharacterIndex logical,
566 CursorInfo& cursorInfo );
569 * @brief Calculates the new cursor index.
571 * It takes into account that in some scripts multiple characters can form a glyph and all of them
572 * need to be jumped with one key event.
574 * @param[in] index The initial new index.
576 * @return The new cursor index.
578 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
581 * @brief Updates the cursor position.
583 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
584 * It sets the position of the secondary cursor if it's a valid one.
585 * Sets which cursors are active.
587 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
590 void UpdateCursorPosition( const CursorInfo& cursorInfo );
593 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
595 * @param[in] handleType One of the selection handles.
596 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
598 void UpdateSelectionHandle( HandleType handleType,
599 const CursorInfo& cursorInfo );
602 * @biref Clamps the horizontal scrolling to get the control always filled with text.
604 * @param[in] actualSize The size of the laid out text.
606 void ClampHorizontalScroll( const Vector2& actualSize );
609 * @biref Clamps the vertical scrolling to get the control always filled with text.
611 * @param[in] actualSize The size of the laid out text.
613 void ClampVerticalScroll( const Vector2& actualSize );
616 * @brief Scrolls the text to make a position visible.
618 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
620 * @param[in] position A position in text coords.
622 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
623 * or moving the selection handles.
625 void ScrollToMakePositionVisible( const Vector2& position );
628 * @brief Scrolls the text to make the cursor visible.
630 * This method is called after deleting text.
632 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
635 // Declared private and left undefined to avoid copies.
637 // Declared private and left undefined to avoid copies.
638 Impl& operator=( const Impl& );
642 ControlInterface& mControlInterface; ///< Reference to the text controller.
643 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
644 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
645 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
646 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
647 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
648 Clipboard mClipboard; ///< Handle to the system clipboard
649 View mView; ///< The view interface to the rendering back-end.
650 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
651 LayoutEngine mLayoutEngine; ///< The layout engine.
652 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
653 Vector4 mTextColor; ///< The regular text color
654 Vector2 mAlignmentOffset; ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
655 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
656 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
657 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
659 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
660 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
661 bool mClipboardHideEnabled:1; ///< Whether the ClipboardHide function work or not
666 } // namespace Toolkit
670 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__