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