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-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,
98 EventData( DecoratorPtr decorator );
102 static bool IsEditingState( State stateToCheck )
104 return ( stateToCheck == EDITING || stateToCheck == EDITING_WITH_POPUP || stateToCheck == EDITING_WITH_GRAB_HANDLE || stateToCheck == EDITING_WITH_PASTE_POPUP );
107 DecoratorPtr mDecorator; ///< Pointer to the decorator.
108 ImfManager mImfManager; ///< The Input Method Framework Manager.
109 std::string mPlaceholderTextActive; ///< The text to display when the TextField is empty with key-input focus.
110 std::string mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive.
111 Vector4 mPlaceholderTextColor; ///< The in/active placeholder text color.
114 * This is used to delay handling events until after the model has been updated.
115 * The number of updates to the model is minimized to improve performance.
117 std::vector<Event> mEventQueue; ///< The queue of touch events etc.
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 bool mIsShowingPlaceholderText : 1; ///< True if the place-holder text is being displayed.
134 bool mPreEditFlag : 1; ///< True if the model contains text in pre-edit state.
135 bool mDecoratorUpdated : 1; ///< True if the decorator was updated during event processing.
136 bool mCursorBlinkEnabled : 1; ///< True if cursor should blink when active.
137 bool mGrabHandleEnabled : 1; ///< True if grab handle is enabled.
138 bool mGrabHandlePopupEnabled : 1; ///< True if the grab handle popu-up should be shown.
139 bool mSelectionEnabled : 1; ///< True if selection handles, highlight etc. are enabled.
140 bool mUpdateCursorHookPosition : 1; ///< True if the cursor hook position must be updated. Used to move the cursor with the keys 'up' and 'down'.
141 bool mUpdateCursorPosition : 1; ///< True if the visual position of the cursor must be recalculated.
142 bool mUpdateGrabHandlePosition : 1; ///< True if the visual position of the grab handle must be recalculated.
143 bool mUpdateLeftSelectionPosition : 1; ///< True if the visual position of the left selection handle must be recalculated.
144 bool mUpdateRightSelectionPosition : 1; ///< True if the visual position of the right selection handle must be recalculated.
145 bool mIsLeftHandleSelected : 1; ///< Whether is the left handle the one which is selected.
146 bool mUpdateHighlightBox : 1; ///< True if the text selection high light box must be updated.
147 bool mScrollAfterUpdatePosition : 1; ///< Whether to scroll after the cursor position is updated.
148 bool mScrollAfterDelete : 1; ///< Whether to scroll after delete characters.
149 bool mAllTextSelected : 1; ///< True if the selection handles are selecting all the text.
150 bool mUpdateInputStyle : 1; ///< Whether to update the input style after moving the cursor.
157 TEXT_REPLACED, ///< The entire text was replaced
158 TEXT_INSERTED, ///< Insert characters at the current cursor position
159 TEXT_DELETED ///< Characters were deleted
168 : mFontDescription(),
169 mDefaultPointSize( 0.f ),
171 familyDefined( false ),
172 weightDefined( false ),
173 widthDefined( false ),
174 slantDefined( false ),
177 // Initially use the default platform font
178 TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
179 fontClient.GetDefaultPlatformFontDescription( mFontDescription );
182 FontId GetFontId( TextAbstraction::FontClient& fontClient )
186 const PointSize26Dot6 pointSize = static_cast<PointSize26Dot6>( mDefaultPointSize * 64.f );
187 mFontId = fontClient.GetFontId( mFontDescription, pointSize );
193 TextAbstraction::FontDescription mFontDescription; ///< The default font's description.
194 float mDefaultPointSize; ///< The default font's point size.
195 FontId mFontId; ///< The font's id of the default font.
196 bool familyDefined:1; ///< Whether the default font's family name is defined.
197 bool weightDefined:1; ///< Whether the default font's weight is defined.
198 bool widthDefined:1; ///< Whether the default font's width is defined.
199 bool slantDefined:1; ///< Whether the default font's slant is defined.
200 bool sizeDefined:1; ///< Whether the default font's point size is defined.
204 * @brief Stores indices used to update the text.
205 * Stores the character index where the text is updated and the number of characters removed and added.
206 * Stores as well indices to the first and the last paragraphs to be updated.
208 struct TextUpdateInfo
211 : mCharacterIndex( 0u ),
212 mNumberOfCharactersToRemove( 0u ),
213 mNumberOfCharactersToAdd( 0u ),
214 mPreviousNumberOfCharacters( 0u ),
215 mParagraphCharacterIndex( 0u ),
216 mRequestedNumberOfCharacters( 0u ),
217 mStartGlyphIndex( 0u ),
218 mStartLineIndex( 0u ),
219 mEstimatedNumberOfLines( 0u ),
221 mFullRelayoutNeeded( true ),
222 mIsLastCharacterNewParagraph( false )
228 CharacterIndex mCharacterIndex; ///< Index to the first character to be updated.
229 Length mNumberOfCharactersToRemove; ///< The number of characters to be removed.
230 Length mNumberOfCharactersToAdd; ///< The number of characters to be added.
231 Length mPreviousNumberOfCharacters; ///< The number of characters before the text update.
233 CharacterIndex mParagraphCharacterIndex; ///< Index of the first character of the first paragraph to be updated.
234 Length mRequestedNumberOfCharacters; ///< The requested number of characters.
235 GlyphIndex mStartGlyphIndex;
236 LineIndex mStartLineIndex;
237 Length mEstimatedNumberOfLines; ///< The estimated number of lines. Used to avoid reallocations when layouting.
239 bool mClearAll:1; ///< Whether the whole text is cleared. i.e. when the text is reset.
240 bool mFullRelayoutNeeded:1; ///< Whether a full re-layout is needed. i.e. when a new size is set to the text control.
241 bool mIsLastCharacterNewParagraph:1; ///< Whether the last character is a new paragraph character.
245 // Clear all info except the mPreviousNumberOfCharacters member.
246 mCharacterIndex = static_cast<CharacterIndex>( -1 );
247 mNumberOfCharactersToRemove = 0u;
248 mNumberOfCharactersToAdd = 0u;
249 mParagraphCharacterIndex = 0u;
250 mRequestedNumberOfCharacters = 0u;
251 mStartGlyphIndex = 0u;
252 mStartLineIndex = 0u;
253 mEstimatedNumberOfLines = 0u;
255 mFullRelayoutNeeded = false;
256 mIsLastCharacterNewParagraph = false;
260 struct UnderlineDefaults
262 std::string properties;
263 // TODO: complete with underline parameters.
266 struct ShadowDefaults
268 std::string properties;
269 // TODO: complete with shadow parameters.
272 struct EmbossDefaults
274 std::string properties;
275 // TODO: complete with emboss parameters.
278 struct OutlineDefaults
280 std::string properties;
281 // TODO: complete with outline parameters.
284 struct Controller::Impl
286 Impl( ControlInterface& controlInterface )
287 : mControlInterface( controlInterface ),
290 mFontDefaults( NULL ),
291 mUnderlineDefaults( NULL ),
292 mShadowDefaults( NULL ),
293 mEmbossDefaults( NULL ),
294 mOutlineDefaults( NULL ),
302 mTextColor( Color::BLACK ),
304 mOperationsPending( NO_OPERATION ),
305 mMaximumNumberOfCharacters( 50u ),
306 mRecalculateNaturalSize( true ),
307 mMarkupProcessorEnabled( false ),
308 mClipboardHideEnabled( true ),
309 mAutoScrollEnabled( false ),
310 mAutoScrollDirectionRTL( false )
312 mLogicalModel = LogicalModel::New();
313 mVisualModel = VisualModel::New();
315 mFontClient = TextAbstraction::FontClient::Get();
316 mClipboard = Clipboard::Get();
318 mView.SetVisualModel( mVisualModel );
320 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
321 mMetrics = Metrics::New( mFontClient );
322 mLayoutEngine.SetMetrics( mMetrics );
324 // Set the text properties to default
325 mVisualModel->SetUnderlineEnabled( false );
326 mVisualModel->SetUnderlineHeight( 0.0f );
331 delete mFontDefaults;
332 delete mUnderlineDefaults;
333 delete mShadowDefaults;
334 delete mEmbossDefaults;
335 delete mOutlineDefaults;
340 * @brief Request a relayout using the ControlInterface.
342 void RequestRelayout();
345 * @brief Request a relayout using the ControlInterface.
347 void QueueModifyEvent( ModifyEvent::Type type )
349 if( ModifyEvent::TEXT_REPLACED == type)
351 // Cancel previously queued inserts etc.
352 mModifyEvents.Clear();
357 mModifyEvents.PushBack( event );
359 // The event will be processed during relayout
364 * @brief Helper to move the cursor, grab handle etc.
366 bool ProcessInputEvents();
369 * @brief Helper to check whether any place-holder text is available.
371 bool IsPlaceholderAvailable() const
373 return ( mEventData &&
374 ( !mEventData->mPlaceholderTextInactive.empty() ||
375 !mEventData->mPlaceholderTextActive.empty() )
379 bool IsShowingPlaceholderText() const
381 return ( mEventData && mEventData->mIsShowingPlaceholderText );
385 * @brief Helper to check whether active place-holder text is available.
387 bool IsFocusedPlaceholderAvailable() const
389 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
392 bool IsShowingRealText() const
394 return ( !IsShowingPlaceholderText() &&
395 0u != mLogicalModel->mText.Count() );
399 * @brief Called when placeholder-text is hidden
401 void PlaceholderCleared()
405 mEventData->mIsShowingPlaceholderText = false;
407 // Remove mPlaceholderTextColor
408 mVisualModel->SetTextColor( mTextColor );
412 void ClearPreEditFlag()
416 mEventData->mPreEditFlag = false;
417 mEventData->mPreEditStartPosition = 0;
418 mEventData->mPreEditLength = 0;
422 void ResetImfManager()
426 // Reset incase we are in a pre-edit state.
427 if( mEventData->mImfManager )
429 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
437 * @brief Helper to notify IMF manager with surrounding text & cursor changes.
439 void NotifyImfManager();
442 * @brief Retrieve the current cursor position.
444 * @return The cursor position.
446 CharacterIndex GetLogicalCursorPosition() const;
449 * @brief Retrieves the number of consecutive white spaces starting from the given @p index.
451 * @param[in] index The character index from where to count the number of consecutive white spaces.
453 * @return The number of consecutive white spaces.
455 Length GetNumberOfWhiteSpaces( CharacterIndex index ) const;
458 * @brief Retrieve any text previously set starting from the given @p index.
460 * @param[in] index The character index from where to retrieve the text.
461 * @param[out] text A string of UTF-8 characters.
463 * @see Dali::Toolkit::Text::Controller::GetText()
465 void GetText( CharacterIndex index, std::string& text ) const;
467 bool IsClipboardEmpty()
469 bool result( mClipboard && mClipboard.NumberOfItems() );
470 return !result; // If NumberOfItems greater than 0, return false
474 * @brief Calculates the start character index of the first paragraph to be updated and
475 * the end character index of the last paragraph to be updated.
477 * @param[out] numberOfCharacters The number of characters to be updated.
479 void CalculateTextUpdateIndices( Length& numberOfCharacters );
482 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
484 * @note It never clears the text stored in utf32.
486 void ClearFullModelData( OperationsMask operations );
489 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
491 * @note It never clears the text stored in utf32.
493 * @param[in] startIndex Index to the first character to be cleared.
494 * @param[in] endIndex Index to the last character to be cleared.
495 * @param[in] operations The operations required.
497 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
500 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
502 * @note It never clears the text stored in utf32.
503 * @note Character indices are transformed to glyph indices.
505 * @param[in] startIndex Index to the first character to be cleared.
506 * @param[in] endIndex Index to the last character to be cleared.
507 * @param[in] operations The operations required.
509 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
512 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
514 * @note It never clears the text stored in utf32.
516 * @param[in] startIndex Index to the first character to be cleared.
517 * @param[in] endIndex Index to the last character to be cleared.
518 * @param[in] operations The operations required.
520 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
523 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
525 * When text or style changes the model is set with some operations pending.
526 * When i.e. the text's size or a relayout is required this method is called
527 * with a given @p operationsRequired parameter. The operations required are
528 * matched with the operations pending to perform the minimum number of operations.
530 * @param[in] operationsRequired The operations required.
532 * @return @e true if the model has been modified.
534 bool UpdateModel( OperationsMask operationsRequired );
537 * @brief Retreieves the default style.
539 * @param[out] inputStyle The default style.
541 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
544 * @brief Retrieve the line height of the default font.
546 float GetDefaultFontLineHeight();
548 void OnCursorKeyEvent( const Event& event );
550 void OnTapEvent( const Event& event );
552 void OnPanEvent( const Event& event );
554 void OnLongPressEvent( const Event& event );
556 void OnHandleEvent( const Event& event );
558 void OnSelectEvent( const Event& event );
560 void OnSelectAllEvent();
563 * @brief Retrieves the selected text. It removes the text if the @p deleteAfterRetrieval parameter is @e true.
565 * @param[out] selectedText The selected text encoded in utf8.
566 * @param[in] deleteAfterRetrieval Whether the text should be deleted after retrieval.
568 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
570 void ShowClipboard();
572 void HideClipboard();
574 void SetClipboardHideEnable(bool enable);
576 bool CopyStringToClipboard( std::string& source );
578 void SendSelectionToClipboard( bool deleteAfterSending );
580 void GetTextFromClipboard( unsigned int itemIndex, std::string& retrievedString );
582 void RepositionSelectionHandles();
583 void RepositionSelectionHandles( float visualX, float visualY );
585 void SetPopupButtons();
587 void ChangeState( EventData::State newState );
590 * @brief Calculates the cursor's position for a given character index in the logical order.
592 * It retrieves as well the line's height and the cursor's height and
593 * if there is a valid alternative cursor, its position and height.
595 * @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.
596 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
598 void GetCursorPosition( CharacterIndex logical,
599 CursorInfo& cursorInfo );
602 * @brief Calculates the new cursor index.
604 * It takes into account that in some scripts multiple characters can form a glyph and all of them
605 * need to be jumped with one key event.
607 * @param[in] index The initial new index.
609 * @return The new cursor index.
611 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
614 * @brief Updates the cursor position.
616 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
617 * It sets the position of the secondary cursor if it's a valid one.
618 * Sets which cursors are active.
620 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
623 void UpdateCursorPosition( const CursorInfo& cursorInfo );
626 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
628 * @param[in] handleType One of the selection handles.
629 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
631 void UpdateSelectionHandle( HandleType handleType,
632 const CursorInfo& cursorInfo );
635 * @biref Clamps the horizontal scrolling to get the control always filled with text.
637 * @param[in] layoutSize The size of the laid out text.
639 void ClampHorizontalScroll( const Vector2& layoutSize );
642 * @biref Clamps the vertical scrolling to get the control always filled with text.
644 * @param[in] layoutSize The size of the laid out text.
646 void ClampVerticalScroll( const Vector2& layoutSize );
649 * @brief Scrolls the text to make a position visible.
651 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
653 * @param[in] position A position in text coords.
654 * @param[in] lineHeight The line height for the given position.
656 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
657 * or moving the selection handles.
659 void ScrollToMakePositionVisible( const Vector2& position, float lineHeight );
662 * @brief Scrolls the text to make the cursor visible.
664 * This method is called after deleting text.
666 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
669 // Declared private and left undefined to avoid copies.
671 // Declared private and left undefined to avoid copies.
672 Impl& operator=( const Impl& );
676 ControlInterface& mControlInterface; ///< Reference to the text controller.
677 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
678 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
679 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
680 UnderlineDefaults* mUnderlineDefaults; ///< Avoid allocating this when the user does not specify underline parameters.
681 ShadowDefaults* mShadowDefaults; ///< Avoid allocating this when the user does not specify shadow parameters.
682 EmbossDefaults* mEmbossDefaults; ///< Avoid allocating this when the user does not specify emboss parameters.
683 OutlineDefaults* mOutlineDefaults; ///< Avoid allocating this when the user does not specify outline parameters.
684 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
685 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
686 Clipboard mClipboard; ///< Handle to the system clipboard
687 View mView; ///< The view interface to the rendering back-end.
688 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
689 LayoutEngine mLayoutEngine; ///< The layout engine.
690 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
691 Vector4 mTextColor; ///< The regular text color
693 * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
694 * Typically this will have a negative value with scrolling occurs.
696 Vector2 mScrollPosition; ///< The text is offset by this position when scrolling.
697 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
698 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
699 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
701 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
702 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
703 bool mClipboardHideEnabled:1; ///< Whether the ClipboardHide function work or not
704 bool mAutoScrollEnabled:1; ///< Whether auto text scrolling is enabled.
705 CharacterDirection mAutoScrollDirectionRTL:1; ///< Direction of auto scrolling, true if rtl
711 } // namespace Toolkit
715 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__