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