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