Merge "replaced toolkit pushbutton images with shorter images." into devel/master
[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     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   : mDefaultPointSize(0.0f),
178     mFontId(0u)
179   {
180   }
181
182   FontId GetFontId( TextAbstraction::FontClient& fontClient )
183   {
184     if( !mFontId )
185     {
186       Dali::TextAbstraction::PointSize26Dot6 pointSize = mDefaultPointSize*64;
187       mFontId = fontClient.GetFontId( mDefaultFontFamily, mDefaultFontStyle, pointSize );
188     }
189
190     return mFontId;
191   }
192
193   std::string mDefaultFontFamily;
194   std::string mDefaultFontStyle;
195   float mDefaultPointSize;
196   FontId mFontId;
197 };
198
199 struct Controller::Impl
200 {
201   Impl( ControlInterface& controlInterface )
202   : mControlInterface( controlInterface ),
203     mLogicalModel(),
204     mVisualModel(),
205     mFontDefaults( NULL ),
206     mEventData( NULL ),
207     mFontClient(),
208     mClipboard(),
209     mView(),
210     mLayoutEngine(),
211     mModifyEvents(),
212     mControlSize(),
213     mTextColor( Color::BLACK ),
214     mAlignmentOffset(),
215     mOperationsPending( NO_OPERATION ),
216     mMaximumNumberOfCharacters( 50 ),
217     mRecalculateNaturalSize( true )
218   {
219     mLogicalModel = LogicalModel::New();
220     mVisualModel  = VisualModel::New();
221
222     mFontClient = TextAbstraction::FontClient::Get();
223     mClipboard = Clipboard::Get();
224
225     mView.SetVisualModel( mVisualModel );
226
227     // Set the text properties to default
228     mVisualModel->SetUnderlineEnabled( false );
229     mVisualModel->SetUnderlineHeight( 0.0f );
230   }
231
232   ~Impl()
233   {
234     delete mEventData;
235   }
236
237   /**
238    * @brief Request a relayout using the ControlInterface.
239    */
240   void RequestRelayout();
241
242   /**
243    * @brief Request a relayout using the ControlInterface.
244    */
245   void QueueModifyEvent( ModifyEvent::Type type )
246   {
247     if( ModifyEvent::TEXT_REPLACED == type)
248     {
249       // Cancel previously queued inserts etc.
250       mModifyEvents.clear();
251     }
252
253     ModifyEvent event;
254     event.type = type;
255     mModifyEvents.push_back( event );
256
257     // The event will be processed during relayout
258     RequestRelayout();
259   }
260
261   /**
262    * @brief Helper to move the cursor, grab handle etc.
263    */
264   bool ProcessInputEvents();
265
266   /**
267    * @brief Helper to check whether any place-holder text is available.
268    */
269   bool IsPlaceholderAvailable() const
270   {
271     return ( mEventData &&
272              ( !mEventData->mPlaceholderTextInactive.empty() ||
273                !mEventData->mPlaceholderTextActive.empty() )
274            );
275   }
276
277   bool IsShowingPlaceholderText() const
278   {
279     return ( mEventData && mEventData->mIsShowingPlaceholderText );
280   }
281
282   /**
283    * @brief Called when placeholder-text is hidden
284    */
285   void PlaceholderCleared()
286   {
287     if( mEventData )
288     {
289       mEventData->mIsShowingPlaceholderText = false;
290
291       // Remove mPlaceholderTextColor
292       mVisualModel->SetTextColor( mTextColor );
293     }
294   }
295
296   void ClearPreEditFlag()
297   {
298     if( mEventData )
299     {
300       mEventData->mPreEditFlag = false;
301       mEventData->mPreEditStartPosition = 0;
302       mEventData->mPreEditLength = 0;
303     }
304   }
305
306   void ResetImfManager()
307   {
308     // Reset incase we are in a pre-edit state.
309     ImfManager imfManager = ImfManager::Get();
310     if ( imfManager )
311     {
312       imfManager.Reset(); // Will trigger a commit message
313     }
314
315     ClearPreEditFlag();
316   }
317
318   bool IsClipboardEmpty()
319   {
320     bool result( mClipboard && mClipboard.NumberOfItems() );
321     return !result; // // If NumberOfItems greater than 0, return false
322   }
323
324   void UpdateModel( OperationsMask operationsRequired );
325
326   /**
327    * @brief Retrieve the default fonts.
328    *
329    * @param[out] fonts The default font family, style and point sizes.
330    * @param[in] numberOfCharacters The number of characters in the logical model.
331    */
332   void GetDefaultFonts( Dali::Vector<FontRun>& fonts, Length numberOfCharacters );
333
334   /**
335    * @brief Retrieve the line height of the default font.
336    */
337   float GetDefaultFontLineHeight();
338
339   void OnCursorKeyEvent( const Event& event );
340
341   void OnTapEvent( const Event& event );
342
343   void OnPanEvent( const Event& event );
344
345   void OnLongPressEvent( const Event& event );
346
347   void OnHandleEvent( const Event& event );
348
349   void OnSelectEvent( const Event& event );
350
351   void OnSelectAllEvent();
352
353   void RetrieveSelection( std::string& selectedText, bool deleteAfterRetreival );
354
355   void ShowClipboard();
356
357   void HideClipboard();
358
359   bool CopyStringToClipboard( std::string& source );
360
361   void SendSelectionToClipboard( bool deleteAfterSending );
362
363   void GetTextFromClipboard( unsigned int itemIndex, std::string& retreivedString );
364
365   void RepositionSelectionHandles( CharacterIndex selectionStart, CharacterIndex selectionEnd );
366   void RepositionSelectionHandles( float visualX, float visualY );
367
368   void SetPopupButtons();
369
370   void ChangeState( EventData::State newState );
371   LineIndex GetClosestLine( float y ) const;
372
373   void FindSelectionIndices( float visualX, float visualY, CharacterIndex& startIndex, CharacterIndex& endIndex );
374
375   /**
376    * @brief Retrieves the cursor's logical position for a given touch point x,y
377    *
378    * @param[in] visualX The touch point x.
379    * @param[in] visualY The touch point y.
380    *
381    * @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.
382    */
383   CharacterIndex GetClosestCursorIndex( float visualX,
384                                         float visualY );
385
386   /**
387    * @brief Calculates the cursor's position for a given character index in the logical order.
388    *
389    * It retrieves as well the line's height and the cursor's height and
390    * if there is a valid alternative cursor, its position and height.
391    *
392    * @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.
393    * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
394    */
395   void GetCursorPosition( CharacterIndex logical,
396                           CursorInfo& cursorInfo );
397
398   /**
399    * @brief Calculates the new cursor index.
400    *
401    * It takes into account that in some scripts multiple characters can form a glyph and all of them
402    * need to be jumped with one key event.
403    *
404    * @param[in] index The initial new index.
405    *
406    * @return The new cursor index.
407    */
408   CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
409
410   /**
411    * @brief Updates the cursor position.
412    *
413    * Retrieves the x,y position of the cursor logical position and sets it into the decorator.
414    * It sets the position of the secondary cursor if it's a valid one.
415    * Sets which cursors are active.
416    */
417   void UpdateCursorPosition();
418
419   /**
420    * @brief Updates the position of the given selection handle.
421    *
422    * @param[in] handleType One of the selection handles.
423    */
424   void UpdateSelectionHandle( HandleType handleType );
425
426   /**
427    * @biref Clamps the horizontal scrolling to get the control always filled with text.
428    *
429    * @param[in] actualSize The size of the laid out text.
430    */
431   void ClampHorizontalScroll( const Vector2& actualSize );
432
433   /**
434    * @biref Clamps the vertical scrolling to get the control always filled with text.
435    *
436    * @param[in] actualSize The size of the laid out text.
437    */
438   void ClampVerticalScroll( const Vector2& actualSize );
439
440   /**
441    * @brief Scrolls the text to make a position visible.
442    *
443    * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
444    *
445    * @param[in] position A position in decorator coords.
446    *
447    * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
448    * or moving the selection handles.
449    */
450   void ScrollToMakePositionVisible( const Vector2& position );
451
452   /**
453    * @brief Scrolls the text to make the cursor visible.
454    *
455    * This method is called after deleting text.
456    */
457   void ScrollTextToMatchCursor();
458
459   ControlInterface& mControlInterface;     ///< Reference to the text controller.
460   LogicalModelPtr mLogicalModel;           ///< Pointer to the logical model.
461   VisualModelPtr  mVisualModel;            ///< Pointer to the visual model.
462   FontDefaults* mFontDefaults;             ///< Avoid allocating this when the user does not specify a font.
463   EventData* mEventData;                   ///< Avoid allocating everything for text input until EnableTextInput().
464   TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
465   Clipboard mClipboard;                   ///< Handle to the system clipboard
466   View mView;                              ///< The view interface to the rendering back-end.
467   LayoutEngine mLayoutEngine;              ///< The layout engine.
468   std::vector<ModifyEvent> mModifyEvents;  ///< Temporary stores the text set until the next relayout.
469   Size mControlSize;                       ///< The size of the control.
470   Vector4 mTextColor;                      ///< The regular text color
471   Vector2 mAlignmentOffset;                ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
472   OperationsMask mOperationsPending;       ///< Operations pending to be done to layout the text.
473   Length mMaximumNumberOfCharacters;       ///< Maximum number of characters that can be inserted.
474   bool mRecalculateNaturalSize:1;          ///< Whether the natural size needs to be recalculated.
475 };
476
477 } // namespace Text
478
479 } // namespace Toolkit
480
481 } // namespace Dali
482
483 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__