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