9ee83cce2a4daa42a43d574cd2211b2a8bfbda14
[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/input-style.h>
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/text-view.h>
31 #include <dali-toolkit/internal/text/visual-model-impl.h>
32
33 namespace Dali
34 {
35
36 namespace Toolkit
37 {
38
39 namespace Text
40 {
41
42 struct Event
43 {
44   // Used to queue input events until DoRelayout()
45   enum Type
46   {
47     CURSOR_KEY_EVENT,
48     TAP_EVENT,
49     PAN_EVENT,
50     LONG_PRESS_EVENT,
51     GRAB_HANDLE_EVENT,
52     LEFT_SELECTION_HANDLE_EVENT,
53     RIGHT_SELECTION_HANDLE_EVENT,
54     SELECT,
55     SELECT_ALL
56   };
57
58   union Param
59   {
60     int mInt;
61     unsigned int mUint;
62     float mFloat;
63   };
64
65   Event( Type eventType )
66   : type( eventType )
67   {
68     p1.mInt = 0;
69     p2.mInt = 0;
70     p3.mInt = 0;
71   }
72
73   Type type;
74   Param p1;
75   Param p2;
76   Param p3;
77 };
78
79 struct CursorInfo
80 {
81   CursorInfo()
82   : primaryPosition(),
83     secondaryPosition(),
84     lineOffset( 0.f ),
85     lineHeight( 0.f ),
86     primaryCursorHeight( 0.f ),
87     secondaryCursorHeight( 0.f ),
88     isSecondaryCursor( false )
89   {}
90
91   ~CursorInfo()
92   {}
93
94   Vector2 primaryPosition;       ///< The primary cursor's position.
95   Vector2 secondaryPosition;     ///< The secondary cursor's position.
96   float   lineOffset;            ///< The vertical offset where the line containing the cursor starts.
97   float   lineHeight;            ///< The height of the line where the cursor is placed.
98   float   primaryCursorHeight;   ///< The primary cursor's height.
99   float   secondaryCursorHeight; ///< The secondary cursor's height.
100   bool    isSecondaryCursor;     ///< Whether the secondary cursor is valid.
101 };
102
103 struct EventData
104 {
105   enum State
106   {
107     INACTIVE,
108     INTERRUPTED,
109     SELECTING,
110     EDITING,
111     EDITING_WITH_POPUP,
112     EDITING_WITH_GRAB_HANDLE,
113     EDITING_WITH_PASTE_POPUP,
114     GRAB_HANDLE_PANNING,
115     SELECTION_HANDLE_PANNING
116   };
117
118   EventData( DecoratorPtr decorator );
119
120   ~EventData();
121
122   static bool IsEditingState( State stateToCheck )
123   {
124     return ( stateToCheck == EDITING || stateToCheck == EDITING_WITH_POPUP || stateToCheck == EDITING_WITH_GRAB_HANDLE || stateToCheck == EDITING_WITH_PASTE_POPUP );
125   }
126
127   DecoratorPtr       mDecorator;               ///< Pointer to the decorator.
128   ImfManager         mImfManager;              ///< The Input Method Framework Manager.
129   std::string        mPlaceholderTextActive;   ///< The text to display when the TextField is empty with key-input focus.
130   std::string        mPlaceholderTextInactive; ///< The text to display when the TextField is empty and inactive.
131   Vector4            mPlaceholderTextColor;    ///< The in/active placeholder text color.
132
133   /**
134    * This is used to delay handling events until after the model has been updated.
135    * The number of updates to the model is minimized to improve performance.
136    */
137   std::vector<Event> mEventQueue;              ///< The queue of touch events etc.
138
139   InputStyle         mInputStyle;              ///< The style to be set to the new inputed text.
140
141   /**
142    * 0,0 means that the top-left corner of the layout matches the top-left corner of the UI control.
143    * Typically this will have a negative value with scrolling occurs.
144    */
145   Vector2            mScrollPosition;          ///< The text is offset by this position when scrolling.
146
147   State              mState;                   ///< Selection mode, edit mode etc.
148
149   CharacterIndex     mPrimaryCursorPosition;   ///< Index into logical model for primary cursor.
150   CharacterIndex     mLeftSelectionPosition;   ///< Index into logical model for left selection handle.
151   CharacterIndex     mRightSelectionPosition;  ///< Index into logical model for right selection handle.
152
153   CharacterIndex     mPreEditStartPosition;    ///< Used to remove the pre-edit text if necessary.
154   Length             mPreEditLength;           ///< Used to remove the pre-edit text if necessary.
155
156   bool mIsShowingPlaceholderText        : 1;   ///< True if the place-holder text is being displayed.
157   bool mPreEditFlag                     : 1;   ///< True if the model contains text in pre-edit state.
158   bool mDecoratorUpdated                : 1;   ///< True if the decorator was updated during event processing.
159   bool mCursorBlinkEnabled              : 1;   ///< True if cursor should blink when active.
160   bool mGrabHandleEnabled               : 1;   ///< True if grab handle is enabled.
161   bool mGrabHandlePopupEnabled          : 1;   ///< True if the grab handle popu-up should be shown.
162   bool mSelectionEnabled                : 1;   ///< True if selection handles, highlight etc. are enabled.
163   bool mHorizontalScrollingEnabled      : 1;   ///< True if horizontal scrolling is enabled.
164   bool mVerticalScrollingEnabled        : 1;   ///< True if vertical scrolling is enabled.
165   bool mUpdateCursorPosition            : 1;   ///< True if the visual position of the cursor must be recalculated.
166   bool mUpdateLeftSelectionPosition     : 1;   ///< True if the visual position of the left selection handle must be recalculated.
167   bool mUpdateRightSelectionPosition    : 1;   ///< True if the visual position of the right selection handle must be recalculated.
168   bool mScrollAfterUpdatePosition       : 1;   ///< Whether to scroll after the cursor position is updated.
169   bool mScrollAfterDelete               : 1;   ///< Whether to scroll after delete characters.
170   bool mAllTextSelected                 : 1;   ///< True if the selection handles are selecting all the text.
171   bool mUpdateInputStyle                : 1;   ///< Whether to update the input style after moving the cursor.
172 };
173
174 struct ModifyEvent
175 {
176   enum Type
177   {
178     TEXT_REPLACED,    ///< The entire text was replaced
179     TEXT_INSERTED,    ///< Insert characters at the current cursor position
180     TEXT_DELETED      ///< Characters were deleted
181   };
182
183   Type type;
184 };
185
186 struct FontDefaults
187 {
188   FontDefaults()
189   : mFontDescription(),
190     mFontStyle(),
191     mDefaultPointSize( 0.f ),
192     mFontId( 0u ),
193     familyDefined( false ),
194     weightDefined( false ),
195     widthDefined( false ),
196     slantDefined( false ),
197     sizeDefined( false )
198   {
199     // Initially use the default platform font
200     TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
201     fontClient.GetDefaultPlatformFontDescription( mFontDescription );
202   }
203
204   FontId GetFontId( TextAbstraction::FontClient& fontClient )
205   {
206     if( !mFontId )
207     {
208       const PointSize26Dot6 pointSize = static_cast<PointSize26Dot6>( mDefaultPointSize * 64.f );
209       mFontId = fontClient.GetFontId( mFontDescription, pointSize );
210     }
211
212     return mFontId;
213   }
214
215   TextAbstraction::FontDescription mFontDescription;  ///< The default font's description.
216   std::string                      mFontStyle;        ///< The font's style string set through the property system.
217   float                            mDefaultPointSize; ///< The default font's point size.
218   FontId                           mFontId;           ///< The font's id of the default font.
219   bool familyDefined:1; ///< Whether the default font's family name is defined.
220   bool weightDefined:1; ///< Whether the default font's weight is defined.
221   bool  widthDefined:1; ///< Whether the default font's width is defined.
222   bool  slantDefined:1; ///< Whether the default font's slant is defined.
223   bool   sizeDefined:1; ///< Whether the default font's point size is defined.
224 };
225
226 struct Controller::Impl
227 {
228   Impl( ControlInterface& controlInterface )
229   : mControlInterface( controlInterface ),
230     mLogicalModel(),
231     mVisualModel(),
232     mFontDefaults( NULL ),
233     mEventData( NULL ),
234     mFontClient(),
235     mClipboard(),
236     mView(),
237     mMetrics(),
238     mLayoutEngine(),
239     mModifyEvents(),
240     mTextColor( Color::BLACK ),
241     mAlignmentOffset(),
242     mOperationsPending( NO_OPERATION ),
243     mMaximumNumberOfCharacters( 50u ),
244     mRecalculateNaturalSize( true ),
245     mMarkupProcessorEnabled( false )
246   {
247     mLogicalModel = LogicalModel::New();
248     mVisualModel  = VisualModel::New();
249
250     mFontClient = TextAbstraction::FontClient::Get();
251     mClipboard = Clipboard::Get();
252
253     mView.SetVisualModel( mVisualModel );
254
255     // Use this to access FontClient i.e. to get down-scaled Emoji metrics.
256     mMetrics = Metrics::New( mFontClient );
257     mLayoutEngine.SetMetrics( mMetrics );
258
259     // Set the text properties to default
260     mVisualModel->SetUnderlineEnabled( false );
261     mVisualModel->SetUnderlineHeight( 0.0f );
262   }
263
264   ~Impl()
265   {
266     delete mFontDefaults;
267     delete mEventData;
268   }
269
270   /**
271    * @brief Request a relayout using the ControlInterface.
272    */
273   void RequestRelayout();
274
275   /**
276    * @brief Request a relayout using the ControlInterface.
277    */
278   void QueueModifyEvent( ModifyEvent::Type type )
279   {
280     if( ModifyEvent::TEXT_REPLACED == type)
281     {
282       // Cancel previously queued inserts etc.
283       mModifyEvents.Clear();
284     }
285
286     ModifyEvent event;
287     event.type = type;
288     mModifyEvents.PushBack( event );
289
290     // The event will be processed during relayout
291     RequestRelayout();
292   }
293
294   /**
295    * @brief Helper to move the cursor, grab handle etc.
296    */
297   bool ProcessInputEvents();
298
299   /**
300    * @brief Helper to check whether any place-holder text is available.
301    */
302   bool IsPlaceholderAvailable() const
303   {
304     return ( mEventData &&
305              ( !mEventData->mPlaceholderTextInactive.empty() ||
306                !mEventData->mPlaceholderTextActive.empty() )
307            );
308   }
309
310   bool IsShowingPlaceholderText() const
311   {
312     return ( mEventData && mEventData->mIsShowingPlaceholderText );
313   }
314
315   /**
316    * @brief Helper to check whether active place-holder text is available.
317    */
318   bool IsFocusedPlaceholderAvailable() const
319   {
320     return ( mEventData && !mEventData->mPlaceholderTextActive.empty() );
321   }
322
323   bool IsShowingRealText() const
324   {
325     return ( !IsShowingPlaceholderText() &&
326              0u != mLogicalModel->mText.Count() );
327   }
328
329   /**
330    * @brief Called when placeholder-text is hidden
331    */
332   void PlaceholderCleared()
333   {
334     if( mEventData )
335     {
336       mEventData->mIsShowingPlaceholderText = false;
337
338       // Remove mPlaceholderTextColor
339       mVisualModel->SetTextColor( mTextColor );
340     }
341   }
342
343   void ClearPreEditFlag()
344   {
345     if( mEventData )
346     {
347       mEventData->mPreEditFlag = false;
348       mEventData->mPreEditStartPosition = 0;
349       mEventData->mPreEditLength = 0;
350     }
351   }
352
353   void ResetImfManager()
354   {
355     if( mEventData )
356     {
357       // Reset incase we are in a pre-edit state.
358       if( mEventData->mImfManager )
359       {
360         mEventData->mImfManager.Reset(); // Will trigger a message ( commit, get surrounding )
361       }
362
363       ClearPreEditFlag();
364     }
365   }
366
367   bool IsClipboardEmpty()
368   {
369     bool result( mClipboard && mClipboard.NumberOfItems() );
370     return !result; // // If NumberOfItems greater than 0, return false
371   }
372
373   /**
374    * @brief Updates the logical and visual models.
375    *
376    * When text or style changes the model is set with some operations pending.
377    * When i.e. the text's size or a relayout is required this method is called
378    * with a given @p operationsRequired parameter. The operations required are
379    * matched with the operations pending to perform the minimum number of operations.
380    *
381    * @param[in] operationsRequired The operations required.
382    */
383   void UpdateModel( OperationsMask operationsRequired );
384
385   /**
386    * @brief Updates the style runs in the visual model when the text's styles changes.
387    *
388    * @param[in] operationsRequired The operations required.
389    *
390    * @return @e true if the model has been modified.
391    */
392   bool UpdateModelStyle( OperationsMask operationsRequired );
393
394   /**
395    * @brief Retreieves the default style.
396    *
397    * @param[out] inputStyle The default style.
398    */
399   void RetrieveDefaultInputStyle( InputStyle& inputStyle );
400
401   /**
402    * @brief Retrieve the line height of the default font.
403    */
404   float GetDefaultFontLineHeight();
405
406   void OnCursorKeyEvent( const Event& event );
407
408   void OnTapEvent( const Event& event );
409
410   void OnPanEvent( const Event& event );
411
412   void OnLongPressEvent( const Event& event );
413
414   void OnHandleEvent( const Event& event );
415
416   void OnSelectEvent( const Event& event );
417
418   void OnSelectAllEvent();
419
420   void RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval );
421
422   void ShowClipboard();
423
424   void HideClipboard();
425
426   bool CopyStringToClipboard( std::string& source );
427
428   void SendSelectionToClipboard( bool deleteAfterSending );
429
430   void GetTextFromClipboard( unsigned int itemIndex, std::string& retrievedString );
431
432   void RepositionSelectionHandles();
433   void RepositionSelectionHandles( float visualX, float visualY );
434
435   void SetPopupButtons();
436
437   void ChangeState( EventData::State newState );
438   LineIndex GetClosestLine( float y ) const;
439
440   void FindSelectionIndices( float visualX, float visualY, CharacterIndex& startIndex, CharacterIndex& endIndex );
441
442   /**
443    * @brief Retrieves the cursor's logical position for a given touch point x,y
444    *
445    * @param[in] visualX The touch point x.
446    * @param[in] visualY The touch point y.
447    *
448    * @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.
449    */
450   CharacterIndex GetClosestCursorIndex( float visualX,
451                                         float visualY );
452
453   /**
454    * @brief Calculates the cursor's position for a given character index in the logical order.
455    *
456    * It retrieves as well the line's height and the cursor's height and
457    * if there is a valid alternative cursor, its position and height.
458    *
459    * @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.
460    * @param[out] cursorInfo The line's height, the cursor's height, the cursor's position and whether there is an alternative cursor.
461    */
462   void GetCursorPosition( CharacterIndex logical,
463                           CursorInfo& cursorInfo );
464
465   /**
466    * @brief Calculates the new cursor index.
467    *
468    * It takes into account that in some scripts multiple characters can form a glyph and all of them
469    * need to be jumped with one key event.
470    *
471    * @param[in] index The initial new index.
472    *
473    * @return The new cursor index.
474    */
475   CharacterIndex CalculateNewCursorIndex( CharacterIndex index ) const;
476
477   /**
478    * @brief Updates the cursor position.
479    *
480    * Sets the cursor's position into the decorator. It transforms the cursor's position into decorator's coords.
481    * It sets the position of the secondary cursor if it's a valid one.
482    * Sets which cursors are active.
483    *
484    * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
485    *
486    */
487   void UpdateCursorPosition( const CursorInfo& cursorInfo );
488
489   /**
490    * @brief Updates the position of the given selection handle. It transforms the handle's position into decorator's coords.
491    *
492    * @param[in] handleType One of the selection handles.
493    * @param[in] cursorInfo Contains the selection handle position in Actor's coords.
494    */
495   void UpdateSelectionHandle( HandleType handleType,
496                               const CursorInfo& cursorInfo );
497
498   /**
499    * @biref Clamps the horizontal scrolling to get the control always filled with text.
500    *
501    * @param[in] actualSize The size of the laid out text.
502    */
503   void ClampHorizontalScroll( const Vector2& actualSize );
504
505   /**
506    * @biref Clamps the vertical scrolling to get the control always filled with text.
507    *
508    * @param[in] actualSize The size of the laid out text.
509    */
510   void ClampVerticalScroll( const Vector2& actualSize );
511
512   /**
513    * @brief Scrolls the text to make a position visible.
514    *
515    * @pre mEventData must not be NULL. (there is a text-input or selection capabilities).
516    *
517    * @param[in] position A position in decorator coords.
518    *
519    * This method is called after inserting text, moving the cursor with the grab handle or the keypad,
520    * or moving the selection handles.
521    */
522   void ScrollToMakePositionVisible( const Vector2& position );
523
524   /**
525    * @brief Scrolls the text to make the cursor visible.
526    *
527    * This method is called after deleting text.
528    */
529   void ScrollTextToMatchCursor( const CursorInfo& cursorInfo);
530
531   ControlInterface& mControlInterface;     ///< Reference to the text controller.
532   LogicalModelPtr mLogicalModel;           ///< Pointer to the logical model.
533   VisualModelPtr  mVisualModel;            ///< Pointer to the visual model.
534   FontDefaults* mFontDefaults;             ///< Avoid allocating this when the user does not specify a font.
535   EventData* mEventData;                   ///< Avoid allocating everything for text input until EnableTextInput().
536   TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
537   Clipboard mClipboard;                    ///< Handle to the system clipboard
538   View mView;                              ///< The view interface to the rendering back-end.
539   MetricsPtr mMetrics;                     ///< A wrapper around FontClient used to get metrics & potentially down-scaled Emoji metrics.
540   LayoutEngine mLayoutEngine;              ///< The layout engine.
541   Vector<ModifyEvent> mModifyEvents;       ///< Temporary stores the text set until the next relayout.
542   Vector4 mTextColor;                      ///< The regular text color
543   Vector2 mAlignmentOffset;                ///< Vertical and horizontal offset of the whole text inside the control due to alignment.
544   OperationsMask mOperationsPending;       ///< Operations pending to be done to layout the text.
545   Length mMaximumNumberOfCharacters;       ///< Maximum number of characters that can be inserted.
546
547   bool mRecalculateNaturalSize:1;          ///< Whether the natural size needs to be recalculated.
548   bool mMarkupProcessorEnabled:1;          ///< Whether the mark-up procesor is enabled.
549 };
550
551 } // namespace Text
552
553 } // namespace Toolkit
554
555 } // namespace Dali
556
557 #endif // __DALI_TOOLKIT_TEXT_CONTROLLER_H__