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 )
305 mLogicalModel = LogicalModel::New();
306 mVisualModel = VisualModel::New();
308 mFontClient = TextAbstraction::FontClient::Get();
309 mClipboard = Clipboard::Get();
311 mView.SetVisualModel( mVisualModel );
313 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
314 mMetrics = Metrics::New( mFontClient );
315 mLayoutEngine.SetMetrics( mMetrics );
317 // Set the text properties to default
318 mVisualModel->SetUnderlineEnabled( false );
319 mVisualModel->SetUnderlineHeight( 0.0f );
324 delete mFontDefaults;
329 * @brief Request a relayout using the ControlInterface.
331 void RequestRelayout();
334 * @brief Request a relayout using the ControlInterface.
336 void QueueModifyEvent( ModifyEvent::Type type )
338 if( ModifyEvent::TEXT_REPLACED == type)
340 // Cancel previously queued inserts etc.
341 mModifyEvents.Clear();
346 mModifyEvents.PushBack( event );
348 // The event will be processed during relayout
353 * @brief Helper to move the cursor, grab handle etc.
355 bool ProcessInputEvents();
358 * @brief Helper to check whether any place-holder text is available.
360 bool IsPlaceholderAvailable() const
362 return ( mEventData &&
363 ( !mEventData->mPlaceholderTextInactive.empty() ||
364 !mEventData->mPlaceholderTextActive.empty() )
368 bool IsShowingPlaceholderText() const
370 return ( mEventData && mEventData->mIsShowingPlaceholderText );
374 * @brief Helper to check whether active place-holder text is available.
376 bool IsFocusedPlaceholderAvailable() const
378 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
381 bool IsShowingRealText() const
383 return ( !IsShowingPlaceholderText() &&
384 0u != mLogicalModel->mText.Count() );
388 * @brief Called when placeholder-text is hidden
390 void PlaceholderCleared()
394 mEventData->mIsShowingPlaceholderText = false;
396 // Remove mPlaceholderTextColor
397 mVisualModel->SetTextColor( mTextColor );
401 void ClearPreEditFlag()
405 mEventData->mPreEditFlag = false;
406 mEventData->mPreEditStartPosition = 0;
407 mEventData->mPreEditLength = 0;
411 void ResetImfManager()
415 // Reset incase we are in a pre-edit state.
416 if( mEventData->mImfManager )
418 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
425 bool IsClipboardEmpty()
427 bool result( mClipboard && mClipboard.NumberOfItems() );
428 return !result; // If NumberOfItems greater than 0, return false
432 * @brief Calculates the start character index of the first paragraph to be updated and
433 * the end character index of the last paragraph to be updated.
435 * @param[out] numberOfCharacters The number of characters to be updated.
437 void CalculateTextUpdateIndices( Length& numberOfCharacters );
440 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
442 * @note It never clears the text stored in utf32.
444 void ClearFullModelData( OperationsMask operations );
447 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
449 * @note It never clears the text stored in utf32.
451 * @param[in] startIndex Index to the first character to be cleared.
452 * @param[in] endIndex Index to the last character to be cleared.
453 * @param[in] operations The operations required.
455 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
458 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
460 * @note It never clears the text stored in utf32.
461 * @note Character indices are transformed to glyph indices.
463 * @param[in] startIndex Index to the first character to be cleared.
464 * @param[in] endIndex Index to the last character to be cleared.
465 * @param[in] operations The operations required.
467 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
470 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
472 * @note It never clears the text stored in utf32.
474 * @param[in] startIndex Index to the first character to be cleared.
475 * @param[in] endIndex Index to the last character to be cleared.
476 * @param[in] operations The operations required.
478 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
481 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
483 * When text or style changes the model is set with some operations pending.
484 * When i.e. the text's size or a relayout is required this method is called
485 * with a given @p operationsRequired parameter. The operations required are
486 * matched with the operations pending to perform the minimum number of operations.
488 * @param[in] operationsRequired The operations required.
490 * @return @e true if the model has been modified.
492 bool UpdateModel( OperationsMask operationsRequired );
495 * @brief Retreieves the default style.
497 * @param[out] inputStyle The default style.
499 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
502 * @brief Retrieve the line height of the default font.
504 float GetDefaultFontLineHeight();
506 void OnCursorKeyEvent( const Event& event );
508 void OnTapEvent( const Event& event );
510 void OnPanEvent( const Event& event );
512 void OnLongPressEvent( const Event& event );
514 void OnHandleEvent( const Event& event );
516 void OnSelectEvent( const Event& event );
518 void OnSelectAllEvent();
520 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
522 void ShowClipboard();
524 void HideClipboard();
526 bool CopyStringToClipboard( std::string& source );
528 void SendSelectionToClipboard( bool deleteAfterSending );
530 void GetTextFromClipboard( unsigned int itemIndex, std::string& retrievedString );
532 void RepositionSelectionHandles();
533 void RepositionSelectionHandles( float visualX, float visualY );
535 void SetPopupButtons();
537 void ChangeState( EventData::State newState );
538 LineIndex GetClosestLine( float y ) const;
540 void FindSelectionIndices( float visualX, float visualY, CharacterIndex& startIndex, CharacterIndex& endIndex );
543 * @brief Retrieves the cursor's logical position for a given touch point x,y
545 * @param[in] visualX The touch point x.
546 * @param[in] visualY The touch point y.
548 * @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.
550 CharacterIndex GetClosestCursorIndex( float visualX,
554 * @brief Calculates the cursor's position for a given character index in the logical order.
556 * It retrieves as well the line's height and the cursor's height and
557 * if there is a valid alternative cursor, its position and height.
559 * @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.
560 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
562 void GetCursorPosition( CharacterIndex logical,
563 CursorInfo& cursorInfo );
566 * @brief Calculates the new cursor index.
568 * It takes into account that in some scripts multiple characters can form a glyph and all of them
569 * need to be jumped with one key event.
571 * @param[in] index The initial new index.
573 * @return The new cursor index.
575 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
578 * @brief Updates the cursor position.
580 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
581 * It sets the position of the secondary cursor if it's a valid one.
582 * Sets which cursors are active.
584 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
587 void UpdateCursorPosition( const CursorInfo& cursorInfo );
590 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
592 * @param[in] handleType One of the selection handles.
593 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
595 void UpdateSelectionHandle( HandleType handleType,
596 const CursorInfo& cursorInfo );
599 * @biref Clamps the horizontal scrolling to get the control always filled with text.
601 * @param[in] actualSize The size of the laid out text.
603 void ClampHorizontalScroll( const Vector2& actualSize );
606 * @biref Clamps the vertical scrolling to get the control always filled with text.
608 * @param[in] actualSize The size of the laid out text.
610 void ClampVerticalScroll( const Vector2& actualSize );
613 * @brief Scrolls the text to make a position visible.
615 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
617 * @param[in] position A position in text coords.
619 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
620 * or moving the selection handles.
622 void ScrollToMakePositionVisible( const Vector2& position );
625 * @brief Scrolls the text to make the cursor visible.
627 * This method is called after deleting text.
629 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
632 // Declared private and left undefined to avoid copies.
634 // Declared private and left undefined to avoid copies.
635 Impl& operator=( const Impl& );
639 ControlInterface& mControlInterface; ///< Reference to the text controller.
640 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
641 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
642 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
643 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
644 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
645 Clipboard mClipboard; ///< Handle to the system clipboard
646 View mView; ///< The view interface to the rendering back-end.
647 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
648 LayoutEngine mLayoutEngine; ///< The layout engine.
649 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
650 Vector4 mTextColor; ///< The regular text color
651 Vector2 mAlignmentOffset; ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
652 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
653 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
654 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
656 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
657 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
662 } // namespace Toolkit
666 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__