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