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