1 #ifndef DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H
2 #define DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H
5 * Copyright (c) 2016 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-scroller-data.h>
30 #include <dali-toolkit/internal/text/text-controller.h>
31 #include <dali-toolkit/internal/text/text-view.h>
32 #include <dali-toolkit/internal/text/visual-model-impl.h>
43 //Forward declarations
48 // Used to queue input events until DoRelayout()
56 LEFT_SELECTION_HANDLE_EVENT,
57 RIGHT_SELECTION_HANDLE_EVENT,
69 Event( Type eventType )
92 EDITING_WITH_GRAB_HANDLE,
93 EDITING_WITH_PASTE_POPUP,
95 SELECTION_HANDLE_PANNING,
99 EventData( DecoratorPtr decorator );
103 static bool IsEditingState( State stateToCheck )
105 return ( stateToCheck == EDITING || stateToCheck == EDITING_WITH_POPUP || stateToCheck == EDITING_WITH_GRAB_HANDLE || stateToCheck == EDITING_WITH_PASTE_POPUP );
108 DecoratorPtr mDecorator; ///< Pointer to the decorator.
109 ImfManager mImfManager; ///< The Input Method Framework Manager.
110 std::string mPlaceholderTextActive; ///< The text to display when the TextField is empty with key-input focus.
111 std::string mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive.
112 Vector4 mPlaceholderTextColor; ///< The in/active placeholder text color.
115 * This is used to delay handling events until after the model has been updated.
116 * The number of updates to the model is minimized to improve performance.
118 std::vector<Event> mEventQueue; ///< The queue of touch events etc.
120 Vector<InputStyle::Mask> mInputStyleChangedQueue; ///< Queue of changes in the input style. Used to emit the signal in the iddle callback.
122 InputStyle mInputStyle; ///< The style to be set to the new inputed text.
124 State mPreviousState; ///< Stores the current state before it's updated with the new one.
125 State mState; ///< Selection mode, edit mode etc.
127 CharacterIndex mPrimaryCursorPosition; ///< Index into logical model for primary cursor.
128 CharacterIndex mLeftSelectionPosition; ///< Index into logical model for left selection handle.
129 CharacterIndex mRightSelectionPosition; ///< Index into logical model for right selection handle.
131 CharacterIndex mPreEditStartPosition; ///< Used to remove the pre-edit text if necessary.
132 Length mPreEditLength; ///< Used to remove the pre-edit text if necessary.
134 float mCursorHookPositionX; ///< Used to move the cursor with the keys or when scrolling the text vertically with the handles.
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 mUpdateHighlightBox : 1; ///< True if the text selection high light box must be updated.
150 bool mScrollAfterUpdatePosition : 1; ///< Whether to scroll after the cursor position is updated.
151 bool mScrollAfterDelete : 1; ///< Whether to scroll after delete characters.
152 bool mAllTextSelected : 1; ///< True if the selection handles are selecting all the text.
153 bool mUpdateInputStyle : 1; ///< Whether to update the input style after moving the cursor.
160 TEXT_REPLACED, ///< The entire text was replaced
161 TEXT_INSERTED, ///< Insert characters at the current cursor position
162 TEXT_DELETED ///< Characters were deleted
171 : mFontDescription(),
172 mDefaultPointSize( 0.f ),
174 familyDefined( false ),
175 weightDefined( false ),
176 widthDefined( false ),
177 slantDefined( false ),
180 // Initially use the default platform font
181 TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
182 fontClient.GetDefaultPlatformFontDescription( mFontDescription );
185 FontId GetFontId( TextAbstraction::FontClient& fontClient )
189 const PointSize26Dot6 pointSize = static_cast<PointSize26Dot6>( mDefaultPointSize * 64.f );
190 mFontId = fontClient.GetFontId( mFontDescription, pointSize );
196 TextAbstraction::FontDescription mFontDescription; ///< The default font's description.
197 float mDefaultPointSize; ///< The default font's point size.
198 FontId mFontId; ///< The font's id of the default font.
199 bool familyDefined:1; ///< Whether the default font's family name is defined.
200 bool weightDefined:1; ///< Whether the default font's weight is defined.
201 bool widthDefined:1; ///< Whether the default font's width is defined.
202 bool slantDefined:1; ///< Whether the default font's slant is defined.
203 bool sizeDefined:1; ///< Whether the default font's point size is defined.
207 * @brief Stores indices used to update the text.
208 * Stores the character index where the text is updated and the number of characters removed and added.
209 * Stores as well indices to the first and the last paragraphs to be updated.
211 struct TextUpdateInfo
214 : mCharacterIndex( 0u ),
215 mNumberOfCharactersToRemove( 0u ),
216 mNumberOfCharactersToAdd( 0u ),
217 mPreviousNumberOfCharacters( 0u ),
218 mParagraphCharacterIndex( 0u ),
219 mRequestedNumberOfCharacters( 0u ),
220 mStartGlyphIndex( 0u ),
221 mStartLineIndex( 0u ),
222 mEstimatedNumberOfLines( 0u ),
224 mFullRelayoutNeeded( true ),
225 mIsLastCharacterNewParagraph( false )
231 CharacterIndex mCharacterIndex; ///< Index to the first character to be updated.
232 Length mNumberOfCharactersToRemove; ///< The number of characters to be removed.
233 Length mNumberOfCharactersToAdd; ///< The number of characters to be added.
234 Length mPreviousNumberOfCharacters; ///< The number of characters before the text update.
236 CharacterIndex mParagraphCharacterIndex; ///< Index of the first character of the first paragraph to be updated.
237 Length mRequestedNumberOfCharacters; ///< The requested number of characters.
238 GlyphIndex mStartGlyphIndex;
239 LineIndex mStartLineIndex;
240 Length mEstimatedNumberOfLines; ///< The estimated number of lines. Used to avoid reallocations when layouting.
242 bool mClearAll:1; ///< Whether the whole text is cleared. i.e. when the text is reset.
243 bool mFullRelayoutNeeded:1; ///< Whether a full re-layout is needed. i.e. when a new size is set to the text control.
244 bool mIsLastCharacterNewParagraph:1; ///< Whether the last character is a new paragraph character.
248 // Clear all info except the mPreviousNumberOfCharacters member.
249 mCharacterIndex = static_cast<CharacterIndex>( -1 );
250 mNumberOfCharactersToRemove = 0u;
251 mNumberOfCharactersToAdd = 0u;
252 mParagraphCharacterIndex = 0u;
253 mRequestedNumberOfCharacters = 0u;
254 mStartGlyphIndex = 0u;
255 mStartLineIndex = 0u;
256 mEstimatedNumberOfLines = 0u;
258 mFullRelayoutNeeded = false;
259 mIsLastCharacterNewParagraph = false;
263 struct UnderlineDefaults
265 std::string properties;
266 // TODO: complete with underline parameters.
269 struct ShadowDefaults
271 std::string properties;
272 // TODO: complete with shadow parameters.
275 struct EmbossDefaults
277 std::string properties;
278 // TODO: complete with emboss parameters.
281 struct OutlineDefaults
283 std::string properties;
284 // TODO: complete with outline parameters.
287 struct Controller::Impl
289 Impl( ControlInterface* controlInterface,
290 EditableControlInterface* editableControlInterface )
291 : mControlInterface( controlInterface ),
292 mEditableControlInterface( editableControlInterface ),
295 mFontDefaults( NULL ),
296 mUnderlineDefaults( NULL ),
297 mShadowDefaults( NULL ),
298 mEmbossDefaults( NULL ),
299 mOutlineDefaults( NULL ),
301 mAutoScrollData( NULL ),
308 mTextColor( Color::BLACK ),
311 mOperationsPending( NO_OPERATION ),
312 mMaximumNumberOfCharacters( 50u ),
313 mRecalculateNaturalSize( true ),
314 mMarkupProcessorEnabled( false ),
315 mClipboardHideEnabled( true ),
316 mIsAutoScrollEnabled( false )
318 mLogicalModel = LogicalModel::New();
319 mVisualModel = VisualModel::New();
321 mFontClient = TextAbstraction::FontClient::Get();
322 mClipboard = Clipboard::Get();
324 mView.SetVisualModel( mVisualModel );
326 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
327 mMetrics = Metrics::New( mFontClient );
328 mLayoutEngine.SetMetrics( mMetrics );
330 // Set the text properties to default
331 mVisualModel->SetUnderlineEnabled( false );
332 mVisualModel->SetUnderlineHeight( 0.0f );
337 delete mFontDefaults;
338 delete mUnderlineDefaults;
339 delete mShadowDefaults;
340 delete mEmbossDefaults;
341 delete mOutlineDefaults;
343 delete mAutoScrollData;
346 // Text Controller Implementation.
349 * @copydoc Text::Controller::RequestRelayout()
351 void RequestRelayout();
354 * @brief Request a relayout using the ControlInterface.
356 void QueueModifyEvent( ModifyEvent::Type type )
358 if( ModifyEvent::TEXT_REPLACED == type)
360 // Cancel previously queued inserts etc.
361 mModifyEvents.Clear();
366 mModifyEvents.PushBack( event );
368 // The event will be processed during relayout
373 * @brief Helper to move the cursor, grab handle etc.
375 bool ProcessInputEvents();
378 * @brief Helper to check whether any place-holder text is available.
380 bool IsPlaceholderAvailable() const
382 return ( mEventData &&
383 ( !mEventData->mPlaceholderTextInactive.empty() ||
384 !mEventData->mPlaceholderTextActive.empty() )
388 bool IsShowingPlaceholderText() const
390 return ( mEventData && mEventData->mIsShowingPlaceholderText );
394 * @brief Helper to check whether active place-holder text is available.
396 bool IsFocusedPlaceholderAvailable() const
398 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
401 bool IsShowingRealText() const
403 return ( !IsShowingPlaceholderText() &&
404 0u != mLogicalModel->mText.Count() );
408 * @brief Called when placeholder-text is hidden
410 void PlaceholderCleared()
414 mEventData->mIsShowingPlaceholderText = false;
416 // Remove mPlaceholderTextColor
417 mVisualModel->SetTextColor( mTextColor );
421 void ClearPreEditFlag()
425 mEventData->mPreEditFlag = false;
426 mEventData->mPreEditStartPosition = 0;
427 mEventData->mPreEditLength = 0;
431 void ResetImfManager()
435 // Reset incase we are in a pre-edit state.
436 if( mEventData->mImfManager )
438 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
446 * @brief Helper to notify IMF manager with surrounding text & cursor changes.
448 void NotifyImfManager();
451 * @brief Helper to notify IMF manager with multi line status.
453 void NotifyImfMultiLineStatus();
456 * @brief Retrieve the current cursor position.
458 * @return The cursor position.
460 CharacterIndex GetLogicalCursorPosition() const;
463 * @brief Retrieves the number of consecutive white spaces starting from the given @p index.
465 * @param[in] index The character index from where to count the number of consecutive white spaces.
467 * @return The number of consecutive white spaces.
469 Length GetNumberOfWhiteSpaces( CharacterIndex index ) const;
472 * @brief Retrieve any text previously set starting from the given @p index.
474 * @param[in] index The character index from where to retrieve the text.
475 * @param[out] text A string of UTF-8 characters.
477 * @see Dali::Toolkit::Text::Controller::GetText()
479 void GetText( CharacterIndex index, std::string& text ) const;
481 bool IsClipboardEmpty()
483 bool result( mClipboard && mClipboard.NumberOfItems() );
484 return !result; // If NumberOfItems greater than 0, return false
487 bool IsClipboardVisible()
489 bool result( mClipboard && mClipboard.IsVisible() );
494 * @brief Calculates the start character index of the first paragraph to be updated and
495 * the end character index of the last paragraph to be updated.
497 * @param[out] numberOfCharacters The number of characters to be updated.
499 void CalculateTextUpdateIndices( Length& numberOfCharacters );
502 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
504 * @note It never clears the text stored in utf32.
506 void ClearFullModelData( OperationsMask operations );
509 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
511 * @note It never clears the text stored in utf32.
513 * @param[in] startIndex Index to the first character to be cleared.
514 * @param[in] endIndex Index to the last character to be cleared.
515 * @param[in] operations The operations required.
517 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
520 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
522 * @note It never clears the text stored in utf32.
523 * @note Character indices are transformed to glyph indices.
525 * @param[in] startIndex Index to the first character to be cleared.
526 * @param[in] endIndex Index to the last character to be cleared.
527 * @param[in] operations The operations required.
529 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
532 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
534 * @note It never clears the text stored in utf32.
536 * @param[in] startIndex Index to the first character to be cleared.
537 * @param[in] endIndex Index to the last character to be cleared.
538 * @param[in] operations The operations required.
540 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
543 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
545 * When text or style changes the model is set with some operations pending.
546 * When i.e. the text's size or a relayout is required this method is called
547 * with a given @p operationsRequired parameter. The operations required are
548 * matched with the operations pending to perform the minimum number of operations.
550 * @param[in] operationsRequired The operations required.
552 * @return @e true if the model has been modified.
554 bool UpdateModel( OperationsMask operationsRequired );
557 * @brief Retreieves the default style.
559 * @param[out] inputStyle The default style.
561 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
564 * @brief Retrieve the line height of the default font.
566 float GetDefaultFontLineHeight();
568 void OnCursorKeyEvent( const Event& event );
570 void OnTapEvent( const Event& event );
572 void OnPanEvent( const Event& event );
574 void OnLongPressEvent( const Event& event );
576 void OnHandleEvent( const Event& event );
578 void OnSelectEvent( const Event& event );
580 void OnSelectAllEvent();
583 * @brief Retrieves the selected text. It removes the text if the @p deleteAfterRetrieval parameter is @e true.
585 * @param[out] selectedText The selected text encoded in utf8.
586 * @param[in] deleteAfterRetrieval Whether the text should be deleted after retrieval.
588 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
590 void ShowClipboard();
592 void HideClipboard();
594 void SetClipboardHideEnable(bool enable);
596 bool CopyStringToClipboard( std::string& source );
598 void SendSelectionToClipboard( bool deleteAfterSending );
600 void RequestGetTextFromClipboard();
602 void RepositionSelectionHandles();
603 void RepositionSelectionHandles( float visualX, float visualY );
605 void SetPopupButtons();
607 void ChangeState( EventData::State newState );
610 * @brief Calculates the cursor's position for a given character index in the logical order.
612 * It retrieves as well the line's height and the cursor's height and
613 * if there is a valid alternative cursor, its position and height.
615 * @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.
616 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
618 void GetCursorPosition( CharacterIndex logical,
619 CursorInfo& cursorInfo );
622 * @brief Calculates the new cursor index.
624 * It takes into account that in some scripts multiple characters can form a glyph and all of them
625 * need to be jumped with one key event.
627 * @param[in] index The initial new index.
629 * @return The new cursor index.
631 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
634 * @brief Updates the cursor position.
636 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
637 * It sets the position of the secondary cursor if it's a valid one.
638 * Sets which cursors are active.
640 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
643 void UpdateCursorPosition( const CursorInfo& cursorInfo );
646 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
648 * @param[in] handleType One of the selection handles.
649 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
651 void UpdateSelectionHandle( HandleType handleType,
652 const CursorInfo& cursorInfo );
655 * @biref Clamps the horizontal scrolling to get the control always filled with text.
657 * @param[in] layoutSize The size of the laid out text.
659 void ClampHorizontalScroll( const Vector2& layoutSize );
662 * @biref Clamps the vertical scrolling to get the control always filled with text.
664 * @param[in] layoutSize The size of the laid out text.
666 void ClampVerticalScroll( const Vector2& layoutSize );
669 * @brief Scrolls the text to make a position visible.
671 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
673 * @param[in] position A position in text coords.
674 * @param[in] lineHeight The line height for the given position.
676 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
677 * or moving the selection handles.
679 void ScrollToMakePositionVisible( const Vector2& position, float lineHeight );
682 * @brief Scrolls the text to make the cursor visible.
684 * This method is called after deleting text.
686 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
689 // Declared private and left undefined to avoid copies.
691 // Declared private and left undefined to avoid copies.
692 Impl& operator=( const Impl& );
696 ControlInterface* mControlInterface; ///< Reference to the text controller.
697 EditableControlInterface* mEditableControlInterface; ///< Reference to the editable text controller.
698 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
699 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
700 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
701 UnderlineDefaults* mUnderlineDefaults; ///< Avoid allocating this when the user does not specify underline parameters.
702 ShadowDefaults* mShadowDefaults; ///< Avoid allocating this when the user does not specify shadow parameters.
703 EmbossDefaults* mEmbossDefaults; ///< Avoid allocating this when the user does not specify emboss parameters.
704 OutlineDefaults* mOutlineDefaults; ///< Avoid allocating this when the user does not specify outline parameters.
705 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
706 ScrollerData* mAutoScrollData; ///< Avoid allocating this when the user does not specify the auto text scrolling feature.
707 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
708 Clipboard mClipboard; ///< Handle to the system clipboard
709 View mView; ///< The view interface to the rendering back-end.
710 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
711 LayoutEngine mLayoutEngine; ///< The layout engine.
712 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
713 Vector4 mTextColor; ///< The regular text color
715 * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
716 * Typically this will have a negative value with scrolling occurs.
718 Vector2 mScrollPosition; ///< The text is offset by this position when scrolling.
719 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
720 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
721 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
723 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
724 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
725 bool mClipboardHideEnabled:1; ///< Whether the ClipboardHide function work or not.
726 bool mIsAutoScrollEnabled:1; ///< Whether auto text scrolling is enabled.
731 } // namespace Toolkit
735 #endif // DALI_TOOLKIT_TEXT_CONTROLLER_H