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