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