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