Fix cursor position issues.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-controller-impl.h
1 #ifndef __DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H__
2 #define __DALI_TOOLKIT_TEXT_CONTROLLER_IMPL_H__
3
4 /*
5  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
6  *
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
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/adaptor-framework/clipboard.h>
23 #include <dali/devel-api/text-abstraction/font-client.h>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/internal/text/layouts/layout-engine.h>
27 #include <dali-toolkit/internal/text/logical-model-impl.h>
28 #include <dali-toolkit/internal/text/text-controller.h>
29 #include <dali-toolkit/internal/text/text-view.h>
30 #include <dali-toolkit/internal/text/visual-model-impl.h>
31
32 namespace Dali
33 {
34
35 namespace Toolkit
36 {
37
38 namespace Text
39 {
40
41 struct Event
42 {
43   // Used to queue input events until DoRelayout()
44   enum Type
45   {
46     CURSOR_KEY_EVENT,
47     TAP_EVENT,
48     PAN_EVENT,
49     LONG_PRESS_EVENT,
50     GRAB_HANDLE_EVENT,
51     LEFT_SELECTION_HANDLE_EVENT,
52     RIGHT_SELECTION_HANDLE_EVENT,
53     SELECT,
54     SELECT_ALL
55   };
56
57   union Param
58   {
59     int mInt;
60     unsigned int mUint;
61     float mFloat;
62   };
63
64   Event( Type eventType )
65   : type( eventType )
66   {
67     p1.mInt = 0;
68     p2.mInt = 0;
69     p3.mInt = 0;
70   }
71
72   Type type;
73   Param p1;
74   Param p2;
75   Param p3;
76 };
77
78 struct CursorInfo
79 {
80   CursorInfo()
81   : primaryPosition(),
82     secondaryPosition(),
83     lineHeight( 0.f ),
84     primaryCursorHeight( 0.f ),
85     secondaryCursorHeight( 0.f ),
86     isSecondaryCursor( false )
87   {}
88
89   ~CursorInfo()
90   {}
91
92   Vector2 primaryPosition;       ///< The primary cursor's position.
93   Vector2 secondaryPosition;     ///< The secondary cursor's position.
94   float   lineHeight;            ///< The height of the line where the cursor is placed.
95   float   primaryCursorHeight;   ///< The primary cursor's height.
96   float   secondaryCursorHeight; ///< The secondary cursor's height.
97   bool    isSecondaryCursor;     ///< Whether the secondary cursor is valid.
98 };
99
100 struct EventData
101 {
102   enum State
103   {
104     INACTIVE,
105     INTERRUPTED,
106     SELECTING,
107     SELECTION_CHANGED,
108     EDITING,
109     EDITING_WITH_POPUP,
110     EDITING_WITH_GRAB_HANDLE,
111     GRAB_HANDLE_PANNING,
112     SELECTION_HANDLE_PANNING
113   };
114
115   EventData( DecoratorPtr decorator );
116
117   ~EventData();
118
119   DecoratorPtr       mDecorator;               ///< Pointer to the decorator
120   std::string        mPlaceholderTextActive;   ///< The text to display when the TextField is empty with key-input focus
121   std::string        mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive
122   Vector4            mPlaceholderTextColor;    ///< The in/active placeholder text color
123
124   /**
125    * This is used to delay handling events until after the model has been updated.
126    * The number of updates to the model is minimized to improve performance.
127    */
128   std::vector<Event> mEventQueue;              ///< The queue of touch events etc.
129
130   /**
131    * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
132    * Typically this will have a negative value with scrolling occurs.
133    */
134   Vector2            mScrollPosition;          ///< The text is offset by this position when scrolling.
135
136   State              mState;                   ///< Selection mode, edit mode etc.
137
138   CharacterIndex     mPrimaryCursorPosition;   ///< Index into logical model for primary cursor.
139   CharacterIndex     mLeftSelectionPosition;   ///< Index into logical model for left selection handle.
140   CharacterIndex     mRightSelectionPosition;  ///< Index into logical model for right selection handle.
141
142   CharacterIndex     mPreEditStartPosition;    ///< Used to remove the pre-edit text if necessary.
143   Length             mPreEditLength;           ///< Used to remove the pre-edit text if necessary.
144
145   bool mIsShowingPlaceholderText        : 1;   ///< True if the place-holder text is being displayed.
146   bool mPreEditFlag                     : 1;   ///< True if the model contains text in pre-edit state.
147   bool mDecoratorUpdated                : 1;   ///< True if the decorator was updated during event processing.
148   bool mCursorBlinkEnabled              : 1;   ///< True if cursor should blink when active.
149   bool mGrabHandleEnabled               : 1;   ///< True if grab handle is enabled.
150   bool mGrabHandlePopupEnabled          : 1;   ///< True if the grab handle popu-up should be shown.
151   bool mSelectionEnabled                : 1;   ///< True if selection handles, highlight etc. are enabled.
152   bool mHorizontalScrollingEnabled      : 1;   ///< True if horizontal scrolling is enabled.
153   bool mVerticalScrollingEnabled        : 1;   ///< True if vertical scrolling is enabled.
154   bool mUpdateCursorPosition            : 1;   ///< True if the visual position of the cursor must be recalculated.
155   bool mUpdateLeftSelectionPosition     : 1;   ///< True if the visual position of the left selection handle must be recalculated.
156   bool mUpdateRightSelectionPosition    : 1;   ///< True if the visual position of the right selection handle must be recalculated.
157   bool mScrollAfterUpdatePosition       : 1;   ///< Whether to scroll after the cursor position is updated.
158   bool mScrollAfterDelete               : 1;   ///< Whether to scroll after delete characters.
159   bool mAllTextSelected                 : 1;   ///< True if the selection handles are selecting all the text
160 };
161
162 struct ModifyEvent
163 {
164   enum Type
165   {
166     TEXT_REPLACED,    ///< The entire text was replaced
167     TEXT_INSERTED,    ///< Insert characters at the current cursor position
168     TEXT_DELETED      ///< Characters were deleted
169   };
170
171   Type type;
172 };
173
174 struct FontDefaults
175 {
176   FontDefaults()
177   : mFontDescription(),
178     mFontStyle(),
179     mDefaultPointSize(0.0f),
180     mFontId(0u)
181   {
182     // Initially use the default platform font
183     TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
184     fontClient.GetDefaultPlatformFontDescription( mFontDescription );
185   }
186
187   FontId GetFontId( TextAbstraction::FontClient& fontClient )
188   {
189     if( !mFontId )
190     {
191       Dali::TextAbstraction::PointSize26Dot6 pointSize = mDefaultPointSize*64;
192       mFontId = fontClient.GetFontId( mFontDescription, pointSize );
193     }
194
195     return mFontId;
196   }
197
198   TextAbstraction::FontDescription mFontDescription;
199   std::string mFontStyle;
200   float mDefaultPointSize;
201   FontId mFontId;
202 };
203
204 struct Controller::Impl
205 {
206   Impl( ControlInterface& controlInterface )
207   : mControlInterface( controlInterface ),
208     mLogicalModel(),
209     mVisualModel(),
210     mFontDefaults( NULL ),
211     mEventData( NULL ),
212     mFontClient(),
213     mClipboard(),
214     mView(),
215     mMetrics(),
216     mLayoutEngine(),
217     mModifyEvents(),
218     mTextColor( Color::BLACK ),
219     mAlignmentOffset(),
220     mOperationsPending( NO_OPERATION ),
221     mMaximumNumberOfCharacters( 50 ),
222     mRecalculateNaturalSize( true ),
223     mUserDefinedFontFamily( false )
224   {
225     mLogicalModel = LogicalModel::New();
226     mVisualModel  = VisualModel::New();
227
228     mFontClient = TextAbstraction::FontClient::Get();
229     mClipboard = Clipboard::Get();
230
231     mView.SetVisualModel( mVisualModel );
232
233     // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
234     mMetrics = Metrics::New( mFontClient );
235     mLayoutEngine.SetMetrics( mMetrics );
236
237     // Set the text properties to default
238     mVisualModel->SetUnderlineEnabled( false );
239     mVisualModel->SetUnderlineHeight( 0.0f );
240   }
241
242   ~Impl()
243   {
244     delete mFontDefaults;
245     delete mEventData;
246   }
247
248   /**
249    * @brief Request a relayout using the ControlInterface.
250    */
251   void RequestRelayout();
252
253   /**
254    * @brief Request a relayout using the ControlInterface.
255    */
256   void QueueModifyEvent( ModifyEvent::Type type )
257   {
258     if( ModifyEvent::TEXT_REPLACED == type)
259     {
260       // Cancel previously queued inserts etc.
261       mModifyEvents.clear();
262     }
263
264     ModifyEvent event;
265     event.type = type;
266     mModifyEvents.push_back( event );
267
268     // The event will be processed during relayout
269     RequestRelayout();
270   }
271
272   /**
273    * @brief Helper to move the cursor, grab handle etc.
274    */
275   bool ProcessInputEvents();
276
277   /**
278    * @brief Helper to check whether any place-holder text is available.
279    */
280   bool IsPlaceholderAvailable() const
281   {
282     return ( mEventData &&
283              ( !mEventData->mPlaceholderTextInactive.empty() ||
284                !mEventData->mPlaceholderTextActive.empty() )
285            );
286   }
287
288   bool IsShowingPlaceholderText() const
289   {
290     return ( mEventData && mEventData->mIsShowingPlaceholderText );
291   }
292
293   /**
294    * @brief Helper to check whether active place-holder text is available.
295    */
296   bool IsFocusedPlaceholderAvailable() const
297   {
298     return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
299   }
300
301   bool IsShowingRealText() const
302   {
303     return ( !IsShowingPlaceholderText() &&
304              0u != mLogicalModel->mText.Count() );
305   }
306
307   /**
308    * @brief Called when placeholder-text is hidden
309    */
310   void PlaceholderCleared()
311   {
312     if( mEventData )
313     {
314       mEventData->mIsShowingPlaceholderText = false;
315
316       // Remove mPlaceholderTextColor
317       mVisualModel->SetTextColor( mTextColor );
318     }
319   }
320
321   void ClearPreEditFlag()
322   {
323     if( mEventData )
324     {
325       mEventData->mPreEditFlag = false;
326       mEventData->mPreEditStartPosition = 0;
327       mEventData->mPreEditLength = 0;
328     }
329   }
330
331   void ResetImfManager()
332   {
333     if( mEventData )
334     {
335       // Reset incase we are in a pre-edit state.
336       ImfManager imfManager = ImfManager::Get();
337       if ( imfManager )
338       {
339         imfManager.Reset(); // Will trigger a commit message
340       }
341
342       ClearPreEditFlag();
343     }
344   }
345
346   bool IsClipboardEmpty()
347   {
348     bool result( mClipboard && mClipboard.NumberOfItems() );
349     return !result; // // If NumberOfItems greater than 0, return false
350   }
351
352   void UpdateModel( OperationsMask operationsRequired );
353
354   /**
355    * @brief Retrieve the default fonts.
356    *
357    * @param[out] fonts The default font family, style and point sizes.
358    * @param[in] numberOfCharacters The number of characters in the logical model.
359    */
360   void GetDefaultFonts( Dali::Vector<FontRun>& fonts, Length numberOfCharacters );
361
362   /**
363    * @brief Retrieve the line height of the default font.
364    */
365   float GetDefaultFontLineHeight();
366
367   void OnCursorKeyEvent( const Event& event );
368
369   void OnTapEvent( const Event& event );
370
371   void OnPanEvent( const Event& event );
372
373   void OnLongPressEvent( const Event& event );
374
375   void OnHandleEvent( const Event& event );
376
377   void OnSelectEvent( const Event& event );
378
379   void OnSelectAllEvent();
380
381   void RetrieveSelection( std::string& selectedText, bool deleteAfterRetreival );
382
383   void ShowClipboard();
384
385   void HideClipboard();
386
387   bool CopyStringToClipboard( std::string& source );
388
389   void SendSelectionToClipboard( bool deleteAfterSending );
390
391   void GetTextFromClipboard( unsigned int itemIndex, std::string& retreivedString );
392
393   void RepositionSelectionHandles();
394   void RepositionSelectionHandles( float visualX, float visualY );
395
396   void SetPopupButtons();
397
398   void ChangeState( EventData::State newState );
399   LineIndex GetClosestLine( float y ) const;
400
401   void FindSelectionIndices( float visualX, float visualY, CharacterIndex& startIndex, CharacterIndex& endIndex );
402
403   /**
404    * @brief Retrieves the cursor's logical position for a given touch point x,y
405    *
406    * @param[in] visualX The touch point x.
407    * @param[in] visualY The touch point y.
408    *
409    * @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.
410    */
411   CharacterIndex GetClosestCursorIndex( float visualX,
412                                         float visualY );
413
414   /**
415    * @brief Calculates the cursor's position for a given character index in the logical order.
416    *
417    * It retrieves as well the line's height and the cursor's height and
418    * if there is a valid alternative cursor, its position and height.
419    *
420    * @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.
421    * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
422    */
423   void GetCursorPosition( CharacterIndex logical,
424                           CursorInfo& cursorInfo );
425
426   /**
427    * @brief Calculates the new cursor index.
428    *
429    * It takes into account that in some scripts multiple characters can form a glyph and all of them
430    * need to be jumped with one key event.
431    *
432    * @param[in] index The initial new index.
433    *
434    * @return The new cursor index.
435    */
436   CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
437
438   /**
439    * @brief Updates the cursor position.
440    *
441    * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
442    * It sets the position of the secondary cursor if it's a valid one.
443    * Sets which cursors are active.
444    *
445    * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
446    *
447    */
448   void UpdateCursorPosition( const CursorInfo& cursorInfo );
449
450   /**
451    * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
452    *
453    * @param[in] handleType One of the selection handles.
454    * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
455    */
456   void UpdateSelectionHandle( HandleType handleType,
457                               const CursorInfo& cursorInfo );
458
459   /**
460    * @biref Clamps the horizontal scrolling to get the control always filled with text.
461    *
462    * @param[in] actualSize The size of the laid out text.
463    */
464   void ClampHorizontalScroll( const Vector2& actualSize );
465
466   /**
467    * @biref Clamps the vertical scrolling to get the control always filled with text.
468    *
469    * @param[in] actualSize The size of the laid out text.
470    */
471   void ClampVerticalScroll( const Vector2& actualSize );
472
473   /**
474    * @brief Scrolls the text to make a position visible.
475    *
476    * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
477    *
478    * @param[in] position A position in decorator coords.
479    *
480    * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
481    * or moving the selection handles.
482    */
483   void ScrollToMakePositionVisible( const Vector2& position );
484
485   /**
486    * @brief Scrolls the text to make the cursor visible.
487    *
488    * This method is called after deleting text.
489    */
490   void ScrollTextToMatchCursor( const CursorInfo& cursorInfo);
491
492   ControlInterface& mControlInterface;     ///< Reference to the text controller.
493   LogicalModelPtr mLogicalModel;           ///< Pointer to the logical model.
494   VisualModelPtr  mVisualModel;            ///< Pointer to the visual model.
495   FontDefaults* mFontDefaults;             ///< Avoid allocating this when the user does not specify a font.
496   EventData* mEventData;                   ///< Avoid allocating everything for text input until EnableTextInput().
497   TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
498   Clipboard mClipboard;                    ///< Handle to the system clipboard
499   View mView;                              ///< The view interface to the rendering back-end.
500   MetricsPtr mMetrics;                     ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
501   LayoutEngine mLayoutEngine;              ///< The layout engine.
502   std::vector<ModifyEvent> mModifyEvents;  ///< Temporary stores the text set until the next relayout.
503   Vector4 mTextColor;                      ///< The regular text color
504   Vector2 mAlignmentOffset;                ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
505   OperationsMask mOperationsPending;       ///< Operations pending to be done to layout the text.
506   Length mMaximumNumberOfCharacters;       ///< Maximum number of characters that can be inserted.
507
508   bool mRecalculateNaturalSize:1;          ///< Whether the natural size needs to be recalculated.
509   bool mUserDefinedFontFamily:1;           ///< Whether the Font family was set by the user instead of being left as sytem default.
510 };
511
512 } // namespace Text
513
514 } // namespace Toolkit
515
516 } // namespace Dali
517
518 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__