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>
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
97 EventData( DecoratorPtr decorator );
101 static bool IsEditingState( State stateToCheck )
103 return ( stateToCheck == EDITING || stateToCheck == EDITING_WITH_POPUP || stateToCheck == EDITING_WITH_GRAB_HANDLE || stateToCheck == EDITING_WITH_PASTE_POPUP );
106 DecoratorPtr mDecorator; ///< Pointer to the decorator.
107 ImfManager mImfManager; ///< The Input Method Framework Manager.
108 std::string mPlaceholderTextActive; ///< The text to display when the TextField is empty with key-input focus.
109 std::string mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive.
110 Vector4 mPlaceholderTextColor; ///< The in/active placeholder text color.
113 * This is used to delay handling events until after the model has been updated.
114 * The number of updates to the model is minimized to improve performance.
116 std::vector<Event> mEventQueue; ///< The queue of touch events etc.
118 InputStyle mInputStyle; ///< The style to be set to the new inputed text.
121 * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
122 * Typically this will have a negative value with scrolling occurs.
124 Vector2 mScrollPosition; ///< The text is offset by this position when scrolling.
126 State mState; ///< Selection mode, edit mode etc.
128 CharacterIndex mPrimaryCursorPosition; ///< Index into logical model for primary cursor.
129 CharacterIndex mLeftSelectionPosition; ///< Index into logical model for left selection handle.
130 CharacterIndex mRightSelectionPosition; ///< Index into logical model for right selection handle.
132 CharacterIndex mPreEditStartPosition; ///< Used to remove the pre-edit text if necessary.
133 Length mPreEditLength; ///< Used to remove the pre-edit text if necessary.
135 bool mIsShowingPlaceholderText : 1; ///< True if the place-holder text is being displayed.
136 bool mPreEditFlag : 1; ///< True if the model contains text in pre-edit state.
137 bool mDecoratorUpdated : 1; ///< True if the decorator was updated during event processing.
138 bool mCursorBlinkEnabled : 1; ///< True if cursor should blink when active.
139 bool mGrabHandleEnabled : 1; ///< True if grab handle is enabled.
140 bool mGrabHandlePopupEnabled : 1; ///< True if the grab handle popu-up should be shown.
141 bool mSelectionEnabled : 1; ///< True if selection handles, highlight etc. are enabled.
142 bool mHorizontalScrollingEnabled : 1; ///< True if horizontal scrolling is enabled.
143 bool mVerticalScrollingEnabled : 1; ///< True if vertical scrolling is enabled.
144 bool mUpdateCursorPosition : 1; ///< True if the visual position of the cursor must be recalculated.
145 bool mUpdateLeftSelectionPosition : 1; ///< True if the visual position of the left selection handle must be recalculated.
146 bool mUpdateRightSelectionPosition : 1; ///< True if the visual position of the right selection handle must be recalculated.
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(),
170 mDefaultPointSize( 0.f ),
172 familyDefined( false ),
173 weightDefined( false ),
174 widthDefined( false ),
175 slantDefined( false ),
178 // Initially use the default platform font
179 TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
180 fontClient.GetDefaultPlatformFontDescription( mFontDescription );
183 FontId GetFontId( TextAbstraction::FontClient& fontClient )
187 const PointSize26Dot6 pointSize = static_cast<PointSize26Dot6>( mDefaultPointSize * 64.f );
188 mFontId = fontClient.GetFontId( mFontDescription, pointSize );
194 TextAbstraction::FontDescription mFontDescription; ///< The default font's description.
195 std::string mFontStyle; ///< The font's style string set through the property system.
196 float mDefaultPointSize; ///< The default font's point size.
197 FontId mFontId; ///< The font's id of the default font.
198 bool familyDefined:1; ///< Whether the default font's family name is defined.
199 bool weightDefined:1; ///< Whether the default font's weight is defined.
200 bool widthDefined:1; ///< Whether the default font's width is defined.
201 bool slantDefined:1; ///< Whether the default font's slant is defined.
202 bool sizeDefined:1; ///< Whether the default font's point size is defined.
206 * @brief Stores indices used to update the text.
207 * Stores the character index where the text is updated and the number of characters removed and added.
208 * Stores as well indices to the first and the last paragraphs to be updated.
210 struct TextUpdateInfo
213 : mCharacterIndex( 0u ),
214 mNumberOfCharactersToRemove( 0u ),
215 mNumberOfCharactersToAdd( 0u ),
216 mPreviousNumberOfCharacters( 0u ),
217 mParagraphCharacterIndex( 0u ),
218 mRequestedNumberOfCharacters( 0u ),
219 mStartGlyphIndex( 0u ),
220 mStartLineIndex( 0u ),
221 mEstimatedNumberOfLines( 0u ),
223 mFullRelayoutNeeded( true ),
224 mIsLastCharacterNewParagraph( false )
230 CharacterIndex mCharacterIndex; ///< Index to the first character to be updated.
231 Length mNumberOfCharactersToRemove; ///< The number of characters to be removed.
232 Length mNumberOfCharactersToAdd; ///< The number of characters to be added.
233 Length mPreviousNumberOfCharacters; ///< The number of characters before the text update.
235 CharacterIndex mParagraphCharacterIndex; ///< Index of the first character of the first paragraph to be updated.
236 Length mRequestedNumberOfCharacters; ///< The requested number of characters.
237 GlyphIndex mStartGlyphIndex;
238 LineIndex mStartLineIndex;
239 Length mEstimatedNumberOfLines; ///< The estimated number of lines. Used to avoid reallocations when layouting.
241 bool mClearAll:1; ///< Whether the whole text is cleared. i.e. when the text is reset.
242 bool mFullRelayoutNeeded:1; ///< Whether a full re-layout is needed. i.e. when a new size is set to the text control.
243 bool mIsLastCharacterNewParagraph:1; ///< Whether the last character is a new paragraph character.
247 // Clear all info except the mPreviousNumberOfCharacters member.
248 mCharacterIndex = static_cast<CharacterIndex>( -1 );
249 mNumberOfCharactersToRemove = 0u;
250 mNumberOfCharactersToAdd = 0u;
251 mParagraphCharacterIndex = 0u;
252 mRequestedNumberOfCharacters = 0u;
253 mStartGlyphIndex = 0u;
254 mStartLineIndex = 0u;
255 mEstimatedNumberOfLines = 0u;
257 mFullRelayoutNeeded = false;
258 mIsLastCharacterNewParagraph = false;
262 struct Controller::Impl
264 Impl( ControlInterface& controlInterface )
265 : mControlInterface( controlInterface ),
268 mFontDefaults( NULL ),
276 mTextColor( Color::BLACK ),
279 mOperationsPending( NO_OPERATION ),
280 mMaximumNumberOfCharacters( 50u ),
281 mRecalculateNaturalSize( true ),
282 mMarkupProcessorEnabled( false ),
283 mClipboardHideEnabled( true ),
284 mAutoScrollEnabled( false ),
285 mAutoScrollDirectionRTL( false )
287 mLogicalModel = LogicalModel::New();
288 mVisualModel = VisualModel::New();
290 mFontClient = TextAbstraction::FontClient::Get();
291 mClipboard = Clipboard::Get();
293 mView.SetVisualModel( mVisualModel );
295 // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
296 mMetrics = Metrics::New( mFontClient );
297 mLayoutEngine.SetMetrics( mMetrics );
299 // Set the text properties to default
300 mVisualModel->SetUnderlineEnabled( false );
301 mVisualModel->SetUnderlineHeight( 0.0f );
306 delete mFontDefaults;
311 * @brief Request a relayout using the ControlInterface.
313 void RequestRelayout();
316 * @brief Request a relayout using the ControlInterface.
318 void QueueModifyEvent( ModifyEvent::Type type )
320 if( ModifyEvent::TEXT_REPLACED == type)
322 // Cancel previously queued inserts etc.
323 mModifyEvents.Clear();
328 mModifyEvents.PushBack( event );
330 // The event will be processed during relayout
335 * @brief Helper to move the cursor, grab handle etc.
337 bool ProcessInputEvents();
340 * @brief Helper to check whether any place-holder text is available.
342 bool IsPlaceholderAvailable() const
344 return ( mEventData &&
345 ( !mEventData->mPlaceholderTextInactive.empty() ||
346 !mEventData->mPlaceholderTextActive.empty() )
350 bool IsShowingPlaceholderText() const
352 return ( mEventData && mEventData->mIsShowingPlaceholderText );
356 * @brief Helper to check whether active place-holder text is available.
358 bool IsFocusedPlaceholderAvailable() const
360 return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
363 bool IsShowingRealText() const
365 return ( !IsShowingPlaceholderText() &&
366 0u != mLogicalModel->mText.Count() );
370 * @brief Called when placeholder-text is hidden
372 void PlaceholderCleared()
376 mEventData->mIsShowingPlaceholderText = false;
378 // Remove mPlaceholderTextColor
379 mVisualModel->SetTextColor( mTextColor );
383 void ClearPreEditFlag()
387 mEventData->mPreEditFlag = false;
388 mEventData->mPreEditStartPosition = 0;
389 mEventData->mPreEditLength = 0;
393 void ResetImfManager()
397 // Reset incase we are in a pre-edit state.
398 if( mEventData->mImfManager )
400 mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
407 bool IsClipboardEmpty()
409 bool result( mClipboard && mClipboard.NumberOfItems() );
410 return !result; // If NumberOfItems greater than 0, return false
414 * @brief Calculates the start character index of the first paragraph to be updated and
415 * the end character index of the last paragraph to be updated.
417 * @param[out] numberOfCharacters The number of characters to be updated.
419 void CalculateTextUpdateIndices( Length& numberOfCharacters );
422 * @brief Helper to clear completely the parts of the model specified by the given @p operations.
424 * @note It never clears the text stored in utf32.
426 void ClearFullModelData( OperationsMask operations );
429 * @brief Helper to clear completely the parts of the model related with the characters specified by the given @p operations.
431 * @note It never clears the text stored in utf32.
433 * @param[in] startIndex Index to the first character to be cleared.
434 * @param[in] endIndex Index to the last character to be cleared.
435 * @param[in] operations The operations required.
437 void ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
440 * @brief Helper to clear completely the parts of the model related with the glyphs specified by the given @p operations.
442 * @note It never clears the text stored in utf32.
443 * @note Character indices are transformed to glyph indices.
445 * @param[in] startIndex Index to the first character to be cleared.
446 * @param[in] endIndex Index to the last character to be cleared.
447 * @param[in] operations The operations required.
449 void ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
452 * @brief Helper to clear the parts of the model specified by the given @p operations and from @p startIndex to @p endIndex.
454 * @note It never clears the text stored in utf32.
456 * @param[in] startIndex Index to the first character to be cleared.
457 * @param[in] endIndex Index to the last character to be cleared.
458 * @param[in] operations The operations required.
460 void ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations );
463 * @brief Updates the logical and visual models. Updates the style runs in the visual model when the text's styles changes.
465 * When text or style changes the model is set with some operations pending.
466 * When i.e. the text's size or a relayout is required this method is called
467 * with a given @p operationsRequired parameter. The operations required are
468 * matched with the operations pending to perform the minimum number of operations.
470 * @param[in] operationsRequired The operations required.
472 * @return @e true if the model has been modified.
474 bool UpdateModel( OperationsMask operationsRequired );
477 * @brief Retreieves the default style.
479 * @param[out] inputStyle The default style.
481 void RetrieveDefaultInputStyle( InputStyle& inputStyle );
484 * @brief Retrieve the line height of the default font.
486 float GetDefaultFontLineHeight();
488 void OnCursorKeyEvent( const Event& event );
490 void OnTapEvent( const Event& event );
492 void OnPanEvent( const Event& event );
494 void OnLongPressEvent( const Event& event );
496 void OnHandleEvent( const Event& event );
498 void OnSelectEvent( const Event& event );
500 void OnSelectAllEvent();
503 * @brief Retrieves the selected text. It removes the text if the @p deleteAfterRetrieval parameter is @e true.
505 * @param[out] selectedText The selected text encoded in utf8.
506 * @param[in] deleteAfterRetrieval Whether the text should be deleted after retrieval.
508 void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
510 void ShowClipboard();
512 void HideClipboard();
514 void SetClipboardHideEnable(bool enable);
516 bool CopyStringToClipboard( std::string& source );
518 void SendSelectionToClipboard( bool deleteAfterSending );
520 void GetTextFromClipboard( unsigned int itemIndex, std::string& retrievedString );
522 void RepositionSelectionHandles();
523 void RepositionSelectionHandles( float visualX, float visualY );
525 void SetPopupButtons();
527 void ChangeState( EventData::State newState );
530 * @brief Calculates the cursor's position for a given character index in the logical order.
532 * It retrieves as well the line's height and the cursor's height and
533 * if there is a valid alternative cursor, its position and height.
535 * @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.
536 * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
538 void GetCursorPosition( CharacterIndex logical,
539 CursorInfo& cursorInfo );
542 * @brief Calculates the new cursor index.
544 * It takes into account that in some scripts multiple characters can form a glyph and all of them
545 * need to be jumped with one key event.
547 * @param[in] index The initial new index.
549 * @return The new cursor index.
551 CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
554 * @brief Updates the cursor position.
556 * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
557 * It sets the position of the secondary cursor if it's a valid one.
558 * Sets which cursors are active.
560 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
563 void UpdateCursorPosition( const CursorInfo& cursorInfo );
566 * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
568 * @param[in] handleType One of the selection handles.
569 * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
571 void UpdateSelectionHandle( HandleType handleType,
572 const CursorInfo& cursorInfo );
575 * @biref Clamps the horizontal scrolling to get the control always filled with text.
577 * @param[in] actualSize The size of the laid out text.
579 void ClampHorizontalScroll( const Vector2& actualSize );
582 * @biref Clamps the vertical scrolling to get the control always filled with text.
584 * @param[in] actualSize The size of the laid out text.
586 void ClampVerticalScroll( const Vector2& actualSize );
589 * @brief Scrolls the text to make a position visible.
591 * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
593 * @param[in] position A position in text coords.
595 * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
596 * or moving the selection handles.
598 void ScrollToMakePositionVisible( const Vector2& position );
601 * @brief Scrolls the text to make the cursor visible.
603 * This method is called after deleting text.
605 void ScrollTextToMatchCursor( const CursorInfo& cursorInfo );
608 // Declared private and left undefined to avoid copies.
610 // Declared private and left undefined to avoid copies.
611 Impl& operator=( const Impl& );
615 ControlInterface& mControlInterface; ///< Reference to the text controller.
616 LogicalModelPtr mLogicalModel; ///< Pointer to the logical model.
617 VisualModelPtr mVisualModel; ///< Pointer to the visual model.
618 FontDefaults* mFontDefaults; ///< Avoid allocating this when the user does not specify a font.
619 EventData* mEventData; ///< Avoid allocating everything for text input until EnableTextInput().
620 TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
621 Clipboard mClipboard; ///< Handle to the system clipboard
622 View mView; ///< The view interface to the rendering back-end.
623 MetricsPtr mMetrics; ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
624 LayoutEngine mLayoutEngine; ///< The layout engine.
625 Vector<ModifyEvent> mModifyEvents; ///< Temporary stores the text set until the next relayout.
626 Vector4 mTextColor; ///< The regular text color
627 Vector2 mAlignmentOffset; ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
628 TextUpdateInfo mTextUpdateInfo; ///< Info of the characters updated.
629 OperationsMask mOperationsPending; ///< Operations pending to be done to layout the text.
630 Length mMaximumNumberOfCharacters; ///< Maximum number of characters that can be inserted.
632 bool mRecalculateNaturalSize:1; ///< Whether the natural size needs to be recalculated.
633 bool mMarkupProcessorEnabled:1; ///< Whether the mark-up procesor is enabled.
634 bool mClipboardHideEnabled:1; ///< Whether the ClipboardHide function work or not
635 bool mAutoScrollEnabled:1; ///< Whether auto text scrolling is enabled.
636 CharacterDirection mAutoScrollDirectionRTL:1; ///< Direction of auto scrolling, true if rtl
642 } // namespace Toolkit
646 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__